Introduce TelegramObject.api_kwargs (#3233)

This commit is contained in:
Bibo-Joshi
2022-10-07 11:51:53 +02:00
committed by GitHub
parent fb87418473
commit 1c20ff3fb9
172 changed files with 1176 additions and 793 deletions
+6
View File
@@ -15,3 +15,9 @@
.. |thumbdocstringnopath| replace:: |thumbdocstringbase| |uploadinputnopath|
.. |editreplymarkup| replace:: It is currently only possible to edit messages without :attr:`telegram.Message.reply_markup` or with inline keyboards.
.. |toapikwargsbase| replace:: These arguments are also considered by :meth:`~telegram.TelegramObject.to_dict` and :meth:`~telegram.TelegramObject.to_json`, i.e. when passing objects to Telegram. Passing them to Telegram is however not guaranteed to work for all kinds of objects, e.g. this will fail for objects that can not directly be JSON serialized.
.. |toapikwargsarg| replace:: Arbitrary keyword arguments. Can be used to store data for which there are no dedicated attributes. |toapikwargsbase|
.. |toapikwargsattr| replace:: Optional. Arbitrary keyword arguments. Used to store data for which there are no dedicated attributes. |toapikwargsbase|
+1
View File
@@ -216,6 +216,7 @@ class Bot(TelegramObject, AbstractAsyncContextManager):
private_key_password: bytes = None,
local_mode: bool = False,
):
super().__init__(api_kwargs=None)
if not token:
raise InvalidToken("You must pass the token you received from https://t.me/Botfather!")
self._token = token
+3 -2
View File
@@ -17,9 +17,9 @@
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents a Telegram Bot Command."""
from typing import Any
from telegram._telegramobject import TelegramObject
from telegram._utils.types import JSONDict
class BotCommand(TelegramObject):
@@ -42,7 +42,8 @@ class BotCommand(TelegramObject):
__slots__ = ("description", "command")
def __init__(self, command: str, description: str, **_kwargs: Any):
def __init__(self, command: str, description: str, *, api_kwargs: JSONDict = None):
super().__init__(api_kwargs=api_kwargs)
self.command = command
self.description = description
+20 -24
View File
@@ -18,7 +18,7 @@
# along with this program. If not, see [http://www.gnu.org/licenses/].
# pylint: disable=redefined-builtin
"""This module contains objects representing Telegram bot command scopes."""
from typing import TYPE_CHECKING, Any, ClassVar, Dict, Optional, Type, Union
from typing import TYPE_CHECKING, ClassVar, Dict, Optional, Type, Union
from telegram import constants
from telegram._telegramobject import TelegramObject
@@ -75,7 +75,8 @@ class BotCommandScope(TelegramObject):
CHAT_MEMBER: ClassVar[str] = constants.BotCommandScopeType.CHAT_MEMBER
""":const:`telegram.constants.BotCommandScopeType.CHAT_MEMBER`"""
def __init__(self, type: str, **_kwargs: Any):
def __init__(self, type: str, *, api_kwargs: JSONDict = None):
super().__init__(api_kwargs=api_kwargs)
self.type = type
self._id_attrs = (self.type,)
@@ -107,9 +108,9 @@ class BotCommandScope(TelegramObject):
cls.CHAT_MEMBER: BotCommandScopeChatMember,
}
if cls is BotCommandScope:
return _class_mapping.get(data["type"], cls)(**data, bot=bot)
return cls(**data)
if cls is BotCommandScope and data.get("type") in _class_mapping:
return _class_mapping[data.pop("type")].de_json(data=data, bot=bot)
return super().de_json(data=data, bot=bot)
class BotCommandScopeDefault(BotCommandScope):
@@ -119,15 +120,14 @@ class BotCommandScopeDefault(BotCommandScope):
.. _`narrower scope`: https://core.telegram.org/bots/api#determining-list-of-commands
.. versionadded:: 13.7
Attributes:
type (:obj:`str`): Scope type :tg-const:`telegram.BotCommandScope.DEFAULT`.
"""
__slots__ = ()
def __init__(self, **_kwargs: Any):
super().__init__(type=BotCommandScope.DEFAULT)
def __init__(self, *, api_kwargs: JSONDict = None):
super().__init__(type=BotCommandScope.DEFAULT, api_kwargs=api_kwargs)
class BotCommandScopeAllPrivateChats(BotCommandScope):
@@ -141,38 +141,36 @@ class BotCommandScopeAllPrivateChats(BotCommandScope):
__slots__ = ()
def __init__(self, **_kwargs: Any):
super().__init__(type=BotCommandScope.ALL_PRIVATE_CHATS)
def __init__(self, *, api_kwargs: JSONDict = None):
super().__init__(type=BotCommandScope.ALL_PRIVATE_CHATS, api_kwargs=api_kwargs)
class BotCommandScopeAllGroupChats(BotCommandScope):
"""Represents the scope of bot commands, covering all group and supergroup chats.
.. versionadded:: 13.7
Attributes:
type (:obj:`str`): Scope type :tg-const:`telegram.BotCommandScope.ALL_GROUP_CHATS`.
"""
__slots__ = ()
def __init__(self, **_kwargs: Any):
super().__init__(type=BotCommandScope.ALL_GROUP_CHATS)
def __init__(self, *, api_kwargs: JSONDict = None):
super().__init__(type=BotCommandScope.ALL_GROUP_CHATS, api_kwargs=api_kwargs)
class BotCommandScopeAllChatAdministrators(BotCommandScope):
"""Represents the scope of bot commands, covering all group and supergroup chat administrators.
.. versionadded:: 13.7
Attributes:
type (:obj:`str`): Scope type :tg-const:`telegram.BotCommandScope.ALL_CHAT_ADMINISTRATORS`.
"""
__slots__ = ()
def __init__(self, **_kwargs: Any):
super().__init__(type=BotCommandScope.ALL_CHAT_ADMINISTRATORS)
def __init__(self, *, api_kwargs: JSONDict = None):
super().__init__(type=BotCommandScope.ALL_CHAT_ADMINISTRATORS, api_kwargs=api_kwargs)
class BotCommandScopeChat(BotCommandScope):
@@ -186,7 +184,6 @@ class BotCommandScopeChat(BotCommandScope):
Args:
chat_id (:obj:`str` | :obj:`int`): Unique identifier for the target chat or username of the
target supergroup (in the format ``@supergroupusername``)
Attributes:
type (:obj:`str`): Scope type :tg-const:`telegram.BotCommandScope.CHAT`.
chat_id (:obj:`str` | :obj:`int`): Unique identifier for the target chat or username of the
@@ -195,8 +192,8 @@ class BotCommandScopeChat(BotCommandScope):
__slots__ = ("chat_id",)
def __init__(self, chat_id: Union[str, int], **_kwargs: Any):
super().__init__(type=BotCommandScope.CHAT)
def __init__(self, chat_id: Union[str, int], *, api_kwargs: JSONDict = None):
super().__init__(type=BotCommandScope.CHAT, api_kwargs=api_kwargs)
self.chat_id = (
chat_id if isinstance(chat_id, str) and chat_id.startswith("@") else int(chat_id)
)
@@ -215,7 +212,6 @@ class BotCommandScopeChatAdministrators(BotCommandScope):
Args:
chat_id (:obj:`str` | :obj:`int`): Unique identifier for the target chat or username of the
target supergroup (in the format ``@supergroupusername``)
Attributes:
type (:obj:`str`): Scope type :tg-const:`telegram.BotCommandScope.CHAT_ADMINISTRATORS`.
chat_id (:obj:`str` | :obj:`int`): Unique identifier for the target chat or username of the
@@ -224,8 +220,8 @@ class BotCommandScopeChatAdministrators(BotCommandScope):
__slots__ = ("chat_id",)
def __init__(self, chat_id: Union[str, int], **_kwargs: Any):
super().__init__(type=BotCommandScope.CHAT_ADMINISTRATORS)
def __init__(self, chat_id: Union[str, int], *, api_kwargs: JSONDict = None):
super().__init__(type=BotCommandScope.CHAT_ADMINISTRATORS, api_kwargs=api_kwargs)
self.chat_id = (
chat_id if isinstance(chat_id, str) and chat_id.startswith("@") else int(chat_id)
)
@@ -255,8 +251,8 @@ class BotCommandScopeChatMember(BotCommandScope):
__slots__ = ("chat_id", "user_id")
def __init__(self, chat_id: Union[str, int], user_id: int, **_kwargs: Any):
super().__init__(type=BotCommandScope.CHAT_MEMBER)
def __init__(self, chat_id: Union[str, int], user_id: int, *, api_kwargs: JSONDict = None):
super().__init__(type=BotCommandScope.CHAT_MEMBER, api_kwargs=api_kwargs)
self.chat_id = (
chat_id if isinstance(chat_id, str) and chat_id.startswith("@") else int(chat_id)
)
+8 -10
View File
@@ -18,7 +18,7 @@
# along with this program. If not, see [http://www.gnu.org/licenses/].
# pylint: disable=redefined-builtin
"""This module contains an object that represents a Telegram CallbackQuery"""
from typing import TYPE_CHECKING, Any, ClassVar, List, Optional, Tuple, Union
from typing import TYPE_CHECKING, ClassVar, List, Optional, Tuple, Union
from telegram import constants
from telegram._files.location import Location
@@ -79,7 +79,6 @@ class CallbackQuery(TelegramObject):
inline mode, that originated the query.
game_short_name (:obj:`str`, optional): Short name of a Game to be returned, serves as
the unique identifier for the game
bot (:class:`telegram.Bot`, optional): The Bot to use for instance methods.
Attributes:
id (:obj:`str`): Unique identifier for this query.
@@ -96,7 +95,7 @@ class CallbackQuery(TelegramObject):
inline_message_id (:obj:`str`): Optional. Identifier of the message sent via the bot in
inline mode, that originated the query.
game_short_name (:obj:`str`): Optional. Short name of a Game to be returned.
bot (:class:`telegram.Bot`, optional): The Bot to use for instance methods.
"""
@@ -112,16 +111,17 @@ class CallbackQuery(TelegramObject):
def __init__(
self,
id: str, # pylint: disable=invalid-name
id: str,
from_user: User,
chat_instance: str,
message: Message = None,
data: str = None,
inline_message_id: str = None,
game_short_name: str = None,
bot: "Bot" = None,
**_kwargs: Any,
*,
api_kwargs: JSONDict = None,
):
super().__init__(api_kwargs=api_kwargs)
# Required
self.id = id # pylint: disable=invalid-name
self.from_user = from_user
@@ -132,8 +132,6 @@ class CallbackQuery(TelegramObject):
self.inline_message_id = inline_message_id
self.game_short_name = game_short_name
self.set_bot(bot)
self._id_attrs = (self.id,)
@classmethod
@@ -144,10 +142,10 @@ class CallbackQuery(TelegramObject):
if not data:
return None
data["from_user"] = User.de_json(data.get("from"), bot)
data["from_user"] = User.de_json(data.pop("from", None), bot)
data["message"] = Message.de_json(data.get("message"), bot)
return cls(bot=bot, **data)
return super().de_json(data=data, bot=bot)
async def answer(
self,
+20 -13
View File
@@ -19,7 +19,7 @@
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents a Telegram Chat."""
from datetime import datetime
from typing import TYPE_CHECKING, Any, ClassVar, List, Optional, Tuple, Union
from typing import TYPE_CHECKING, ClassVar, List, Optional, Tuple, Union
from telegram import constants
from telegram._chatlocation import ChatLocation
@@ -73,6 +73,11 @@ class Chat(TelegramObject):
``api_kwargs``. Use a named argument for those,
and notice that some positional arguments changed position as a result.
.. versionchanged:: 20.0
Removed the attribute ``all_members_are_administrators``. As long as Telegram provides
this field for backwards compatibility, it is available through
:attr:`~telegram.TelegramObject.api_kwargs`.
Args:
id (:obj:`int`): Unique identifier for this chat. This number may be greater than 32 bits
and some programming languages may have difficulty/silent defects in interpreting it.
@@ -114,7 +119,7 @@ class Chat(TelegramObject):
be forwarded to other chats. Returned only in :meth:`telegram.Bot.get_chat`.
.. versionadded:: 13.9
bot (:class:`telegram.Bot`, optional): The Bot to use for instance methods.
sticker_set_name (:obj:`str`, optional): For supergroups, name of group sticker set.
Returned only in :meth:`telegram.Bot.get_chat`.
can_set_sticker_set (:obj:`bool`, optional): :obj:`True`, if the bot can change group the
@@ -139,9 +144,6 @@ class Chat(TelegramObject):
in the private chat. Returned only in :meth:`telegram.Bot.get_chat`.
.. versionadded:: 20.0
**kwargs (:obj:`dict`): Arbitrary keyword arguments.
Attributes:
id (:obj:`int`): Unique identifier for this chat.
type (:obj:`str`): Type of chat.
@@ -220,7 +222,6 @@ class Chat(TelegramObject):
"title",
"photo",
"linked_chat_id",
"all_members_are_administrators",
"message_auto_delete_time",
"has_protected_content",
"has_private_forwards",
@@ -245,13 +246,12 @@ class Chat(TelegramObject):
def __init__(
self,
id: int, # pylint: disable=invalid-name
id: int,
type: str,
title: str = None,
username: str = None,
first_name: str = None,
last_name: str = None,
bot: "Bot" = None,
photo: ChatPhoto = None,
description: str = None,
invite_link: str = None,
@@ -269,8 +269,10 @@ class Chat(TelegramObject):
join_to_send_messages: bool = None,
join_by_request: bool = None,
has_restricted_voice_and_video_messages: bool = None,
**_kwargs: Any,
*,
api_kwargs: JSONDict = None,
):
super().__init__(api_kwargs=api_kwargs)
# Required
self.id = id # pylint: disable=invalid-name
self.type = enum.get_member(constants.ChatType, type, type)
@@ -279,8 +281,6 @@ class Chat(TelegramObject):
self.username = username
self.first_name = first_name
self.last_name = last_name
# TODO: Remove (also from tests), when Telegram drops this completely
self.all_members_are_administrators = _kwargs.get("all_members_are_administrators")
self.photo = photo
self.bio = bio
self.has_private_forwards = has_private_forwards
@@ -301,7 +301,6 @@ class Chat(TelegramObject):
self.join_by_request = join_by_request
self.has_restricted_voice_and_video_messages = has_restricted_voice_and_video_messages
self.set_bot(bot)
self._id_attrs = (self.id,)
@property
@@ -346,7 +345,15 @@ class Chat(TelegramObject):
data["permissions"] = ChatPermissions.de_json(data.get("permissions"), bot)
data["location"] = ChatLocation.de_json(data.get("location"), bot)
return cls(bot=bot, **data)
api_kwargs = {}
# This is a deprecated field that TG still returns for backwards compatibility
# Let's filter it out to speed up the de-json process
if "all_members_are_administrators" in data:
api_kwargs["all_members_are_administrators"] = data.pop(
"all_members_are_administrators"
)
return super()._de_json(data=data, bot=bot, api_kwargs=api_kwargs)
async def leave(
self,
+4 -3
View File
@@ -18,9 +18,8 @@
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains the class which represents a Telegram ChatAdministratorRights."""
from typing import Any
from telegram._telegramobject import TelegramObject
from telegram._utils.types import JSONDict
class ChatAdministratorRights(TelegramObject):
@@ -119,8 +118,10 @@ class ChatAdministratorRights(TelegramObject):
can_post_messages: bool = None,
can_edit_messages: bool = None,
can_pin_messages: bool = None,
**_kwargs: Any,
*,
api_kwargs: JSONDict = None,
) -> None:
super().__init__(api_kwargs=api_kwargs)
# Required
self.is_anonymous = is_anonymous
self.can_manage_chat = can_manage_chat
+5 -4
View File
@@ -18,7 +18,7 @@
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents an invite link for a chat."""
import datetime
from typing import TYPE_CHECKING, Any, Optional
from typing import TYPE_CHECKING, Optional
from telegram._telegramobject import TelegramObject
from telegram._user import User
@@ -65,7 +65,6 @@ class ChatInviteLink(TelegramObject):
created using this link.
.. versionadded:: 13.8
Attributes:
invite_link (:obj:`str`): The invite link. If the link was created by another chat
administrator, then the second part of the link will be replaced with ``''``.
@@ -113,8 +112,10 @@ class ChatInviteLink(TelegramObject):
member_limit: int = None,
name: str = None,
pending_join_request_count: int = None,
**_kwargs: Any,
*,
api_kwargs: JSONDict = None,
):
super().__init__(api_kwargs=api_kwargs)
# Required
self.invite_link = invite_link
self.creator = creator
@@ -148,7 +149,7 @@ class ChatInviteLink(TelegramObject):
data["creator"] = User.de_json(data.get("creator"), bot)
data["expire_date"] = from_timestamp(data.get("expire_date", None))
return cls(**data)
return super().de_json(data=data, bot=bot)
def to_dict(self) -> JSONDict:
"""See :meth:`telegram.TelegramObject.to_dict`."""
+6 -7
View File
@@ -18,7 +18,7 @@
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents a Telegram ChatJoinRequest."""
import datetime
from typing import TYPE_CHECKING, Any, Optional
from typing import TYPE_CHECKING, Optional
from telegram._chat import Chat
from telegram._chatinvitelink import ChatInviteLink
@@ -53,7 +53,6 @@ class ChatJoinRequest(TelegramObject):
bio (:obj:`str`, optional): Bio of the user.
invite_link (:class:`telegram.ChatInviteLink`, optional): Chat invite link that was used
by the user to send the join request.
bot (:class:`telegram.Bot`, optional): The Bot to use for instance methods.
Attributes:
chat (:class:`telegram.Chat`): Chat to which the request was sent.
@@ -74,9 +73,10 @@ class ChatJoinRequest(TelegramObject):
date: datetime.datetime,
bio: str = None,
invite_link: ChatInviteLink = None,
bot: "Bot" = None,
**_kwargs: Any,
*,
api_kwargs: JSONDict = None,
):
super().__init__(api_kwargs=api_kwargs)
# Required
self.chat = chat
self.from_user = from_user
@@ -86,7 +86,6 @@ class ChatJoinRequest(TelegramObject):
self.bio = bio
self.invite_link = invite_link
self.set_bot(bot)
self._id_attrs = (self.chat, self.from_user, self.date)
@classmethod
@@ -98,11 +97,11 @@ class ChatJoinRequest(TelegramObject):
return None
data["chat"] = Chat.de_json(data.get("chat"), bot)
data["from_user"] = User.de_json(data.get("from"), bot)
data["from_user"] = User.de_json(data.pop("from", None), bot)
data["date"] = from_timestamp(data.get("date", None))
data["invite_link"] = ChatInviteLink.de_json(data.get("invite_link"), bot)
return cls(bot=bot, **data)
return super().de_json(data=data, bot=bot)
def to_dict(self) -> JSONDict:
"""See :meth:`telegram.TelegramObject.to_dict`."""
+5 -5
View File
@@ -18,7 +18,7 @@
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents a location to which a chat is connected."""
from typing import TYPE_CHECKING, Any, Optional
from typing import TYPE_CHECKING, Optional
from telegram._files.location import Location
from telegram._telegramobject import TelegramObject
@@ -38,8 +38,6 @@ class ChatLocation(TelegramObject):
location (:class:`telegram.Location`): The location to which the supergroup is connected.
Can't be a live location.
address (:obj:`str`): Location address; 1-64 characters, as defined by the chat owner
**kwargs (:obj:`dict`): Arbitrary keyword arguments.
Attributes:
location (:class:`telegram.Location`): The location to which the supergroup is connected.
address (:obj:`str`): Location address, as defined by the chat owner
@@ -52,8 +50,10 @@ class ChatLocation(TelegramObject):
self,
location: Location,
address: str,
**_kwargs: Any,
*,
api_kwargs: JSONDict = None,
):
super().__init__(api_kwargs=api_kwargs)
self.location = location
self.address = address
@@ -69,4 +69,4 @@ class ChatLocation(TelegramObject):
data["location"] = Location.de_json(data.get("location"), bot)
return cls(bot=bot, **data)
return super().de_json(data=data, bot=bot)
+51 -22
View File
@@ -83,7 +83,14 @@ class ChatMember(TelegramObject):
RESTRICTED: ClassVar[str] = constants.ChatMemberStatus.RESTRICTED
""":const:`telegram.constants.ChatMemberStatus.RESTRICTED`"""
def __init__(self, user: User, status: str, **_kwargs: object):
def __init__(
self,
user: User,
status: str,
*,
api_kwargs: JSONDict = None,
):
super().__init__(api_kwargs=api_kwargs)
# Required by all subclasses
self.user = user
self.status = status
@@ -98,9 +105,6 @@ class ChatMember(TelegramObject):
if not data:
return None
data["user"] = User.de_json(data.get("user"), bot)
data["until_date"] = from_timestamp(data.get("until_date", None))
_class_mapping: Dict[str, Type["ChatMember"]] = {
cls.OWNER: ChatMemberOwner,
cls.ADMINISTRATOR: ChatMemberAdministrator,
@@ -110,9 +114,14 @@ class ChatMember(TelegramObject):
cls.BANNED: ChatMemberBanned,
}
if cls is ChatMember:
return _class_mapping.get(data["status"], cls)(**data, bot=bot)
return cls(**data)
if cls is ChatMember and data.get("status") in _class_mapping:
return _class_mapping[data.pop("status")].de_json(data=data, bot=bot)
data["user"] = User.de_json(data.get("user"), bot)
if "until_date" in data:
data["until_date"] = from_timestamp(data["until_date"])
return super().de_json(data=data, bot=bot)
def to_dict(self) -> JSONDict:
"""See :meth:`telegram.TelegramObject.to_dict`."""
@@ -154,9 +163,10 @@ class ChatMemberOwner(ChatMember):
user: User,
is_anonymous: bool,
custom_title: str = None,
**_kwargs: object,
*,
api_kwargs: JSONDict = None,
):
super().__init__(status=ChatMember.OWNER, user=user)
super().__init__(status=ChatMember.OWNER, user=user, api_kwargs=api_kwargs)
self.is_anonymous = is_anonymous
self.custom_title = custom_title
@@ -167,9 +177,10 @@ class ChatMemberAdministrator(ChatMember):
.. versionadded:: 13.7
.. versionchanged:: 20.0
Argument and attribute ``can_manage_voice_chats`` were renamed to
:paramref:`can_manage_video_chats` and :attr:`can_manage_video_chats` in accordance to
Bot API 6.0.
* Argument and attribute ``can_manage_voice_chats`` were renamed to
:paramref:`can_manage_video_chats` and :attr:`can_manage_video_chats` in accordance to
Bot API 6.0.
Args:
user (:class:`telegram.User`): Information about the user.
@@ -276,9 +287,10 @@ class ChatMemberAdministrator(ChatMember):
can_edit_messages: bool = None,
can_pin_messages: bool = None,
custom_title: str = None,
**_kwargs: object,
*,
api_kwargs: JSONDict = None,
):
super().__init__(status=ChatMember.ADMINISTRATOR, user=user)
super().__init__(status=ChatMember.ADMINISTRATOR, user=user, api_kwargs=api_kwargs)
self.can_be_edited = can_be_edited
self.is_anonymous = is_anonymous
self.can_manage_chat = can_manage_chat
@@ -313,8 +325,13 @@ class ChatMemberMember(ChatMember):
__slots__ = ()
def __init__(self, user: User, **_kwargs: object):
super().__init__(status=ChatMember.MEMBER, user=user)
def __init__(
self,
user: User,
*,
api_kwargs: JSONDict = None,
):
super().__init__(status=ChatMember.MEMBER, user=user, api_kwargs=api_kwargs)
class ChatMemberRestricted(ChatMember):
@@ -400,9 +417,10 @@ class ChatMemberRestricted(ChatMember):
can_send_other_messages: bool,
can_add_web_page_previews: bool,
until_date: datetime.datetime,
**_kwargs: object,
*,
api_kwargs: JSONDict = None,
):
super().__init__(status=ChatMember.RESTRICTED, user=user)
super().__init__(status=ChatMember.RESTRICTED, user=user, api_kwargs=api_kwargs)
self.is_member = is_member
self.can_change_info = can_change_info
self.can_invite_users = can_invite_users
@@ -433,8 +451,13 @@ class ChatMemberLeft(ChatMember):
__slots__ = ()
def __init__(self, user: User, **_kwargs: object):
super().__init__(status=ChatMember.LEFT, user=user)
def __init__(
self,
user: User,
*,
api_kwargs: JSONDict = None,
):
super().__init__(status=ChatMember.LEFT, user=user, api_kwargs=api_kwargs)
class ChatMemberBanned(ChatMember):
@@ -460,6 +483,12 @@ class ChatMemberBanned(ChatMember):
__slots__ = ("until_date",)
def __init__(self, user: User, until_date: datetime.datetime, **_kwargs: object):
super().__init__(status=ChatMember.BANNED, user=user)
def __init__(
self,
user: User,
until_date: datetime.datetime,
*,
api_kwargs: JSONDict = None,
):
super().__init__(status=ChatMember.BANNED, user=user, api_kwargs=api_kwargs)
self.until_date = until_date
+6 -4
View File
@@ -18,7 +18,7 @@
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents a Telegram ChatMemberUpdated."""
import datetime
from typing import TYPE_CHECKING, Any, Dict, Optional, Tuple, Union
from typing import TYPE_CHECKING, Dict, Optional, Tuple, Union
from telegram._chat import Chat
from telegram._chatinvitelink import ChatInviteLink
@@ -83,8 +83,10 @@ class ChatMemberUpdated(TelegramObject):
old_chat_member: ChatMember,
new_chat_member: ChatMember,
invite_link: ChatInviteLink = None,
**_kwargs: Any,
*,
api_kwargs: JSONDict = None,
):
super().__init__(api_kwargs=api_kwargs)
# Required
self.chat = chat
self.from_user = from_user
@@ -112,13 +114,13 @@ class ChatMemberUpdated(TelegramObject):
return None
data["chat"] = Chat.de_json(data.get("chat"), bot)
data["from_user"] = User.de_json(data.get("from"), bot)
data["from_user"] = User.de_json(data.pop("from", None), bot)
data["date"] = from_timestamp(data.get("date"))
data["old_chat_member"] = ChatMember.de_json(data.get("old_chat_member"), bot)
data["new_chat_member"] = ChatMember.de_json(data.get("new_chat_member"), bot)
data["invite_link"] = ChatInviteLink.de_json(data.get("invite_link"), bot)
return cls(**data)
return super().de_json(data=data, bot=bot)
def to_dict(self) -> JSONDict:
"""See :meth:`telegram.TelegramObject.to_dict`."""
+4 -3
View File
@@ -18,9 +18,8 @@
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents a Telegram ChatPermission."""
from typing import Any
from telegram._telegramobject import TelegramObject
from telegram._utils.types import JSONDict
class ChatPermissions(TelegramObject):
@@ -99,8 +98,10 @@ class ChatPermissions(TelegramObject):
can_change_info: bool = None,
can_invite_users: bool = None,
can_pin_messages: bool = None,
**_kwargs: Any,
*,
api_kwargs: JSONDict = None,
):
super().__init__(api_kwargs=api_kwargs)
# Required
self.can_send_messages = can_send_messages
self.can_send_media_messages = can_send_media_messages
+7 -5
View File
@@ -19,7 +19,7 @@
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents a Telegram ChosenInlineResult."""
from typing import TYPE_CHECKING, Any, Optional
from typing import TYPE_CHECKING, Optional
from telegram._files.location import Location
from telegram._telegramobject import TelegramObject
@@ -52,7 +52,6 @@ class ChosenInlineResult(TelegramObject):
only if there is an inline keyboard attached to the message. Will be also received in
callback queries and can be used to edit the message.
query (:obj:`str`): The query that was used to obtain the result.
**kwargs (:obj:`dict`): Arbitrary keyword arguments.
Attributes:
result_id (:obj:`str`): The unique identifier for the result that was chosen.
@@ -72,8 +71,11 @@ class ChosenInlineResult(TelegramObject):
query: str,
location: Location = None,
inline_message_id: str = None,
**_kwargs: Any,
*,
api_kwargs: JSONDict = None,
):
super().__init__(api_kwargs=api_kwargs)
# Required
self.result_id = result_id
self.from_user = from_user
@@ -93,8 +95,8 @@ class ChosenInlineResult(TelegramObject):
return None
# Required
data["from_user"] = User.de_json(data.pop("from"), bot)
data["from_user"] = User.de_json(data.pop("from", None), bot)
# Optionals
data["location"] = Location.de_json(data.get("location"), bot)
return cls(**data)
return super().de_json(data=data, bot=bot)
+4 -2
View File
@@ -17,10 +17,11 @@
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents a Telegram Dice."""
from typing import Any, ClassVar, List
from typing import ClassVar, List
from telegram import constants
from telegram._telegramobject import TelegramObject
from telegram._utils.types import JSONDict
class Dice(TelegramObject):
@@ -67,7 +68,8 @@ class Dice(TelegramObject):
__slots__ = ("emoji", "value")
def __init__(self, value: int, emoji: str, **_kwargs: Any):
def __init__(self, value: int, emoji: str, *, api_kwargs: JSONDict = None):
super().__init__(api_kwargs=api_kwargs)
self.value = value
self.emoji = emoji
+10 -5
View File
@@ -24,7 +24,7 @@ from telegram._utils.defaultvalue import DEFAULT_NONE
from telegram._utils.types import JSONDict, ODVInput
if TYPE_CHECKING:
from telegram import Bot, File
from telegram import File
class _BaseMedium(TelegramObject):
@@ -39,7 +39,6 @@ class _BaseMedium(TelegramObject):
is supposed to be the same over time and for different bots.
Can't be used to download or reuse the file.
file_size (:obj:`int`, optional): File size.
bot (:class:`telegram.Bot`, optional): The Bot to use for instance methods.
Attributes:
file_id (:obj:`str`): File identifier.
@@ -47,21 +46,27 @@ class _BaseMedium(TelegramObject):
is supposed to be the same over time and for different bots.
Can't be used to download or reuse the file.
file_size (:obj:`int`): Optional. File size.
bot (:class:`telegram.Bot`): Optional. The Bot to use for instance methods.
"""
__slots__ = ("file_id", "file_size", "file_unique_id")
def __init__(
self, file_id: str, file_unique_id: str, file_size: int = None, bot: "Bot" = None
self,
file_id: str,
file_unique_id: str,
file_size: int = None,
*,
api_kwargs: JSONDict = None,
):
super().__init__(api_kwargs=api_kwargs)
# Required
self.file_id: str = str(file_id)
self.file_unique_id = str(file_unique_id)
# Optionals
self.file_size = file_size
self.set_bot(bot)
self._id_attrs = (self.file_unique_id,)
+11 -6
View File
@@ -45,7 +45,6 @@ class _BaseThumbedMedium(_BaseMedium):
Can't be used to download or reuse the file.
file_size (:obj:`int`, optional): File size.
thumb (:class:`telegram.PhotoSize`, optional): Thumbnail as defined by sender.
bot (:class:`telegram.Bot`, optional): The Bot to use for instance methods.
Attributes:
file_id (:obj:`str`): File identifier.
@@ -54,7 +53,7 @@ class _BaseThumbedMedium(_BaseMedium):
Can't be used to download or reuse the file.
file_size (:obj:`int`): Optional. File size.
thumb (:class:`telegram.PhotoSize`): Optional. Thumbnail as defined by sender.
bot (:class:`telegram.Bot`): Optional. The Bot to use for instance methods.
"""
@@ -66,10 +65,14 @@ class _BaseThumbedMedium(_BaseMedium):
file_unique_id: str,
file_size: int = None,
thumb: PhotoSize = None,
bot: "Bot" = None,
*,
api_kwargs: JSONDict = None,
):
super().__init__(
file_id=file_id, file_unique_id=file_unique_id, file_size=file_size, bot=bot
file_id=file_id,
file_unique_id=file_unique_id,
file_size=file_size,
api_kwargs=api_kwargs,
)
self.thumb = thumb
@@ -83,6 +86,8 @@ class _BaseThumbedMedium(_BaseMedium):
if not data:
return None
data["thumb"] = PhotoSize.de_json(data.get("thumb"), bot)
# In case this wasn't already done by the subclass
if not isinstance(data.get("thumb"), PhotoSize):
data["thumb"] = PhotoSize.de_json(data.get("thumb"), bot)
return cls(bot=bot, **data)
return super().de_json(data=data, bot=bot)
+5 -10
View File
@@ -17,13 +17,10 @@
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents a Telegram Animation."""
from typing import TYPE_CHECKING, Any
from telegram._files._basethumbedmedium import _BaseThumbedMedium
from telegram._files.photosize import PhotoSize
if TYPE_CHECKING:
from telegram import Bot
from telegram._utils.types import JSONDict
class Animation(_BaseThumbedMedium):
@@ -45,8 +42,6 @@ class Animation(_BaseThumbedMedium):
file_name (:obj:`str`, optional): Original animation filename as defined by sender.
mime_type (:obj:`str`, optional): MIME type of the file as defined by sender.
file_size (:obj:`int`, optional): File size in bytes.
bot (:class:`telegram.Bot`, optional): The Bot to use for instance methods.
**kwargs (:obj:`dict`): Arbitrary keyword arguments.
Attributes:
file_id (:obj:`str`): File identifier.
@@ -60,7 +55,7 @@ class Animation(_BaseThumbedMedium):
file_name (:obj:`str`): Optional. Original animation filename as defined by sender.
mime_type (:obj:`str`): Optional. MIME type of the file as defined by sender.
file_size (:obj:`int`): Optional. File size in bytes.
bot (:class:`telegram.Bot`): Optional. The Bot to use for instance methods.
"""
@@ -77,15 +72,15 @@ class Animation(_BaseThumbedMedium):
file_name: str = None,
mime_type: str = None,
file_size: int = None,
bot: "Bot" = None,
**_kwargs: Any,
*,
api_kwargs: JSONDict = None,
):
super().__init__(
file_id=file_id,
file_unique_id=file_unique_id,
file_size=file_size,
thumb=thumb,
bot=bot,
api_kwargs=api_kwargs,
)
# Required
self.width = width
+6 -11
View File
@@ -18,13 +18,9 @@
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents a Telegram Audio."""
from typing import TYPE_CHECKING, Any
from telegram._files._basethumbedmedium import _BaseThumbedMedium
from telegram._files.photosize import PhotoSize
if TYPE_CHECKING:
from telegram import Bot
from telegram._utils.types import JSONDict
class Audio(_BaseThumbedMedium):
@@ -33,6 +29,7 @@ class Audio(_BaseThumbedMedium):
Objects of this class are comparable in terms of equality. Two objects of this class are
considered equal, if their :attr:`file_unique_id` is equal.
Args:
file_id (:obj:`str`): Identifier for this file, which can be used to download
or reuse the file.
@@ -47,8 +44,6 @@ class Audio(_BaseThumbedMedium):
file_size (:obj:`int`, optional): File size in bytes.
thumb (:class:`telegram.PhotoSize`, optional): Thumbnail of the album cover to
which the music file belongs.
bot (:class:`telegram.Bot`, optional): The Bot to use for instance methods.
**kwargs (:obj:`dict`): Arbitrary keyword arguments.
Attributes:
file_id (:obj:`str`): Identifier for this file.
@@ -64,7 +59,7 @@ class Audio(_BaseThumbedMedium):
file_size (:obj:`int`): Optional. File size in bytes.
thumb (:class:`telegram.PhotoSize`): Optional. Thumbnail of the album cover to
which the music file belongs.
bot (:class:`telegram.Bot`): Optional. The Bot to use for instance methods.
"""
@@ -80,16 +75,16 @@ class Audio(_BaseThumbedMedium):
mime_type: str = None,
file_size: int = None,
thumb: PhotoSize = None,
bot: "Bot" = None,
file_name: str = None,
**_kwargs: Any,
*,
api_kwargs: JSONDict = None,
):
super().__init__(
file_id=file_id,
file_unique_id=file_unique_id,
file_size=file_size,
thumb=thumb,
bot=bot,
api_kwargs=api_kwargs,
)
# Required
self.duration = duration
+5 -8
View File
@@ -17,14 +17,14 @@
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents a Telegram ChatPhoto."""
from typing import TYPE_CHECKING, Any
from typing import TYPE_CHECKING
from telegram._telegramobject import TelegramObject
from telegram._utils.defaultvalue import DEFAULT_NONE
from telegram._utils.types import JSONDict, ODVInput
if TYPE_CHECKING:
from telegram import Bot, File
from telegram import File
class ChatPhoto(TelegramObject):
@@ -46,8 +46,6 @@ class ChatPhoto(TelegramObject):
big_file_unique_id (:obj:`str`): Unique file identifier of big (640x640) chat photo,
which is supposed to be the same over time and for different bots.
Can't be used to download or reuse the file.
bot (:class:`telegram.Bot`, optional): The Bot to use for instance methods
**kwargs (:obj:`dict`): Arbitrary keyword arguments.
Attributes:
small_file_id (:obj:`str`): File identifier of small (160x160) chat photo.
@@ -78,16 +76,15 @@ class ChatPhoto(TelegramObject):
small_file_unique_id: str,
big_file_id: str,
big_file_unique_id: str,
bot: "Bot" = None,
**_kwargs: Any,
*,
api_kwargs: JSONDict = None,
):
super().__init__(api_kwargs=api_kwargs)
self.small_file_id = small_file_id
self.small_file_unique_id = small_file_unique_id
self.big_file_id = big_file_id
self.big_file_unique_id = big_file_unique_id
self.set_bot(bot)
self._id_attrs = (
self.small_file_unique_id,
self.big_file_unique_id,
+4 -4
View File
@@ -18,9 +18,8 @@
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents a Telegram Contact."""
from typing import Any
from telegram._telegramobject import TelegramObject
from telegram._utils.types import JSONDict
class Contact(TelegramObject):
@@ -35,7 +34,6 @@ class Contact(TelegramObject):
last_name (:obj:`str`, optional): Contact's last name.
user_id (:obj:`int`, optional): Contact's user identifier in Telegram.
vcard (:obj:`str`, optional): Additional data about the contact in the form of a vCard.
**kwargs (:obj:`dict`): Arbitrary keyword arguments.
Attributes:
phone_number (:obj:`str`): Contact's phone number.
@@ -55,8 +53,10 @@ class Contact(TelegramObject):
last_name: str = None,
user_id: int = None,
vcard: str = None,
**_kwargs: Any,
*,
api_kwargs: JSONDict = None,
):
super().__init__(api_kwargs=api_kwargs)
# Required
self.phone_number = str(phone_number)
self.first_name = first_name
+5 -11
View File
@@ -18,13 +18,9 @@
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents a Telegram Document."""
from typing import TYPE_CHECKING, Any
from telegram._files._basethumbedmedium import _BaseThumbedMedium
from telegram._files.photosize import PhotoSize
if TYPE_CHECKING:
from telegram import Bot
from telegram._utils.types import JSONDict
class Document(_BaseThumbedMedium):
@@ -43,8 +39,6 @@ class Document(_BaseThumbedMedium):
file_name (:obj:`str`, optional): Original filename as defined by sender.
mime_type (:obj:`str`, optional): MIME type of the file as defined by sender.
file_size (:obj:`int`, optional): File size in bytes.
bot (:class:`telegram.Bot`, optional): The Bot to use for instance methods.
**kwargs (:obj:`dict`): Arbitrary keyword arguments.
Attributes:
file_id (:obj:`str`): File identifier.
@@ -55,7 +49,7 @@ class Document(_BaseThumbedMedium):
file_name (:obj:`str`): Original filename.
mime_type (:obj:`str`): Optional. MIME type of the file.
file_size (:obj:`int`): Optional. File size in bytes.
bot (:class:`telegram.Bot`): Optional. The Bot to use for instance methods.
"""
@@ -69,15 +63,15 @@ class Document(_BaseThumbedMedium):
file_name: str = None,
mime_type: str = None,
file_size: int = None,
bot: "Bot" = None,
**_kwargs: Any,
*,
api_kwargs: JSONDict = None,
):
super().__init__(
file_id=file_id,
file_unique_id=file_unique_id,
file_size=file_size,
thumb=thumb,
bot=bot,
api_kwargs=api_kwargs,
)
# Optional
self.mime_type = mime_type
+8 -8
View File
@@ -21,16 +21,16 @@ import shutil
import urllib.parse as urllib_parse
from base64 import b64decode
from pathlib import Path
from typing import IO, TYPE_CHECKING, Any, Optional, Union
from typing import IO, TYPE_CHECKING, Optional, Union
from telegram._passport.credentials import decrypt
from telegram._telegramobject import TelegramObject
from telegram._utils.defaultvalue import DEFAULT_NONE
from telegram._utils.files import is_local_file
from telegram._utils.types import FilePathInput, ODVInput
from telegram._utils.types import FilePathInput, JSONDict, ODVInput
if TYPE_CHECKING:
from telegram import Bot, FileCredentials
from telegram import FileCredentials
class File(TelegramObject):
@@ -56,8 +56,6 @@ class File(TelegramObject):
Can't be used to download or reuse the file.
file_size (:obj:`int`, optional): Optional. File size in bytes, if known.
file_path (:obj:`str`, optional): File path. Use :attr:`download` to get the file.
bot (:obj:`telegram.Bot`, optional): Bot to use with shortcut method.
**kwargs (:obj:`dict`): Arbitrary keyword arguments.
Attributes:
file_id (:obj:`str`): Identifier for this file.
@@ -81,18 +79,20 @@ class File(TelegramObject):
self,
file_id: str,
file_unique_id: str,
bot: "Bot" = None,
file_size: int = None,
file_path: str = None,
**_kwargs: Any,
*,
api_kwargs: JSONDict = None,
):
super().__init__(api_kwargs=api_kwargs)
# Required
self.file_id = str(file_id)
self.file_unique_id = str(file_unique_id)
# Optionals
self.file_size = file_size
self.file_path = file_path
self.set_bot(bot)
self._credentials: Optional["FileCredentials"] = None
self._id_attrs = (self.file_unique_id,)
+53 -5
View File
@@ -80,7 +80,10 @@ class InputMedia(TelegramObject):
caption: str = None,
caption_entities: Union[List[MessageEntity], Tuple[MessageEntity, ...]] = None,
parse_mode: ODVInput[str] = DEFAULT_NONE,
*,
api_kwargs: JSONDict = None,
):
super().__init__(api_kwargs=api_kwargs)
self.type = media_type
self.media = media
self.caption = caption
@@ -170,6 +173,8 @@ class InputMediaAnimation(InputMedia):
duration: int = None,
caption_entities: Union[List[MessageEntity], Tuple[MessageEntity, ...]] = None,
filename: str = None,
*,
api_kwargs: JSONDict = None,
):
if isinstance(media, Animation):
width = media.width if width is None else width
@@ -181,7 +186,14 @@ class InputMediaAnimation(InputMedia):
# things to work in local mode.
media = parse_file_input(media, filename=filename, attach=True, local_mode=True)
super().__init__(InputMediaType.ANIMATION, media, caption, caption_entities, parse_mode)
super().__init__(
InputMediaType.ANIMATION,
media,
caption,
caption_entities,
parse_mode,
api_kwargs=api_kwargs,
)
self.thumb = self._parse_thumb_input(thumb)
self.width = width
self.height = height
@@ -232,11 +244,20 @@ class InputMediaPhoto(InputMedia):
parse_mode: ODVInput[str] = DEFAULT_NONE,
caption_entities: Union[List[MessageEntity], Tuple[MessageEntity, ...]] = None,
filename: str = None,
*,
api_kwargs: JSONDict = None,
):
# We use local_mode=True because we don't have access to the actual setting and want
# things to work in local mode.
media = parse_file_input(media, PhotoSize, filename=filename, attach=True, local_mode=True)
super().__init__(InputMediaType.PHOTO, media, caption, caption_entities, parse_mode)
super().__init__(
InputMediaType.PHOTO,
media,
caption,
caption_entities,
parse_mode,
api_kwargs=api_kwargs,
)
class InputMediaVideo(InputMedia):
@@ -312,6 +333,8 @@ class InputMediaVideo(InputMedia):
thumb: FileInput = None,
caption_entities: Union[List[MessageEntity], Tuple[MessageEntity, ...]] = None,
filename: str = None,
*,
api_kwargs: JSONDict = None,
):
if isinstance(media, Video):
@@ -324,7 +347,14 @@ class InputMediaVideo(InputMedia):
# things to work in local mode.
media = parse_file_input(media, filename=filename, attach=True, local_mode=True)
super().__init__(InputMediaType.VIDEO, media, caption, caption_entities, parse_mode)
super().__init__(
InputMediaType.VIDEO,
media,
caption,
caption_entities,
parse_mode,
api_kwargs=api_kwargs,
)
self.width = width
self.height = height
self.duration = duration
@@ -399,6 +429,8 @@ class InputMediaAudio(InputMedia):
title: str = None,
caption_entities: Union[List[MessageEntity], Tuple[MessageEntity, ...]] = None,
filename: str = None,
*,
api_kwargs: JSONDict = None,
):
if isinstance(media, Audio):
duration = media.duration if duration is None else duration
@@ -410,7 +442,14 @@ class InputMediaAudio(InputMedia):
# things to work in local mode.
media = parse_file_input(media, filename=filename, attach=True, local_mode=True)
super().__init__(InputMediaType.AUDIO, media, caption, caption_entities, parse_mode)
super().__init__(
InputMediaType.AUDIO,
media,
caption,
caption_entities,
parse_mode,
api_kwargs=api_kwargs,
)
self.thumb = self._parse_thumb_input(thumb)
self.duration = duration
self.title = title
@@ -475,10 +514,19 @@ class InputMediaDocument(InputMedia):
disable_content_type_detection: bool = None,
caption_entities: Union[List[MessageEntity], Tuple[MessageEntity, ...]] = None,
filename: str = None,
*,
api_kwargs: JSONDict = None,
):
# We use local_mode=True because we don't have access to the actual setting and want
# things to work in local mode.
media = parse_file_input(media, Document, filename=filename, attach=True, local_mode=True)
super().__init__(InputMediaType.DOCUMENT, media, caption, caption_entities, parse_mode)
super().__init__(
InputMediaType.DOCUMENT,
media,
caption,
caption_entities,
parse_mode,
api_kwargs=api_kwargs,
)
self.thumb = self._parse_thumb_input(thumb)
self.disable_content_type_detection = disable_content_type_detection
+4 -4
View File
@@ -18,9 +18,8 @@
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents a Telegram Location."""
from typing import Any
from telegram._telegramobject import TelegramObject
from telegram._utils.types import JSONDict
class Location(TelegramObject):
@@ -40,7 +39,6 @@ class Location(TelegramObject):
1-:tg-const:`telegram.constants.LocationLimit.HEADING`. For active live locations only.
proximity_alert_radius (:obj:`int`, optional): Maximum distance for proximity alerts about
approaching another chat member, in meters. For sent live locations only.
**kwargs (:obj:`dict`): Arbitrary keyword arguments.
Attributes:
longitude (:obj:`float`): Longitude as defined by sender.
@@ -73,8 +71,10 @@ class Location(TelegramObject):
live_period: int = None,
heading: int = None,
proximity_alert_radius: int = None,
**_kwargs: Any,
*,
api_kwargs: JSONDict = None,
):
super().__init__(api_kwargs=api_kwargs)
# Required
self.longitude = longitude
self.latitude = latitude
+8 -11
View File
@@ -18,12 +18,8 @@
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents a Telegram PhotoSize."""
from typing import TYPE_CHECKING, Any
from telegram._files._basemedium import _BaseMedium
if TYPE_CHECKING:
from telegram import Bot
from telegram._utils.types import JSONDict
class PhotoSize(_BaseMedium):
@@ -41,8 +37,6 @@ class PhotoSize(_BaseMedium):
width (:obj:`int`): Photo width.
height (:obj:`int`): Photo height.
file_size (:obj:`int`, optional): File size in bytes.
bot (:class:`telegram.Bot`, optional): The Bot to use for instance methods.
**kwargs (:obj:`dict`): Arbitrary keyword arguments.
Attributes:
file_id (:obj:`str`): Identifier for this file.
@@ -52,7 +46,7 @@ class PhotoSize(_BaseMedium):
width (:obj:`int`): Photo width.
height (:obj:`int`): Photo height.
file_size (:obj:`int`): Optional. File size in bytes.
bot (:class:`telegram.Bot`): Optional. The Bot to use for instance methods.
"""
@@ -65,11 +59,14 @@ class PhotoSize(_BaseMedium):
width: int,
height: int,
file_size: int = None,
bot: "Bot" = None,
**_kwargs: Any,
*,
api_kwargs: JSONDict = None,
):
super().__init__(
file_id=file_id, file_unique_id=file_unique_id, file_size=file_size, bot=bot
file_id=file_id,
file_unique_id=file_unique_id,
file_size=file_size,
api_kwargs=api_kwargs,
)
# Required
self.width = width
+29 -23
View File
@@ -18,7 +18,7 @@
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains objects that represent stickers."""
from typing import TYPE_CHECKING, Any, ClassVar, List, Optional
from typing import TYPE_CHECKING, ClassVar, List, Optional
from telegram import constants
from telegram._files._basethumbedmedium import _BaseThumbedMedium
@@ -67,16 +67,15 @@ class Sticker(_BaseThumbedMedium):
mask_position (:class:`telegram.MaskPosition`, optional): For mask stickers, the
position where the mask should be placed.
file_size (:obj:`int`, optional): File size in bytes.
bot (:class:`telegram.Bot`, optional): The Bot to use for instance methods.
premium_animation (:class:`telegram.File`, optional): For premium regular stickers,
premium animation for the sticker.
.. versionadded:: 20.0
custom_emoji (:obj:`str`, optional): For custom emoji stickers, unique identifier of the
custom_emoji_id (:obj:`str`, optional): For custom emoji stickers, unique identifier of the
custom emoji.
.. versionadded:: 20.0
_kwargs (:obj:`dict`): Arbitrary keyword arguments.
Attributes:
file_id (:obj:`str`): Identifier for this file.
@@ -101,12 +100,12 @@ class Sticker(_BaseThumbedMedium):
mask_position (:class:`telegram.MaskPosition`): Optional. For mask stickers, the position
where the mask should be placed.
file_size (:obj:`int`): Optional. File size in bytes.
bot (:class:`telegram.Bot`): Optional. The Bot to use for instance methods.
premium_animation (:class:`telegram.File`): Optional. For premium regular stickers,
premium animation for the sticker.
.. versionadded:: 20.0
custom_emoji (:obj:`str`): Optional. For custom emoji stickers, unique identifier of the
custom_emoji_id (:obj:`str`): Optional. For custom emoji stickers, unique identifier of the
custom emoji.
.. versionadded:: 20.0
@@ -139,17 +138,17 @@ class Sticker(_BaseThumbedMedium):
file_size: int = None,
set_name: str = None,
mask_position: "MaskPosition" = None,
bot: "Bot" = None,
premium_animation: "File" = None,
custom_emoji_id: str = None,
**_kwargs: Any,
*,
api_kwargs: JSONDict = None,
):
super().__init__(
file_id=file_id,
file_unique_id=file_unique_id,
file_size=file_size,
thumb=thumb,
bot=bot,
api_kwargs=api_kwargs,
)
# Required
self.width = width
@@ -183,7 +182,7 @@ class Sticker(_BaseThumbedMedium):
data["mask_position"] = MaskPosition.de_json(data.get("mask_position"), bot)
data["premium_animation"] = File.de_json(data.get("premium_animation"), bot)
return cls(bot=bot, **data)
return super().de_json(data=data, bot=bot)
class StickerSet(TelegramObject):
@@ -251,8 +250,10 @@ class StickerSet(TelegramObject):
is_video: bool,
sticker_type: str,
thumb: PhotoSize = None,
**_kwargs: Any,
*,
api_kwargs: JSONDict = None,
):
super().__init__(api_kwargs=api_kwargs)
self.name = name
self.title = title
self.is_animated = is_animated
@@ -273,7 +274,13 @@ class StickerSet(TelegramObject):
data["thumb"] = PhotoSize.de_json(data.get("thumb"), bot)
data["stickers"] = Sticker.de_list(data.get("stickers"), bot)
return cls(bot=bot, **data)
api_kwargs = {}
# This is a deprecated field that TG still returns for backwards compatibility
# Let's filter it out to speed up the de-json process
if "contains_masks" in data:
api_kwargs["contains_masks"] = data.pop("contains_masks")
return super()._de_json(data=data, bot=bot, api_kwargs=api_kwargs)
def to_dict(self) -> JSONDict:
"""See :meth:`telegram.TelegramObject.to_dict`."""
@@ -324,20 +331,19 @@ class MaskPosition(TelegramObject):
CHIN: ClassVar[str] = constants.MaskPosition.CHIN
""":const:`telegram.constants.MaskPosition.CHIN`"""
def __init__(self, point: str, x_shift: float, y_shift: float, scale: float, **_kwargs: Any):
def __init__(
self,
point: str,
x_shift: float,
y_shift: float,
scale: float,
*,
api_kwargs: JSONDict = None,
):
super().__init__(api_kwargs=api_kwargs)
self.point = point
self.x_shift = x_shift
self.y_shift = y_shift
self.scale = scale
self._id_attrs = (self.point, self.x_shift, self.y_shift, self.scale)
@classmethod
def de_json(cls, data: Optional[JSONDict], bot: "Bot") -> Optional["MaskPosition"]:
"""See :meth:`telegram.TelegramObject.de_json`."""
data = cls._parse_data(data)
if data is None:
return None
return cls(**data)
+6 -4
View File
@@ -18,7 +18,7 @@
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents a Telegram Venue."""
from typing import TYPE_CHECKING, Any, Optional
from typing import TYPE_CHECKING, Optional
from telegram._files.location import Location
from telegram._telegramobject import TelegramObject
@@ -49,7 +49,6 @@ class Venue(TelegramObject):
google_place_type (:obj:`str`, optional): Google Places type of the venue. (See
`supported types <https://developers.google.com/maps/documentation/places/web-service\
/supported_types>`_.)
**kwargs (:obj:`dict`): Arbitrary keyword arguments.
Attributes:
location (:class:`telegram.Location`): Venue location.
@@ -81,8 +80,11 @@ class Venue(TelegramObject):
foursquare_type: str = None,
google_place_id: str = None,
google_place_type: str = None,
**_kwargs: Any,
*,
api_kwargs: JSONDict = None,
):
super().__init__(api_kwargs=api_kwargs)
# Required
self.location = location
self.title = title
@@ -105,4 +107,4 @@ class Venue(TelegramObject):
data["location"] = Location.de_json(data.get("location"), bot)
return cls(**data)
return super().de_json(data=data, bot=bot)
+5 -11
View File
@@ -18,13 +18,9 @@
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents a Telegram Video."""
from typing import TYPE_CHECKING, Any
from telegram._files._basethumbedmedium import _BaseThumbedMedium
from telegram._files.photosize import PhotoSize
if TYPE_CHECKING:
from telegram import Bot
from telegram._utils.types import JSONDict
class Video(_BaseThumbedMedium):
@@ -46,8 +42,6 @@ class Video(_BaseThumbedMedium):
file_name (:obj:`str`, optional): Original filename as defined by sender.
mime_type (:obj:`str`, optional): MIME type of a file as defined by sender.
file_size (:obj:`int`, optional): File size in bytes.
bot (:class:`telegram.Bot`, optional): The Bot to use for instance methods.
**kwargs (:obj:`dict`): Arbitrary keyword arguments.
Attributes:
file_id (:obj:`str`): Identifier for this file.
@@ -61,7 +55,7 @@ class Video(_BaseThumbedMedium):
file_name (:obj:`str`): Optional. Original filename as defined by sender.
mime_type (:obj:`str`): Optional. MIME type of a file as defined by sender.
file_size (:obj:`int`): Optional. File size in bytes.
bot (:class:`telegram.Bot`): Optional. The Bot to use for instance methods.
"""
@@ -77,16 +71,16 @@ class Video(_BaseThumbedMedium):
thumb: PhotoSize = None,
mime_type: str = None,
file_size: int = None,
bot: "Bot" = None,
file_name: str = None,
**_kwargs: Any,
*,
api_kwargs: JSONDict = None,
):
super().__init__(
file_id=file_id,
file_unique_id=file_unique_id,
file_size=file_size,
thumb=thumb,
bot=bot,
api_kwargs=api_kwargs,
)
# Required
self.width = width
+4 -11
View File
@@ -18,13 +18,9 @@
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents a Telegram VideoNote."""
from typing import TYPE_CHECKING, Any
from telegram._files._basethumbedmedium import _BaseThumbedMedium
from telegram._files.photosize import PhotoSize
if TYPE_CHECKING:
from telegram import Bot
from telegram._utils.types import JSONDict
class VideoNote(_BaseThumbedMedium):
@@ -44,8 +40,6 @@ class VideoNote(_BaseThumbedMedium):
duration (:obj:`int`): Duration of the video in seconds as defined by sender.
thumb (:class:`telegram.PhotoSize`, optional): Video thumbnail.
file_size (:obj:`int`, optional): File size in bytes.
bot (:class:`telegram.Bot`, optional): The Bot to use for instance methods.
**kwargs (:obj:`dict`): Arbitrary keyword arguments.
Attributes:
file_id (:obj:`str`): Identifier for this file.
@@ -56,7 +50,6 @@ class VideoNote(_BaseThumbedMedium):
duration (:obj:`int`): Duration of the video in seconds as defined by sender.
thumb (:class:`telegram.PhotoSize`): Optional. Video thumbnail.
file_size (:obj:`int`): Optional. File size in bytes.
bot (:class:`telegram.Bot`): Optional. The Bot to use for instance methods.
"""
@@ -70,15 +63,15 @@ class VideoNote(_BaseThumbedMedium):
duration: int,
thumb: PhotoSize = None,
file_size: int = None,
bot: "Bot" = None,
**_kwargs: Any,
*,
api_kwargs: JSONDict = None,
):
super().__init__(
file_id=file_id,
file_unique_id=file_unique_id,
file_size=file_size,
thumb=thumb,
bot=bot,
api_kwargs=api_kwargs,
)
# Required
self.length = length
+4 -11
View File
@@ -18,12 +18,8 @@
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents a Telegram Voice."""
from typing import TYPE_CHECKING, Any
from telegram._files._basemedium import _BaseMedium
if TYPE_CHECKING:
from telegram import Bot
from telegram._utils.types import JSONDict
class Voice(_BaseMedium):
@@ -41,8 +37,6 @@ class Voice(_BaseMedium):
duration (:obj:`int`, optional): Duration of the audio in seconds as defined by sender.
mime_type (:obj:`str`, optional): MIME type of the file as defined by sender.
file_size (:obj:`int`, optional): File size in bytes.
bot (:class:`telegram.Bot`, optional): The Bot to use for instance methods.
**kwargs (:obj:`dict`): Arbitrary keyword arguments.
Attributes:
file_id (:obj:`str`): Identifier for this file.
@@ -52,7 +46,6 @@ class Voice(_BaseMedium):
duration (:obj:`int`): Duration of the audio in seconds as defined by sender.
mime_type (:obj:`str`): Optional. MIME type of the file as defined by sender.
file_size (:obj:`int`): Optional. File size in bytes.
bot (:class:`telegram.Bot`): Optional. The Bot to use for instance methods.
"""
@@ -65,14 +58,14 @@ class Voice(_BaseMedium):
duration: int,
mime_type: str = None,
file_size: int = None,
bot: "Bot" = None,
**_kwargs: Any,
*,
api_kwargs: JSONDict = None,
):
super().__init__(
file_id=file_id,
file_unique_id=file_unique_id,
file_size=file_size,
bot=bot,
api_kwargs=api_kwargs,
)
# Required
self.duration = duration
+4 -5
View File
@@ -18,9 +18,8 @@
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents a Telegram ForceReply."""
from typing import Any
from telegram._telegramobject import TelegramObject
from telegram._utils.types import JSONDict
class ForceReply(TelegramObject):
@@ -51,8 +50,6 @@ class ForceReply(TelegramObject):
.. versionadded:: 13.7
**kwargs (:obj:`dict`): Arbitrary keyword arguments.
Attributes:
force_reply (:obj:`True`): Shows reply interface to the user, as if they manually selected
the bots message and tapped 'Reply'.
@@ -70,8 +67,10 @@ class ForceReply(TelegramObject):
self,
selective: bool = None,
input_field_placeholder: str = None,
**_kwargs: Any,
*,
api_kwargs: JSONDict = None,
):
super().__init__(api_kwargs=api_kwargs)
self.force_reply = True
self.selective = selective
self.input_field_placeholder = input_field_placeholder
+5 -3
View File
@@ -19,7 +19,7 @@
"""This module contains an object that represents a Telegram Game."""
import sys
from typing import TYPE_CHECKING, Any, Dict, List, Optional
from typing import TYPE_CHECKING, Dict, List, Optional
from telegram._files.animation import Animation
from telegram._files.photosize import PhotoSize
@@ -88,8 +88,10 @@ class Game(TelegramObject):
text: str = None,
text_entities: List[MessageEntity] = None,
animation: Animation = None,
**_kwargs: Any,
*,
api_kwargs: JSONDict = None,
):
super().__init__(api_kwargs=api_kwargs)
# Required
self.title = title
self.description = description
@@ -113,7 +115,7 @@ class Game(TelegramObject):
data["text_entities"] = MessageEntity.de_list(data.get("text_entities"), bot)
data["animation"] = Animation.de_json(data.get("animation"), bot)
return cls(**data)
return super().de_json(data=data, bot=bot)
def to_dict(self) -> JSONDict:
"""See :meth:`telegram.TelegramObject.to_dict`."""
+3 -2
View File
@@ -48,7 +48,8 @@ class GameHighScore(TelegramObject):
__slots__ = ("position", "user", "score")
def __init__(self, position: int, user: User, score: int):
def __init__(self, position: int, user: User, score: int, *, api_kwargs: JSONDict = None):
super().__init__(api_kwargs=api_kwargs)
self.position = position
self.user = user
self.score = score
@@ -65,4 +66,4 @@ class GameHighScore(TelegramObject):
data["user"] = User.de_json(data.get("user"), bot)
return cls(**data)
return super().de_json(data=data, bot=bot)
+5 -4
View File
@@ -18,7 +18,7 @@
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents a Telegram InlineKeyboardButton."""
from typing import TYPE_CHECKING, Any, Optional, Union
from typing import TYPE_CHECKING, Optional, Union
from telegram._games.callbackgame import CallbackGame
from telegram._loginurl import LoginUrl
@@ -115,7 +115,6 @@ class InlineKeyboardButton(TelegramObject):
pay (:obj:`bool`, optional): Specify :obj:`True`, to send a Pay button. This type of button
must always be the `first` button in the first row and can only be used in invoice
messages.
**kwargs (:obj:`dict`): Arbitrary keyword arguments.
Attributes:
text (:obj:`str`): Label text on the button.
@@ -174,8 +173,10 @@ class InlineKeyboardButton(TelegramObject):
pay: bool = None,
login_url: LoginUrl = None,
web_app: WebAppInfo = None,
**_kwargs: Any,
*,
api_kwargs: JSONDict = None,
):
super().__init__(api_kwargs=api_kwargs)
# Required
self.text = text
@@ -216,7 +217,7 @@ class InlineKeyboardButton(TelegramObject):
data["web_app"] = WebAppInfo.de_json(data.get("web_app"), bot)
data["callback_game"] = CallbackGame.de_json(data.get("callback_game"), bot)
return cls(**data)
return super().de_json(data=data, bot=bot)
def update_callback_data(self, callback_data: Union[str, object]) -> None:
"""
+11 -11
View File
@@ -18,7 +18,7 @@
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents a Telegram InlineKeyboardMarkup."""
from typing import TYPE_CHECKING, Any, List, Optional
from typing import TYPE_CHECKING, List, Optional
from telegram._inline.inlinekeyboardbutton import InlineKeyboardButton
from telegram._telegramobject import TelegramObject
@@ -42,7 +42,6 @@ class InlineKeyboardMarkup(TelegramObject):
Args:
inline_keyboard (List[List[:class:`telegram.InlineKeyboardButton`]]): List of button rows,
each represented by a list of InlineKeyboardButton objects.
**kwargs (:obj:`dict`): Arbitrary keyword arguments.
Attributes:
inline_keyboard (List[List[:class:`telegram.InlineKeyboardButton`]]): List of button rows,
@@ -52,7 +51,13 @@ class InlineKeyboardMarkup(TelegramObject):
__slots__ = ("inline_keyboard",)
def __init__(self, inline_keyboard: List[List[InlineKeyboardButton]], **_kwargs: Any):
def __init__(
self,
inline_keyboard: List[List[InlineKeyboardButton]],
*,
api_kwargs: JSONDict = None,
):
super().__init__(api_kwargs=api_kwargs)
if not check_keyboard_type(inline_keyboard):
raise ValueError(
"The parameter `inline_keyboard` should be a list of "
@@ -76,8 +81,6 @@ class InlineKeyboardMarkup(TelegramObject):
@classmethod
def de_json(cls, data: Optional[JSONDict], bot: "Bot") -> Optional["InlineKeyboardMarkup"]:
"""See :meth:`telegram.TelegramObject.de_json`."""
data = cls._parse_data(data)
if not data:
return None
@@ -102,10 +105,9 @@ class InlineKeyboardMarkup(TelegramObject):
Args:
button (:class:`telegram.InlineKeyboardButton`): The button to use in the markup
**kwargs (:obj:`dict`): Arbitrary keyword arguments.
"""
return cls([[button]], **kwargs)
return cls([[button]], **kwargs) # type: ignore[arg-type]
@classmethod
def from_row(
@@ -120,10 +122,9 @@ class InlineKeyboardMarkup(TelegramObject):
Args:
button_row (List[:class:`telegram.InlineKeyboardButton`]): The button to use in the
markup
**kwargs (:obj:`dict`): Arbitrary keyword arguments.
"""
return cls([button_row], **kwargs)
return cls([button_row], **kwargs) # type: ignore[arg-type]
@classmethod
def from_column(
@@ -138,11 +139,10 @@ class InlineKeyboardMarkup(TelegramObject):
Args:
button_column (List[:class:`telegram.InlineKeyboardButton`]): The button to use in the
markup
**kwargs (:obj:`dict`): Arbitrary keyword arguments.
"""
button_grid = [[button] for button in button_column]
return cls(button_grid, **kwargs)
return cls(button_grid, **kwargs) # type: ignore[arg-type]
def __hash__(self) -> int:
return hash(tuple(tuple(button for button in row) for row in self.inline_keyboard))
+11 -14
View File
@@ -19,7 +19,7 @@
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents a Telegram InlineQuery."""
from typing import TYPE_CHECKING, Any, Callable, ClassVar, Optional, Sequence, Union
from typing import TYPE_CHECKING, Callable, ClassVar, Optional, Sequence, Union
from telegram import constants
from telegram._files.location import Location
@@ -44,11 +44,10 @@ class InlineQuery(TelegramObject):
In Python :keyword:`from` is a reserved word use :paramref:`from_user` instead.
.. versionchanged:: 20.0
* The following are now keyword-only arguments in Bot methods:
``{read, write, connect, pool}_timeout``, :paramref:`answer.api_kwargs`,
``auto_pagination``. Use a named argument for those,
and notice that some positional arguments changed position as a result.
The following are now keyword-only arguments in Bot methods:
``{read, write, connect, pool}_timeout``, :paramref:`answer.api_kwargs`,
``auto_pagination``. Use a named argument for those,
and notice that some positional arguments changed position as a result.
Args:
id (:obj:`str`): Unique identifier for this query.
@@ -65,8 +64,6 @@ class InlineQuery(TelegramObject):
.. versionadded:: 13.5
location (:class:`telegram.Location`, optional): Sender location, only for bots that
request user location.
bot (:class:`telegram.Bot`, optional): The Bot to use for instance methods.
**kwargs (:obj:`dict`): Arbitrary keyword arguments.
Attributes:
id (:obj:`str`): Unique identifier for this query.
@@ -85,15 +82,16 @@ class InlineQuery(TelegramObject):
def __init__(
self,
id: str, # pylint: disable=redefined-builtin, invalid-name
id: str, # pylint: disable=redefined-builtin
from_user: User,
query: str,
offset: str,
location: Location = None,
bot: "Bot" = None,
chat_type: str = None,
**_kwargs: Any,
*,
api_kwargs: JSONDict = None,
):
super().__init__(api_kwargs=api_kwargs)
# Required
self.id = id # pylint: disable=invalid-name
self.from_user = from_user
@@ -104,7 +102,6 @@ class InlineQuery(TelegramObject):
self.location = location
self.chat_type = chat_type
self.set_bot(bot)
self._id_attrs = (self.id,)
@classmethod
@@ -115,10 +112,10 @@ class InlineQuery(TelegramObject):
if not data:
return None
data["from_user"] = User.de_json(data.get("from"), bot)
data["from_user"] = User.de_json(data.pop("from", None), bot)
data["location"] = Location.de_json(data.get("location"), bot)
return cls(bot=bot, **data)
return super().de_json(data=data, bot=bot)
async def answer(
self,
+3 -4
View File
@@ -19,8 +19,6 @@
# pylint: disable=redefined-builtin
"""This module contains the classes that represent Telegram InlineQueryResult."""
from typing import Any
from telegram._telegramobject import TelegramObject
from telegram._utils.types import JSONDict
@@ -38,7 +36,6 @@ class InlineQueryResult(TelegramObject):
Args:
type (:obj:`str`): Type of the result.
id (:obj:`str`): Unique identifier for this result, 1-64 Bytes.
**kwargs (:obj:`dict`): Arbitrary keyword arguments.
Attributes:
type (:obj:`str`): Type of the result.
@@ -48,7 +45,9 @@ class InlineQueryResult(TelegramObject):
__slots__ = ("type", "id")
def __init__(self, type: str, id: str, **_kwargs: Any): # pylint: disable=invalid-name
def __init__(self, type: str, id: str, *, api_kwargs: JSONDict = None):
super().__init__(api_kwargs=api_kwargs)
# Required
self.type = type
self.id = str(id) # pylint: disable=invalid-name
+5 -4
View File
@@ -18,10 +18,11 @@
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains the classes that represent Telegram InlineQueryResultArticle."""
from typing import TYPE_CHECKING, Any
from typing import TYPE_CHECKING
from telegram._inline.inlinekeyboardmarkup import InlineKeyboardMarkup
from telegram._inline.inlinequeryresult import InlineQueryResult
from telegram._utils.types import JSONDict
from telegram.constants import InlineQueryResultType
if TYPE_CHECKING:
@@ -47,7 +48,6 @@ class InlineQueryResultArticle(InlineQueryResult):
thumb_url (:obj:`str`, optional): Url of the thumbnail for the result.
thumb_width (:obj:`int`, optional): Thumbnail width.
thumb_height (:obj:`int`, optional): Thumbnail height.
**kwargs (:obj:`dict`): Arbitrary keyword arguments.
Attributes:
type (:obj:`str`): :tg-const:`telegram.constants.InlineQueryResultType.ARTICLE`.
@@ -91,11 +91,12 @@ class InlineQueryResultArticle(InlineQueryResult):
thumb_url: str = None,
thumb_width: int = None,
thumb_height: int = None,
**_kwargs: Any,
*,
api_kwargs: JSONDict = None,
):
# Required
super().__init__(InlineQueryResultType.ARTICLE, id)
super().__init__(InlineQueryResultType.ARTICLE, id, api_kwargs=api_kwargs)
self.title = title
self.input_message_content = input_message_content
+5 -5
View File
@@ -18,13 +18,13 @@
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains the classes that represent Telegram InlineQueryResultAudio."""
from typing import TYPE_CHECKING, Any, List, Tuple, Union
from typing import TYPE_CHECKING, List, Tuple, Union
from telegram._inline.inlinekeyboardmarkup import InlineKeyboardMarkup
from telegram._inline.inlinequeryresult import InlineQueryResult
from telegram._messageentity import MessageEntity
from telegram._utils.defaultvalue import DEFAULT_NONE
from telegram._utils.types import ODVInput
from telegram._utils.types import JSONDict, ODVInput
from telegram.constants import InlineQueryResultType
if TYPE_CHECKING:
@@ -56,7 +56,6 @@ class InlineQueryResultAudio(InlineQueryResult):
to the message.
input_message_content (:class:`telegram.InputMessageContent`, optional): Content of the
message to be sent instead of the audio.
**kwargs (:obj:`dict`): Arbitrary keyword arguments.
Attributes:
type (:obj:`str`): :tg-const:`telegram.constants.InlineQueryResultType.AUDIO`.
@@ -105,11 +104,12 @@ class InlineQueryResultAudio(InlineQueryResult):
input_message_content: "InputMessageContent" = None,
parse_mode: ODVInput[str] = DEFAULT_NONE,
caption_entities: Union[Tuple[MessageEntity, ...], List[MessageEntity]] = None,
**_kwargs: Any,
*,
api_kwargs: JSONDict = None,
):
# Required
super().__init__(InlineQueryResultType.AUDIO, id)
super().__init__(InlineQueryResultType.AUDIO, id, api_kwargs=api_kwargs)
self.audio_url = audio_url
self.title = title
@@ -18,13 +18,13 @@
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains the classes that represent Telegram InlineQueryResultCachedAudio."""
from typing import TYPE_CHECKING, Any, List, Tuple, Union
from typing import TYPE_CHECKING, List, Tuple, Union
from telegram._inline.inlinekeyboardmarkup import InlineKeyboardMarkup
from telegram._inline.inlinequeryresult import InlineQueryResult
from telegram._messageentity import MessageEntity
from telegram._utils.defaultvalue import DEFAULT_NONE
from telegram._utils.types import ODVInput
from telegram._utils.types import JSONDict, ODVInput
from telegram.constants import InlineQueryResultType
if TYPE_CHECKING:
@@ -53,7 +53,6 @@ class InlineQueryResultCachedAudio(InlineQueryResult):
to the message.
input_message_content (:class:`telegram.InputMessageContent`, optional): Content of the
message to be sent instead of the audio.
**kwargs (:obj:`dict`): Arbitrary keyword arguments.
Attributes:
type (:obj:`str`): :tg-const:`telegram.constants.InlineQueryResultType.AUDIO`.
@@ -93,10 +92,11 @@ class InlineQueryResultCachedAudio(InlineQueryResult):
input_message_content: "InputMessageContent" = None,
parse_mode: ODVInput[str] = DEFAULT_NONE,
caption_entities: Union[Tuple[MessageEntity, ...], List[MessageEntity]] = None,
**_kwargs: Any,
*,
api_kwargs: JSONDict = None,
):
# Required
super().__init__(InlineQueryResultType.AUDIO, id)
super().__init__(InlineQueryResultType.AUDIO, id, api_kwargs=api_kwargs)
self.audio_file_id = audio_file_id
# Optionals
@@ -18,13 +18,13 @@
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains the classes that represent Telegram InlineQueryResultCachedDocument."""
from typing import TYPE_CHECKING, Any, List, Tuple, Union
from typing import TYPE_CHECKING, List, Tuple, Union
from telegram._inline.inlinekeyboardmarkup import InlineKeyboardMarkup
from telegram._inline.inlinequeryresult import InlineQueryResult
from telegram._messageentity import MessageEntity
from telegram._utils.defaultvalue import DEFAULT_NONE
from telegram._utils.types import ODVInput
from telegram._utils.types import JSONDict, ODVInput
from telegram.constants import InlineQueryResultType
if TYPE_CHECKING:
@@ -55,7 +55,6 @@ class InlineQueryResultCachedDocument(InlineQueryResult):
to the message.
input_message_content (:class:`telegram.InputMessageContent`, optional): Content of the
message to be sent instead of the file.
**kwargs (:obj:`dict`): Arbitrary keyword arguments.
Attributes:
type (:obj:`str`): :tg-const:`telegram.constants.InlineQueryResultType.DOCUMENT`.
@@ -101,10 +100,11 @@ class InlineQueryResultCachedDocument(InlineQueryResult):
input_message_content: "InputMessageContent" = None,
parse_mode: ODVInput[str] = DEFAULT_NONE,
caption_entities: Union[Tuple[MessageEntity, ...], List[MessageEntity]] = None,
**_kwargs: Any,
*,
api_kwargs: JSONDict = None,
):
# Required
super().__init__(InlineQueryResultType.DOCUMENT, id)
super().__init__(InlineQueryResultType.DOCUMENT, id, api_kwargs=api_kwargs)
self.title = title
self.document_file_id = document_file_id
@@ -18,13 +18,13 @@
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains the classes that represent Telegram InlineQueryResultCachedGif."""
from typing import TYPE_CHECKING, Any, List, Tuple, Union
from typing import TYPE_CHECKING, List, Tuple, Union
from telegram._inline.inlinekeyboardmarkup import InlineKeyboardMarkup
from telegram._inline.inlinequeryresult import InlineQueryResult
from telegram._messageentity import MessageEntity
from telegram._utils.defaultvalue import DEFAULT_NONE
from telegram._utils.types import ODVInput
from telegram._utils.types import JSONDict, ODVInput
from telegram.constants import InlineQueryResultType
if TYPE_CHECKING:
@@ -55,7 +55,6 @@ class InlineQueryResultCachedGif(InlineQueryResult):
to the message.
input_message_content (:class:`telegram.InputMessageContent`, optional): Content of the
message to be sent instead of the gif.
**kwargs (:obj:`dict`): Arbitrary keyword arguments.
Attributes:
type (:obj:`str`): :tg-const:`telegram.constants.InlineQueryResultType.GIF`.
@@ -98,10 +97,11 @@ class InlineQueryResultCachedGif(InlineQueryResult):
input_message_content: "InputMessageContent" = None,
parse_mode: ODVInput[str] = DEFAULT_NONE,
caption_entities: Union[Tuple[MessageEntity, ...], List[MessageEntity]] = None,
**_kwargs: Any,
*,
api_kwargs: JSONDict = None,
):
# Required
super().__init__(InlineQueryResultType.GIF, id)
super().__init__(InlineQueryResultType.GIF, id, api_kwargs=api_kwargs)
self.gif_file_id = gif_file_id
# Optionals
@@ -18,13 +18,13 @@
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains the classes that represent Telegram InlineQueryResultMpeg4Gif."""
from typing import TYPE_CHECKING, Any, List, Tuple, Union
from typing import TYPE_CHECKING, List, Tuple, Union
from telegram._inline.inlinekeyboardmarkup import InlineKeyboardMarkup
from telegram._inline.inlinequeryresult import InlineQueryResult
from telegram._messageentity import MessageEntity
from telegram._utils.defaultvalue import DEFAULT_NONE
from telegram._utils.types import ODVInput
from telegram._utils.types import JSONDict, ODVInput
from telegram.constants import InlineQueryResultType
if TYPE_CHECKING:
@@ -55,7 +55,6 @@ class InlineQueryResultCachedMpeg4Gif(InlineQueryResult):
to the message.
input_message_content (:class:`telegram.InputMessageContent`, optional): Content of the
message to be sent instead of the MPEG-4 file.
**kwargs (:obj:`dict`): Arbitrary keyword arguments.
Attributes:
type (:obj:`str`): :tg-const:`telegram.constants.InlineQueryResultType.MPEG4GIF`.
@@ -98,10 +97,11 @@ class InlineQueryResultCachedMpeg4Gif(InlineQueryResult):
input_message_content: "InputMessageContent" = None,
parse_mode: ODVInput[str] = DEFAULT_NONE,
caption_entities: Union[Tuple[MessageEntity, ...], List[MessageEntity]] = None,
**_kwargs: Any,
*,
api_kwargs: JSONDict = None,
):
# Required
super().__init__(InlineQueryResultType.MPEG4GIF, id)
super().__init__(InlineQueryResultType.MPEG4GIF, id, api_kwargs=api_kwargs)
self.mpeg4_file_id = mpeg4_file_id
# Optionals
@@ -18,13 +18,13 @@
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains the classes that represent Telegram InlineQueryResultPhoto"""
from typing import TYPE_CHECKING, Any, List, Tuple, Union
from typing import TYPE_CHECKING, List, Tuple, Union
from telegram._inline.inlinekeyboardmarkup import InlineKeyboardMarkup
from telegram._inline.inlinequeryresult import InlineQueryResult
from telegram._messageentity import MessageEntity
from telegram._utils.defaultvalue import DEFAULT_NONE
from telegram._utils.types import ODVInput
from telegram._utils.types import JSONDict, ODVInput
from telegram.constants import InlineQueryResultType
if TYPE_CHECKING:
@@ -56,7 +56,6 @@ class InlineQueryResultCachedPhoto(InlineQueryResult):
to the message.
input_message_content (:class:`telegram.InputMessageContent`, optional): Content of the
message to be sent instead of the photo.
**kwargs (:obj:`dict`): Arbitrary keyword arguments.
Attributes:
type (:obj:`str`): :tg-const:`telegram.constants.InlineQueryResultType.PHOTO`.
@@ -102,10 +101,11 @@ class InlineQueryResultCachedPhoto(InlineQueryResult):
input_message_content: "InputMessageContent" = None,
parse_mode: ODVInput[str] = DEFAULT_NONE,
caption_entities: Union[Tuple[MessageEntity, ...], List[MessageEntity]] = None,
**_kwargs: Any,
*,
api_kwargs: JSONDict = None,
):
# Required
super().__init__(InlineQueryResultType.PHOTO, id)
super().__init__(InlineQueryResultType.PHOTO, id, api_kwargs=api_kwargs)
self.photo_file_id = photo_file_id
# Optionals
@@ -18,10 +18,11 @@
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains the classes that represent Telegram InlineQueryResultCachedSticker."""
from typing import TYPE_CHECKING, Any
from typing import TYPE_CHECKING
from telegram._inline.inlinekeyboardmarkup import InlineKeyboardMarkup
from telegram._inline.inlinequeryresult import InlineQueryResult
from telegram._utils.types import JSONDict
from telegram.constants import InlineQueryResultType
if TYPE_CHECKING:
@@ -41,7 +42,6 @@ class InlineQueryResultCachedSticker(InlineQueryResult):
to the message.
input_message_content (:class:`telegram.InputMessageContent`, optional): Content of the
message to be sent instead of the sticker.
**kwargs (:obj:`dict`): Arbitrary keyword arguments.
Attributes:
type (:obj:`str`): :tg-const:`telegram.constants.InlineQueryResultType.STICKER`.
@@ -62,10 +62,11 @@ class InlineQueryResultCachedSticker(InlineQueryResult):
sticker_file_id: str,
reply_markup: InlineKeyboardMarkup = None,
input_message_content: "InputMessageContent" = None,
**_kwargs: Any,
*,
api_kwargs: JSONDict = None,
):
# Required
super().__init__(InlineQueryResultType.STICKER, id)
super().__init__(InlineQueryResultType.STICKER, id, api_kwargs=api_kwargs)
self.sticker_file_id = sticker_file_id
# Optionals
@@ -18,13 +18,13 @@
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains the classes that represent Telegram InlineQueryResultCachedVideo."""
from typing import TYPE_CHECKING, Any, List, Tuple, Union
from typing import TYPE_CHECKING, List, Tuple, Union
from telegram._inline.inlinekeyboardmarkup import InlineKeyboardMarkup
from telegram._inline.inlinequeryresult import InlineQueryResult
from telegram._messageentity import MessageEntity
from telegram._utils.defaultvalue import DEFAULT_NONE
from telegram._utils.types import ODVInput
from telegram._utils.types import JSONDict, ODVInput
from telegram.constants import InlineQueryResultType
if TYPE_CHECKING:
@@ -56,7 +56,6 @@ class InlineQueryResultCachedVideo(InlineQueryResult):
to the message.
input_message_content (:class:`telegram.InputMessageContent`, optional): Content of the
message to be sent instead of the video.
**kwargs (:obj:`dict`): Arbitrary keyword arguments.
Attributes:
type (:obj:`str`): :tg-const:`telegram.constants.InlineQueryResultType.VIDEO`.
@@ -102,10 +101,11 @@ class InlineQueryResultCachedVideo(InlineQueryResult):
input_message_content: "InputMessageContent" = None,
parse_mode: ODVInput[str] = DEFAULT_NONE,
caption_entities: Union[Tuple[MessageEntity, ...], List[MessageEntity]] = None,
**_kwargs: Any,
*,
api_kwargs: JSONDict = None,
):
# Required
super().__init__(InlineQueryResultType.VIDEO, id)
super().__init__(InlineQueryResultType.VIDEO, id, api_kwargs=api_kwargs)
self.video_file_id = video_file_id
self.title = title
@@ -18,13 +18,13 @@
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains the classes that represent Telegram InlineQueryResultCachedVoice."""
from typing import TYPE_CHECKING, Any, List, Tuple, Union
from typing import TYPE_CHECKING, List, Tuple, Union
from telegram._inline.inlinekeyboardmarkup import InlineKeyboardMarkup
from telegram._inline.inlinequeryresult import InlineQueryResult
from telegram._messageentity import MessageEntity
from telegram._utils.defaultvalue import DEFAULT_NONE
from telegram._utils.types import ODVInput
from telegram._utils.types import JSONDict, ODVInput
from telegram.constants import InlineQueryResultType
if TYPE_CHECKING:
@@ -54,7 +54,6 @@ class InlineQueryResultCachedVoice(InlineQueryResult):
to the message.
input_message_content (:class:`telegram.InputMessageContent`, optional): Content of the
message to be sent instead of the voice message.
**kwargs (:obj:`dict`): Arbitrary keyword arguments.
Attributes:
type (:obj:`str`): :tg-const:`telegram.constants.InlineQueryResultType.VOICE`.
@@ -97,10 +96,11 @@ class InlineQueryResultCachedVoice(InlineQueryResult):
input_message_content: "InputMessageContent" = None,
parse_mode: ODVInput[str] = DEFAULT_NONE,
caption_entities: Union[Tuple[MessageEntity, ...], List[MessageEntity]] = None,
**_kwargs: Any,
*,
api_kwargs: JSONDict = None,
):
# Required
super().__init__(InlineQueryResultType.VOICE, id)
super().__init__(InlineQueryResultType.VOICE, id, api_kwargs=api_kwargs)
self.voice_file_id = voice_file_id
self.title = title
+5 -4
View File
@@ -18,10 +18,11 @@
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains the classes that represent Telegram InlineQueryResultContact."""
from typing import TYPE_CHECKING, Any
from typing import TYPE_CHECKING
from telegram._inline.inlinekeyboardmarkup import InlineKeyboardMarkup
from telegram._inline.inlinequeryresult import InlineQueryResult
from telegram._utils.types import JSONDict
from telegram.constants import InlineQueryResultType
if TYPE_CHECKING:
@@ -48,7 +49,6 @@ class InlineQueryResultContact(InlineQueryResult):
thumb_url (:obj:`str`, optional): Url of the thumbnail for the result.
thumb_width (:obj:`int`, optional): Thumbnail width.
thumb_height (:obj:`int`, optional): Thumbnail height.
**kwargs (:obj:`dict`): Arbitrary keyword arguments.
Attributes:
type (:obj:`str`): :tg-const:`telegram.constants.InlineQueryResultType.CONTACT`.
@@ -92,10 +92,11 @@ class InlineQueryResultContact(InlineQueryResult):
thumb_width: int = None,
thumb_height: int = None,
vcard: str = None,
**_kwargs: Any,
*,
api_kwargs: JSONDict = None,
):
# Required
super().__init__(InlineQueryResultType.CONTACT, id)
super().__init__(InlineQueryResultType.CONTACT, id, api_kwargs=api_kwargs)
self.phone_number = phone_number
self.first_name = first_name
@@ -18,13 +18,13 @@
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains the classes that represent Telegram InlineQueryResultDocument"""
from typing import TYPE_CHECKING, Any, List, Tuple, Union
from typing import TYPE_CHECKING, List, Tuple, Union
from telegram._inline.inlinekeyboardmarkup import InlineKeyboardMarkup
from telegram._inline.inlinequeryresult import InlineQueryResult
from telegram._messageentity import MessageEntity
from telegram._utils.defaultvalue import DEFAULT_NONE
from telegram._utils.types import ODVInput
from telegram._utils.types import JSONDict, ODVInput
from telegram.constants import InlineQueryResultType
if TYPE_CHECKING:
@@ -61,7 +61,6 @@ class InlineQueryResultDocument(InlineQueryResult):
thumb_url (:obj:`str`, optional): URL of the thumbnail (JPEG only) for the file.
thumb_width (:obj:`int`, optional): Thumbnail width.
thumb_height (:obj:`int`, optional): Thumbnail height.
**kwargs (:obj:`dict`): Arbitrary keyword arguments.
Attributes:
type (:obj:`str`): :tg-const:`telegram.constants.InlineQueryResultType.DOCUMENT`.
@@ -120,10 +119,11 @@ class InlineQueryResultDocument(InlineQueryResult):
thumb_height: int = None,
parse_mode: ODVInput[str] = DEFAULT_NONE,
caption_entities: Union[Tuple[MessageEntity, ...], List[MessageEntity]] = None,
**_kwargs: Any,
*,
api_kwargs: JSONDict = None,
):
# Required
super().__init__(InlineQueryResultType.DOCUMENT, id)
super().__init__(InlineQueryResultType.DOCUMENT, id, api_kwargs=api_kwargs)
self.document_url = document_url
self.title = title
self.mime_type = mime_type
+4 -5
View File
@@ -18,10 +18,9 @@
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains the classes that represent Telegram InlineQueryResultGame."""
from typing import Any
from telegram._inline.inlinekeyboardmarkup import InlineKeyboardMarkup
from telegram._inline.inlinequeryresult import InlineQueryResult
from telegram._utils.types import JSONDict
from telegram.constants import InlineQueryResultType
@@ -33,7 +32,6 @@ class InlineQueryResultGame(InlineQueryResult):
game_short_name (:obj:`str`): Short name of the game.
reply_markup (:class:`telegram.InlineKeyboardMarkup`, optional): Inline keyboard attached
to the message.
**kwargs (:obj:`dict`): Arbitrary keyword arguments.
Attributes:
type (:obj:`str`): :tg-const:`telegram.constants.InlineQueryResultType.GAME`.
@@ -51,10 +49,11 @@ class InlineQueryResultGame(InlineQueryResult):
id: str, # pylint: disable=redefined-builtin
game_short_name: str,
reply_markup: InlineKeyboardMarkup = None,
**_kwargs: Any,
*,
api_kwargs: JSONDict = None,
):
# Required
super().__init__(InlineQueryResultType.GAME, id)
super().__init__(InlineQueryResultType.GAME, id, api_kwargs=api_kwargs)
self.id = id
self.game_short_name = game_short_name
+5 -5
View File
@@ -18,13 +18,13 @@
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains the classes that represent Telegram InlineQueryResultGif."""
from typing import TYPE_CHECKING, Any, List, Tuple, Union
from typing import TYPE_CHECKING, List, Tuple, Union
from telegram._inline.inlinekeyboardmarkup import InlineKeyboardMarkup
from telegram._inline.inlinequeryresult import InlineQueryResult
from telegram._messageentity import MessageEntity
from telegram._utils.defaultvalue import DEFAULT_NONE
from telegram._utils.types import ODVInput
from telegram._utils.types import JSONDict, ODVInput
from telegram.constants import InlineQueryResultType
if TYPE_CHECKING:
@@ -61,7 +61,6 @@ class InlineQueryResultGif(InlineQueryResult):
to the message.
input_message_content (:class:`telegram.InputMessageContent`, optional): Content of the
message to be sent instead of the GIF animation.
**kwargs (:obj:`dict`): Arbitrary keyword arguments.
Attributes:
type (:obj:`str`): :tg-const:`telegram.constants.InlineQueryResultType.GIF`.
@@ -120,11 +119,12 @@ class InlineQueryResultGif(InlineQueryResult):
parse_mode: ODVInput[str] = DEFAULT_NONE,
thumb_mime_type: str = None,
caption_entities: Union[Tuple[MessageEntity, ...], List[MessageEntity]] = None,
**_kwargs: Any,
*,
api_kwargs: JSONDict = None,
):
# Required
super().__init__(InlineQueryResultType.GIF, id)
super().__init__(InlineQueryResultType.GIF, id, api_kwargs=api_kwargs)
self.gif_url = gif_url
self.thumb_url = thumb_url
@@ -18,10 +18,11 @@
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains the classes that represent Telegram InlineQueryResultLocation."""
from typing import TYPE_CHECKING, Any
from typing import TYPE_CHECKING
from telegram._inline.inlinekeyboardmarkup import InlineKeyboardMarkup
from telegram._inline.inlinequeryresult import InlineQueryResult
from telegram._utils.types import JSONDict
from telegram.constants import InlineQueryResultType
if TYPE_CHECKING:
@@ -56,7 +57,6 @@ class InlineQueryResultLocation(InlineQueryResult):
thumb_url (:obj:`str`, optional): Url of the thumbnail for the result.
thumb_width (:obj:`int`, optional): Thumbnail width.
thumb_height (:obj:`int`, optional): Thumbnail height.
**kwargs (:obj:`dict`): Arbitrary keyword arguments.
Attributes:
type (:obj:`str`): :tg-const:`telegram.constants.InlineQueryResultType.LOCATION`.
@@ -112,10 +112,11 @@ class InlineQueryResultLocation(InlineQueryResult):
horizontal_accuracy: float = None,
heading: int = None,
proximity_alert_radius: int = None,
**_kwargs: Any,
*,
api_kwargs: JSONDict = None,
):
# Required
super().__init__(InlineQueryResultType.LOCATION, id)
super().__init__(InlineQueryResultType.LOCATION, id, api_kwargs=api_kwargs)
self.latitude = latitude
self.longitude = longitude
self.title = title
@@ -18,13 +18,13 @@
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains the classes that represent Telegram InlineQueryResultMpeg4Gif."""
from typing import TYPE_CHECKING, Any, List, Tuple, Union
from typing import TYPE_CHECKING, List, Tuple, Union
from telegram._inline.inlinekeyboardmarkup import InlineKeyboardMarkup
from telegram._inline.inlinequeryresult import InlineQueryResult
from telegram._messageentity import MessageEntity
from telegram._utils.defaultvalue import DEFAULT_NONE
from telegram._utils.types import ODVInput
from telegram._utils.types import JSONDict, ODVInput
from telegram.constants import InlineQueryResultType
if TYPE_CHECKING:
@@ -61,7 +61,6 @@ class InlineQueryResultMpeg4Gif(InlineQueryResult):
to the message.
input_message_content (:class:`telegram.InputMessageContent`, optional): Content of the
message to be sent instead of the video animation.
**kwargs (:obj:`dict`): Arbitrary keyword arguments.
Attributes:
type (:obj:`str`): :tg-const:`telegram.constants.InlineQueryResultType.MPEG4GIF`.
@@ -120,11 +119,12 @@ class InlineQueryResultMpeg4Gif(InlineQueryResult):
parse_mode: ODVInput[str] = DEFAULT_NONE,
thumb_mime_type: str = None,
caption_entities: Union[Tuple[MessageEntity, ...], List[MessageEntity]] = None,
**_kwargs: Any,
*,
api_kwargs: JSONDict = None,
):
# Required
super().__init__(InlineQueryResultType.MPEG4GIF, id)
super().__init__(InlineQueryResultType.MPEG4GIF, id, api_kwargs=api_kwargs)
self.mpeg4_url = mpeg4_url
self.thumb_url = thumb_url
+5 -5
View File
@@ -18,13 +18,13 @@
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains the classes that represent Telegram InlineQueryResultPhoto."""
from typing import TYPE_CHECKING, Any, List, Tuple, Union
from typing import TYPE_CHECKING, List, Tuple, Union
from telegram._inline.inlinekeyboardmarkup import InlineKeyboardMarkup
from telegram._inline.inlinequeryresult import InlineQueryResult
from telegram._messageentity import MessageEntity
from telegram._utils.defaultvalue import DEFAULT_NONE
from telegram._utils.types import ODVInput
from telegram._utils.types import JSONDict, ODVInput
from telegram.constants import InlineQueryResultType
if TYPE_CHECKING:
@@ -59,7 +59,6 @@ class InlineQueryResultPhoto(InlineQueryResult):
to the message.
input_message_content (:class:`telegram.InputMessageContent`, optional): Content of the
message to be sent instead of the photo.
**kwargs (:obj:`dict`): Arbitrary keyword arguments.
Attributes:
type (:obj:`str`): :tg-const:`telegram.constants.InlineQueryResultType.PHOTO`.
@@ -115,10 +114,11 @@ class InlineQueryResultPhoto(InlineQueryResult):
input_message_content: "InputMessageContent" = None,
parse_mode: ODVInput[str] = DEFAULT_NONE,
caption_entities: Union[Tuple[MessageEntity, ...], List[MessageEntity]] = None,
**_kwargs: Any,
*,
api_kwargs: JSONDict = None,
):
# Required
super().__init__(InlineQueryResultType.PHOTO, id)
super().__init__(InlineQueryResultType.PHOTO, id, api_kwargs=api_kwargs)
self.photo_url = photo_url
self.thumb_url = thumb_url
+5 -4
View File
@@ -18,10 +18,11 @@
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains the classes that represent Telegram InlineQueryResultVenue."""
from typing import TYPE_CHECKING, Any
from typing import TYPE_CHECKING
from telegram._inline.inlinekeyboardmarkup import InlineKeyboardMarkup
from telegram._inline.inlinequeryresult import InlineQueryResult
from telegram._utils.types import JSONDict
from telegram.constants import InlineQueryResultType
if TYPE_CHECKING:
@@ -59,7 +60,6 @@ class InlineQueryResultVenue(InlineQueryResult):
thumb_url (:obj:`str`, optional): Url of the thumbnail for the result.
thumb_width (:obj:`int`, optional): Thumbnail width.
thumb_height (:obj:`int`, optional): Thumbnail height.
**kwargs (:obj:`dict`): Arbitrary keyword arguments.
Attributes:
type (:obj:`str`): :tg-const:`telegram.constants.InlineQueryResultType.VENUE`.
@@ -114,11 +114,12 @@ class InlineQueryResultVenue(InlineQueryResult):
thumb_height: int = None,
google_place_id: str = None,
google_place_type: str = None,
**_kwargs: Any,
*,
api_kwargs: JSONDict = None,
):
# Required
super().__init__(InlineQueryResultType.VENUE, id)
super().__init__(InlineQueryResultType.VENUE, id, api_kwargs=api_kwargs)
self.latitude = latitude
self.longitude = longitude
self.title = title
+5 -5
View File
@@ -18,13 +18,13 @@
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains the classes that represent Telegram InlineQueryResultVideo."""
from typing import TYPE_CHECKING, Any, List, Tuple, Union
from typing import TYPE_CHECKING, List, Tuple, Union
from telegram._inline.inlinekeyboardmarkup import InlineKeyboardMarkup
from telegram._inline.inlinequeryresult import InlineQueryResult
from telegram._messageentity import MessageEntity
from telegram._utils.defaultvalue import DEFAULT_NONE
from telegram._utils.types import ODVInput
from telegram._utils.types import JSONDict, ODVInput
from telegram.constants import InlineQueryResultType
if TYPE_CHECKING:
@@ -67,7 +67,6 @@ class InlineQueryResultVideo(InlineQueryResult):
message to be sent instead of the video. This field is required if
InlineQueryResultVideo is used to send an HTML-page as a result
(e.g., a YouTube video).
**kwargs (:obj:`dict`): Arbitrary keyword arguments.
Attributes:
type (:obj:`str`): :tg-const:`telegram.constants.InlineQueryResultType.VIDEO`.
@@ -130,11 +129,12 @@ class InlineQueryResultVideo(InlineQueryResult):
input_message_content: "InputMessageContent" = None,
parse_mode: ODVInput[str] = DEFAULT_NONE,
caption_entities: Union[Tuple[MessageEntity, ...], List[MessageEntity]] = None,
**_kwargs: Any,
*,
api_kwargs: JSONDict = None,
):
# Required
super().__init__(InlineQueryResultType.VIDEO, id)
super().__init__(InlineQueryResultType.VIDEO, id, api_kwargs=api_kwargs)
self.video_url = video_url
self.mime_type = mime_type
self.thumb_url = thumb_url
+6 -6
View File
@@ -18,13 +18,13 @@
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains the classes that represent Telegram InlineQueryResultVoice."""
from typing import TYPE_CHECKING, Any, List, Tuple, Union
from typing import TYPE_CHECKING, List, Tuple, Union
from telegram._inline.inlinekeyboardmarkup import InlineKeyboardMarkup
from telegram._inline.inlinequeryresult import InlineQueryResult
from telegram._messageentity import MessageEntity
from telegram._utils.defaultvalue import DEFAULT_NONE
from telegram._utils.types import ODVInput
from telegram._utils.types import JSONDict, ODVInput
from telegram.constants import InlineQueryResultType
if TYPE_CHECKING:
@@ -35,7 +35,7 @@ class InlineQueryResultVoice(InlineQueryResult):
"""
Represents a link to a voice recording in an .ogg container encoded with OPUS. By default,
this voice recording will be sent by the user. Alternatively, you can use
:attr:`input_message_content` to send a message with the specified content instead of the
:attr:`input_message_content` to send a message with the specified content instead of
the voice message.
Args:
@@ -56,7 +56,6 @@ class InlineQueryResultVoice(InlineQueryResult):
to the message.
input_message_content (:class:`telegram.InputMessageContent`, optional): Content of the
message to be sent instead of the voice recording.
**kwargs (:obj:`dict`): Arbitrary keyword arguments.
Attributes:
type (:obj:`str`): :tg-const:`telegram.constants.InlineQueryResultType.VOICE`.
@@ -102,11 +101,12 @@ class InlineQueryResultVoice(InlineQueryResult):
input_message_content: "InputMessageContent" = None,
parse_mode: ODVInput[str] = DEFAULT_NONE,
caption_entities: Union[Tuple[MessageEntity, ...], List[MessageEntity]] = None,
**_kwargs: Any,
*,
api_kwargs: JSONDict = None,
):
# Required
super().__init__(InlineQueryResultType.VOICE, id)
super().__init__(InlineQueryResultType.VOICE, id, api_kwargs=api_kwargs)
self.voice_url = voice_url
self.title = title
@@ -18,9 +18,8 @@
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains the classes that represent Telegram InputContactMessageContent."""
from typing import Any
from telegram._inline.inputmessagecontent import InputMessageContent
from telegram._utils.types import JSONDict
class InputContactMessageContent(InputMessageContent):
@@ -35,7 +34,6 @@ class InputContactMessageContent(InputMessageContent):
last_name (:obj:`str`, optional): Contact's last name.
vcard (:obj:`str`, optional): Additional data about the contact in the form of a vCard,
0-2048 bytes.
**kwargs (:obj:`dict`): Arbitrary keyword arguments.
Attributes:
phone_number (:obj:`str`): Contact's phone number.
@@ -54,8 +52,11 @@ class InputContactMessageContent(InputMessageContent):
first_name: str,
last_name: str = None,
vcard: str = None,
**_kwargs: Any,
*,
api_kwargs: JSONDict = None,
):
super().__init__(api_kwargs=api_kwargs)
# Required
self.phone_number = phone_number
self.first_name = first_name
@@ -18,7 +18,7 @@
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains a class that represents a Telegram InputInvoiceMessageContent."""
from typing import TYPE_CHECKING, Any, List, Optional
from typing import TYPE_CHECKING, List, Optional
from telegram._inline.inputmessagecontent import InputMessageContent
from telegram._payment.labeledprice import LabeledPrice
@@ -89,7 +89,6 @@ class InputInvoiceMessageContent(InputMessageContent):
should be sent to provider.
is_flexible (:obj:`bool`, optional): Pass :obj:`True`, if the final price depends on the
shipping method.
**kwargs (:obj:`dict`): Arbitrary keyword arguments.
Attributes:
title (:obj:`str`): Product name. :tg-const:`telegram.Invoice.MIN_TITLE_LENGTH`-
@@ -179,8 +178,10 @@ class InputInvoiceMessageContent(InputMessageContent):
send_phone_number_to_provider: bool = None,
send_email_to_provider: bool = None,
is_flexible: bool = None,
**_kwargs: Any,
*,
api_kwargs: JSONDict = None,
):
super().__init__(api_kwargs=api_kwargs)
# Required
self.title = title
self.description = description
@@ -247,4 +248,4 @@ class InputInvoiceMessageContent(InputMessageContent):
data["prices"] = LabeledPrice.de_list(data.get("prices"), bot)
return cls(**data, bot=bot)
return super().de_json(data=data, bot=bot)
@@ -18,9 +18,8 @@
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains the classes that represent Telegram InputLocationMessageContent."""
from typing import Any
from telegram._inline.inputmessagecontent import InputMessageContent
from telegram._utils.types import JSONDict
class InputLocationMessageContent(InputMessageContent):
@@ -44,7 +43,6 @@ class InputLocationMessageContent(InputMessageContent):
proximity_alert_radius (:obj:`int`, optional): For live locations, a maximum distance for
proximity alerts about approaching another chat member, in meters. Must be between 1
and :tg-const:`telegram.constants.LocationLimit.HEADING` if specified.
**kwargs (:obj:`dict`): Arbitrary keyword arguments.
Attributes:
latitude (:obj:`float`): Latitude of the location in degrees.
@@ -72,8 +70,10 @@ class InputLocationMessageContent(InputMessageContent):
horizontal_accuracy: float = None,
heading: int = None,
proximity_alert_radius: int = None,
**_kwargs: Any,
*,
api_kwargs: JSONDict = None,
):
super().__init__(api_kwargs=api_kwargs)
# Required
self.latitude = latitude
self.longitude = longitude
+4 -3
View File
@@ -18,7 +18,7 @@
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains the classes that represent Telegram InputTextMessageContent."""
from typing import Any, List, Tuple, Union
from typing import List, Tuple, Union
from telegram._inline.inputmessagecontent import InputMessageContent
from telegram._messageentity import MessageEntity
@@ -47,7 +47,6 @@ class InputTextMessageContent(InputMessageContent):
:paramref:`parse_mode`.
disable_web_page_preview (:obj:`bool`, optional): Disables link previews for links in the
sent message.
**kwargs (:obj:`dict`): Arbitrary keyword arguments.
Attributes:
message_text (:obj:`str`): Text of the message to be sent,
@@ -72,8 +71,10 @@ class InputTextMessageContent(InputMessageContent):
parse_mode: ODVInput[str] = DEFAULT_NONE,
disable_web_page_preview: ODVInput[bool] = DEFAULT_NONE,
entities: Union[Tuple[MessageEntity, ...], List[MessageEntity]] = None,
**_kwargs: Any,
*,
api_kwargs: JSONDict = None,
):
super().__init__(api_kwargs=api_kwargs)
# Required
self.message_text = message_text
# Optionals
+5 -4
View File
@@ -18,9 +18,8 @@
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains the classes that represent Telegram InputVenueMessageContent."""
from typing import Any
from telegram._inline.inputmessagecontent import InputMessageContent
from telegram._utils.types import JSONDict
class InputVenueMessageContent(InputMessageContent):
@@ -47,7 +46,6 @@ class InputVenueMessageContent(InputMessageContent):
google_place_type (:obj:`str`, optional): Google Places type of the venue. (See
`supported types <https://developers.google.com/maps/documentation/places/web-service\
/supported_types>`_.)
**kwargs (:obj:`dict`): Arbitrary keyword arguments.
Attributes:
latitude (:obj:`float`): Latitude of the location in degrees.
@@ -82,8 +80,11 @@ class InputVenueMessageContent(InputMessageContent):
foursquare_type: str = None,
google_place_id: str = None,
google_place_type: str = None,
**_kwargs: Any,
*,
api_kwargs: JSONDict = None,
):
super().__init__(api_kwargs=api_kwargs)
# Required
self.latitude = latitude
self.longitude = longitude
+5 -4
View File
@@ -18,7 +18,7 @@
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents a Telegram KeyboardButton."""
from typing import TYPE_CHECKING, Any, Optional
from typing import TYPE_CHECKING, Optional
from telegram._keyboardbuttonpolltype import KeyboardButtonPollType
from telegram._telegramobject import TelegramObject
@@ -67,7 +67,6 @@ class KeyboardButton(TelegramObject):
Available in private chats only.
.. versionadded:: 20.0
Attributes:
text (:obj:`str`): Text of the button.
request_contact (:obj:`bool`): Optional. The user's phone number will be sent.
@@ -88,8 +87,10 @@ class KeyboardButton(TelegramObject):
request_location: bool = None,
request_poll: KeyboardButtonPollType = None,
web_app: WebAppInfo = None,
**_kwargs: Any,
*,
api_kwargs: JSONDict = None,
):
super().__init__(api_kwargs=api_kwargs)
# Required
self.text = text
# Optionals
@@ -117,4 +118,4 @@ class KeyboardButton(TelegramObject):
data["request_poll"] = KeyboardButtonPollType.de_json(data.get("request_poll"), bot)
data["web_app"] = WebAppInfo.de_json(data.get("web_app"), bot)
return cls(**data)
return super().de_json(data=data, bot=bot)
+5 -2
View File
@@ -17,9 +17,9 @@
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents a type of a Telegram Poll."""
from typing import Any
from telegram._telegramobject import TelegramObject
from telegram._utils.types import JSONDict
class KeyboardButtonPollType(TelegramObject):
@@ -40,7 +40,10 @@ class KeyboardButtonPollType(TelegramObject):
__slots__ = ("type",)
def __init__(self, type: str = None, **_kwargs: Any): # pylint: disable=redefined-builtin
def __init__(
self, type: str = None, *, api_kwargs: JSONDict = None # skipcq: PYL-W0622
): # pylint: disable=redefined-builtin
super().__init__(api_kwargs=api_kwargs)
self.type = type
self._id_attrs = (self.type,)
+4 -2
View File
@@ -17,9 +17,9 @@
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents a Telegram LoginUrl."""
from typing import Any
from telegram._telegramobject import TelegramObject
from telegram._utils.types import JSONDict
class LoginUrl(TelegramObject):
@@ -76,8 +76,10 @@ class LoginUrl(TelegramObject):
forward_text: bool = None,
bot_username: str = None,
request_write_access: bool = None,
**_kwargs: Any,
*,
api_kwargs: JSONDict = None,
):
super().__init__(api_kwargs=api_kwargs)
# Required
self.url = url
# Optional
+20 -15
View File
@@ -17,7 +17,7 @@
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains objects related to Telegram menu buttons."""
from typing import TYPE_CHECKING, Any, ClassVar, Dict, Optional, Type
from typing import TYPE_CHECKING, ClassVar, Dict, Optional, Type
from telegram import constants
from telegram._telegramobject import TelegramObject
@@ -54,7 +54,10 @@ class MenuButton(TelegramObject):
__slots__ = ("type",)
def __init__(self, type: str, **_kwargs: Any): # pylint: disable=redefined-builtin
def __init__(
self, type: str, *, api_kwargs: JSONDict = None # skipcq: PYL-W0622
): # pylint: disable=redefined-builtin
super().__init__(api_kwargs=api_kwargs)
self.type = type
self._id_attrs = (self.type,)
@@ -74,7 +77,10 @@ class MenuButton(TelegramObject):
"""
data = cls._parse_data(data)
if not data:
if data is None:
return None
if not data and cls is MenuButton:
return None
_class_mapping: Dict[str, Type["MenuButton"]] = {
@@ -83,9 +89,10 @@ class MenuButton(TelegramObject):
cls.DEFAULT: MenuButtonDefault,
}
if cls is MenuButton and data["type"] in _class_mapping:
return _class_mapping[data["type"]].de_json(data, bot=bot)
return cls(**data, bot=bot)
if cls is MenuButton and data.get("type") in _class_mapping:
return _class_mapping[data.pop("type")].de_json(data, bot=bot)
out = super().de_json(data=data, bot=bot)
return out
COMMANDS: ClassVar[str] = constants.MenuButtonType.COMMANDS
""":const:`telegram.constants.MenuButtonType.COMMANDS`"""
@@ -99,15 +106,14 @@ class MenuButtonCommands(MenuButton):
"""Represents a menu button, which opens the bot's list of commands.
.. versionadded:: 20.0
Attributes:
type (:obj:`str`): :tg-const:`telegram.constants.MenuButtonType.COMMANDS`.
"""
__slots__ = ()
def __init__(self, **_kwargs: Any):
super().__init__(type=constants.MenuButtonType.COMMANDS)
def __init__(self, *, api_kwargs: JSONDict = None):
super().__init__(type=constants.MenuButtonType.COMMANDS, api_kwargs=api_kwargs)
class MenuButtonWebApp(MenuButton):
@@ -136,8 +142,8 @@ class MenuButtonWebApp(MenuButton):
__slots__ = ("text", "web_app")
def __init__(self, text: str, web_app: WebAppInfo, **_kwargs: Any):
super().__init__(type=constants.MenuButtonType.WEB_APP)
def __init__(self, text: str, web_app: WebAppInfo, *, api_kwargs: JSONDict = None):
super().__init__(type=constants.MenuButtonType.WEB_APP, api_kwargs=api_kwargs)
self.text = text
self.web_app = web_app
@@ -153,7 +159,7 @@ class MenuButtonWebApp(MenuButton):
data["web_app"] = WebAppInfo.de_json(data.get("web_app"), bot)
return cls(bot=bot, **data)
return super().de_json(data=data, bot=bot) # type: ignore[return-value]
def to_dict(self) -> JSONDict:
"""See :meth:`telegram.TelegramObject.to_dict`."""
@@ -166,12 +172,11 @@ class MenuButtonDefault(MenuButton):
"""Describes that no specific value for the menu button was set.
.. versionadded:: 20.0
Attributes:
type (:obj:`str`): :tg-const:`telegram.constants.MenuButtonType.DEFAULT`.
"""
__slots__ = ()
def __init__(self, **_kwargs: Any):
super().__init__(type=constants.MenuButtonType.DEFAULT)
def __init__(self, *, api_kwargs: JSONDict = None):
super().__init__(type=constants.MenuButtonType.DEFAULT, api_kwargs=api_kwargs)
+7 -8
View File
@@ -21,7 +21,7 @@
import datetime
import sys
from html import escape
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Union
from typing import TYPE_CHECKING, Dict, List, Optional, Tuple, Union
from telegram._chat import Chat
from telegram._dice import Dice
@@ -247,7 +247,6 @@ class Message(TelegramObject):
.. versionadded:: 20.0
reply_markup (:class:`telegram.InlineKeyboardMarkup`, optional): Inline keyboard attached
to the message. ``login_url`` buttons are represented as ordinary url buttons.
bot (:class:`telegram.Bot`, optional): The Bot to use for instance methods.
Attributes:
message_id (:obj:`int`): Unique message identifier inside this chat.
@@ -368,7 +367,6 @@ class Message(TelegramObject):
.. versionadded:: 20.0
reply_markup (:class:`telegram.InlineKeyboardMarkup`): Optional. Inline keyboard attached
to the message.
bot (:class:`telegram.Bot`): Optional. The Bot to use for instance methods.
.. |custom_emoji_formatting_note| replace:: Custom emoji entities will currently be ignored
by this function. Instead, the supplied replacement for the emoji will be used.
@@ -487,7 +485,6 @@ class Message(TelegramObject):
poll: Poll = None,
forward_sender_name: str = None,
reply_markup: InlineKeyboardMarkup = None,
bot: "Bot" = None,
dice: Dice = None,
via_bot: User = None,
proximity_alert_triggered: ProximityAlertTriggered = None,
@@ -500,8 +497,11 @@ class Message(TelegramObject):
is_automatic_forward: bool = None,
has_protected_content: bool = None,
web_app_data: WebAppData = None,
**_kwargs: Any,
*,
api_kwargs: JSONDict = None,
):
super().__init__(api_kwargs=api_kwargs)
# Required
self.message_id = message_id
# Optionals
@@ -563,7 +563,6 @@ class Message(TelegramObject):
self.video_chat_participants_invited = video_chat_participants_invited
self.reply_markup = reply_markup
self.web_app_data = web_app_data
self.set_bot(bot)
self._effective_attachment = DEFAULT_NONE
@@ -605,7 +604,7 @@ class Message(TelegramObject):
if not data:
return None
data["from_user"] = User.de_json(data.get("from"), bot)
data["from_user"] = User.de_json(data.pop("from", None), bot)
data["sender_chat"] = Chat.de_json(data.get("sender_chat"), bot)
data["date"] = from_timestamp(data["date"])
data["chat"] = Chat.de_json(data.get("chat"), bot)
@@ -655,7 +654,7 @@ class Message(TelegramObject):
)
data["web_app_data"] = WebAppData.de_json(data.get("web_app_data"), bot)
return cls(bot=bot, **data)
return super().de_json(data=data, bot=bot)
@property
def effective_attachment(
+4 -4
View File
@@ -20,9 +20,8 @@
deletion.
"""
from typing import Any
from telegram._telegramobject import TelegramObject
from telegram._utils.types import JSONDict
class MessageAutoDeleteTimerChanged(TelegramObject):
@@ -36,7 +35,6 @@ class MessageAutoDeleteTimerChanged(TelegramObject):
Args:
message_auto_delete_time (:obj:`int`): New auto-delete time for messages in the
chat.
**kwargs (:obj:`dict`): Arbitrary keyword arguments.
Attributes:
message_auto_delete_time (:obj:`int`): New auto-delete time for messages in the
@@ -49,8 +47,10 @@ class MessageAutoDeleteTimerChanged(TelegramObject):
def __init__(
self,
message_auto_delete_time: int,
**_kwargs: Any,
*,
api_kwargs: JSONDict = None,
):
super().__init__(api_kwargs=api_kwargs)
self.message_auto_delete_time = message_auto_delete_time
self._id_attrs = (self.message_auto_delete_time,)
+5 -4
View File
@@ -18,7 +18,7 @@
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents a Telegram MessageEntity."""
from typing import TYPE_CHECKING, Any, ClassVar, List, Optional
from typing import TYPE_CHECKING, ClassVar, List, Optional
from telegram import constants
from telegram._telegramobject import TelegramObject
@@ -62,7 +62,6 @@ class MessageEntity(TelegramObject):
information about the sticker.
.. versionadded:: 20.0
Attributes:
type (:obj:`str`): Type of the entity.
offset (:obj:`int`): Offset in UTF-16 code units to the start of the entity.
@@ -87,8 +86,10 @@ class MessageEntity(TelegramObject):
user: User = None,
language: str = None,
custom_emoji_id: str = None,
**_kwargs: Any,
*,
api_kwargs: JSONDict = None,
):
super().__init__(api_kwargs=api_kwargs)
# Required
self.type = enum.get_member(constants.MessageEntityType, type, type)
self.offset = offset
@@ -111,7 +112,7 @@ class MessageEntity(TelegramObject):
data["user"] = User.de_json(data.get("user"), bot)
return cls(**data)
return super().de_json(data=data, bot=bot)
MENTION: ClassVar[str] = constants.MessageEntityType.MENTION
""":const:`telegram.constants.MessageEntityType.MENTION`"""
+7 -3
View File
@@ -17,9 +17,9 @@
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents an instance of a Telegram MessageId."""
from typing import Any
from telegram._telegramobject import TelegramObject
from telegram._utils.types import JSONDict
class MessageId(TelegramObject):
@@ -28,13 +28,17 @@ class MessageId(TelegramObject):
Objects of this class are comparable in terms of equality. Two objects of this class are
considered equal, if their :attr:`message_id` is equal.
Args:
message_id (:obj:`int`): Unique message identifier.
Attributes:
message_id (:obj:`int`): Unique message identifier
message_id (:obj:`int`): Unique message identifier.
"""
__slots__ = ("message_id",)
def __init__(self, message_id: int, **_kwargs: Any):
def __init__(self, message_id: int, *, api_kwargs: JSONDict = None):
super().__init__(api_kwargs=api_kwargs)
self.message_id = message_id
self._id_attrs = (self.message_id,)
+38 -27
View File
@@ -19,7 +19,7 @@
# pylint: disable=missing-module-docstring, redefined-builtin
import json
from base64 import b64decode
from typing import TYPE_CHECKING, Any, List, Optional, no_type_check
from typing import TYPE_CHECKING, List, Optional, no_type_check
try:
from cryptography.hazmat.backends import default_backend
@@ -46,7 +46,7 @@ if TYPE_CHECKING:
@no_type_check
def decrypt(secret, hash, data):
def decrypt(secret, hash, data): # skipcq: PYL-W0622
"""
Decrypt per telegram docs at https://core.telegram.org/passport.
@@ -95,7 +95,7 @@ def decrypt(secret, hash, data):
@no_type_check
def decrypt_json(secret, hash, data):
def decrypt_json(secret, hash, data): # skipcq: PYL-W0622
"""Decrypts data using secret and hash and then decodes utf-8 string and loads json"""
return json.loads(decrypt(secret, hash, data).decode("utf-8"))
@@ -118,7 +118,6 @@ class EncryptedCredentials(TelegramObject):
authentication or base64 encrypted data.
hash (:obj:`str`): Base64-encoded data hash for data authentication.
secret (:obj:`str`): Decrypted or encrypted secret used for decryption.
**kwargs (:obj:`dict`): Arbitrary keyword arguments.
Attributes:
data (:class:`telegram.Credentials` or :obj:`str`): Decrypted data with unique user's
@@ -137,7 +136,15 @@ class EncryptedCredentials(TelegramObject):
"_decrypted_data",
)
def __init__(self, data: str, hash: str, secret: str, bot: "Bot" = None, **_kwargs: Any):
def __init__(
self,
data: str,
hash: str, # skipcq: PYL-W0622
secret: str,
*,
api_kwargs: JSONDict = None,
):
super().__init__(api_kwargs=api_kwargs)
# Required
self.data = data
self.hash = hash
@@ -145,7 +152,6 @@ class EncryptedCredentials(TelegramObject):
self._id_attrs = (self.data, self.hash, self.secret)
self.set_bot(bot)
self._decrypted_secret: Optional[str] = None
self._decrypted_data: Optional["Credentials"] = None
@@ -208,13 +214,18 @@ class Credentials(TelegramObject):
__slots__ = ("nonce", "secure_data")
def __init__(self, secure_data: "SecureData", nonce: str, bot: "Bot" = None, **_kwargs: Any):
def __init__(
self,
secure_data: "SecureData",
nonce: str,
*,
api_kwargs: JSONDict = None,
):
super().__init__(api_kwargs=api_kwargs)
# Required
self.secure_data = secure_data
self.nonce = nonce
self.set_bot(bot)
@classmethod
def de_json(cls, data: Optional[JSONDict], bot: "Bot") -> Optional["Credentials"]:
"""See :meth:`telegram.TelegramObject.de_json`."""
@@ -225,7 +236,7 @@ class Credentials(TelegramObject):
data["secure_data"] = SecureData.de_json(data.get("secure_data"), bot=bot)
return cls(bot=bot, **data)
return super().de_json(data=data, bot=bot)
class SecureData(TelegramObject):
@@ -283,9 +294,11 @@ class SecureData(TelegramObject):
rental_agreement: "SecureValue" = None,
passport_registration: "SecureValue" = None,
temporary_registration: "SecureValue" = None,
bot: "Bot" = None,
**_kwargs: Any,
*,
api_kwargs: JSONDict = None,
):
super().__init__(api_kwargs=api_kwargs)
# Optionals
self.temporary_registration = temporary_registration
self.passport_registration = passport_registration
@@ -299,8 +312,6 @@ class SecureData(TelegramObject):
self.passport = passport
self.personal_details = personal_details
self.set_bot(bot)
@classmethod
def de_json(cls, data: Optional[JSONDict], bot: "Bot") -> Optional["SecureData"]:
"""See :meth:`telegram.TelegramObject.de_json`."""
@@ -325,7 +336,7 @@ class SecureData(TelegramObject):
data["passport"] = SecureValue.de_json(data.get("passport"), bot=bot)
data["personal_details"] = SecureValue.de_json(data.get("personal_details"), bot=bot)
return cls(bot=bot, **data)
return super().de_json(data=data, bot=bot)
class SecureValue(TelegramObject):
@@ -365,9 +376,10 @@ class SecureValue(TelegramObject):
selfie: "FileCredentials" = None,
files: List["FileCredentials"] = None,
translation: List["FileCredentials"] = None,
bot: "Bot" = None,
**_kwargs: Any,
*,
api_kwargs: JSONDict = None,
):
super().__init__(api_kwargs=api_kwargs)
self.data = data
self.front_side = front_side
self.reverse_side = reverse_side
@@ -375,8 +387,6 @@ class SecureValue(TelegramObject):
self.files = files
self.translation = translation
self.set_bot(bot)
@classmethod
def de_json(cls, data: Optional[JSONDict], bot: "Bot") -> Optional["SecureValue"]:
"""See :meth:`telegram.TelegramObject.de_json`."""
@@ -392,7 +402,7 @@ class SecureValue(TelegramObject):
data["files"] = FileCredentials.de_list(data.get("files"), bot=bot)
data["translation"] = FileCredentials.de_list(data.get("translation"), bot=bot)
return cls(bot=bot, **data)
return super().de_json(data=data, bot=bot)
def to_dict(self) -> JSONDict:
"""See :meth:`telegram.TelegramObject.to_dict`."""
@@ -409,7 +419,10 @@ class _CredentialsBase(TelegramObject):
__slots__ = ("hash", "secret", "file_hash", "data_hash")
def __init__(self, hash: str, secret: str, bot: "Bot" = None, **_kwargs: Any):
def __init__(
self, hash: str, secret: str, *, api_kwargs: JSONDict = None
): # skipcq: PYL-W0622
super().__init__(api_kwargs=api_kwargs)
self.hash = hash
self.secret = secret
@@ -417,8 +430,6 @@ class _CredentialsBase(TelegramObject):
self.file_hash = self.hash
self.data_hash = self.hash
self.set_bot(bot)
class DataCredentials(_CredentialsBase):
"""
@@ -436,8 +447,8 @@ class DataCredentials(_CredentialsBase):
__slots__ = ()
def __init__(self, data_hash: str, secret: str, **_kwargs: Any):
super().__init__(data_hash, secret, **_kwargs)
def __init__(self, data_hash: str, secret: str, *, api_kwargs: JSONDict = None):
super().__init__(hash=data_hash, secret=secret, api_kwargs=api_kwargs)
def to_dict(self) -> JSONDict:
"""See :meth:`telegram.TelegramObject.to_dict`."""
@@ -465,8 +476,8 @@ class FileCredentials(_CredentialsBase):
__slots__ = ()
def __init__(self, file_hash: str, secret: str, **_kwargs: Any):
super().__init__(file_hash, secret, **_kwargs)
def __init__(self, file_hash: str, secret: str, *, api_kwargs: JSONDict = None):
super().__init__(hash=file_hash, secret=secret, api_kwargs=api_kwargs)
def to_dict(self) -> JSONDict:
"""See :meth:`telegram.TelegramObject.to_dict`."""
+15 -15
View File
@@ -17,12 +17,9 @@
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
# pylint: disable=missing-module-docstring
from typing import TYPE_CHECKING, Any
from telegram._telegramobject import TelegramObject
if TYPE_CHECKING:
from telegram import Bot
from telegram._utils.types import JSONDict
class PersonalDetails(TelegramObject):
@@ -71,9 +68,10 @@ class PersonalDetails(TelegramObject):
last_name_native: str = None,
middle_name: str = None,
middle_name_native: str = None,
bot: "Bot" = None,
**_kwargs: Any,
*,
api_kwargs: JSONDict = None,
):
super().__init__(api_kwargs=api_kwargs)
# Required
self.first_name = first_name
self.last_name = last_name
@@ -86,8 +84,6 @@ class PersonalDetails(TelegramObject):
self.last_name_native = last_name_native
self.middle_name_native = middle_name_native
self.set_bot(bot)
class ResidentialAddress(TelegramObject):
"""
@@ -119,9 +115,10 @@ class ResidentialAddress(TelegramObject):
state: str,
country_code: str,
post_code: str,
bot: "Bot" = None,
**_kwargs: Any,
*,
api_kwargs: JSONDict = None,
):
super().__init__(api_kwargs=api_kwargs)
# Required
self.street_line1 = street_line1
self.street_line2 = street_line2
@@ -130,8 +127,6 @@ class ResidentialAddress(TelegramObject):
self.country_code = country_code
self.post_code = post_code
self.set_bot(bot)
class IdDocumentData(TelegramObject):
"""
@@ -144,8 +139,13 @@ class IdDocumentData(TelegramObject):
__slots__ = ("document_no", "expiry_date")
def __init__(self, document_no: str, expiry_date: str, bot: "Bot" = None, **_kwargs: Any):
def __init__(
self,
document_no: str,
expiry_date: str,
*,
api_kwargs: JSONDict = None,
):
super().__init__(api_kwargs=api_kwargs)
self.document_no = document_no
self.expiry_date = expiry_date
self.set_bot(bot)
+7 -10
View File
@@ -18,7 +18,7 @@
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents a Telegram EncryptedPassportElement."""
from base64 import b64decode
from typing import TYPE_CHECKING, Any, List, Optional
from typing import TYPE_CHECKING, List, Optional
from telegram._passport.credentials import decrypt_json
from telegram._passport.data import IdDocumentData, PersonalDetails, ResidentialAddress
@@ -75,8 +75,6 @@ class EncryptedPassportElement(TelegramObject):
requested for "passport", "driver_license", "identity_card", "internal_passport",
"utility_bill", "bank_statement", "rental_agreement", "passport_registration" and
"temporary_registration" types.
bot (:class:`telegram.Bot`, optional): The Bot to use for instance methods.
**kwargs (:obj:`dict`): Arbitrary keyword arguments.
Attributes:
type (:obj:`str`): Element type. One of "personal_details", "passport", "driver_license",
@@ -110,7 +108,6 @@ class EncryptedPassportElement(TelegramObject):
requested for "passport", "driver_license", "identity_card", "internal_passport",
"utility_bill", "bank_statement", "rental_agreement", "passport_registration" and
"temporary_registration" types.
bot (:class:`telegram.Bot`): Optional. The Bot to use for instance methods.
"""
@@ -139,10 +136,12 @@ class EncryptedPassportElement(TelegramObject):
reverse_side: PassportFile = None,
selfie: PassportFile = None,
translation: List[PassportFile] = None,
bot: "Bot" = None,
credentials: "Credentials" = None, # pylint: disable=unused-argument
**_kwargs: Any,
*,
api_kwargs: JSONDict = None,
):
super().__init__(api_kwargs=api_kwargs)
# Required
self.type = type
# Optionals
@@ -167,8 +166,6 @@ class EncryptedPassportElement(TelegramObject):
self.selfie,
)
self.set_bot(bot)
@classmethod
def de_json(cls, data: Optional[JSONDict], bot: "Bot") -> Optional["EncryptedPassportElement"]:
"""See :meth:`telegram.TelegramObject.de_json`."""
@@ -183,7 +180,7 @@ class EncryptedPassportElement(TelegramObject):
data["selfie"] = PassportFile.de_json(data.get("selfie"), bot)
data["translation"] = PassportFile.de_list(data.get("translation"), bot) or None
return cls(bot=bot, **data)
return super().de_json(data=data, bot=bot)
@classmethod
def de_json_decrypted(
@@ -246,7 +243,7 @@ class EncryptedPassportElement(TelegramObject):
or None
)
return cls(bot=bot, **data)
return super().de_json(data=data, bot=bot)
def to_dict(self) -> JSONDict:
"""See :meth:`telegram.TelegramObject.to_dict`."""
+7 -8
View File
@@ -18,7 +18,7 @@
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""Contains information about Telegram Passport data shared with the bot by the user."""
from typing import TYPE_CHECKING, Any, List, Optional
from typing import TYPE_CHECKING, List, Optional
from telegram._passport.credentials import EncryptedCredentials
from telegram._passport.encryptedpassportelement import EncryptedPassportElement
@@ -42,14 +42,12 @@ class PassportData(TelegramObject):
data (List[:class:`telegram.EncryptedPassportElement`]): Array with encrypted information
about documents and other Telegram Passport elements that was shared with the bot.
credentials (:class:`telegram.EncryptedCredentials`)): Encrypted credentials.
bot (:class:`telegram.Bot`, optional): The Bot to use for instance methods.
**kwargs (:obj:`dict`): Arbitrary keyword arguments.
Attributes:
data (List[:class:`telegram.EncryptedPassportElement`]): Array with encrypted information
about documents and other Telegram Passport elements that was shared with the bot.
credentials (:class:`telegram.EncryptedCredentials`): Encrypted credentials.
bot (:class:`telegram.Bot`, optional): The Bot to use for instance methods.
"""
@@ -59,13 +57,14 @@ class PassportData(TelegramObject):
self,
data: List[EncryptedPassportElement],
credentials: EncryptedCredentials,
bot: "Bot" = None,
**_kwargs: Any,
*,
api_kwargs: JSONDict = None,
):
super().__init__(api_kwargs=api_kwargs)
self.data = data
self.credentials = credentials
self.set_bot(bot)
self._decrypted_data: Optional[List[EncryptedPassportElement]] = None
self._id_attrs = tuple([x.type for x in data] + [credentials.hash])
@@ -80,7 +79,7 @@ class PassportData(TelegramObject):
data["data"] = EncryptedPassportElement.de_list(data.get("data"), bot)
data["credentials"] = EncryptedCredentials.de_json(data.get("credentials"), bot)
return cls(bot=bot, **data)
return super().de_json(data=data, bot=bot)
def to_dict(self) -> JSONDict:
"""See :meth:`telegram.TelegramObject.to_dict`."""
+29 -31
View File
@@ -19,9 +19,8 @@
# pylint: disable=redefined-builtin
"""This module contains the classes that represent Telegram PassportElementError."""
from typing import Any
from telegram._telegramobject import TelegramObject
from telegram._utils.types import JSONDict
class PassportElementError(TelegramObject):
@@ -36,7 +35,6 @@ class PassportElementError(TelegramObject):
Args:
source (:obj:`str`): Error source.
type (:obj:`str`): The section of the user's Telegram Passport which has the error.
**kwargs (:obj:`dict`): Arbitrary keyword arguments.
Attributes:
source (:obj:`str`): Error source.
@@ -47,7 +45,8 @@ class PassportElementError(TelegramObject):
__slots__ = ("message", "source", "type")
def __init__(self, source: str, type: str, message: str, **_kwargs: Any):
def __init__(self, source: str, type: str, message: str, *, api_kwargs: JSONDict = None):
super().__init__(api_kwargs=api_kwargs)
# Required
self.source = str(source)
self.type = str(type)
@@ -72,7 +71,6 @@ class PassportElementErrorDataField(PassportElementError):
field_name (:obj:`str`): Name of the data field which has the error.
data_hash (:obj:`str`): Base64-encoded data hash.
message (:obj:`str`): Error message.
**kwargs (:obj:`dict`): Arbitrary keyword arguments.
Attributes:
type (:obj:`str`): The section of the user's Telegram Passport which has the error, one of
@@ -86,9 +84,17 @@ class PassportElementErrorDataField(PassportElementError):
__slots__ = ("data_hash", "field_name")
def __init__(self, type: str, field_name: str, data_hash: str, message: str, **_kwargs: Any):
def __init__(
self,
type: str,
field_name: str,
data_hash: str,
message: str,
*,
api_kwargs: JSONDict = None,
):
# Required
super().__init__("data", type, message)
super().__init__("data", type, message, api_kwargs=api_kwargs)
self.field_name = field_name
self.data_hash = data_hash
@@ -110,7 +116,6 @@ class PassportElementErrorFile(PassportElementError):
``"passport_registration"``, ``"temporary_registration"``.
file_hash (:obj:`str`): Base64-encoded file hash.
message (:obj:`str`): Error message.
**kwargs (:obj:`dict`): Arbitrary keyword arguments.
Attributes:
type (:obj:`str`): The section of the user's Telegram Passport which has the issue, one of
@@ -123,9 +128,9 @@ class PassportElementErrorFile(PassportElementError):
__slots__ = ("file_hash",)
def __init__(self, type: str, file_hash: str, message: str, **_kwargs: Any):
def __init__(self, type: str, file_hash: str, message: str, *, api_kwargs: JSONDict = None):
# Required
super().__init__("file", type, message)
super().__init__("file", type, message, api_kwargs=api_kwargs)
self.file_hash = file_hash
self._id_attrs = (self.source, self.type, self.file_hash, self.message)
@@ -146,7 +151,6 @@ class PassportElementErrorFiles(PassportElementError):
``"passport_registration"``, ``"temporary_registration"``.
file_hashes (List[:obj:`str`]): List of base64-encoded file hashes.
message (:obj:`str`): Error message.
**kwargs (:obj:`dict`): Arbitrary keyword arguments.
Attributes:
type (:obj:`str`): The section of the user's Telegram Passport which has the issue, one of
@@ -159,9 +163,9 @@ class PassportElementErrorFiles(PassportElementError):
__slots__ = ("file_hashes",)
def __init__(self, type: str, file_hashes: str, message: str, **_kwargs: Any):
def __init__(self, type: str, file_hashes: str, message: str, *, api_kwargs: JSONDict = None):
# Required
super().__init__("files", type, message)
super().__init__("files", type, message, api_kwargs=api_kwargs)
self.file_hashes = file_hashes
self._id_attrs = (self.source, self.type, self.message) + tuple(file_hashes)
@@ -182,7 +186,6 @@ class PassportElementErrorFrontSide(PassportElementError):
file_hash (:obj:`str`): Base64-encoded hash of the file with the front side of the
document.
message (:obj:`str`): Error message.
**kwargs (:obj:`dict`): Arbitrary keyword arguments.
Attributes:
type (:obj:`str`): The section of the user's Telegram Passport which has the issue, one of
@@ -195,9 +198,9 @@ class PassportElementErrorFrontSide(PassportElementError):
__slots__ = ("file_hash",)
def __init__(self, type: str, file_hash: str, message: str, **_kwargs: Any):
def __init__(self, type: str, file_hash: str, message: str, *, api_kwargs: JSONDict = None):
# Required
super().__init__("front_side", type, message)
super().__init__("front_side", type, message, api_kwargs=api_kwargs)
self.file_hash = file_hash
self._id_attrs = (self.source, self.type, self.file_hash, self.message)
@@ -218,7 +221,6 @@ class PassportElementErrorReverseSide(PassportElementError):
file_hash (:obj:`str`): Base64-encoded hash of the file with the reverse side of the
document.
message (:obj:`str`): Error message.
**kwargs (:obj:`dict`): Arbitrary keyword arguments.
Attributes:
type (:obj:`str`): The section of the user's Telegram Passport which has the issue, one of
@@ -231,9 +233,9 @@ class PassportElementErrorReverseSide(PassportElementError):
__slots__ = ("file_hash",)
def __init__(self, type: str, file_hash: str, message: str, **_kwargs: Any):
def __init__(self, type: str, file_hash: str, message: str, *, api_kwargs: JSONDict = None):
# Required
super().__init__("reverse_side", type, message)
super().__init__("reverse_side", type, message, api_kwargs=api_kwargs)
self.file_hash = file_hash
self._id_attrs = (self.source, self.type, self.file_hash, self.message)
@@ -253,7 +255,6 @@ class PassportElementErrorSelfie(PassportElementError):
``"passport"``, ``"driver_license"``, ``"identity_card"``, ``"internal_passport"``.
file_hash (:obj:`str`): Base64-encoded hash of the file with the selfie.
message (:obj:`str`): Error message.
**kwargs (:obj:`dict`): Arbitrary keyword arguments.
Attributes:
type (:obj:`str`): The section of the user's Telegram Passport which has the issue, one of
@@ -265,9 +266,9 @@ class PassportElementErrorSelfie(PassportElementError):
__slots__ = ("file_hash",)
def __init__(self, type: str, file_hash: str, message: str, **_kwargs: Any):
def __init__(self, type: str, file_hash: str, message: str, *, api_kwargs: JSONDict = None):
# Required
super().__init__("selfie", type, message)
super().__init__("selfie", type, message, api_kwargs=api_kwargs)
self.file_hash = file_hash
self._id_attrs = (self.source, self.type, self.file_hash, self.message)
@@ -289,7 +290,6 @@ class PassportElementErrorTranslationFile(PassportElementError):
``"rental_agreement"``, ``"passport_registration"``, ``"temporary_registration"``.
file_hash (:obj:`str`): Base64-encoded hash of the file.
message (:obj:`str`): Error message.
**kwargs (:obj:`dict`): Arbitrary keyword arguments.
Attributes:
type (:obj:`str`): Type of element of the user's Telegram Passport which has the issue,
@@ -303,9 +303,9 @@ class PassportElementErrorTranslationFile(PassportElementError):
__slots__ = ("file_hash",)
def __init__(self, type: str, file_hash: str, message: str, **_kwargs: Any):
def __init__(self, type: str, file_hash: str, message: str, *, api_kwargs: JSONDict = None):
# Required
super().__init__("translation_file", type, message)
super().__init__("translation_file", type, message, api_kwargs=api_kwargs)
self.file_hash = file_hash
self._id_attrs = (self.source, self.type, self.file_hash, self.message)
@@ -327,7 +327,6 @@ class PassportElementErrorTranslationFiles(PassportElementError):
``"rental_agreement"``, ``"passport_registration"``, ``"temporary_registration"``.
file_hashes (List[:obj:`str`]): List of base64-encoded file hashes.
message (:obj:`str`): Error message.
**kwargs (:obj:`dict`): Arbitrary keyword arguments.
Attributes:
type (:obj:`str`): Type of element of the user's Telegram Passport which has the issue,
@@ -341,9 +340,9 @@ class PassportElementErrorTranslationFiles(PassportElementError):
__slots__ = ("file_hashes",)
def __init__(self, type: str, file_hashes: str, message: str, **_kwargs: Any):
def __init__(self, type: str, file_hashes: str, message: str, *, api_kwargs: JSONDict = None):
# Required
super().__init__("translation_files", type, message)
super().__init__("translation_files", type, message, api_kwargs=api_kwargs)
self.file_hashes = file_hashes
self._id_attrs = (self.source, self.type, self.message) + tuple(file_hashes)
@@ -362,7 +361,6 @@ class PassportElementErrorUnspecified(PassportElementError):
type (:obj:`str`): Type of element of the user's Telegram Passport which has the issue.
element_hash (:obj:`str`): Base64-encoded element hash.
message (:obj:`str`): Error message.
**kwargs (:obj:`dict`): Arbitrary keyword arguments.
Attributes:
type (:obj:`str`): Type of element of the user's Telegram Passport which has the issue.
@@ -373,9 +371,9 @@ class PassportElementErrorUnspecified(PassportElementError):
__slots__ = ("element_hash",)
def __init__(self, type: str, element_hash: str, message: str, **_kwargs: Any):
def __init__(self, type: str, element_hash: str, message: str, *, api_kwargs: JSONDict = None):
# Required
super().__init__("unspecified", type, message)
super().__init__("unspecified", type, message, api_kwargs=api_kwargs)
self.element_hash = element_hash
self._id_attrs = (self.source, self.type, self.element_hash, self.message)
+8 -8
View File
@@ -18,7 +18,7 @@
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents a Encrypted PassportFile."""
from typing import TYPE_CHECKING, Any, List, Optional
from typing import TYPE_CHECKING, List, Optional
from telegram._telegramobject import TelegramObject
from telegram._utils.defaultvalue import DEFAULT_NONE
@@ -44,8 +44,6 @@ class PassportFile(TelegramObject):
Can't be used to download or reuse the file.
file_size (:obj:`int`): File size in bytes.
file_date (:obj:`int`): Unix time when the file was uploaded.
bot (:class:`telegram.Bot`, optional): The Bot to use for instance methods.
**kwargs (:obj:`dict`): Arbitrary keyword arguments.
Attributes:
file_id (:obj:`str`): Identifier for this file.
@@ -54,7 +52,7 @@ class PassportFile(TelegramObject):
Can't be used to download or reuse the file.
file_size (:obj:`int`): File size in bytes.
file_date (:obj:`int`): Unix time when the file was uploaded.
bot (:class:`telegram.Bot`): Optional. The Bot to use for instance methods.
"""
@@ -72,17 +70,19 @@ class PassportFile(TelegramObject):
file_unique_id: str,
file_date: int,
file_size: int,
bot: "Bot" = None,
credentials: "FileCredentials" = None,
**_kwargs: Any,
*,
api_kwargs: JSONDict = None,
):
super().__init__(api_kwargs=api_kwargs)
# Required
self.file_id = file_id
self.file_unique_id = file_unique_id
self.file_size = file_size
self.file_date = file_date
# Optionals
self.set_bot(bot)
self._credentials = credentials
self._id_attrs = (self.file_unique_id,)
@@ -110,7 +110,7 @@ class PassportFile(TelegramObject):
data["credentials"] = credentials
return cls(bot=bot, **data)
return super().de_json(data=data, bot=bot)
@classmethod
def de_list_decrypted(
+5 -3
View File
@@ -18,10 +18,11 @@
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents a Telegram Invoice."""
from typing import Any, ClassVar
from typing import ClassVar
from telegram import constants
from telegram._telegramobject import TelegramObject
from telegram._utils.types import JSONDict
class Invoice(TelegramObject):
@@ -43,7 +44,6 @@ class Invoice(TelegramObject):
`currencies.json <https://core.telegram.org/bots/payments/currencies.json>`_,
it shows the number of digits past the decimal point for each currency
(2 for the majority of currencies).
**kwargs (:obj:`dict`): Arbitrary keyword arguments.
Attributes:
title (:obj:`str`): Product name.
@@ -69,8 +69,10 @@ class Invoice(TelegramObject):
start_parameter: str,
currency: str,
total_amount: int,
**_kwargs: Any,
*,
api_kwargs: JSONDict = None,
):
super().__init__(api_kwargs=api_kwargs)
self.title = title
self.description = description
self.start_parameter = start_parameter
+3 -4
View File
@@ -18,9 +18,8 @@
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents a Telegram LabeledPrice."""
from typing import Any
from telegram._telegramobject import TelegramObject
from telegram._utils.types import JSONDict
class LabeledPrice(TelegramObject):
@@ -39,7 +38,6 @@ class LabeledPrice(TelegramObject):
`currencies.json <https://core.telegram.org/bots/payments/currencies.json>`_,
it shows the number of digits past the decimal point for each currency
(2 for the majority of currencies).
**kwargs (:obj:`dict`): Arbitrary keyword arguments.
Attributes:
label (:obj:`str`): Portion label.
@@ -49,7 +47,8 @@ class LabeledPrice(TelegramObject):
__slots__ = ("label", "amount")
def __init__(self, label: str, amount: int, **_kwargs: Any):
def __init__(self, label: str, amount: int, *, api_kwargs: JSONDict = None):
super().__init__(api_kwargs=api_kwargs)
self.label = label
self.amount = amount
+5 -4
View File
@@ -18,7 +18,7 @@
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents a Telegram OrderInfo."""
from typing import TYPE_CHECKING, Any, Optional
from typing import TYPE_CHECKING, Optional
from telegram._payment.shippingaddress import ShippingAddress
from telegram._telegramobject import TelegramObject
@@ -40,7 +40,6 @@ class OrderInfo(TelegramObject):
phone_number (:obj:`str`, optional): User's phone number.
email (:obj:`str`, optional): User email.
shipping_address (:class:`telegram.ShippingAddress`, optional): User shipping address.
**kwargs (:obj:`dict`): Arbitrary keyword arguments.
Attributes:
name (:obj:`str`): Optional. User name.
@@ -58,8 +57,10 @@ class OrderInfo(TelegramObject):
phone_number: str = None,
email: str = None,
shipping_address: str = None,
**_kwargs: Any,
*,
api_kwargs: JSONDict = None,
):
super().__init__(api_kwargs=api_kwargs)
self.name = name
self.phone_number = phone_number
self.email = email
@@ -77,4 +78,4 @@ class OrderInfo(TelegramObject):
data["shipping_address"] = ShippingAddress.de_json(data.get("shipping_address"), bot)
return cls(**data)
return super().de_json(data=data, bot=bot)
+8 -11
View File
@@ -18,7 +18,7 @@
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents a Telegram PreCheckoutQuery."""
from typing import TYPE_CHECKING, Any, Optional
from typing import TYPE_CHECKING, Optional
from telegram._payment.orderinfo import OrderInfo
from telegram._telegramobject import TelegramObject
@@ -53,8 +53,6 @@ class PreCheckoutQuery(TelegramObject):
shipping_option_id (:obj:`str`, optional): Identifier of the shipping option chosen by the
user.
order_info (:class:`telegram.OrderInfo`, optional): Order info provided by the user.
bot (:class:`telegram.Bot`, optional): The Bot to use for instance methods.
**kwargs (:obj:`dict`): Arbitrary keyword arguments.
Attributes:
id (:obj:`str`): Unique query identifier.
@@ -65,7 +63,7 @@ class PreCheckoutQuery(TelegramObject):
shipping_option_id (:obj:`str`): Optional. Identifier of the shipping option chosen by the
user.
order_info (:class:`telegram.OrderInfo`): Optional. Order info provided by the user.
bot (:class:`telegram.Bot`): Optional. The Bot to use for instance methods.
"""
@@ -81,16 +79,17 @@ class PreCheckoutQuery(TelegramObject):
def __init__(
self,
id: str, # pylint: disable=redefined-builtin, invalid-name
id: str, # pylint: disable=redefined-builtin
from_user: User,
currency: str,
total_amount: int,
invoice_payload: str,
shipping_option_id: str = None,
order_info: OrderInfo = None,
bot: "Bot" = None,
**_kwargs: Any,
*,
api_kwargs: JSONDict = None,
):
super().__init__(api_kwargs=api_kwargs)
self.id = id # pylint: disable=invalid-name
self.from_user = from_user
self.currency = currency
@@ -99,8 +98,6 @@ class PreCheckoutQuery(TelegramObject):
self.shipping_option_id = shipping_option_id
self.order_info = order_info
self.set_bot(bot)
self._id_attrs = (self.id,)
@classmethod
@@ -111,10 +108,10 @@ class PreCheckoutQuery(TelegramObject):
if not data:
return None
data["from_user"] = User.de_json(data.pop("from"), bot)
data["from_user"] = User.de_json(data.pop("from", None), bot)
data["order_info"] = OrderInfo.de_json(data.get("order_info"), bot)
return cls(bot=bot, **data)
return super().de_json(data=data, bot=bot)
async def answer( # pylint: disable=invalid-name
self,
+4 -4
View File
@@ -18,9 +18,8 @@
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents a Telegram ShippingAddress."""
from typing import Any
from telegram._telegramobject import TelegramObject
from telegram._utils.types import JSONDict
class ShippingAddress(TelegramObject):
@@ -37,7 +36,6 @@ class ShippingAddress(TelegramObject):
street_line1 (:obj:`str`): First line for the address.
street_line2 (:obj:`str`): Second line for the address.
post_code (:obj:`str`): Address post code.
**kwargs (:obj:`dict`): Arbitrary keyword arguments.
Attributes:
country_code (:obj:`str`): ISO 3166-1 alpha-2 country code.
@@ -66,8 +64,10 @@ class ShippingAddress(TelegramObject):
street_line1: str,
street_line2: str,
post_code: str,
**_kwargs: Any,
*,
api_kwargs: JSONDict = None,
):
super().__init__(api_kwargs=api_kwargs)
self.country_code = country_code
self.state = state
self.city = city
+6 -4
View File
@@ -18,7 +18,7 @@
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents a Telegram ShippingOption."""
from typing import TYPE_CHECKING, Any, List
from typing import TYPE_CHECKING, List
from telegram._telegramobject import TelegramObject
from telegram._utils.types import JSONDict
@@ -39,7 +39,6 @@ class ShippingOption(TelegramObject):
id (:obj:`str`): Shipping option identifier.
title (:obj:`str`): Option title.
prices (List[:class:`telegram.LabeledPrice`]): List of price portions.
**kwargs (:obj:`dict`): Arbitrary keyword arguments.
Attributes:
id (:obj:`str`): Shipping option identifier.
@@ -52,11 +51,14 @@ class ShippingOption(TelegramObject):
def __init__(
self,
id: str, # pylint: disable=redefined-builtin, invalid-name
id: str, # pylint: disable=redefined-builtin
title: str,
prices: List["LabeledPrice"],
**_kwargs: Any,
*,
api_kwargs: JSONDict = None,
):
super().__init__(api_kwargs=api_kwargs)
self.id = id # pylint: disable=invalid-name
self.title = title
self.prices = prices
+8 -11
View File
@@ -18,7 +18,7 @@
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents a Telegram ShippingQuery."""
from typing import TYPE_CHECKING, Any, List, Optional
from typing import TYPE_CHECKING, List, Optional
from telegram._payment.shippingaddress import ShippingAddress
from telegram._payment.shippingoption import ShippingOption
@@ -45,15 +45,13 @@ class ShippingQuery(TelegramObject):
from_user (:class:`telegram.User`): User who sent the query.
invoice_payload (:obj:`str`): Bot specified invoice payload.
shipping_address (:class:`telegram.ShippingAddress`): User specified shipping address.
bot (:class:`telegram.Bot`, optional): The Bot to use for instance methods.
**kwargs (:obj:`dict`): Arbitrary keyword arguments.
Attributes:
id (:obj:`str`): Unique query identifier.
from_user (:class:`telegram.User`): User who sent the query.
invoice_payload (:obj:`str`): Bot specified invoice payload.
shipping_address (:class:`telegram.ShippingAddress`): User specified shipping address.
bot (:class:`telegram.Bot`): Optional. The Bot to use for instance methods.
"""
@@ -61,20 +59,19 @@ class ShippingQuery(TelegramObject):
def __init__(
self,
id: str, # pylint: disable=redefined-builtin, invalid-name
id: str, # pylint: disable=redefined-builtin
from_user: User,
invoice_payload: str,
shipping_address: ShippingAddress,
bot: "Bot" = None,
**_kwargs: Any,
*,
api_kwargs: JSONDict = None,
):
super().__init__(api_kwargs=api_kwargs)
self.id = id # pylint: disable=invalid-name
self.from_user = from_user
self.invoice_payload = invoice_payload
self.shipping_address = shipping_address
self.set_bot(bot)
self._id_attrs = (self.id,)
@classmethod
@@ -85,10 +82,10 @@ class ShippingQuery(TelegramObject):
if not data:
return None
data["from_user"] = User.de_json(data.pop("from"), bot)
data["from_user"] = User.de_json(data.pop("from", None), bot)
data["shipping_address"] = ShippingAddress.de_json(data.get("shipping_address"), bot)
return cls(bot=bot, **data)
return super().de_json(data=data, bot=bot)
async def answer( # pylint: disable=invalid-name
self,
+5 -4
View File
@@ -18,7 +18,7 @@
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents a Telegram SuccessfulPayment."""
from typing import TYPE_CHECKING, Any, Optional
from typing import TYPE_CHECKING, Optional
from telegram._payment.orderinfo import OrderInfo
from telegram._telegramobject import TelegramObject
@@ -49,7 +49,6 @@ class SuccessfulPayment(TelegramObject):
order_info (:class:`telegram.OrderInfo`, optional): Order info provided by the user.
telegram_payment_charge_id (:obj:`str`): Telegram payment identifier.
provider_payment_charge_id (:obj:`str`): Provider payment identifier.
**kwargs (:obj:`dict`): Arbitrary keyword arguments.
Attributes:
currency (:obj:`str`): Three-letter ISO 4217 currency code.
@@ -82,8 +81,10 @@ class SuccessfulPayment(TelegramObject):
provider_payment_charge_id: str,
shipping_option_id: str = None,
order_info: OrderInfo = None,
**_kwargs: Any,
*,
api_kwargs: JSONDict = None,
):
super().__init__(api_kwargs=api_kwargs)
self.currency = currency
self.total_amount = total_amount
self.invoice_payload = invoice_payload
@@ -104,4 +105,4 @@ class SuccessfulPayment(TelegramObject):
data["order_info"] = OrderInfo.de_json(data.get("order_info"), bot)
return cls(**data)
return super().de_json(data=data, bot=bot)
+13 -7
View File
@@ -20,7 +20,7 @@
import datetime
import sys
from typing import TYPE_CHECKING, Any, ClassVar, Dict, List, Optional
from typing import TYPE_CHECKING, ClassVar, Dict, List, Optional
from telegram import constants
from telegram._messageentity import MessageEntity
@@ -53,7 +53,8 @@ class PollOption(TelegramObject):
__slots__ = ("voter_count", "text")
def __init__(self, text: str, voter_count: int, **_kwargs: Any):
def __init__(self, text: str, voter_count: int, *, api_kwargs: JSONDict = None):
super().__init__(api_kwargs=api_kwargs)
self.text = text
self.voter_count = voter_count
@@ -85,7 +86,10 @@ class PollAnswer(TelegramObject):
__slots__ = ("option_ids", "user", "poll_id")
def __init__(self, poll_id: str, user: User, option_ids: List[int], **_kwargs: Any):
def __init__(
self, poll_id: str, user: User, option_ids: List[int], *, api_kwargs: JSONDict = None
):
super().__init__(api_kwargs=api_kwargs)
self.poll_id = poll_id
self.user = user
self.option_ids = option_ids
@@ -102,7 +106,7 @@ class PollAnswer(TelegramObject):
data["user"] = User.de_json(data.get("user"), bot)
return cls(**data)
return super().de_json(data=data, bot=bot)
class Poll(TelegramObject):
@@ -177,7 +181,7 @@ class Poll(TelegramObject):
def __init__(
self,
id: str, # pylint: disable=redefined-builtin, invalid-name
id: str, # pylint: disable=redefined-builtin
question: str,
options: List[PollOption],
total_voter_count: int,
@@ -190,8 +194,10 @@ class Poll(TelegramObject):
explanation_entities: List[MessageEntity] = None,
open_period: int = None,
close_date: datetime.datetime = None,
**_kwargs: Any,
*,
api_kwargs: JSONDict = None,
):
super().__init__(api_kwargs=api_kwargs)
self.id = id # pylint: disable=invalid-name
self.question = question
self.options = options
@@ -220,7 +226,7 @@ class Poll(TelegramObject):
data["explanation_entities"] = MessageEntity.de_list(data.get("explanation_entities"), bot)
data["close_date"] = from_timestamp(data.get("close_date"))
return cls(**data)
return super().de_json(data=data, bot=bot)
def to_dict(self) -> JSONDict:
"""See :meth:`telegram.TelegramObject.to_dict`."""
+6 -3
View File
@@ -17,7 +17,7 @@
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents a Telegram Proximity Alert."""
from typing import TYPE_CHECKING, Any, Optional
from typing import TYPE_CHECKING, Optional
from telegram._telegramobject import TelegramObject
from telegram._user import User
@@ -49,7 +49,10 @@ class ProximityAlertTriggered(TelegramObject):
__slots__ = ("traveler", "distance", "watcher")
def __init__(self, traveler: User, watcher: User, distance: int, **_kwargs: Any):
def __init__(
self, traveler: User, watcher: User, distance: int, *, api_kwargs: JSONDict = None
):
super().__init__(api_kwargs=api_kwargs)
self.traveler = traveler
self.watcher = watcher
self.distance = distance
@@ -67,4 +70,4 @@ class ProximityAlertTriggered(TelegramObject):
data["traveler"] = User.de_json(data.get("traveler"), bot)
data["watcher"] = User.de_json(data.get("watcher"), bot)
return cls(bot=bot, **data)
return super().de_json(data=data, bot=bot)
+7 -10
View File
@@ -18,7 +18,7 @@
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents a Telegram ReplyKeyboardMarkup."""
from typing import Any, List, Sequence, Union
from typing import List, Sequence, Union
from telegram._keyboardbutton import KeyboardButton
from telegram._telegramobject import TelegramObject
@@ -62,8 +62,6 @@ class ReplyKeyboardMarkup(TelegramObject):
.. versionadded:: 13.7
**kwargs (:obj:`dict`): Arbitrary keyword arguments.
Attributes:
keyboard (List[List[:class:`telegram.KeyboardButton` | :obj:`str`]]): Array of button rows.
resize_keyboard (:obj:`bool`): Optional. Requests clients to resize the keyboard.
@@ -92,8 +90,10 @@ class ReplyKeyboardMarkup(TelegramObject):
one_time_keyboard: bool = None,
selective: bool = None,
input_field_placeholder: str = None,
**_kwargs: Any,
*,
api_kwargs: JSONDict = None,
):
super().__init__(api_kwargs=api_kwargs)
if not check_keyboard_type(keyboard):
raise ValueError(
"The parameter `keyboard` should be a list of list of "
@@ -169,7 +169,6 @@ class ReplyKeyboardMarkup(TelegramObject):
field when the reply is active.
.. versionadded:: 13.7
**kwargs (:obj:`dict`): Arbitrary keyword arguments.
"""
return cls(
[[button]],
@@ -177,7 +176,7 @@ class ReplyKeyboardMarkup(TelegramObject):
one_time_keyboard=one_time_keyboard,
selective=selective,
input_field_placeholder=input_field_placeholder,
**kwargs,
**kwargs, # type: ignore[arg-type]
)
@classmethod
@@ -221,7 +220,6 @@ class ReplyKeyboardMarkup(TelegramObject):
field when the reply is active.
.. versionadded:: 13.7
**kwargs (:obj:`dict`): Arbitrary keyword arguments.
"""
return cls(
@@ -230,7 +228,7 @@ class ReplyKeyboardMarkup(TelegramObject):
one_time_keyboard=one_time_keyboard,
selective=selective,
input_field_placeholder=input_field_placeholder,
**kwargs,
**kwargs, # type: ignore[arg-type]
)
@classmethod
@@ -274,7 +272,6 @@ class ReplyKeyboardMarkup(TelegramObject):
field when the reply is active.
.. versionadded:: 13.7
**kwargs (:obj:`dict`): Arbitrary keyword arguments.
"""
button_grid = [[button] for button in button_column]
@@ -284,7 +281,7 @@ class ReplyKeyboardMarkup(TelegramObject):
one_time_keyboard=one_time_keyboard,
selective=selective,
input_field_placeholder=input_field_placeholder,
**kwargs,
**kwargs, # type: ignore[arg-type]
)
def __hash__(self) -> int:
+3 -4
View File
@@ -17,9 +17,9 @@
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents a Telegram ReplyKeyboardRemove."""
from typing import Any
from telegram._telegramobject import TelegramObject
from telegram._utils.types import JSONDict
class ReplyKeyboardRemove(TelegramObject):
@@ -46,8 +46,6 @@ class ReplyKeyboardRemove(TelegramObject):
2) If the bot's message is a reply (has `reply_to_message_id`), sender of the original
message.
**kwargs (:obj:`dict`): Arbitrary keyword arguments.
Attributes:
remove_keyboard (:obj:`True`): Requests clients to remove the custom keyboard.
selective (:obj:`bool`): Optional. Use this parameter if you want to remove the keyboard
@@ -57,7 +55,8 @@ class ReplyKeyboardRemove(TelegramObject):
__slots__ = ("selective", "remove_keyboard")
def __init__(self, selective: bool = None, **_kwargs: Any):
def __init__(self, selective: bool = None, *, api_kwargs: JSONDict = None):
super().__init__(api_kwargs=api_kwargs)
# Required
self.remove_keyboard = True
# Optionals
+3 -3
View File
@@ -18,9 +18,8 @@
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents a Telegram Sent Web App Message."""
from typing import Any
from telegram._telegramobject import TelegramObject
from telegram._utils.types import JSONDict
class SentWebAppMessage(TelegramObject):
@@ -44,7 +43,8 @@ class SentWebAppMessage(TelegramObject):
__slots__ = ("inline_message_id",)
def __init__(self, inline_message_id: str = None, **_kwargs: Any):
def __init__(self, inline_message_id: str = None, *, api_kwargs: JSONDict = None):
super().__init__(api_kwargs=api_kwargs)
# Optionals
self.inline_message_id = inline_message_id
+97 -26
View File
@@ -17,9 +17,10 @@
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""Base class for Telegram Objects."""
import inspect
import json
from copy import deepcopy
from typing import TYPE_CHECKING, Dict, List, Optional, Tuple, Type, TypeVar, Union
from typing import TYPE_CHECKING, Dict, List, Optional, Set, Tuple, Type, TypeVar, Union
from telegram._utils.types import JSONDict
from telegram._utils.warnings import warn
@@ -44,28 +45,59 @@ class TelegramObject:
assert telegram_object.get_bot() is copy.deepcopy(telegram_object).get_bot()
.. versionchanged:: 20.0
``telegram_object['from']`` will look up the key ``from_user``. This is to account for
special cases like :attr:`Message.from_user` that deviate from the official Bot API.
* ``telegram_object['from']`` will look up the key ``from_user``. This is to account for
special cases like :attr:`Message.from_user` that deviate from the official Bot API.
* Removed argument and attribute ``bot`` for several subclasses. Use
:meth:`set_bot` and :meth:`get_bot` instead.
* Removed the possibility to pass arbitrary keyword arguments for several subclasses.
Arguments:
api_kwargs (Dict[:obj:`str`, any], optional): |toapikwargsarg|
.. versionadded:: 20.0
Attributes:
api_kwargs (Dict[:obj:`str`, any]): |toapikwargsattr|
.. versionadded:: 20.0
"""
# type hints in __new__ are not read by mypy (https://github.com/python/mypy/issues/1021). As a
# workaround we can type hint instance variables in __new__ using a syntax defined in PEP 526 -
# https://www.python.org/dev/peps/pep-0526/#class-and-instance-variable-annotations
if TYPE_CHECKING:
_id_attrs: Tuple[object, ...]
_bot: Optional["Bot"]
# Adding slots reduces memory usage & allows for faster attribute access.
# Only instance variables should be added to __slots__.
__slots__ = ("_id_attrs", "_bot")
__slots__ = ("_id_attrs", "_bot", "api_kwargs")
# pylint: disable=unused-argument
def __new__(cls, *args: object, **kwargs: object) -> "TelegramObject":
# We add _id_attrs in __new__ instead of __init__ since we want to add this to the slots
# w/o calling __init__ in all of the subclasses.
instance = super().__new__(cls)
instance._id_attrs = ()
instance._bot = None
return instance
# Used to cache the names of the parameters of the __init__ method of the class
# Must be a private attribute to avoid name clashes between subclasses
__INIT_PARAMS: Set[str] = set()
# Used to check if __INIT_PARAMS has been set for the current class. Unfortunately, we can't
# just check if `__INIT_PARAMS is None`, since subclasses use the parent class' __INIT_PARAMS
# unless it's overridden
__INIT_PARAMS_CHECK: Optional[Type["TelegramObject"]] = None
def __init__(self, *, api_kwargs: JSONDict = None) -> None:
self._id_attrs: Tuple[object, ...] = ()
self._bot: Optional["Bot"] = None
# We don't do anything with api_kwargs here - see docstring of _apply_api_kwargs
self.api_kwargs: JSONDict = api_kwargs or {}
def _apply_api_kwargs(self) -> None:
"""Loops through the api kwargs and for every key that exists as attribute of the
object (and is None), it moves the value from `api_kwargs` to the attribute.
This method is currently only called in the unpickling process, i.e. not on "normal" init.
This is because
* automating this is tricky to get right: It should be called at the *end* of the __init__,
preferably only once at the end of the __init__ of the last child class. This could be
done via __init_subclass__, but it's hard to not destroy the signature of __init__ in the
process.
* calling it manually in every __init__ is tedious
* There probably is no use case for it anyway. If you manually initialize a TO subclass,
then you can pass everything as proper argument.
"""
# we convert to list to ensure that the list doesn't change length while we loop
for key in list(self.api_kwargs.keys()):
if getattr(self, key, True) is None:
setattr(self, key, self.api_kwargs.pop(key))
def __str__(self) -> str:
return str(self.to_dict())
@@ -93,8 +125,13 @@ class TelegramObject:
This method is used for unpickling. The data, which is in the form a dictionary, is
converted back into a class. Should be modified in place.
"""
# Make sure that we have a `_bot` attribute. This is necessary, since __getstate__ omits
# this as Bots are not pickable.
setattr(self, "_bot", None)
for key, val in state.items():
setattr(self, key, val)
self._apply_api_kwargs()
def __deepcopy__(self: Tele_co, memodict: dict) -> Tele_co:
"""This method deepcopies the object and sets the bot on the newly created copy."""
@@ -111,7 +148,7 @@ class TelegramObject:
result.set_bot(bot) # Assign the bots back
self.set_bot(bot)
return result # type: ignore[return-value]
return result
def _get_attrs(
self,
@@ -163,6 +200,10 @@ class TelegramObject:
@staticmethod
def _parse_data(data: Optional[JSONDict]) -> Optional[JSONDict]:
"""Should be called by subclasses that override de_json to ensure that the input
is not altered. Whoever calls de_json might still want to use the original input
for something else.
"""
return None if data is None else data.copy()
@classmethod
@@ -177,14 +218,36 @@ class TelegramObject:
The Telegram object.
"""
data = cls._parse_data(data)
return cls._de_json(data=data, bot=bot)
@classmethod
def _de_json(
cls: Type[Tele_co], data: Optional[JSONDict], bot: "Bot", api_kwargs: JSONDict = None
) -> Optional[Tele_co]:
if data is None:
return None
if cls == TelegramObject:
return cls()
return cls(bot=bot, **data)
# try-except is significantly faster in case we already have a correct argument set
try:
obj = cls(**data, api_kwargs=api_kwargs)
except TypeError as exc:
if "__init__() got an unexpected keyword argument" not in str(exc):
raise exc
if cls.__INIT_PARAMS_CHECK is not cls:
signature = inspect.signature(cls)
cls.__INIT_PARAMS = set(signature.parameters.keys())
cls.__INIT_PARAMS_CHECK = cls
api_kwargs = api_kwargs or {}
existing_kwargs: JSONDict = {}
for key, value in data.items():
(existing_kwargs if key in cls.__INIT_PARAMS else api_kwargs)[key] = value
obj = cls(api_kwargs=api_kwargs, **existing_kwargs)
obj.set_bot(bot=bot)
return obj
@classmethod
def de_list(
@@ -208,6 +271,9 @@ class TelegramObject:
def to_json(self) -> str:
"""Gives a JSON representation of object.
.. versionchanged:: 20.0
Now includes all entries of :attr:`api_kwargs`.
Returns:
:obj:`str`
"""
@@ -216,10 +282,15 @@ class TelegramObject:
def to_dict(self) -> JSONDict:
"""Gives representation of object as :obj:`dict`.
.. versionchanged:: 20.0
Now includes all entries of :attr:`api_kwargs`.
Returns:
:obj:`dict`
"""
return self._get_attrs(recursive=True)
out = self._get_attrs(recursive=True)
out.update(out.pop("api_kwargs", {})) # type: ignore[call-overload]
return out
def get_bot(self) -> "Bot":
"""Returns the :class:`telegram.Bot` instance associated with this object.
+5 -5
View File
@@ -18,7 +18,7 @@
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents a Telegram Update."""
from typing import TYPE_CHECKING, Any, ClassVar, List, Optional
from typing import TYPE_CHECKING, ClassVar, List, Optional
from telegram import constants
from telegram._callbackquery import CallbackQuery
@@ -94,8 +94,6 @@ class Update(TelegramObject):
receive these updates.
.. versionadded:: 13.8
**kwargs (:obj:`dict`): Arbitrary keyword arguments.
Attributes:
update_id (:obj:`int`): The update's unique identifier.
message (:class:`telegram.Message`): Optional. New incoming message.
@@ -236,8 +234,10 @@ class Update(TelegramObject):
my_chat_member: ChatMemberUpdated = None,
chat_member: ChatMemberUpdated = None,
chat_join_request: ChatJoinRequest = None,
**_kwargs: Any,
*,
api_kwargs: JSONDict = None,
):
super().__init__(api_kwargs=api_kwargs)
# Required
self.update_id = update_id
# Optionals
@@ -421,4 +421,4 @@ class Update(TelegramObject):
data["chat_member"] = ChatMemberUpdated.de_json(data.get("chat_member"), bot)
data["chat_join_request"] = ChatJoinRequest.de_json(data.get("chat_join_request"), bot)
return cls(**data)
return super().de_json(data=data, bot=bot)
+6 -10
View File
@@ -19,7 +19,7 @@
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents a Telegram User."""
from datetime import datetime
from typing import TYPE_CHECKING, Any, List, Optional, Tuple, Union
from typing import TYPE_CHECKING, List, Optional, Tuple, Union
from telegram._inline.inlinekeyboardbutton import InlineKeyboardButton
from telegram._menubutton import MenuButton
@@ -33,7 +33,6 @@ if TYPE_CHECKING:
from telegram import (
Animation,
Audio,
Bot,
Contact,
Document,
InlineKeyboardMarkup,
@@ -63,7 +62,6 @@ class User(TelegramObject):
considered equal, if their :attr:`id` is equal.
.. versionchanged:: 20.0
The following are now keyword-only arguments in Bot methods:
``location``, ``filename``, ``venue``, ``contact``,
``{read, write, connect, pool}_timeout`` ``api_kwargs``. Use a named argument for those,
@@ -82,7 +80,7 @@ class User(TelegramObject):
disabled for the bot. Returned only in :attr:`telegram.Bot.get_me` requests.
supports_inline_queries (:obj:`str`, optional): :obj:`True`, if the bot supports inline
queries. Returned only in :attr:`telegram.Bot.get_me` requests.
bot (:class:`telegram.Bot`, optional): The Bot to use for instance methods.
is_premium (:obj:`bool`, optional): :obj:`True`, if this user is a Telegram Premium user.
.. versionadded:: 20.0
@@ -90,7 +88,6 @@ class User(TelegramObject):
the bot to the attachment menu.
.. versionadded:: 20.0
Attributes:
id (:obj:`int`): Unique identifier for this user or bot.
is_bot (:obj:`bool`): :obj:`True`, if this user is a bot.
@@ -104,7 +101,6 @@ class User(TelegramObject):
disabled for the bot. Returned only in :attr:`telegram.Bot.get_me` requests.
supports_inline_queries (:obj:`str`): Optional. :obj:`True`, if the bot supports inline
queries. Returned only in :attr:`telegram.Bot.get_me` requests.
bot (:class:`telegram.Bot`): Optional. The Bot to use for instance methods.
is_premium (:obj:`bool`): Optional. :obj:`True`, if this user is a Telegram
Premium user.
@@ -131,7 +127,7 @@ class User(TelegramObject):
def __init__(
self,
id: int, # pylint: disable=invalid-name
id: int,
first_name: str,
is_bot: bool,
last_name: str = None,
@@ -140,11 +136,12 @@ class User(TelegramObject):
can_join_groups: bool = None,
can_read_all_group_messages: bool = None,
supports_inline_queries: bool = None,
bot: "Bot" = None,
is_premium: bool = None,
added_to_attachment_menu: bool = None,
**_kwargs: Any,
*,
api_kwargs: JSONDict = None,
):
super().__init__(api_kwargs=api_kwargs)
# Required
self.id = id # pylint: disable=invalid-name
self.first_name = first_name
@@ -158,7 +155,6 @@ class User(TelegramObject):
self.supports_inline_queries = supports_inline_queries
self.is_premium = is_premium
self.added_to_attachment_menu = added_to_attachment_menu
self.set_bot(bot)
self._id_attrs = (self.id,)
+6 -3
View File
@@ -18,7 +18,7 @@
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents a Telegram UserProfilePhotos."""
from typing import TYPE_CHECKING, Any, List, Optional
from typing import TYPE_CHECKING, List, Optional
from telegram._files.photosize import PhotoSize
from telegram._telegramobject import TelegramObject
@@ -47,7 +47,10 @@ class UserProfilePhotos(TelegramObject):
__slots__ = ("photos", "total_count")
def __init__(self, total_count: int, photos: List[List[PhotoSize]], **_kwargs: Any):
def __init__(
self, total_count: int, photos: List[List[PhotoSize]], *, api_kwargs: JSONDict = None
):
super().__init__(api_kwargs=api_kwargs)
# Required
self.total_count = total_count
self.photos = photos
@@ -64,7 +67,7 @@ class UserProfilePhotos(TelegramObject):
data["photos"] = [PhotoSize.de_list(photo, bot) for photo in data["photos"]]
return cls(**data)
return super().de_json(data=data, bot=bot)
def to_dict(self) -> JSONDict:
"""See :meth:`telegram.TelegramObject.to_dict`."""
-1
View File
@@ -75,7 +75,6 @@ class DefaultValue(Generic[DVType]):
Args:
value (:class:`object`): The value of the default argument
Attributes:
value (:class:`object`): The value of the default argument
+23 -12
View File
@@ -42,9 +42,6 @@ class VideoChatStarted(TelegramObject):
__slots__ = ()
def __init__(self, **_kwargs: object): # skipcq: PTC-W0049
pass
class VideoChatEnded(TelegramObject):
"""
@@ -61,7 +58,6 @@ class VideoChatEnded(TelegramObject):
Args:
duration (:obj:`int`): Voice chat duration in seconds.
**kwargs (:obj:`dict`): Arbitrary keyword arguments.
Attributes:
duration (:obj:`int`): Voice chat duration in seconds.
@@ -70,7 +66,13 @@ class VideoChatEnded(TelegramObject):
__slots__ = ("duration",)
def __init__(self, duration: int, **_kwargs: object) -> None:
def __init__(
self,
duration: int,
*,
api_kwargs: JSONDict = None,
) -> None:
super().__init__(api_kwargs=api_kwargs)
self.duration = duration
self._id_attrs = (self.duration,)
@@ -88,7 +90,6 @@ class VideoChatParticipantsInvited(TelegramObject):
Args:
users (List[:class:`telegram.User`]): New members that were invited to the video chat.
**kwargs (:obj:`dict`): Arbitrary keyword arguments.
Attributes:
users (List[:class:`telegram.User`]): New members that were invited to the video chat.
@@ -97,7 +98,13 @@ class VideoChatParticipantsInvited(TelegramObject):
__slots__ = ("users",)
def __init__(self, users: List[User], **_kwargs: object) -> None:
def __init__(
self,
users: List[User],
*,
api_kwargs: JSONDict = None,
) -> None:
super().__init__(api_kwargs=api_kwargs)
self.users = users
self._id_attrs = (self.users,)
@@ -112,7 +119,7 @@ class VideoChatParticipantsInvited(TelegramObject):
return None
data["users"] = User.de_list(data.get("users", []), bot)
return cls(**data)
return super().de_json(data=data, bot=bot)
def to_dict(self) -> JSONDict:
"""See :meth:`telegram.TelegramObject.to_dict`."""
@@ -138,8 +145,6 @@ class VideoChatScheduled(TelegramObject):
Args:
start_date (:obj:`datetime.datetime`): Point in time (Unix timestamp) when the video
chat is supposed to be started by a chat administrator
**kwargs (:obj:`dict`): Arbitrary keyword arguments.
Attributes:
start_date (:obj:`datetime.datetime`): Point in time (Unix timestamp) when the video
chat is supposed to be started by a chat administrator
@@ -148,7 +153,13 @@ class VideoChatScheduled(TelegramObject):
__slots__ = ("start_date",)
def __init__(self, start_date: dtm.datetime, **_kwargs: object) -> None:
def __init__(
self,
start_date: dtm.datetime,
*,
api_kwargs: JSONDict = None,
) -> None:
super().__init__(api_kwargs=api_kwargs)
self.start_date = start_date
self._id_attrs = (self.start_date,)
@@ -163,7 +174,7 @@ class VideoChatScheduled(TelegramObject):
data["start_date"] = from_timestamp(data["start_date"])
return cls(**data, bot=bot)
return super().de_json(data=data, bot=bot)
def to_dict(self) -> JSONDict:
"""See :meth:`telegram.TelegramObject.to_dict`."""
+3 -3
View File
@@ -18,9 +18,8 @@
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents a Telegram WebAppData."""
from typing import Any
from telegram._telegramobject import TelegramObject
from telegram._utils.types import JSONDict
class WebAppData(TelegramObject):
@@ -52,7 +51,8 @@ class WebAppData(TelegramObject):
__slots__ = ("data", "button_text")
def __init__(self, data: str, button_text: str, **_kwargs: Any):
def __init__(self, data: str, button_text: str, *, api_kwargs: JSONDict = None):
super().__init__(api_kwargs=api_kwargs)
# Required
self.data = data
self.button_text = button_text
+3 -3
View File
@@ -18,9 +18,8 @@
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents a Telegram Web App Info."""
from typing import Any
from telegram._telegramobject import TelegramObject
from telegram._utils.types import JSONDict
class WebAppInfo(TelegramObject):
@@ -47,7 +46,8 @@ class WebAppInfo(TelegramObject):
__slots__ = ("url",)
def __init__(self, url: str, **_kwargs: Any):
def __init__(self, url: str, *, api_kwargs: JSONDict = None):
super().__init__(api_kwargs=api_kwargs)
# Required
self.url = url
+5 -4
View File
@@ -18,7 +18,7 @@
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents a Telegram WebhookInfo."""
from typing import TYPE_CHECKING, Any, List, Optional
from typing import TYPE_CHECKING, List, Optional
from telegram._telegramobject import TelegramObject
from telegram._utils.datetime import from_timestamp
@@ -61,7 +61,6 @@ class WebhookInfo(TelegramObject):
that happened when trying to synchronize available updates with Telegram datacenters.
.. versionadded:: 20.0
Attributes:
url (:obj:`str`): Webhook URL.
has_custom_certificate (:obj:`bool`): If a custom certificate was provided for webhook.
@@ -102,8 +101,10 @@ class WebhookInfo(TelegramObject):
allowed_updates: List[str] = None,
ip_address: str = None,
last_synchronization_error_date: int = None,
**_kwargs: Any,
*,
api_kwargs: JSONDict = None,
):
super().__init__(api_kwargs=api_kwargs)
# Required
self.url = url
self.has_custom_certificate = has_custom_certificate
@@ -142,4 +143,4 @@ class WebhookInfo(TelegramObject):
data.get("last_synchronization_error_date")
)
return cls(bot=bot, **data)
return super().de_json(data=data, bot=bot)
-1
View File
@@ -128,7 +128,6 @@ class BasePersistence(Generic[UD, CD, BD], ABC):
seconds.
.. versionadded:: 20.0
Attributes:
store_data (:class:`PersistenceInput`): Specifies which kinds of data will be saved by this
persistence instance.

Some files were not shown because too many files have changed in this diff Show More