Add new autogenerated methods and types and add prototype of sessions.

This commit is contained in:
Alex Root Junior 2019-11-03 22:14:41 +02:00
parent 43c565d39b
commit 278999761c
173 changed files with 7717 additions and 2793 deletions

File diff suppressed because it is too large Load diff

View file

View file

@ -0,0 +1,18 @@
from typing import TypeVar
from ..methods import TelegramMethod
from ..session.aiohttp import AiohttpSession
from ..session.base import BaseSession
T = TypeVar("T")
class BaseBot:
def __init__(self, token: str, session: BaseSession = None):
if session is None:
session = AiohttpSession()
self.session = session
self.token = token
async def emit(self, method: TelegramMethod[T]) -> T:
return await self.session.make_request(self.token, method)

2144
aiogram/api/client/bot.py Normal file

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,137 @@
from .add_sticker_to_set import AddStickerToSet
from .answer_callback_query import AnswerCallbackQuery
from .answer_inline_query import AnswerInlineQuery
from .answer_pre_checkout_query import AnswerPreCheckoutQuery
from .answer_shipping_query import AnswerShippingQuery
from .base import Request, Response, TelegramMethod
from .create_new_sticker_set import CreateNewStickerSet
from .delete_chat_photo import DeleteChatPhoto
from .delete_chat_sticker_set import DeleteChatStickerSet
from .delete_message import DeleteMessage
from .delete_sticker_from_set import DeleteStickerFromSet
from .delete_webhook import DeleteWebhook
from .edit_message_caption import EditMessageCaption
from .edit_message_live_location import EditMessageLiveLocation
from .edit_message_media import EditMessageMedia
from .edit_message_reply_markup import EditMessageReplyMarkup
from .edit_message_text import EditMessageText
from .export_chat_invite_link import ExportChatInviteLink
from .forward_message import ForwardMessage
from .get_chat import GetChat
from .get_chat_administrators import GetChatAdministrators
from .get_chat_member import GetChatMember
from .get_chat_members_count import GetChatMembersCount
from .get_file import GetFile
from .get_game_high_scores import GetGameHighScores
from .get_me import GetMe
from .get_sticker_set import GetStickerSet
from .get_updates import GetUpdates
from .get_user_profile_photos import GetUserProfilePhotos
from .get_webhook_info import GetWebhookInfo
from .kick_chat_member import KickChatMember
from .leave_chat import LeaveChat
from .pin_chat_message import PinChatMessage
from .promote_chat_member import PromoteChatMember
from .restrict_chat_member import RestrictChatMember
from .send_animation import SendAnimation
from .send_audio import SendAudio
from .send_chat_action import SendChatAction
from .send_contact import SendContact
from .send_document import SendDocument
from .send_game import SendGame
from .send_invoice import SendInvoice
from .send_location import SendLocation
from .send_media_group import SendMediaGroup
from .send_message import SendMessage
from .send_photo import SendPhoto
from .send_poll import SendPoll
from .send_sticker import SendSticker
from .send_venue import SendVenue
from .send_video import SendVideo
from .send_video_note import SendVideoNote
from .send_voice import SendVoice
from .set_chat_description import SetChatDescription
from .set_chat_permissions import SetChatPermissions
from .set_chat_photo import SetChatPhoto
from .set_chat_sticker_set import SetChatStickerSet
from .set_chat_title import SetChatTitle
from .set_game_score import SetGameScore
from .set_passport_data_errors import SetPassportDataErrors
from .set_sticker_position_in_set import SetStickerPositionInSet
from .set_webhook import SetWebhook
from .stop_message_live_location import StopMessageLiveLocation
from .stop_poll import StopPoll
from .unban_chat_member import UnbanChatMember
from .unpin_chat_message import UnpinChatMessage
from .upload_sticker_file import UploadStickerFile
__all__ = (
"TelegramMethod",
"Request",
"Response",
"GetUpdates",
"SetWebhook",
"DeleteWebhook",
"GetWebhookInfo",
"GetMe",
"SendMessage",
"ForwardMessage",
"SendPhoto",
"SendAudio",
"SendDocument",
"SendVideo",
"SendAnimation",
"SendVoice",
"SendVideoNote",
"SendMediaGroup",
"SendLocation",
"EditMessageLiveLocation",
"StopMessageLiveLocation",
"SendVenue",
"SendContact",
"SendPoll",
"SendChatAction",
"GetUserProfilePhotos",
"GetFile",
"KickChatMember",
"UnbanChatMember",
"RestrictChatMember",
"PromoteChatMember",
"SetChatPermissions",
"ExportChatInviteLink",
"SetChatPhoto",
"DeleteChatPhoto",
"SetChatTitle",
"SetChatDescription",
"PinChatMessage",
"UnpinChatMessage",
"LeaveChat",
"GetChat",
"GetChatAdministrators",
"GetChatMembersCount",
"GetChatMember",
"SetChatStickerSet",
"DeleteChatStickerSet",
"AnswerCallbackQuery",
"EditMessageText",
"EditMessageCaption",
"EditMessageMedia",
"EditMessageReplyMarkup",
"StopPoll",
"DeleteMessage",
"SendSticker",
"GetStickerSet",
"UploadStickerFile",
"CreateNewStickerSet",
"AddStickerToSet",
"SetStickerPositionInSet",
"DeleteStickerFromSet",
"AnswerInlineQuery",
"SendInvoice",
"AnswerShippingQuery",
"AnswerPreCheckoutQuery",
"SetPassportDataErrors",
"SendGame",
"SetGameScore",
"GetGameHighScores",
)

View file

@ -0,0 +1,34 @@
from typing import Any, Dict, Optional, Union
from ..types import InputFile, MaskPosition
from .base import Request, TelegramMethod
class AddStickerToSet(TelegramMethod[bool]):
"""
Use this method to add a new sticker to a set created by the bot. Returns True on success.
Source: https://core.telegram.org/bots/api#addstickertoset
"""
__returning__ = bool
user_id: int
"""User identifier of sticker set owner"""
name: str
"""Sticker set name"""
png_sticker: Union[InputFile, str]
"""Png image with the sticker, must be up to 512 kilobytes in size, dimensions must not exceed 512px, and either width or height must be exactly 512px. Pass a file_id as a String to send a file that already exists on the Telegram servers, pass an HTTP URL as a String for Telegram to get a file from the Internet, or upload a new one using multipart/form-data."""
emojis: str
"""One or more emoji corresponding to the sticker"""
mask_position: Optional[MaskPosition] = None
"""A JSON-serialized object for position where the mask should be placed on faces"""
def build_request(self) -> Request:
data: Dict[str, Any] = self.dict(exclude_unset=True, exclude={})
files: Dict[str, Any] = {}
return Request(method="addStickerToSet", data=data, files=files)

View file

@ -0,0 +1,36 @@
from typing import Any, Dict, Optional
from .base import Request, TelegramMethod
class AnswerCallbackQuery(TelegramMethod[bool]):
"""
Use this method to send answers to callback queries sent from inline keyboards. The answer will be displayed to the user as a notification at the top of the chat screen or as an alert. On success, True is returned.
Alternatively, the user can be redirected to the specified Game URL. For this option to work, you must first create a game for your bot via @Botfather and accept the terms. Otherwise, you may use links like t.me/your_bot?start=XXXX that open your bot with a parameter.
Source: https://core.telegram.org/bots/api#answercallbackquery
"""
__returning__ = bool
callback_query_id: str
"""Unique identifier for the query to be answered"""
text: Optional[str] = None
"""Text of the notification. If not specified, nothing will be shown to the user, 0-200 characters"""
show_alert: Optional[bool] = None
"""If true, an alert will be shown by the client instead of a notification at the top of the chat screen. Defaults to false."""
url: Optional[str] = None
"""URL that will be opened by the user's client. If you have created a Game and accepted the conditions via @Botfather, specify the URL that opens your game note that this will only work if the query comes from a callback_game button.
Otherwise, you may use links like t.me/your_bot?start=XXXX that open your bot with a parameter."""
cache_time: Optional[int] = None
"""The maximum amount of time in seconds that the result of the callback query may be cached client-side. Telegram apps will support caching starting in version 3.14. Defaults to 0."""
def build_request(self) -> Request:
data: Dict[str, Any] = self.dict(exclude_unset=True, exclude={})
files: Dict[str, Any] = {}
return Request(method="answerCallbackQuery", data=data, files=files)

View file

@ -0,0 +1,43 @@
from typing import Any, Dict, List, Optional
from ..types import InlineQueryResult
from .base import Request, TelegramMethod
class AnswerInlineQuery(TelegramMethod[bool]):
"""
Use this method to send answers to an inline query. On success, True is returned.
No more than 50 results per query are allowed.
Source: https://core.telegram.org/bots/api#answerinlinequery
"""
__returning__ = bool
inline_query_id: str
"""Unique identifier for the answered query"""
results: List[InlineQueryResult]
"""A JSON-serialized array of results for the inline query"""
cache_time: Optional[int] = None
"""The maximum amount of time in seconds that the result of the inline query may be cached on the server. Defaults to 300."""
is_personal: Optional[bool] = None
"""Pass True, if results may be cached on the server side only for the user that sent the query. By default, results may be returned to any user who sends the same query"""
next_offset: Optional[str] = None
"""Pass the offset that a client should send in the next query with the same text to receive more results. Pass an empty string if there are no more results or if you dont support pagination. Offset length cant exceed 64 bytes."""
switch_pm_text: Optional[str] = None
"""If passed, clients will display a button with specified text that switches the user to a private chat with the bot and sends the bot a start message with the parameter switch_pm_parameter"""
switch_pm_parameter: Optional[str] = None
"""Deep-linking parameter for the /start message sent to the bot when user presses the switch button. 1-64 characters, only A-Z, a-z, 0-9, _ and - are allowed.
Example: An inline bot that sends YouTube videos can ask the user to connect the bot to their YouTube account to adapt search results accordingly. To do this, it displays a Connect your YouTube account button above the results, or even before showing any. The user presses the button, switches to a private chat with the bot and, in doing so, passes a start parameter that instructs the bot to return an oauth link. Once done, the bot can offer a switch_inline button so that the user can easily return to the chat where they wanted to use the bot's inline capabilities."""
def build_request(self) -> Request:
data: Dict[str, Any] = self.dict(exclude_unset=True, exclude={})
files: Dict[str, Any] = {}
return Request(method="answerInlineQuery", data=data, files=files)

View file

@ -0,0 +1,27 @@
from typing import Any, Dict, Optional
from .base import Request, TelegramMethod
class AnswerPreCheckoutQuery(TelegramMethod[bool]):
"""
Once the user has confirmed their payment and shipping details, the Bot API sends the final confirmation in the form of an Update with the field pre_checkout_query. Use this method to respond to such pre-checkout queries. On success, True is returned. Note: The Bot API must receive an answer within 10 seconds after the pre-checkout query was sent.
Source: https://core.telegram.org/bots/api#answerprecheckoutquery
"""
__returning__ = bool
pre_checkout_query_id: str
"""Unique identifier for the query to be answered"""
ok: bool
"""Specify True if everything is alright (goods are available, etc.) and the bot is ready to proceed with the order. Use False if there are any problems."""
error_message: Optional[str] = None
"""Required if ok is False. Error message in human readable form that explains the reason for failure to proceed with the checkout (e.g. "Sorry, somebody just bought the last of our amazing black T-shirts while you were busy filling out your payment details. Please choose a different color or garment!"). Telegram will display this message to the user."""
def build_request(self) -> Request:
data: Dict[str, Any] = self.dict(exclude_unset=True, exclude={})
files: Dict[str, Any] = {}
return Request(method="answerPreCheckoutQuery", data=data, files=files)

View file

@ -0,0 +1,31 @@
from typing import Any, Dict, List, Optional
from ..types import ShippingOption
from .base import Request, TelegramMethod
class AnswerShippingQuery(TelegramMethod[bool]):
"""
If you sent an invoice requesting a shipping address and the parameter is_flexible was specified, the Bot API will send an Update with a shipping_query field to the bot. Use this method to reply to shipping queries. On success, True is returned.
Source: https://core.telegram.org/bots/api#answershippingquery
"""
__returning__ = bool
shipping_query_id: str
"""Unique identifier for the query to be answered"""
ok: bool
"""Specify True if delivery to the specified address is possible and False if there are any problems (for example, if delivery to the specified address is not possible)"""
shipping_options: Optional[List[ShippingOption]] = None
"""Required if ok is True. A JSON-serialized array of available shipping options."""
error_message: Optional[str] = None
"""Required if ok is False. Error message in human readable form that explains why it is impossible to complete the order (e.g. "Sorry, delivery to your desired address is unavailable'). Telegram will display this message to the user."""
def build_request(self) -> Request:
data: Dict[str, Any] = self.dict(exclude_unset=True, exclude={})
files: Dict[str, Any] = {}
return Request(method="answerShippingQuery", data=data, files=files)

View file

@ -0,0 +1,49 @@
import abc
import io
from typing import Any, Dict, Generic, Optional, Type, TypeVar, Union
from pydantic import BaseConfig, BaseModel, Extra
from pydantic.generics import GenericModel
from aiogram.api.types import InputFile, ResponseParameters
T = TypeVar("T")
class Request(BaseModel):
method: str
data: Dict[str, Optional[Any]]
files: Optional[Dict[str, Union[io.BytesIO, bytes, InputFile]]]
class Config(BaseConfig):
arbitrary_types_allowed = True
class Response(ResponseParameters, GenericModel, Generic[T]):
ok: bool
result: Optional[T] = None
description: Optional[str] = None
error_code: Optional[int] = None
class TelegramMethod(abc.ABC, BaseModel, Generic[T]):
class Config(BaseConfig):
use_enum_values = True
extra = Extra.allow
allow_population_by_field_name = True
arbitrary_types_allowed = True
# orm_mode = True
@property
@abc.abstractmethod
def __returning__(self) -> Type:
pass
@abc.abstractmethod
def build_request(self) -> Request:
pass
def build_response(self, data: Dict[str, Any]) -> Response[T]:
# noinspection PyTypeChecker
return Response[self.__returning__](**data) # type: ignore

View file

@ -0,0 +1,40 @@
from typing import Any, Dict, Optional, Union
from ..types import InputFile, MaskPosition
from .base import Request, TelegramMethod
class CreateNewStickerSet(TelegramMethod[bool]):
"""
Use this method to create new sticker set owned by a user. The bot will be able to edit the created sticker set. Returns True on success.
Source: https://core.telegram.org/bots/api#createnewstickerset
"""
__returning__ = bool
user_id: int
"""User identifier of created sticker set owner"""
name: str
"""Short name of sticker set, to be used in t.me/addstickers/ URLs (e.g., animals). Can contain only english letters, digits and underscores. Must begin with a letter, can't contain consecutive underscores and must end in '_by_<bot username>'. <bot_username> is case insensitive. 1-64 characters."""
title: str
"""Sticker set title, 1-64 characters"""
png_sticker: Union[InputFile, str]
"""Png image with the sticker, must be up to 512 kilobytes in size, dimensions must not exceed 512px, and either width or height must be exactly 512px. Pass a file_id as a String to send a file that already exists on the Telegram servers, pass an HTTP URL as a String for Telegram to get a file from the Internet, or upload a new one using multipart/form-data."""
emojis: str
"""One or more emoji corresponding to the sticker"""
contains_masks: Optional[bool] = None
"""Pass True, if a set of mask stickers should be created"""
mask_position: Optional[MaskPosition] = None
"""A JSON-serialized object for position where the mask should be placed on faces"""
def build_request(self) -> Request:
data: Dict[str, Any] = self.dict(exclude_unset=True, exclude={})
files: Dict[str, Any] = {}
return Request(method="createNewStickerSet", data=data, files=files)

View file

@ -0,0 +1,21 @@
from typing import Any, Dict, Union
from .base import Request, TelegramMethod
class DeleteChatPhoto(TelegramMethod[bool]):
"""
Use this method to delete a chat photo. Photos can't be changed for private chats. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Returns True on success.
Source: https://core.telegram.org/bots/api#deletechatphoto
"""
__returning__ = bool
chat_id: Union[int, str]
"""Unique identifier for the target chat or username of the target channel (in the format @channelusername)"""
def build_request(self) -> Request:
data: Dict[str, Any] = self.dict(exclude_unset=True, exclude={})
files: Dict[str, Any] = {}
return Request(method="deleteChatPhoto", data=data, files=files)

View file

@ -0,0 +1,21 @@
from typing import Any, Dict, Union
from .base import Request, TelegramMethod
class DeleteChatStickerSet(TelegramMethod[bool]):
"""
Use this method to delete a group sticker set from a supergroup. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Use the field can_set_sticker_set optionally returned in getChat requests to check if the bot can use this method. Returns True on success.
Source: https://core.telegram.org/bots/api#deletechatstickerset
"""
__returning__ = bool
chat_id: Union[int, str]
"""Unique identifier for the target chat or username of the target supergroup (in the format @supergroupusername)"""
def build_request(self) -> Request:
data: Dict[str, Any] = self.dict(exclude_unset=True, exclude={})
files: Dict[str, Any] = {}
return Request(method="deleteChatStickerSet", data=data, files=files)

View file

@ -0,0 +1,31 @@
from typing import Any, Dict, Union
from .base import Request, TelegramMethod
class DeleteMessage(TelegramMethod[bool]):
"""
Use this method to delete a message, including service messages, with the following limitations:
- A message can only be deleted if it was sent less than 48 hours ago.
- Bots can delete outgoing messages in private chats, groups, and supergroups.
- Bots can delete incoming messages in private chats.
- Bots granted can_post_messages permissions can delete outgoing messages in channels.
- If the bot is an administrator of a group, it can delete any message there.
- If the bot has can_delete_messages permission in a supergroup or a channel, it can delete any message there.
Returns True on success.
Source: https://core.telegram.org/bots/api#deletemessage
"""
__returning__ = bool
chat_id: Union[int, str]
"""Unique identifier for the target chat or username of the target channel (in the format @channelusername)"""
message_id: int
"""Identifier of the message to delete"""
def build_request(self) -> Request:
data: Dict[str, Any] = self.dict(exclude_unset=True, exclude={})
files: Dict[str, Any] = {}
return Request(method="deleteMessage", data=data, files=files)

View file

@ -0,0 +1,21 @@
from typing import Any, Dict
from .base import Request, TelegramMethod
class DeleteStickerFromSet(TelegramMethod[bool]):
"""
Use this method to delete a sticker from a set created by the bot. Returns True on success.
Source: https://core.telegram.org/bots/api#deletestickerfromset
"""
__returning__ = bool
sticker: str
"""File identifier of the sticker"""
def build_request(self) -> Request:
data: Dict[str, Any] = self.dict(exclude_unset=True, exclude={})
files: Dict[str, Any] = {}
return Request(method="deleteStickerFromSet", data=data, files=files)

View file

@ -0,0 +1,18 @@
from typing import Any, Dict
from .base import Request, TelegramMethod
class DeleteWebhook(TelegramMethod[bool]):
"""
Use this method to remove webhook integration if you decide to switch back to getUpdates. Returns True on success. Requires no parameters.
Source: https://core.telegram.org/bots/api#deletewebhook
"""
__returning__ = bool
def build_request(self) -> Request:
data: Dict[str, Any] = self.dict(exclude_unset=True, exclude={})
files: Dict[str, Any] = {}
return Request(method="deleteWebhook", data=data, files=files)

View file

@ -0,0 +1,37 @@
from typing import Any, Dict, Optional, Union
from ..types import InlineKeyboardMarkup, Message
from .base import Request, TelegramMethod
class EditMessageCaption(TelegramMethod[Union[Message, bool]]):
"""
Use this method to edit captions of messages. On success, if edited message is sent by the bot, the edited Message is returned, otherwise True is returned.
Source: https://core.telegram.org/bots/api#editmessagecaption
"""
__returning__ = Union[Message, bool]
chat_id: Optional[Union[int, str]] = None
"""Required if inline_message_id is not specified. Unique identifier for the target chat or username of the target channel (in the format @channelusername)"""
message_id: Optional[int] = None
"""Required if inline_message_id is not specified. Identifier of the message to edit"""
inline_message_id: Optional[str] = None
"""Required if chat_id and message_id are not specified. Identifier of the inline message"""
caption: Optional[str] = None
"""New caption of the message"""
parse_mode: Optional[str] = None
"""Send Markdown or HTML, if you want Telegram apps to show bold, italic, fixed-width text or inline URLs in the media caption."""
reply_markup: Optional[InlineKeyboardMarkup] = None
"""A JSON-serialized object for an inline keyboard."""
def build_request(self) -> Request:
data: Dict[str, Any] = self.dict(exclude_unset=True, exclude={})
files: Dict[str, Any] = {}
return Request(method="editMessageCaption", data=data, files=files)

View file

@ -0,0 +1,37 @@
from typing import Any, Dict, Optional, Union
from ..types import InlineKeyboardMarkup, Message
from .base import Request, TelegramMethod
class EditMessageLiveLocation(TelegramMethod[Union[Message, bool]]):
"""
Use this method to edit live location messages. A location can be edited until its live_period expires or editing is explicitly disabled by a call to stopMessageLiveLocation. On success, if the edited message was sent by the bot, the edited Message is returned, otherwise True is returned.
Source: https://core.telegram.org/bots/api#editmessagelivelocation
"""
__returning__ = Union[Message, bool]
latitude: float
"""Latitude of new location"""
longitude: float
"""Longitude of new location"""
chat_id: Optional[Union[int, str]] = None
"""Required if inline_message_id is not specified. Unique identifier for the target chat or username of the target channel (in the format @channelusername)"""
message_id: Optional[int] = None
"""Required if inline_message_id is not specified. Identifier of the message to edit"""
inline_message_id: Optional[str] = None
"""Required if chat_id and message_id are not specified. Identifier of the inline message"""
reply_markup: Optional[InlineKeyboardMarkup] = None
"""A JSON-serialized object for a new inline keyboard."""
def build_request(self) -> Request:
data: Dict[str, Any] = self.dict(exclude_unset=True, exclude={})
files: Dict[str, Any] = {}
return Request(method="editMessageLiveLocation", data=data, files=files)

View file

@ -0,0 +1,34 @@
from typing import Any, Dict, Optional, Union
from ..types import InlineKeyboardMarkup, InputMedia, Message
from .base import Request, TelegramMethod
class EditMessageMedia(TelegramMethod[Union[Message, bool]]):
"""
Use this method to edit animation, audio, document, photo, or video messages. If a message is a part of a message album, then it can be edited only to a photo or a video. Otherwise, message type can be changed arbitrarily. When inline message is edited, new file can't be uploaded. Use previously uploaded file via its file_id or specify a URL. On success, if the edited message was sent by the bot, the edited Message is returned, otherwise True is returned.
Source: https://core.telegram.org/bots/api#editmessagemedia
"""
__returning__ = Union[Message, bool]
media: InputMedia
"""A JSON-serialized object for a new media content of the message"""
chat_id: Optional[Union[int, str]] = None
"""Required if inline_message_id is not specified. Unique identifier for the target chat or username of the target channel (in the format @channelusername)"""
message_id: Optional[int] = None
"""Required if inline_message_id is not specified. Identifier of the message to edit"""
inline_message_id: Optional[str] = None
"""Required if chat_id and message_id are not specified. Identifier of the inline message"""
reply_markup: Optional[InlineKeyboardMarkup] = None
"""A JSON-serialized object for a new inline keyboard."""
def build_request(self) -> Request:
data: Dict[str, Any] = self.dict(exclude_unset=True, exclude={})
files: Dict[str, Any] = {}
return Request(method="editMessageMedia", data=data, files=files)

View file

@ -0,0 +1,31 @@
from typing import Any, Dict, Optional, Union
from ..types import InlineKeyboardMarkup, Message
from .base import Request, TelegramMethod
class EditMessageReplyMarkup(TelegramMethod[Union[Message, bool]]):
"""
Use this method to edit only the reply markup of messages. On success, if edited message is sent by the bot, the edited Message is returned, otherwise True is returned.
Source: https://core.telegram.org/bots/api#editmessagereplymarkup
"""
__returning__ = Union[Message, bool]
chat_id: Optional[Union[int, str]] = None
"""Required if inline_message_id is not specified. Unique identifier for the target chat or username of the target channel (in the format @channelusername)"""
message_id: Optional[int] = None
"""Required if inline_message_id is not specified. Identifier of the message to edit"""
inline_message_id: Optional[str] = None
"""Required if chat_id and message_id are not specified. Identifier of the inline message"""
reply_markup: Optional[InlineKeyboardMarkup] = None
"""A JSON-serialized object for an inline keyboard."""
def build_request(self) -> Request:
data: Dict[str, Any] = self.dict(exclude_unset=True, exclude={})
files: Dict[str, Any] = {}
return Request(method="editMessageReplyMarkup", data=data, files=files)

View file

@ -0,0 +1,40 @@
from typing import Any, Dict, Optional, Union
from ..types import InlineKeyboardMarkup, Message
from .base import Request, TelegramMethod
class EditMessageText(TelegramMethod[Union[Message, bool]]):
"""
Use this method to edit text and game messages. On success, if edited message is sent by the bot, the edited Message is returned, otherwise True is returned.
Source: https://core.telegram.org/bots/api#editmessagetext
"""
__returning__ = Union[Message, bool]
text: str
"""New text of the message"""
chat_id: Optional[Union[int, str]] = None
"""Required if inline_message_id is not specified. Unique identifier for the target chat or username of the target channel (in the format @channelusername)"""
message_id: Optional[int] = None
"""Required if inline_message_id is not specified. Identifier of the message to edit"""
inline_message_id: Optional[str] = None
"""Required if chat_id and message_id are not specified. Identifier of the inline message"""
parse_mode: Optional[str] = None
"""Send Markdown or HTML, if you want Telegram apps to show bold, italic, fixed-width text or inline URLs in your bot's message."""
disable_web_page_preview: Optional[bool] = None
"""Disables link previews for links in this message"""
reply_markup: Optional[InlineKeyboardMarkup] = None
"""A JSON-serialized object for an inline keyboard."""
def build_request(self) -> Request:
data: Dict[str, Any] = self.dict(exclude_unset=True, exclude={})
files: Dict[str, Any] = {}
return Request(method="editMessageText", data=data, files=files)

View file

@ -0,0 +1,22 @@
from typing import Any, Dict, Union
from .base import Request, TelegramMethod
class ExportChatInviteLink(TelegramMethod[str]):
"""
Use this method to generate a new invite link for a chat; any previously generated link is revoked. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Returns the new invite link as String on success.
Note: Each administrator in a chat generates their own invite links. Bots can't use invite links generated by other administrators. If you want your bot to work with invite links, it will need to generate its own link using exportChatInviteLink after this the link will become available to the bot via the getChat method. If your bot needs to generate a new invite link replacing its previous one, use exportChatInviteLink again.
Source: https://core.telegram.org/bots/api#exportchatinvitelink
"""
__returning__ = str
chat_id: Union[int, str]
"""Unique identifier for the target chat or username of the target channel (in the format @channelusername)"""
def build_request(self) -> Request:
data: Dict[str, Any] = self.dict(exclude_unset=True, exclude={})
files: Dict[str, Any] = {}
return Request(method="exportChatInviteLink", data=data, files=files)

View file

@ -0,0 +1,31 @@
from typing import Any, Dict, Optional, Union
from ..types import Message
from .base import Request, TelegramMethod
class ForwardMessage(TelegramMethod[Message]):
"""
Use this method to forward messages of any kind. On success, the sent Message is returned.
Source: https://core.telegram.org/bots/api#forwardmessage
"""
__returning__ = Message
chat_id: Union[int, str]
"""Unique identifier for the target chat or username of the target channel (in the format @channelusername)"""
from_chat_id: Union[int, str]
"""Unique identifier for the chat where the original message was sent (or channel username in the format @channelusername)"""
message_id: int
"""Message identifier in the chat specified in from_chat_id"""
disable_notification: Optional[bool] = None
"""Sends the message silently. Users will receive a notification with no sound."""
def build_request(self) -> Request:
data: Dict[str, Any] = self.dict(exclude_unset=True, exclude={})
files: Dict[str, Any] = {}
return Request(method="forwardMessage", data=data, files=files)

View file

@ -0,0 +1,22 @@
from typing import Any, Dict, Union
from ..types import Chat
from .base import Request, TelegramMethod
class GetChat(TelegramMethod[Chat]):
"""
Use this method to get up to date information about the chat (current name of the user for one-on-one conversations, current username of a user, group or channel, etc.). Returns a Chat object on success.
Source: https://core.telegram.org/bots/api#getchat
"""
__returning__ = Chat
chat_id: Union[int, str]
"""Unique identifier for the target chat or username of the target supergroup or channel (in the format @channelusername)"""
def build_request(self) -> Request:
data: Dict[str, Any] = self.dict(exclude_unset=True, exclude={})
files: Dict[str, Any] = {}
return Request(method="getChat", data=data, files=files)

View file

@ -0,0 +1,22 @@
from typing import Any, Dict, List, Union
from ..types import ChatMember
from .base import Request, TelegramMethod
class GetChatAdministrators(TelegramMethod[List[ChatMember]]):
"""
Use this method to get a list of administrators in a chat. On success, returns an Array of ChatMember objects that contains information about all chat administrators except other bots. If the chat is a group or a supergroup and no administrators were appointed, only the creator will be returned.
Source: https://core.telegram.org/bots/api#getchatadministrators
"""
__returning__ = List[ChatMember]
chat_id: Union[int, str]
"""Unique identifier for the target chat or username of the target supergroup or channel (in the format @channelusername)"""
def build_request(self) -> Request:
data: Dict[str, Any] = self.dict(exclude_unset=True, exclude={})
files: Dict[str, Any] = {}
return Request(method="getChatAdministrators", data=data, files=files)

View file

@ -0,0 +1,25 @@
from typing import Any, Dict, Union
from ..types import ChatMember
from .base import Request, TelegramMethod
class GetChatMember(TelegramMethod[ChatMember]):
"""
Use this method to get information about a member of a chat. Returns a ChatMember object on success.
Source: https://core.telegram.org/bots/api#getchatmember
"""
__returning__ = ChatMember
chat_id: Union[int, str]
"""Unique identifier for the target chat or username of the target supergroup or channel (in the format @channelusername)"""
user_id: int
"""Unique identifier of the target user"""
def build_request(self) -> Request:
data: Dict[str, Any] = self.dict(exclude_unset=True, exclude={})
files: Dict[str, Any] = {}
return Request(method="getChatMember", data=data, files=files)

View file

@ -0,0 +1,21 @@
from typing import Any, Dict, Union
from .base import Request, TelegramMethod
class GetChatMembersCount(TelegramMethod[int]):
"""
Use this method to get the number of members in a chat. Returns Int on success.
Source: https://core.telegram.org/bots/api#getchatmemberscount
"""
__returning__ = int
chat_id: Union[int, str]
"""Unique identifier for the target chat or username of the target supergroup or channel (in the format @channelusername)"""
def build_request(self) -> Request:
data: Dict[str, Any] = self.dict(exclude_unset=True, exclude={})
files: Dict[str, Any] = {}
return Request(method="getChatMembersCount", data=data, files=files)

View file

@ -0,0 +1,23 @@
from typing import Any, Dict
from ..types import File
from .base import Request, TelegramMethod
class GetFile(TelegramMethod[File]):
"""
Use this method to get basic info about a file and prepare it for downloading. For the moment, bots can download files of up to 20MB in size. On success, a File object is returned. The file can then be downloaded via the link https://api.telegram.org/file/bot<token>/<file_path>, where <file_path> is taken from the response. It is guaranteed that the link will be valid for at least 1 hour. When the link expires, a new one can be requested by calling getFile again.
Note: This function may not preserve the original file name and MIME type. You should save the file's MIME type and name (if available) when the File object is received.
Source: https://core.telegram.org/bots/api#getfile
"""
__returning__ = File
file_id: str
"""File identifier to get info about"""
def build_request(self) -> Request:
data: Dict[str, Any] = self.dict(exclude_unset=True, exclude={})
files: Dict[str, Any] = {}
return Request(method="getFile", data=data, files=files)

View file

@ -0,0 +1,32 @@
from typing import Any, Dict, List, Optional
from ..types import GameHighScore
from .base import Request, TelegramMethod
class GetGameHighScores(TelegramMethod[List[GameHighScore]]):
"""
Use this method to get data for high score tables. Will return the score of the specified user and several of his neighbors in a game. On success, returns an Array of GameHighScore objects.
This method will currently return scores for the target user, plus two of his closest neighbors on each side. Will also return the top three users if the user and his neighbors are not among them. Please note that this behavior is subject to change.
Source: https://core.telegram.org/bots/api#getgamehighscores
"""
__returning__ = List[GameHighScore]
user_id: int
"""Target user id"""
chat_id: Optional[int] = None
"""Required if inline_message_id is not specified. Unique identifier for the target chat"""
message_id: Optional[int] = None
"""Required if inline_message_id is not specified. Identifier of the sent message"""
inline_message_id: Optional[str] = None
"""Required if chat_id and message_id are not specified. Identifier of the inline message"""
def build_request(self) -> Request:
data: Dict[str, Any] = self.dict(exclude_unset=True, exclude={})
files: Dict[str, Any] = {}
return Request(method="getGameHighScores", data=data, files=files)

View file

@ -0,0 +1,19 @@
from typing import Any, Dict
from ..types import User
from .base import Request, TelegramMethod
class GetMe(TelegramMethod[User]):
"""
A simple method for testing your bot's auth token. Requires no parameters. Returns basic information about the bot in form of a User object.
Source: https://core.telegram.org/bots/api#getme
"""
__returning__ = User
def build_request(self) -> Request:
data: Dict[str, Any] = self.dict(exclude_unset=True, exclude={})
files: Dict[str, Any] = {}
return Request(method="getMe", data=data, files=files)

View file

@ -0,0 +1,22 @@
from typing import Any, Dict
from ..types import StickerSet
from .base import Request, TelegramMethod
class GetStickerSet(TelegramMethod[StickerSet]):
"""
Use this method to get a sticker set. On success, a StickerSet object is returned.
Source: https://core.telegram.org/bots/api#getstickerset
"""
__returning__ = StickerSet
name: str
"""Name of the sticker set"""
def build_request(self) -> Request:
data: Dict[str, Any] = self.dict(exclude_unset=True, exclude={})
files: Dict[str, Any] = {}
return Request(method="getStickerSet", data=data, files=files)

View file

@ -0,0 +1,36 @@
from typing import Any, Dict, List, Optional
from ..types import Update
from .base import Request, TelegramMethod
class GetUpdates(TelegramMethod[List[Update]]):
"""
Use this method to receive incoming updates using long polling (wiki). An Array of Update objects is returned.
Notes
1. This method will not work if an outgoing webhook is set up.
2. In order to avoid getting duplicate updates, recalculate offset after each server response.
Source: https://core.telegram.org/bots/api#getupdates
"""
__returning__ = List[Update]
offset: Optional[int] = None
"""Identifier of the first update to be returned. Must be greater by one than the highest among the identifiers of previously received updates. By default, updates starting with the earliest unconfirmed update are returned. An update is considered confirmed as soon as getUpdates is called with an offset higher than its update_id. The negative offset can be specified to retrieve updates starting from -offset update from the end of the updates queue. All previous updates will forgotten."""
limit: Optional[int] = None
"""Limits the number of updates to be retrieved. Values between 1—100 are accepted. Defaults to 100."""
timeout: Optional[int] = None
"""Timeout in seconds for long polling. Defaults to 0, i.e. usual short polling. Should be positive, short polling should be used for testing purposes only."""
allowed_updates: Optional[List[str]] = None
"""List the types of updates you want your bot to receive. For example, specify ['message', 'edited_channel_post', 'callback_query'] to only receive updates of these types. See Update for a complete list of available update types. Specify an empty list to receive all updates regardless of type (default). If not specified, the previous setting will be used.
Please note that this parameter doesn't affect updates created before the call to the getUpdates, so unwanted updates may be received for a short period of time."""
def build_request(self) -> Request:
data: Dict[str, Any] = self.dict(exclude_unset=True, exclude={})
files: Dict[str, Any] = {}
return Request(method="getUpdates", data=data, files=files)

View file

@ -0,0 +1,28 @@
from typing import Any, Dict, Optional
from ..types import UserProfilePhotos
from .base import Request, TelegramMethod
class GetUserProfilePhotos(TelegramMethod[UserProfilePhotos]):
"""
Use this method to get a list of profile pictures for a user. Returns a UserProfilePhotos object.
Source: https://core.telegram.org/bots/api#getuserprofilephotos
"""
__returning__ = UserProfilePhotos
user_id: int
"""Unique identifier of the target user"""
offset: Optional[int] = None
"""Sequential number of the first photo to be returned. By default, all photos are returned."""
limit: Optional[int] = None
"""Limits the number of photos to be retrieved. Values between 1—100 are accepted. Defaults to 100."""
def build_request(self) -> Request:
data: Dict[str, Any] = self.dict(exclude_unset=True, exclude={})
files: Dict[str, Any] = {}
return Request(method="getUserProfilePhotos", data=data, files=files)

View file

@ -0,0 +1,19 @@
from typing import Any, Dict
from ..types import WebhookInfo
from .base import Request, TelegramMethod
class GetWebhookInfo(TelegramMethod[WebhookInfo]):
"""
Use this method to get current webhook status. Requires no parameters. On success, returns a WebhookInfo object. If the bot is using getUpdates, will return an object with the url field empty.
Source: https://core.telegram.org/bots/api#getwebhookinfo
"""
__returning__ = WebhookInfo
def build_request(self) -> Request:
data: Dict[str, Any] = self.dict(exclude_unset=True, exclude={})
files: Dict[str, Any] = {}
return Request(method="getWebhookInfo", data=data, files=files)

View file

@ -0,0 +1,27 @@
from typing import Any, Dict, Optional, Union
from .base import Request, TelegramMethod
class KickChatMember(TelegramMethod[bool]):
"""
Use this method to kick a user from a group, a supergroup or a channel. In the case of supergroups and channels, the user will not be able to return to the group on their own using invite links, etc., unless unbanned first. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Returns True on success.
Source: https://core.telegram.org/bots/api#kickchatmember
"""
__returning__ = bool
chat_id: Union[int, str]
"""Unique identifier for the target group or username of the target supergroup or channel (in the format @channelusername)"""
user_id: int
"""Unique identifier of the target user"""
until_date: Optional[int] = None
"""Date when the user will be unbanned, unix time. If user is banned for more than 366 days or less than 30 seconds from the current time they are considered to be banned forever"""
def build_request(self) -> Request:
data: Dict[str, Any] = self.dict(exclude_unset=True, exclude={})
files: Dict[str, Any] = {}
return Request(method="kickChatMember", data=data, files=files)

View file

@ -0,0 +1,21 @@
from typing import Any, Dict, Union
from .base import Request, TelegramMethod
class LeaveChat(TelegramMethod[bool]):
"""
Use this method for your bot to leave a group, supergroup or channel. Returns True on success.
Source: https://core.telegram.org/bots/api#leavechat
"""
__returning__ = bool
chat_id: Union[int, str]
"""Unique identifier for the target chat or username of the target supergroup or channel (in the format @channelusername)"""
def build_request(self) -> Request:
data: Dict[str, Any] = self.dict(exclude_unset=True, exclude={})
files: Dict[str, Any] = {}
return Request(method="leaveChat", data=data, files=files)

View file

@ -0,0 +1,27 @@
from typing import Any, Dict, Optional, Union
from .base import Request, TelegramMethod
class PinChatMessage(TelegramMethod[bool]):
"""
Use this method to pin a message in a group, a supergroup, or a channel. The bot must be an administrator in the chat for this to work and must have the can_pin_messages admin right in the supergroup or can_edit_messages admin right in the channel. Returns True on success.
Source: https://core.telegram.org/bots/api#pinchatmessage
"""
__returning__ = bool
chat_id: Union[int, str]
"""Unique identifier for the target chat or username of the target channel (in the format @channelusername)"""
message_id: int
"""Identifier of a message to pin"""
disable_notification: Optional[bool] = None
"""Pass True, if it is not necessary to send a notification to all chat members about the new pinned message. Notifications are always disabled in channels."""
def build_request(self) -> Request:
data: Dict[str, Any] = self.dict(exclude_unset=True, exclude={})
files: Dict[str, Any] = {}
return Request(method="pinChatMessage", data=data, files=files)

View file

@ -0,0 +1,48 @@
from typing import Any, Dict, Optional, Union
from .base import Request, TelegramMethod
class PromoteChatMember(TelegramMethod[bool]):
"""
Use this method to promote or demote a user in a supergroup or a channel. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Pass False for all boolean parameters to demote a user. Returns True on success.
Source: https://core.telegram.org/bots/api#promotechatmember
"""
__returning__ = bool
chat_id: Union[int, str]
"""Unique identifier for the target chat or username of the target channel (in the format @channelusername)"""
user_id: int
"""Unique identifier of the target user"""
can_change_info: Optional[bool] = None
"""Pass True, if the administrator can change chat title, photo and other settings"""
can_post_messages: Optional[bool] = None
"""Pass True, if the administrator can create channel posts, channels only"""
can_edit_messages: Optional[bool] = None
"""Pass True, if the administrator can edit messages of other users and can pin messages, channels only"""
can_delete_messages: Optional[bool] = None
"""Pass True, if the administrator can delete messages of other users"""
can_invite_users: Optional[bool] = None
"""Pass True, if the administrator can invite new users to the chat"""
can_restrict_members: Optional[bool] = None
"""Pass True, if the administrator can restrict, ban or unban chat members"""
can_pin_messages: Optional[bool] = None
"""Pass True, if the administrator can pin messages, supergroups only"""
can_promote_members: Optional[bool] = None
"""Pass True, if the administrator can add new administrators with a subset of his own privileges or demote administrators that he has promoted, directly or indirectly (promoted by administrators that were appointed by him)"""
def build_request(self) -> Request:
data: Dict[str, Any] = self.dict(exclude_unset=True, exclude={})
files: Dict[str, Any] = {}
return Request(method="promoteChatMember", data=data, files=files)

View file

@ -0,0 +1,31 @@
from typing import Any, Dict, Optional, Union
from ..types import ChatPermissions
from .base import Request, TelegramMethod
class RestrictChatMember(TelegramMethod[bool]):
"""
Use this method to restrict a user in a supergroup. The bot must be an administrator in the supergroup for this to work and must have the appropriate admin rights. Pass True for all permissions to lift restrictions from a user. Returns True on success.
Source: https://core.telegram.org/bots/api#restrictchatmember
"""
__returning__ = bool
chat_id: Union[int, str]
"""Unique identifier for the target chat or username of the target supergroup (in the format @supergroupusername)"""
user_id: int
"""Unique identifier of the target user"""
permissions: ChatPermissions
"""New user permissions"""
until_date: Optional[int] = None
"""Date when restrictions will be lifted for the user, unix time. If user is restricted for more than 366 days or less than 30 seconds from the current time, they are considered to be restricted forever"""
def build_request(self) -> Request:
data: Dict[str, Any] = self.dict(exclude_unset=True, exclude={})
files: Dict[str, Any] = {}
return Request(method="restrictChatMember", data=data, files=files)

View file

@ -0,0 +1,61 @@
from typing import Any, Dict, Optional, Union
from ..types import (
ForceReply,
InlineKeyboardMarkup,
InputFile,
Message,
ReplyKeyboardMarkup,
ReplyKeyboardRemove,
)
from .base import Request, TelegramMethod
class SendAnimation(TelegramMethod[Message]):
"""
Use this method to send animation files (GIF or H.264/MPEG-4 AVC video without sound). On success, the sent Message is returned. Bots can currently send animation files of up to 50 MB in size, this limit may be changed in the future.
Source: https://core.telegram.org/bots/api#sendanimation
"""
__returning__ = Message
chat_id: Union[int, str]
"""Unique identifier for the target chat or username of the target channel (in the format @channelusername)"""
animation: Union[InputFile, str]
"""Animation to send. Pass a file_id as String to send an animation that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get an animation from the Internet, or upload a new animation using multipart/form-data."""
duration: Optional[int] = None
"""Duration of sent animation in seconds"""
width: Optional[int] = None
"""Animation width"""
height: Optional[int] = None
"""Animation height"""
thumb: Optional[Union[InputFile, str]] = None
"""Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnails width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails cant be reused and can be only uploaded as a new file, so you can pass 'attach://<file_attach_name>' if the thumbnail was uploaded using multipart/form-data under <file_attach_name>."""
caption: Optional[str] = None
"""Animation caption (may also be used when resending animation by file_id), 0-1024 characters"""
parse_mode: Optional[str] = None
"""Send Markdown or HTML, if you want Telegram apps to show bold, italic, fixed-width text or inline URLs in the media caption."""
disable_notification: Optional[bool] = None
"""Sends the message silently. Users will receive a notification with no sound."""
reply_to_message_id: Optional[int] = None
"""If the message is a reply, ID of the original message"""
reply_markup: Optional[
Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply]
] = None
"""Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user."""
def build_request(self) -> Request:
data: Dict[str, Any] = self.dict(exclude_unset=True, exclude={})
files: Dict[str, Any] = {}
return Request(method="sendAnimation", data=data, files=files)

View file

@ -0,0 +1,62 @@
from typing import Any, Dict, Optional, Union
from ..types import (
ForceReply,
InlineKeyboardMarkup,
InputFile,
Message,
ReplyKeyboardMarkup,
ReplyKeyboardRemove,
)
from .base import Request, TelegramMethod
class SendAudio(TelegramMethod[Message]):
"""
Use this method to send audio files, if you want Telegram clients to display them in the music player. Your audio must be in the .MP3 or .M4A format. On success, the sent Message is returned. Bots can currently send audio files of up to 50 MB in size, this limit may be changed in the future.
For sending voice messages, use the sendVoice method instead.
Source: https://core.telegram.org/bots/api#sendaudio
"""
__returning__ = Message
chat_id: Union[int, str]
"""Unique identifier for the target chat or username of the target channel (in the format @channelusername)"""
audio: Union[InputFile, str]
"""Audio file to send. Pass a file_id as String to send an audio file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get an audio file from the Internet, or upload a new one using multipart/form-data."""
caption: Optional[str] = None
"""Audio caption, 0-1024 characters"""
parse_mode: Optional[str] = None
"""Send Markdown or HTML, if you want Telegram apps to show bold, italic, fixed-width text or inline URLs in the media caption."""
duration: Optional[int] = None
"""Duration of the audio in seconds"""
performer: Optional[str] = None
"""Performer"""
title: Optional[str] = None
"""Track name"""
thumb: Optional[Union[InputFile, str]] = None
"""Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnails width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails cant be reused and can be only uploaded as a new file, so you can pass 'attach://<file_attach_name>' if the thumbnail was uploaded using multipart/form-data under <file_attach_name>."""
disable_notification: Optional[bool] = None
"""Sends the message silently. Users will receive a notification with no sound."""
reply_to_message_id: Optional[int] = None
"""If the message is a reply, ID of the original message"""
reply_markup: Optional[
Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply]
] = None
"""Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user."""
def build_request(self) -> Request:
data: Dict[str, Any] = self.dict(exclude_unset=True, exclude={})
files: Dict[str, Any] = {}
return Request(method="sendAudio", data=data, files=files)

View file

@ -0,0 +1,26 @@
from typing import Any, Dict, Union
from .base import Request, TelegramMethod
class SendChatAction(TelegramMethod[bool]):
"""
Use this method when you need to tell the user that something is happening on the bot's side. The status is set for 5 seconds or less (when a message arrives from your bot, Telegram clients clear its typing status). Returns True on success.
Example: The ImageBot needs some time to process a request and upload the image. Instead of sending a text message along the lines of 'Retrieving image, please wait…', the bot may use sendChatAction with action = upload_photo. The user will see a 'sending photo' status for the bot.
We only recommend using this method when a response from the bot will take a noticeable amount of time to arrive.
Source: https://core.telegram.org/bots/api#sendchataction
"""
__returning__ = bool
chat_id: Union[int, str]
"""Unique identifier for the target chat or username of the target channel (in the format @channelusername)"""
action: str
"""Type of action to broadcast. Choose one, depending on what the user is about to receive: typing for text messages, upload_photo for photos, record_video or upload_video for videos, record_audio or upload_audio for audio files, upload_document for general files, find_location for location data, record_video_note or upload_video_note for video notes."""
def build_request(self) -> Request:
data: Dict[str, Any] = self.dict(exclude_unset=True, exclude={})
files: Dict[str, Any] = {}
return Request(method="sendChatAction", data=data, files=files)

View file

@ -0,0 +1,51 @@
from typing import Any, Dict, Optional, Union
from ..types import (
ForceReply,
InlineKeyboardMarkup,
Message,
ReplyKeyboardMarkup,
ReplyKeyboardRemove,
)
from .base import Request, TelegramMethod
class SendContact(TelegramMethod[Message]):
"""
Use this method to send phone contacts. On success, the sent Message is returned.
Source: https://core.telegram.org/bots/api#sendcontact
"""
__returning__ = Message
chat_id: Union[int, str]
"""Unique identifier for the target chat or username of the target channel (in the format @channelusername)"""
phone_number: str
"""Contact's phone number"""
first_name: str
"""Contact's first name"""
last_name: Optional[str] = None
"""Contact's last name"""
vcard: Optional[str] = None
"""Additional data about the contact in the form of a vCard, 0-2048 bytes"""
disable_notification: Optional[bool] = None
"""Sends the message silently. Users will receive a notification with no sound."""
reply_to_message_id: Optional[int] = None
"""If the message is a reply, ID of the original message"""
reply_markup: Optional[
Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply]
] = None
"""Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove keyboard or to force a reply from the user."""
def build_request(self) -> Request:
data: Dict[str, Any] = self.dict(exclude_unset=True, exclude={})
files: Dict[str, Any] = {}
return Request(method="sendContact", data=data, files=files)

View file

@ -0,0 +1,52 @@
from typing import Any, Dict, Optional, Union
from ..types import (
ForceReply,
InlineKeyboardMarkup,
InputFile,
Message,
ReplyKeyboardMarkup,
ReplyKeyboardRemove,
)
from .base import Request, TelegramMethod
class SendDocument(TelegramMethod[Message]):
"""
Use this method to send general files. On success, the sent Message is returned. Bots can currently send files of any type of up to 50 MB in size, this limit may be changed in the future.
Source: https://core.telegram.org/bots/api#senddocument
"""
__returning__ = Message
chat_id: Union[int, str]
"""Unique identifier for the target chat or username of the target channel (in the format @channelusername)"""
document: Union[InputFile, str]
"""File to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a file from the Internet, or upload a new one using multipart/form-data."""
thumb: Optional[Union[InputFile, str]] = None
"""Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnails width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails cant be reused and can be only uploaded as a new file, so you can pass 'attach://<file_attach_name>' if the thumbnail was uploaded using multipart/form-data under <file_attach_name>."""
caption: Optional[str] = None
"""Document caption (may also be used when resending documents by file_id), 0-1024 characters"""
parse_mode: Optional[str] = None
"""Send Markdown or HTML, if you want Telegram apps to show bold, italic, fixed-width text or inline URLs in the media caption."""
disable_notification: Optional[bool] = None
"""Sends the message silently. Users will receive a notification with no sound."""
reply_to_message_id: Optional[int] = None
"""If the message is a reply, ID of the original message"""
reply_markup: Optional[
Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply]
] = None
"""Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user."""
def build_request(self) -> Request:
data: Dict[str, Any] = self.dict(exclude_unset=True, exclude={})
files: Dict[str, Any] = {}
return Request(method="sendDocument", data=data, files=files)

View file

@ -0,0 +1,34 @@
from typing import Any, Dict, Optional
from ..types import InlineKeyboardMarkup, Message
from .base import Request, TelegramMethod
class SendGame(TelegramMethod[Message]):
"""
Use this method to send a game. On success, the sent Message is returned.
Source: https://core.telegram.org/bots/api#sendgame
"""
__returning__ = Message
chat_id: int
"""Unique identifier for the target chat"""
game_short_name: str
"""Short name of the game, serves as the unique identifier for the game. Set up your games via Botfather."""
disable_notification: Optional[bool] = None
"""Sends the message silently. Users will receive a notification with no sound."""
reply_to_message_id: Optional[int] = None
"""If the message is a reply, ID of the original message"""
reply_markup: Optional[InlineKeyboardMarkup] = None
"""A JSON-serialized object for an inline keyboard. If empty, one Play game_title button will be shown. If not empty, the first button must launch the game."""
def build_request(self) -> Request:
data: Dict[str, Any] = self.dict(exclude_unset=True, exclude={})
files: Dict[str, Any] = {}
return Request(method="sendGame", data=data, files=files)

View file

@ -0,0 +1,88 @@
from typing import Any, Dict, List, Optional
from ..types import InlineKeyboardMarkup, LabeledPrice, Message
from .base import Request, TelegramMethod
class SendInvoice(TelegramMethod[Message]):
"""
Use this method to send invoices. On success, the sent Message is returned.
Source: https://core.telegram.org/bots/api#sendinvoice
"""
__returning__ = Message
chat_id: int
"""Unique identifier for the target private chat"""
title: str
"""Product name, 1-32 characters"""
description: str
"""Product description, 1-255 characters"""
payload: str
"""Bot-defined invoice payload, 1-128 bytes. This will not be displayed to the user, use for your internal processes."""
provider_token: str
"""Payments provider token, obtained via Botfather"""
start_parameter: str
"""Unique deep-linking parameter that can be used to generate this invoice when used as a start parameter"""
currency: str
"""Three-letter ISO 4217 currency code, see more on currencies"""
prices: List[LabeledPrice]
"""Price breakdown, a list of components (e.g. product price, tax, discount, delivery cost, delivery tax, bonus, etc.)"""
provider_data: Optional[str] = None
"""JSON-encoded data about the invoice, which will be shared with the payment provider. A detailed description of required fields should be provided by the payment provider."""
photo_url: Optional[str] = None
"""URL of the product photo for the invoice. Can be a photo of the goods or a marketing image for a service. People like it better when they see what they are paying for."""
photo_size: Optional[int] = None
"""Photo size"""
photo_width: Optional[int] = None
"""Photo width"""
photo_height: Optional[int] = None
"""Photo height"""
need_name: Optional[bool] = None
"""Pass True, if you require the user's full name to complete the order"""
need_phone_number: Optional[bool] = None
"""Pass True, if you require the user's phone number to complete the order"""
need_email: Optional[bool] = None
"""Pass True, if you require the user's email address to complete the order"""
need_shipping_address: Optional[bool] = None
"""Pass True, if you require the user's shipping address to complete the order"""
send_phone_number_to_provider: Optional[bool] = None
"""Pass True, if user's phone number should be sent to provider"""
send_email_to_provider: Optional[bool] = None
"""Pass True, if user's email address should be sent to provider"""
is_flexible: Optional[bool] = None
"""Pass True, if the final price depends on the shipping method"""
disable_notification: Optional[bool] = None
"""Sends the message silently. Users will receive a notification with no sound."""
reply_to_message_id: Optional[int] = None
"""If the message is a reply, ID of the original message"""
reply_markup: Optional[InlineKeyboardMarkup] = None
"""A JSON-serialized object for an inline keyboard. If empty, one 'Pay total price' button will be shown. If not empty, the first button must be a Pay button."""
def build_request(self) -> Request:
data: Dict[str, Any] = self.dict(exclude_unset=True, exclude={})
files: Dict[str, Any] = {}
return Request(method="sendInvoice", data=data, files=files)

View file

@ -0,0 +1,48 @@
from typing import Any, Dict, Optional, Union
from ..types import (
ForceReply,
InlineKeyboardMarkup,
Message,
ReplyKeyboardMarkup,
ReplyKeyboardRemove,
)
from .base import Request, TelegramMethod
class SendLocation(TelegramMethod[Message]):
"""
Use this method to send point on the map. On success, the sent Message is returned.
Source: https://core.telegram.org/bots/api#sendlocation
"""
__returning__ = Message
chat_id: Union[int, str]
"""Unique identifier for the target chat or username of the target channel (in the format @channelusername)"""
latitude: float
"""Latitude of the location"""
longitude: float
"""Longitude of the location"""
live_period: Optional[int] = None
"""Period in seconds for which the location will be updated (see Live Locations, should be between 60 and 86400."""
disable_notification: Optional[bool] = None
"""Sends the message silently. Users will receive a notification with no sound."""
reply_to_message_id: Optional[int] = None
"""If the message is a reply, ID of the original message"""
reply_markup: Optional[
Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply]
] = None
"""Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user."""
def build_request(self) -> Request:
data: Dict[str, Any] = self.dict(exclude_unset=True, exclude={})
files: Dict[str, Any] = {}
return Request(method="sendLocation", data=data, files=files)

View file

@ -0,0 +1,31 @@
from typing import Any, Dict, List, Optional, Union
from ..types import InputMediaPhoto, InputMediaVideo, Message
from .base import Request, TelegramMethod
class SendMediaGroup(TelegramMethod[List[Message]]):
"""
Use this method to send a group of photos or videos as an album. On success, an array of the sent Messages is returned.
Source: https://core.telegram.org/bots/api#sendmediagroup
"""
__returning__ = List[Message]
chat_id: Union[int, str]
"""Unique identifier for the target chat or username of the target channel (in the format @channelusername)"""
media: List[Union[InputMediaPhoto, InputMediaVideo]]
"""A JSON-serialized array describing photos and videos to be sent, must include 210 items"""
disable_notification: Optional[bool] = None
"""Sends the messages silently. Users will receive a notification with no sound."""
reply_to_message_id: Optional[int] = None
"""If the messages are a reply, ID of the original message"""
def build_request(self) -> Request:
data: Dict[str, Any] = self.dict(exclude_unset=True, exclude={})
files: Dict[str, Any] = {}
return Request(method="sendMediaGroup", data=data, files=files)

View file

@ -0,0 +1,48 @@
from typing import Any, Dict, Optional, Union
from ..types import (
ForceReply,
InlineKeyboardMarkup,
Message,
ReplyKeyboardMarkup,
ReplyKeyboardRemove,
)
from .base import Request, TelegramMethod
class SendMessage(TelegramMethod[Message]):
"""
Use this method to send text messages. On success, the sent Message is returned.
Source: https://core.telegram.org/bots/api#sendmessage
"""
__returning__ = Message
chat_id: Union[int, str]
"""Unique identifier for the target chat or username of the target channel (in the format @channelusername)"""
text: str
"""Text of the message to be sent"""
parse_mode: Optional[str] = None
"""Send Markdown or HTML, if you want Telegram apps to show bold, italic, fixed-width text or inline URLs in your bot's message."""
disable_web_page_preview: Optional[bool] = None
"""Disables link previews for links in this message"""
disable_notification: Optional[bool] = None
"""Sends the message silently. Users will receive a notification with no sound."""
reply_to_message_id: Optional[int] = None
"""If the message is a reply, ID of the original message"""
reply_markup: Optional[
Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply]
] = None
"""Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user."""
def build_request(self) -> Request:
data: Dict[str, Any] = self.dict(exclude_unset=True, exclude={})
files: Dict[str, Any] = {}
return Request(method="sendMessage", data=data, files=files)

View file

@ -0,0 +1,49 @@
from typing import Any, Dict, Optional, Union
from ..types import (
ForceReply,
InlineKeyboardMarkup,
InputFile,
Message,
ReplyKeyboardMarkup,
ReplyKeyboardRemove,
)
from .base import Request, TelegramMethod
class SendPhoto(TelegramMethod[Message]):
"""
Use this method to send photos. On success, the sent Message is returned.
Source: https://core.telegram.org/bots/api#sendphoto
"""
__returning__ = Message
chat_id: Union[int, str]
"""Unique identifier for the target chat or username of the target channel (in the format @channelusername)"""
photo: Union[InputFile, str]
"""Photo to send. Pass a file_id as String to send a photo that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a photo from the Internet, or upload a new photo using multipart/form-data."""
caption: Optional[str] = None
"""Photo caption (may also be used when resending photos by file_id), 0-1024 characters"""
parse_mode: Optional[str] = None
"""Send Markdown or HTML, if you want Telegram apps to show bold, italic, fixed-width text or inline URLs in the media caption."""
disable_notification: Optional[bool] = None
"""Sends the message silently. Users will receive a notification with no sound."""
reply_to_message_id: Optional[int] = None
"""If the message is a reply, ID of the original message"""
reply_markup: Optional[
Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply]
] = None
"""Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user."""
def build_request(self) -> Request:
data: Dict[str, Any] = self.dict(exclude_unset=True, exclude={})
files: Dict[str, Any] = {}
return Request(method="sendPhoto", data=data, files=files)

View file

@ -0,0 +1,45 @@
from typing import Any, Dict, List, Optional, Union
from ..types import (
ForceReply,
InlineKeyboardMarkup,
Message,
ReplyKeyboardMarkup,
ReplyKeyboardRemove,
)
from .base import Request, TelegramMethod
class SendPoll(TelegramMethod[Message]):
"""
Use this method to send a native poll. A native poll can't be sent to a private chat. On success, the sent Message is returned.
Source: https://core.telegram.org/bots/api#sendpoll
"""
__returning__ = Message
chat_id: Union[int, str]
"""Unique identifier for the target chat or username of the target channel (in the format @channelusername). A native poll can't be sent to a private chat."""
question: str
"""Poll question, 1-255 characters"""
options: List[str]
"""List of answer options, 2-10 strings 1-100 characters each"""
disable_notification: Optional[bool] = None
"""Sends the message silently. Users will receive a notification with no sound."""
reply_to_message_id: Optional[int] = None
"""If the message is a reply, ID of the original message"""
reply_markup: Optional[
Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply]
] = None
"""Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user."""
def build_request(self) -> Request:
data: Dict[str, Any] = self.dict(exclude_unset=True, exclude={})
files: Dict[str, Any] = {}
return Request(method="sendPoll", data=data, files=files)

View file

@ -0,0 +1,43 @@
from typing import Any, Dict, Optional, Union
from ..types import (
ForceReply,
InlineKeyboardMarkup,
InputFile,
Message,
ReplyKeyboardMarkup,
ReplyKeyboardRemove,
)
from .base import Request, TelegramMethod
class SendSticker(TelegramMethod[Message]):
"""
Use this method to send static .WEBP or animated .TGS stickers. On success, the sent Message is returned.
Source: https://core.telegram.org/bots/api#sendsticker
"""
__returning__ = Message
chat_id: Union[int, str]
"""Unique identifier for the target chat or username of the target channel (in the format @channelusername)"""
sticker: Union[InputFile, str]
"""Sticker to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a .webp file from the Internet, or upload a new one using multipart/form-data."""
disable_notification: Optional[bool] = None
"""Sends the message silently. Users will receive a notification with no sound."""
reply_to_message_id: Optional[int] = None
"""If the message is a reply, ID of the original message"""
reply_markup: Optional[
Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply]
] = None
"""Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user."""
def build_request(self) -> Request:
data: Dict[str, Any] = self.dict(exclude_unset=True, exclude={})
files: Dict[str, Any] = {}
return Request(method="sendSticker", data=data, files=files)

View file

@ -0,0 +1,57 @@
from typing import Any, Dict, Optional, Union
from ..types import (
ForceReply,
InlineKeyboardMarkup,
Message,
ReplyKeyboardMarkup,
ReplyKeyboardRemove,
)
from .base import Request, TelegramMethod
class SendVenue(TelegramMethod[Message]):
"""
Use this method to send information about a venue. On success, the sent Message is returned.
Source: https://core.telegram.org/bots/api#sendvenue
"""
__returning__ = Message
chat_id: Union[int, str]
"""Unique identifier for the target chat or username of the target channel (in the format @channelusername)"""
latitude: float
"""Latitude of the venue"""
longitude: float
"""Longitude of the venue"""
title: str
"""Name of the venue"""
address: str
"""Address of the venue"""
foursquare_id: Optional[str] = None
"""Foursquare identifier of the venue"""
foursquare_type: Optional[str] = None
"""Foursquare type of the venue, if known. (For example, 'arts_entertainment/default', 'arts_entertainment/aquarium' or 'food/icecream'.)"""
disable_notification: Optional[bool] = None
"""Sends the message silently. Users will receive a notification with no sound."""
reply_to_message_id: Optional[int] = None
"""If the message is a reply, ID of the original message"""
reply_markup: Optional[
Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply]
] = None
"""Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user."""
def build_request(self) -> Request:
data: Dict[str, Any] = self.dict(exclude_unset=True, exclude={})
files: Dict[str, Any] = {}
return Request(method="sendVenue", data=data, files=files)

View file

@ -0,0 +1,64 @@
from typing import Any, Dict, Optional, Union
from ..types import (
ForceReply,
InlineKeyboardMarkup,
InputFile,
Message,
ReplyKeyboardMarkup,
ReplyKeyboardRemove,
)
from .base import Request, TelegramMethod
class SendVideo(TelegramMethod[Message]):
"""
Use this method to send video files, Telegram clients support mp4 videos (other formats may be sent as Document). On success, the sent Message is returned. Bots can currently send video files of up to 50 MB in size, this limit may be changed in the future.
Source: https://core.telegram.org/bots/api#sendvideo
"""
__returning__ = Message
chat_id: Union[int, str]
"""Unique identifier for the target chat or username of the target channel (in the format @channelusername)"""
video: Union[InputFile, str]
"""Video to send. Pass a file_id as String to send a video that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a video from the Internet, or upload a new video using multipart/form-data."""
duration: Optional[int] = None
"""Duration of sent video in seconds"""
width: Optional[int] = None
"""Video width"""
height: Optional[int] = None
"""Video height"""
thumb: Optional[Union[InputFile, str]] = None
"""Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnails width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails cant be reused and can be only uploaded as a new file, so you can pass 'attach://<file_attach_name>' if the thumbnail was uploaded using multipart/form-data under <file_attach_name>."""
caption: Optional[str] = None
"""Video caption (may also be used when resending videos by file_id), 0-1024 characters"""
parse_mode: Optional[str] = None
"""Send Markdown or HTML, if you want Telegram apps to show bold, italic, fixed-width text or inline URLs in the media caption."""
supports_streaming: Optional[bool] = None
"""Pass True, if the uploaded video is suitable for streaming"""
disable_notification: Optional[bool] = None
"""Sends the message silently. Users will receive a notification with no sound."""
reply_to_message_id: Optional[int] = None
"""If the message is a reply, ID of the original message"""
reply_markup: Optional[
Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply]
] = None
"""Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user."""
def build_request(self) -> Request:
data: Dict[str, Any] = self.dict(exclude_unset=True, exclude={})
files: Dict[str, Any] = {}
return Request(method="sendVideo", data=data, files=files)

View file

@ -0,0 +1,52 @@
from typing import Any, Dict, Optional, Union
from ..types import (
ForceReply,
InlineKeyboardMarkup,
InputFile,
Message,
ReplyKeyboardMarkup,
ReplyKeyboardRemove,
)
from .base import Request, TelegramMethod
class SendVideoNote(TelegramMethod[Message]):
"""
As of v.4.0, Telegram clients support rounded square mp4 videos of up to 1 minute long. Use this method to send video messages. On success, the sent Message is returned.
Source: https://core.telegram.org/bots/api#sendvideonote
"""
__returning__ = Message
chat_id: Union[int, str]
"""Unique identifier for the target chat or username of the target channel (in the format @channelusername)"""
video_note: Union[InputFile, str]
"""Video note to send. Pass a file_id as String to send a video note that exists on the Telegram servers (recommended) or upload a new video using multipart/form-data.. Sending video notes by a URL is currently unsupported"""
duration: Optional[int] = None
"""Duration of sent video in seconds"""
length: Optional[int] = None
"""Video width and height, i.e. diameter of the video message"""
thumb: Optional[Union[InputFile, str]] = None
"""Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnails width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails cant be reused and can be only uploaded as a new file, so you can pass 'attach://<file_attach_name>' if the thumbnail was uploaded using multipart/form-data under <file_attach_name>."""
disable_notification: Optional[bool] = None
"""Sends the message silently. Users will receive a notification with no sound."""
reply_to_message_id: Optional[int] = None
"""If the message is a reply, ID of the original message"""
reply_markup: Optional[
Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply]
] = None
"""Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user."""
def build_request(self) -> Request:
data: Dict[str, Any] = self.dict(exclude_unset=True, exclude={})
files: Dict[str, Any] = {}
return Request(method="sendVideoNote", data=data, files=files)

View file

@ -0,0 +1,52 @@
from typing import Any, Dict, Optional, Union
from ..types import (
ForceReply,
InlineKeyboardMarkup,
InputFile,
Message,
ReplyKeyboardMarkup,
ReplyKeyboardRemove,
)
from .base import Request, TelegramMethod
class SendVoice(TelegramMethod[Message]):
"""
Use this method to send audio files, if you want Telegram clients to display the file as a playable voice message. For this to work, your audio must be in an .ogg file encoded with OPUS (other formats may be sent as Audio or Document). On success, the sent Message is returned. Bots can currently send voice messages of up to 50 MB in size, this limit may be changed in the future.
Source: https://core.telegram.org/bots/api#sendvoice
"""
__returning__ = Message
chat_id: Union[int, str]
"""Unique identifier for the target chat or username of the target channel (in the format @channelusername)"""
voice: Union[InputFile, str]
"""Audio file to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a file from the Internet, or upload a new one using multipart/form-data."""
caption: Optional[str] = None
"""Voice message caption, 0-1024 characters"""
parse_mode: Optional[str] = None
"""Send Markdown or HTML, if you want Telegram apps to show bold, italic, fixed-width text or inline URLs in the media caption."""
duration: Optional[int] = None
"""Duration of the voice message in seconds"""
disable_notification: Optional[bool] = None
"""Sends the message silently. Users will receive a notification with no sound."""
reply_to_message_id: Optional[int] = None
"""If the message is a reply, ID of the original message"""
reply_markup: Optional[
Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply]
] = None
"""Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user."""
def build_request(self) -> Request:
data: Dict[str, Any] = self.dict(exclude_unset=True, exclude={})
files: Dict[str, Any] = {}
return Request(method="sendVoice", data=data, files=files)

View file

@ -0,0 +1,24 @@
from typing import Any, Dict, Optional, Union
from .base import Request, TelegramMethod
class SetChatDescription(TelegramMethod[bool]):
"""
Use this method to change the description of a group, a supergroup or a channel. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Returns True on success.
Source: https://core.telegram.org/bots/api#setchatdescription
"""
__returning__ = bool
chat_id: Union[int, str]
"""Unique identifier for the target chat or username of the target channel (in the format @channelusername)"""
description: Optional[str] = None
"""New chat description, 0-255 characters"""
def build_request(self) -> Request:
data: Dict[str, Any] = self.dict(exclude_unset=True, exclude={})
files: Dict[str, Any] = {}
return Request(method="setChatDescription", data=data, files=files)

View file

@ -0,0 +1,25 @@
from typing import Any, Dict, Union
from ..types import ChatPermissions
from .base import Request, TelegramMethod
class SetChatPermissions(TelegramMethod[bool]):
"""
Use this method to set default chat permissions for all members. The bot must be an administrator in the group or a supergroup for this to work and must have the can_restrict_members admin rights. Returns True on success.
Source: https://core.telegram.org/bots/api#setchatpermissions
"""
__returning__ = bool
chat_id: Union[int, str]
"""Unique identifier for the target chat or username of the target supergroup (in the format @supergroupusername)"""
permissions: ChatPermissions
"""New default chat permissions"""
def build_request(self) -> Request:
data: Dict[str, Any] = self.dict(exclude_unset=True, exclude={})
files: Dict[str, Any] = {}
return Request(method="setChatPermissions", data=data, files=files)

View file

@ -0,0 +1,25 @@
from typing import Any, Dict, Union
from ..types import InputFile
from .base import Request, TelegramMethod
class SetChatPhoto(TelegramMethod[bool]):
"""
Use this method to set a new profile photo for the chat. Photos can't be changed for private chats. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Returns True on success.
Source: https://core.telegram.org/bots/api#setchatphoto
"""
__returning__ = bool
chat_id: Union[int, str]
"""Unique identifier for the target chat or username of the target channel (in the format @channelusername)"""
photo: InputFile
"""New chat photo, uploaded using multipart/form-data"""
def build_request(self) -> Request:
data: Dict[str, Any] = self.dict(exclude_unset=True, exclude={})
files: Dict[str, Any] = {}
return Request(method="setChatPhoto", data=data, files=files)

View file

@ -0,0 +1,24 @@
from typing import Any, Dict, Union
from .base import Request, TelegramMethod
class SetChatStickerSet(TelegramMethod[bool]):
"""
Use this method to set a new group sticker set for a supergroup. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Use the field can_set_sticker_set optionally returned in getChat requests to check if the bot can use this method. Returns True on success.
Source: https://core.telegram.org/bots/api#setchatstickerset
"""
__returning__ = bool
chat_id: Union[int, str]
"""Unique identifier for the target chat or username of the target supergroup (in the format @supergroupusername)"""
sticker_set_name: str
"""Name of the sticker set to be set as the group sticker set"""
def build_request(self) -> Request:
data: Dict[str, Any] = self.dict(exclude_unset=True, exclude={})
files: Dict[str, Any] = {}
return Request(method="setChatStickerSet", data=data, files=files)

View file

@ -0,0 +1,24 @@
from typing import Any, Dict, Union
from .base import Request, TelegramMethod
class SetChatTitle(TelegramMethod[bool]):
"""
Use this method to change the title of a chat. Titles can't be changed for private chats. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Returns True on success.
Source: https://core.telegram.org/bots/api#setchattitle
"""
__returning__ = bool
chat_id: Union[int, str]
"""Unique identifier for the target chat or username of the target channel (in the format @channelusername)"""
title: str
"""New chat title, 1-255 characters"""
def build_request(self) -> Request:
data: Dict[str, Any] = self.dict(exclude_unset=True, exclude={})
files: Dict[str, Any] = {}
return Request(method="setChatTitle", data=data, files=files)

View file

@ -0,0 +1,40 @@
from typing import Any, Dict, Optional, Union
from ..types import Message
from .base import Request, TelegramMethod
class SetGameScore(TelegramMethod[Union[Message, bool]]):
"""
Use this method to set the score of the specified user in a game. On success, if the message was sent by the bot, returns the edited Message, otherwise returns True. Returns an error, if the new score is not greater than the user's current score in the chat and force is False.
Source: https://core.telegram.org/bots/api#setgamescore
"""
__returning__ = Union[Message, bool]
user_id: int
"""User identifier"""
score: int
"""New score, must be non-negative"""
force: Optional[bool] = None
"""Pass True, if the high score is allowed to decrease. This can be useful when fixing mistakes or banning cheaters"""
disable_edit_message: Optional[bool] = None
"""Pass True, if the game message should not be automatically edited to include the current scoreboard"""
chat_id: Optional[int] = None
"""Required if inline_message_id is not specified. Unique identifier for the target chat"""
message_id: Optional[int] = None
"""Required if inline_message_id is not specified. Identifier of the sent message"""
inline_message_id: Optional[str] = None
"""Required if chat_id and message_id are not specified. Identifier of the inline message"""
def build_request(self) -> Request:
data: Dict[str, Any] = self.dict(exclude_unset=True, exclude={})
files: Dict[str, Any] = {}
return Request(method="setGameScore", data=data, files=files)

View file

@ -0,0 +1,26 @@
from typing import Any, Dict, List
from ..types import PassportElementError
from .base import Request, TelegramMethod
class SetPassportDataErrors(TelegramMethod[bool]):
"""
Informs a user that some of the Telegram Passport elements they provided contains errors. The user will not be able to re-submit their Passport to you until the errors are fixed (the contents of the field for which you returned the error must change). Returns True on success.
Use this if the data submitted by the user doesn't satisfy the standards your service requires for any reason. For example, if a birthday date seems invalid, a submitted document is blurry, a scan shows evidence of tampering, etc. Supply some details in the error message to make sure the user knows how to correct the issues.
Source: https://core.telegram.org/bots/api#setpassportdataerrors
"""
__returning__ = bool
user_id: int
"""User identifier"""
errors: List[PassportElementError]
"""A JSON-serialized array describing the errors"""
def build_request(self) -> Request:
data: Dict[str, Any] = self.dict(exclude_unset=True, exclude={})
files: Dict[str, Any] = {}
return Request(method="setPassportDataErrors", data=data, files=files)

View file

@ -0,0 +1,24 @@
from typing import Any, Dict
from .base import Request, TelegramMethod
class SetStickerPositionInSet(TelegramMethod[bool]):
"""
Use this method to move a sticker in a set created by the bot to a specific position . Returns True on success.
Source: https://core.telegram.org/bots/api#setstickerpositioninset
"""
__returning__ = bool
sticker: str
"""File identifier of the sticker"""
position: int
"""New sticker position in the set, zero-based"""
def build_request(self) -> Request:
data: Dict[str, Any] = self.dict(exclude_unset=True, exclude={})
files: Dict[str, Any] = {}
return Request(method="setStickerPositionInSet", data=data, files=files)

View file

@ -0,0 +1,39 @@
from typing import Any, Dict, List, Optional
from ..types import InputFile
from .base import Request, TelegramMethod
class SetWebhook(TelegramMethod[bool]):
"""
Use this method to specify a url and receive incoming updates via an outgoing webhook. Whenever there is an update for the bot, we will send an HTTPS POST request to the specified url, containing a JSON-serialized Update. In case of an unsuccessful request, we will give up after a reasonable amount of attempts. Returns True on success.
If you'd like to make sure that the Webhook request comes from Telegram, we recommend using a secret path in the URL, e.g. https://www.example.com/<token>. Since nobody else knows your bots token, you can be pretty sure its us.
Notes
1. You will not be able to receive updates using getUpdates for as long as an outgoing webhook is set up.
2. To use a self-signed certificate, you need to upload your public key certificate using certificate parameter. Please upload as InputFile, sending a String will not work.
3. Ports currently supported for Webhooks: 443, 80, 88, 8443.
NEW! If you're having any trouble setting up webhooks, please check out this amazing guide to Webhooks.
Source: https://core.telegram.org/bots/api#setwebhook
"""
__returning__ = bool
url: str
"""HTTPS url to send updates to. Use an empty string to remove webhook integration"""
certificate: Optional[InputFile] = None
"""Upload your public key certificate so that the root certificate in use can be checked. See our self-signed guide for details."""
max_connections: Optional[int] = None
"""Maximum allowed number of simultaneous HTTPS connections to the webhook for update delivery, 1-100. Defaults to 40. Use lower values to limit the load on your bots server, and higher values to increase your bots throughput."""
allowed_updates: Optional[List[str]] = None
"""List the types of updates you want your bot to receive. For example, specify ['message', 'edited_channel_post', 'callback_query'] to only receive updates of these types. See Update for a complete list of available update types. Specify an empty list to receive all updates regardless of type (default). If not specified, the previous setting will be used.
Please note that this parameter doesn't affect updates created before the call to the setWebhook, so unwanted updates may be received for a short period of time."""
def build_request(self) -> Request:
data: Dict[str, Any] = self.dict(exclude_unset=True, exclude={})
files: Dict[str, Any] = {}
return Request(method="setWebhook", data=data, files=files)

View file

@ -0,0 +1,31 @@
from typing import Any, Dict, Optional, Union
from ..types import InlineKeyboardMarkup, Message
from .base import Request, TelegramMethod
class StopMessageLiveLocation(TelegramMethod[Union[Message, bool]]):
"""
Use this method to stop updating a live location message before live_period expires. On success, if the message was sent by the bot, the sent Message is returned, otherwise True is returned.
Source: https://core.telegram.org/bots/api#stopmessagelivelocation
"""
__returning__ = Union[Message, bool]
chat_id: Optional[Union[int, str]] = None
"""Required if inline_message_id is not specified. Unique identifier for the target chat or username of the target channel (in the format @channelusername)"""
message_id: Optional[int] = None
"""Required if inline_message_id is not specified. Identifier of the message with live location to stop"""
inline_message_id: Optional[str] = None
"""Required if chat_id and message_id are not specified. Identifier of the inline message"""
reply_markup: Optional[InlineKeyboardMarkup] = None
"""A JSON-serialized object for a new inline keyboard."""
def build_request(self) -> Request:
data: Dict[str, Any] = self.dict(exclude_unset=True, exclude={})
files: Dict[str, Any] = {}
return Request(method="stopMessageLiveLocation", data=data, files=files)

View file

@ -0,0 +1,28 @@
from typing import Any, Dict, Optional, Union
from ..types import InlineKeyboardMarkup, Poll
from .base import Request, TelegramMethod
class StopPoll(TelegramMethod[Poll]):
"""
Use this method to stop a poll which was sent by the bot. On success, the stopped Poll with the final results is returned.
Source: https://core.telegram.org/bots/api#stoppoll
"""
__returning__ = Poll
chat_id: Union[int, str]
"""Unique identifier for the target chat or username of the target channel (in the format @channelusername)"""
message_id: int
"""Identifier of the original message with the poll"""
reply_markup: Optional[InlineKeyboardMarkup] = None
"""A JSON-serialized object for a new message inline keyboard."""
def build_request(self) -> Request:
data: Dict[str, Any] = self.dict(exclude_unset=True, exclude={})
files: Dict[str, Any] = {}
return Request(method="stopPoll", data=data, files=files)

View file

@ -0,0 +1,24 @@
from typing import Any, Dict, Union
from .base import Request, TelegramMethod
class UnbanChatMember(TelegramMethod[bool]):
"""
Use this method to unban a previously kicked user in a supergroup or channel. The user will not return to the group or channel automatically, but will be able to join via link, etc. The bot must be an administrator for this to work. Returns True on success.
Source: https://core.telegram.org/bots/api#unbanchatmember
"""
__returning__ = bool
chat_id: Union[int, str]
"""Unique identifier for the target group or username of the target supergroup or channel (in the format @username)"""
user_id: int
"""Unique identifier of the target user"""
def build_request(self) -> Request:
data: Dict[str, Any] = self.dict(exclude_unset=True, exclude={})
files: Dict[str, Any] = {}
return Request(method="unbanChatMember", data=data, files=files)

View file

@ -0,0 +1,21 @@
from typing import Any, Dict, Union
from .base import Request, TelegramMethod
class UnpinChatMessage(TelegramMethod[bool]):
"""
Use this method to unpin a message in a group, a supergroup, or a channel. The bot must be an administrator in the chat for this to work and must have the can_pin_messages admin right in the supergroup or can_edit_messages admin right in the channel. Returns True on success.
Source: https://core.telegram.org/bots/api#unpinchatmessage
"""
__returning__ = bool
chat_id: Union[int, str]
"""Unique identifier for the target chat or username of the target channel (in the format @channelusername)"""
def build_request(self) -> Request:
data: Dict[str, Any] = self.dict(exclude_unset=True, exclude={})
files: Dict[str, Any] = {}
return Request(method="unpinChatMessage", data=data, files=files)

View file

@ -0,0 +1,25 @@
from typing import Any, Dict
from ..types import File, InputFile
from .base import Request, TelegramMethod
class UploadStickerFile(TelegramMethod[File]):
"""
Use this method to upload a .png file with a sticker for later use in createNewStickerSet and addStickerToSet methods (can be used multiple times). Returns the uploaded File on success.
Source: https://core.telegram.org/bots/api#uploadstickerfile
"""
__returning__ = File
user_id: int
"""User identifier of sticker file owner"""
png_sticker: InputFile
"""Png image with the sticker, must be up to 512 kilobytes in size, dimensions must not exceed 512px, and either width or height must be exactly 512px."""
def build_request(self) -> Request:
data: Dict[str, Any] = self.dict(exclude_unset=True, exclude={})
files: Dict[str, Any] = {}
return Request(method="uploadStickerFile", data=data, files=files)

View file

View file

@ -0,0 +1,51 @@
from typing import Optional, TypeVar
from aiohttp import ClientSession, FormData
from pydantic import BaseModel
from .base import BaseSession, TelegramAPIServer, PRODUCTION
from ..methods import TelegramMethod, Request
T = TypeVar('T')
class AiohttpSession(BaseSession):
def __init__(self, api: TelegramAPIServer = PRODUCTION):
super(AiohttpSession, self).__init__(api=api)
self._session: Optional[ClientSession] = None
async def create_session(self):
if self._session is None or self._session.closed:
self._session = ClientSession()
async def close(self):
if self._session is not None and not self._session.closed:
await self._session.close()
def build_form_data(self, request: Request):
form = FormData()
for key, value in request.data.items():
if value is None:
continue
if isinstance(value, bool):
print("elif isinstance(value, bool):", key, value)
form.add_field(key, value)
else:
print("else:", key, value)
form.add_field(key, str(value))
return form
async def make_request(self, token: str, call: TelegramMethod[T]) -> T:
await self.create_session()
request = call.build_request()
url = self.api.api_url(token=token, method=request.method)
form = self.build_form_data(request)
async with self._session.post(url, data=form) as response:
raw_result = await response.json()
response = call.build_response(raw_result)
if not response.ok:
self.raise_for_status(response)
return response.result

View file

View file

@ -0,0 +1,54 @@
import abc
import asyncio
from typing import TypeVar, Generic
from pydantic.dataclasses import dataclass
from aiogram.api.methods import Response, TelegramMethod
T = TypeVar('T')
@dataclass
class TelegramAPIServer:
base: str
file: str
def api_url(self, token: str, method: str) -> str:
return self.base.format(token=token, method=method)
def file_url(self, token: str, path: str) -> str:
return self.file.format(token=token, path=path)
PRODUCTION = TelegramAPIServer(
base='https://api.telegram.org/bot{token}/{method}',
file='https://api.telegram.org/file/bot{token}/{path}'
)
class BaseSession(abc.ABC, Generic[T]):
def __init__(self, api: TelegramAPIServer = PRODUCTION):
self.api = api
def raise_for_status(self, response: Response[T]):
print(f"ERROR: {response}")
@abc.abstractmethod
async def close(self):
pass
@abc.abstractmethod
async def make_request(self, token: str, method: TelegramMethod[T]) -> T:
pass
def __del__(self):
try:
loop = asyncio.get_running_loop()
except RuntimeError:
loop = None
if loop is None or loop.is_closed():
loop = asyncio.new_event_loop()
loop.run_until_complete(self.close())
return
loop.create_task(self.close())

View file

@ -0,0 +1,199 @@
from .animation import Animation
from .audio import Audio
from .base import TelegramObject
from .callback_game import CallbackGame
from .callback_query import CallbackQuery
from .chat import Chat
from .chat_member import ChatMember
from .chat_permissions import ChatPermissions
from .chat_photo import ChatPhoto
from .chosen_inline_result import ChosenInlineResult
from .contact import Contact
from .document import Document
from .encrypted_credentials import EncryptedCredentials
from .encrypted_passport_element import EncryptedPassportElement
from .file import File
from .force_reply import ForceReply
from .game import Game
from .game_high_score import GameHighScore
from .inline_keyboard_button import InlineKeyboardButton
from .inline_keyboard_markup import InlineKeyboardMarkup
from .inline_query import InlineQuery
from .inline_query_result import InlineQueryResult
from .inline_query_result_article import InlineQueryResultArticle
from .inline_query_result_audio import InlineQueryResultAudio
from .inline_query_result_cached_audio import InlineQueryResultCachedAudio
from .inline_query_result_cached_document import InlineQueryResultCachedDocument
from .inline_query_result_cached_gif import InlineQueryResultCachedGif
from .inline_query_result_cached_mpeg4_gif import InlineQueryResultCachedMpeg4Gif
from .inline_query_result_cached_photo import InlineQueryResultCachedPhoto
from .inline_query_result_cached_sticker import InlineQueryResultCachedSticker
from .inline_query_result_cached_video import InlineQueryResultCachedVideo
from .inline_query_result_cached_voice import InlineQueryResultCachedVoice
from .inline_query_result_contact import InlineQueryResultContact
from .inline_query_result_document import InlineQueryResultDocument
from .inline_query_result_game import InlineQueryResultGame
from .inline_query_result_gif import InlineQueryResultGif
from .inline_query_result_location import InlineQueryResultLocation
from .inline_query_result_mpeg4_gif import InlineQueryResultMpeg4Gif
from .inline_query_result_photo import InlineQueryResultPhoto
from .inline_query_result_venue import InlineQueryResultVenue
from .inline_query_result_video import InlineQueryResultVideo
from .inline_query_result_voice import InlineQueryResultVoice
from .input_contact_message_content import InputContactMessageContent
from .input_file import InputFile
from .input_location_message_content import InputLocationMessageContent
from .input_media import InputMedia
from .input_media_animation import InputMediaAnimation
from .input_media_audio import InputMediaAudio
from .input_media_document import InputMediaDocument
from .input_media_photo import InputMediaPhoto
from .input_media_video import InputMediaVideo
from .input_message_content import InputMessageContent
from .input_text_message_content import InputTextMessageContent
from .input_venue_message_content import InputVenueMessageContent
from .invoice import Invoice
from .keyboard_button import KeyboardButton
from .labeled_price import LabeledPrice
from .location import Location
from .login_url import LoginUrl
from .mask_position import MaskPosition
from .message import Message
from .message_entity import MessageEntity
from .order_info import OrderInfo
from .passport_data import PassportData
from .passport_element_error import PassportElementError
from .passport_element_error_data_field import PassportElementErrorDataField
from .passport_element_error_file import PassportElementErrorFile
from .passport_element_error_files import PassportElementErrorFiles
from .passport_element_error_front_side import PassportElementErrorFrontSide
from .passport_element_error_reverse_side import PassportElementErrorReverseSide
from .passport_element_error_selfie import PassportElementErrorSelfie
from .passport_element_error_translation_file import PassportElementErrorTranslationFile
from .passport_element_error_translation_files import PassportElementErrorTranslationFiles
from .passport_element_error_unspecified import PassportElementErrorUnspecified
from .passport_file import PassportFile
from .photo_size import PhotoSize
from .poll import Poll
from .poll_option import PollOption
from .pre_checkout_query import PreCheckoutQuery
from .reply_keyboard_markup import ReplyKeyboardMarkup
from .reply_keyboard_remove import ReplyKeyboardRemove
from .response_parameters import ResponseParameters
from .shipping_address import ShippingAddress
from .shipping_option import ShippingOption
from .shipping_query import ShippingQuery
from .sticker import Sticker
from .sticker_set import StickerSet
from .successful_payment import SuccessfulPayment
from .update import Update
from .user import User
from .user_profile_photos import UserProfilePhotos
from .venue import Venue
from .video import Video
from .video_note import VideoNote
from .voice import Voice
from .webhook_info import WebhookInfo
__all__ = (
"TelegramObject",
"Update",
"WebhookInfo",
"User",
"Chat",
"Message",
"MessageEntity",
"PhotoSize",
"Audio",
"Document",
"Video",
"Animation",
"Voice",
"VideoNote",
"Contact",
"Location",
"Venue",
"PollOption",
"Poll",
"UserProfilePhotos",
"File",
"ReplyKeyboardMarkup",
"KeyboardButton",
"ReplyKeyboardRemove",
"InlineKeyboardMarkup",
"InlineKeyboardButton",
"LoginUrl",
"CallbackQuery",
"ForceReply",
"ChatPhoto",
"ChatMember",
"ChatPermissions",
"ResponseParameters",
"InputMedia",
"InputMediaPhoto",
"InputMediaVideo",
"InputMediaAnimation",
"InputMediaAudio",
"InputMediaDocument",
"InputFile",
"Sticker",
"StickerSet",
"MaskPosition",
"InlineQuery",
"InlineQueryResult",
"InlineQueryResultArticle",
"InlineQueryResultPhoto",
"InlineQueryResultGif",
"InlineQueryResultMpeg4Gif",
"InlineQueryResultVideo",
"InlineQueryResultAudio",
"InlineQueryResultVoice",
"InlineQueryResultDocument",
"InlineQueryResultLocation",
"InlineQueryResultVenue",
"InlineQueryResultContact",
"InlineQueryResultGame",
"InlineQueryResultCachedPhoto",
"InlineQueryResultCachedGif",
"InlineQueryResultCachedMpeg4Gif",
"InlineQueryResultCachedSticker",
"InlineQueryResultCachedDocument",
"InlineQueryResultCachedVideo",
"InlineQueryResultCachedVoice",
"InlineQueryResultCachedAudio",
"InputMessageContent",
"InputTextMessageContent",
"InputLocationMessageContent",
"InputVenueMessageContent",
"InputContactMessageContent",
"ChosenInlineResult",
"LabeledPrice",
"Invoice",
"ShippingAddress",
"OrderInfo",
"ShippingOption",
"SuccessfulPayment",
"ShippingQuery",
"PreCheckoutQuery",
"PassportData",
"PassportFile",
"EncryptedPassportElement",
"EncryptedCredentials",
"PassportElementError",
"PassportElementErrorDataField",
"PassportElementErrorFrontSide",
"PassportElementErrorReverseSide",
"PassportElementErrorSelfie",
"PassportElementErrorFile",
"PassportElementErrorFiles",
"PassportElementErrorTranslationFile",
"PassportElementErrorTranslationFiles",
"PassportElementErrorUnspecified",
"Game",
"CallbackGame",
"GameHighScore",
)
# Load typing forward refs for every TelegramObject
for entity in __all__[1:]:
globals()[entity].update_forward_refs(**globals())

View file

@ -0,0 +1,33 @@
from __future__ import annotations
from typing import TYPE_CHECKING, Optional
from .base import TelegramObject
if TYPE_CHECKING:
from .photo_size import PhotoSize
class Animation(TelegramObject):
"""
This object represents an animation file (GIF or H.264/MPEG-4 AVC video without sound).
Source: https://core.telegram.org/bots/api#animation
"""
file_id: str
"""Identifier for this file"""
width: int
"""Video width as defined by sender"""
height: int
"""Video height as defined by sender"""
duration: int
"""Duration of the video in seconds as defined by sender"""
thumb: Optional[PhotoSize] = None
"""Animation thumbnail as defined by sender"""
file_name: Optional[str] = None
"""Original animation filename as defined by sender"""
mime_type: Optional[str] = None
"""MIME type of the file as defined by sender"""
file_size: Optional[int] = None
"""File size"""

View file

@ -0,0 +1,31 @@
from __future__ import annotations
from typing import TYPE_CHECKING, Optional
from .base import TelegramObject
if TYPE_CHECKING:
from .photo_size import PhotoSize
class Audio(TelegramObject):
"""
This object represents an audio file to be treated as music by the Telegram clients.
Source: https://core.telegram.org/bots/api#audio
"""
file_id: str
"""Identifier for this file"""
duration: int
"""Duration of the audio in seconds as defined by sender"""
performer: Optional[str] = None
"""Performer of the audio as defined by sender or by audio tags"""
title: Optional[str] = None
"""Title of the audio as defined by sender or by audio tags"""
mime_type: Optional[str] = None
"""MIME type of the file as defined by sender"""
file_size: Optional[int] = None
"""File size"""
thumb: Optional[PhotoSize] = None
"""Thumbnail of the album cover to which the music file belongs"""

10
aiogram/api/types/base.py Normal file
View file

@ -0,0 +1,10 @@
from pydantic import BaseConfig, BaseModel, Extra
class TelegramObject(BaseModel):
class Config(BaseConfig):
use_enum_values = True
orm_mode = True
extra = Extra.allow
allow_mutation = False
allow_population_by_field_name = True

View file

@ -0,0 +1,11 @@
from __future__ import annotations
from .base import TelegramObject
class CallbackGame(TelegramObject):
"""
A placeholder, currently holds no information. Use BotFather to set up your game.
Source: https://core.telegram.org/bots/api#callbackgame
"""

View file

@ -0,0 +1,35 @@
from __future__ import annotations
from typing import TYPE_CHECKING, Optional
from pydantic import Field
from .base import TelegramObject
if TYPE_CHECKING:
from .message import Message
from .user import User
class CallbackQuery(TelegramObject):
"""
This object represents an incoming callback query from a callback button in an inline keyboard. If the button that originated the query was attached to a message sent by the bot, the field message will be present. If the button was attached to a message sent via the bot (in inline mode), the field inline_message_id will be present. Exactly one of the fields data or game_short_name will be present.
NOTE: After the user presses a callback button, Telegram clients will display a progress bar until you call answerCallbackQuery. It is, therefore, necessary to react by calling answerCallbackQuery even if no notification to the user is needed (e.g., without specifying any of the optional parameters).
Source: https://core.telegram.org/bots/api#callbackquery
"""
id: str
"""Unique identifier for this query"""
from_user: User = Field(..., alias="from")
"""Sender"""
chat_instance: str
"""Global identifier, uniquely corresponding to the chat to which the message with the callback button was sent. Useful for high scores in games."""
message: Optional[Message] = None
"""Message with the callback button that originated the query. Note that message content and message date will not be available if the message is too old"""
inline_message_id: Optional[str] = None
"""Identifier of the message sent via the bot in inline mode, that originated the query."""
data: Optional[str] = None
"""Data associated with the callback button. Be aware that a bad client can send arbitrary data in this field."""
game_short_name: Optional[str] = None
"""Short name of a Game to be returned, serves as the unique identifier for the game"""

45
aiogram/api/types/chat.py Normal file
View file

@ -0,0 +1,45 @@
from __future__ import annotations
from typing import TYPE_CHECKING, Optional
from .base import TelegramObject
if TYPE_CHECKING:
from .chat_permissions import ChatPermissions
from .message import Message
from .chat_photo import ChatPhoto
class Chat(TelegramObject):
"""
This object represents a chat.
Source: https://core.telegram.org/bots/api#chat
"""
id: 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. But it is smaller than 52 bits, so a signed 64 bit integer or double-precision float type are safe for storing this identifier."""
type: str
"""Type of chat, can be either 'private', 'group', 'supergroup' or 'channel'"""
title: Optional[str] = None
"""Title, for supergroups, channels and group chats"""
username: Optional[str] = None
"""Username, for private chats, supergroups and channels if available"""
first_name: Optional[str] = None
"""First name of the other party in a private chat"""
last_name: Optional[str] = None
"""Last name of the other party in a private chat"""
photo: Optional[ChatPhoto] = None
"""Chat photo. Returned only in getChat."""
description: Optional[str] = None
"""Description, for groups, supergroups and channel chats. Returned only in getChat."""
invite_link: Optional[str] = None
"""Chat invite link, for groups, supergroups and channel chats. Each administrator in a chat generates their own invite links, so the bot must first generate the link using exportChatInviteLink. Returned only in getChat."""
pinned_message: Optional[Message] = None
"""Pinned message, for groups, supergroups and channels. Returned only in getChat."""
permissions: Optional[ChatPermissions] = None
"""Default chat member permissions, for groups and supergroups. Returned only in getChat."""
sticker_set_name: Optional[str] = None
"""For supergroups, name of group sticker set. Returned only in getChat."""
can_set_sticker_set: Optional[bool] = None
"""True, if the bot can change the group sticker set. Returned only in getChat."""

View file

@ -0,0 +1,53 @@
from __future__ import annotations
from typing import TYPE_CHECKING, Optional
from .base import TelegramObject
if TYPE_CHECKING:
from .user import User
class ChatMember(TelegramObject):
"""
This object contains information about one member of a chat.
Source: https://core.telegram.org/bots/api#chatmember
"""
user: User
"""Information about the user"""
status: str
"""The member's status in the chat. Can be 'creator', 'administrator', 'member', 'restricted', 'left' or 'kicked'"""
until_date: Optional[int] = None
"""Restricted and kicked only. Date when restrictions will be lifted for this user; unix time"""
can_be_edited: Optional[bool] = None
"""Administrators only. True, if the bot is allowed to edit administrator privileges of that user"""
can_post_messages: Optional[bool] = None
"""Administrators only. True, if the administrator can post in the channel; channels only"""
can_edit_messages: Optional[bool] = None
"""Administrators only. True, if the administrator can edit messages of other users and can pin messages; channels only"""
can_delete_messages: Optional[bool] = None
"""Administrators only. True, if the administrator can delete messages of other users"""
can_restrict_members: Optional[bool] = None
"""Administrators only. True, if the administrator can restrict, ban or unban chat members"""
can_promote_members: Optional[bool] = None
"""Administrators only. True, if the administrator can add new administrators with a subset of his own privileges or demote administrators that he has promoted, directly or indirectly (promoted by administrators that were appointed by the user)"""
can_change_info: Optional[bool] = None
"""Administrators and restricted only. True, if the user is allowed to change the chat title, photo and other settings"""
can_invite_users: Optional[bool] = None
"""Administrators and restricted only. True, if the user is allowed to invite new users to the chat"""
can_pin_messages: Optional[bool] = None
"""Administrators and restricted only. True, if the user is allowed to pin messages; groups and supergroups only"""
is_member: Optional[bool] = None
"""Restricted only. True, if the user is a member of the chat at the moment of the request"""
can_send_messages: Optional[bool] = None
"""Restricted only. True, if the user is allowed to send text messages, contacts, locations and venues"""
can_send_media_messages: Optional[bool] = None
"""Restricted only. True, if the user is allowed to send audios, documents, photos, videos, video notes and voice notes"""
can_send_polls: Optional[bool] = None
"""Restricted only. True, if the user is allowed to send polls"""
can_send_other_messages: Optional[bool] = None
"""Restricted only. True, if the user is allowed to send animations, games, stickers and use inline bots"""
can_add_web_page_previews: Optional[bool] = None
"""Restricted only. True, if the user is allowed to add web page previews to their messages"""

View file

@ -0,0 +1,30 @@
from __future__ import annotations
from typing import Optional
from .base import TelegramObject
class ChatPermissions(TelegramObject):
"""
Describes actions that a non-administrator user is allowed to take in a chat.
Source: https://core.telegram.org/bots/api#chatpermissions
"""
can_send_messages: Optional[bool] = None
"""True, if the user is allowed to send text messages, contacts, locations and venues"""
can_send_media_messages: Optional[bool] = None
"""True, if the user is allowed to send audios, documents, photos, videos, video notes and voice notes, implies can_send_messages"""
can_send_polls: Optional[bool] = None
"""True, if the user is allowed to send polls, implies can_send_messages"""
can_send_other_messages: Optional[bool] = None
"""True, if the user is allowed to send animations, games, stickers and use inline bots, implies can_send_media_messages"""
can_add_web_page_previews: Optional[bool] = None
"""True, if the user is allowed to add web page previews to their messages, implies can_send_media_messages"""
can_change_info: Optional[bool] = None
"""True, if the user is allowed to change the chat title, photo and other settings. Ignored in public supergroups"""
can_invite_users: Optional[bool] = None
"""True, if the user is allowed to invite new users to the chat"""
can_pin_messages: Optional[bool] = None
"""True, if the user is allowed to pin messages. Ignored in public supergroups"""

View file

@ -0,0 +1,16 @@
from __future__ import annotations
from .base import TelegramObject
class ChatPhoto(TelegramObject):
"""
This object represents a chat photo.
Source: https://core.telegram.org/bots/api#chatphoto
"""
small_file_id: str
"""File identifier of small (160x160) chat photo. This file_id can be used only for photo download and only for as long as the photo is not changed."""
big_file_id: str
"""File identifier of big (640x640) chat photo. This file_id can be used only for photo download and only for as long as the photo is not changed."""

View file

@ -0,0 +1,31 @@
from __future__ import annotations
from typing import TYPE_CHECKING, Optional
from pydantic import Field
from .base import TelegramObject
if TYPE_CHECKING:
from .location import Location
from .user import User
class ChosenInlineResult(TelegramObject):
"""
Represents a result of an inline query that was chosen by the user and sent to their chat partner.
Note: It is necessary to enable inline feedback via @Botfather in order to receive these objects in updates.
Source: https://core.telegram.org/bots/api#choseninlineresult
"""
result_id: str
"""The unique identifier for the result that was chosen"""
from_user: User = Field(..., alias="from")
"""The user that chose the result"""
query: str
"""The query that was used to obtain the result"""
location: Optional[Location] = None
"""Sender location, only for bots that require user location"""
inline_message_id: Optional[str] = None
"""Identifier of the sent inline message. Available 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."""

View file

@ -0,0 +1,24 @@
from __future__ import annotations
from typing import Optional
from .base import TelegramObject
class Contact(TelegramObject):
"""
This object represents a phone contact.
Source: https://core.telegram.org/bots/api#contact
"""
phone_number: str
"""Contact's phone number"""
first_name: str
"""Contact's first name"""
last_name: Optional[str] = None
"""Contact's last name"""
user_id: Optional[int] = None
"""Contact's user identifier in Telegram"""
vcard: Optional[str] = None
"""Additional data about the contact in the form of a vCard"""

View file

@ -0,0 +1,27 @@
from __future__ import annotations
from typing import TYPE_CHECKING, Optional
from .base import TelegramObject
if TYPE_CHECKING:
from .photo_size import PhotoSize
class Document(TelegramObject):
"""
This object represents a general file (as opposed to photos, voice messages and audio files).
Source: https://core.telegram.org/bots/api#document
"""
file_id: str
"""Identifier for this file"""
thumb: Optional[PhotoSize] = None
"""Document thumbnail as defined by sender"""
file_name: Optional[str] = None
"""Original filename as defined by sender"""
mime_type: Optional[str] = None
"""MIME type of the file as defined by sender"""
file_size: Optional[int] = None
"""File size"""

View file

@ -0,0 +1,18 @@
from __future__ import annotations
from .base import TelegramObject
class EncryptedCredentials(TelegramObject):
"""
Contains data required for decrypting and authenticating EncryptedPassportElement. See the Telegram Passport Documentation for a complete description of the data decryption and authentication processes.
Source: https://core.telegram.org/bots/api#encryptedcredentials
"""
data: str
"""Base64-encoded encrypted JSON-serialized data with unique user's payload, data hashes and secrets required for EncryptedPassportElement decryption and authentication"""
hash: str
"""Base64-encoded data hash for data authentication"""
secret: str
"""Base64-encoded secret, encrypted with the bot's public RSA key, required for data decryption"""

View file

@ -0,0 +1,37 @@
from __future__ import annotations
from typing import TYPE_CHECKING, List, Optional
from .base import TelegramObject
if TYPE_CHECKING:
from .passport_file import PassportFile
class EncryptedPassportElement(TelegramObject):
"""
Contains information about documents or other Telegram Passport elements shared with the bot by the user.
Source: https://core.telegram.org/bots/api#encryptedpassportelement
"""
type: str
"""Element type. One of 'personal_details', 'passport', 'driver_license', 'identity_card', 'internal_passport', 'address', 'utility_bill', 'bank_statement', 'rental_agreement', 'passport_registration', 'temporary_registration', 'phone_number', 'email'."""
hash: str
"""Base64-encoded element hash for using in PassportElementErrorUnspecified"""
data: Optional[str] = None
"""Base64-encoded encrypted Telegram Passport element data provided by the user, available for 'personal_details', 'passport', 'driver_license', 'identity_card', 'internal_passport' and 'address' types. Can be decrypted and verified using the accompanying EncryptedCredentials."""
phone_number: Optional[str] = None
"""User's verified phone number, available only for 'phone_number' type"""
email: Optional[str] = None
"""User's verified email address, available only for 'email' type"""
files: Optional[List[PassportFile]] = None
"""Array of encrypted files with documents provided by the user, available for 'utility_bill', 'bank_statement', 'rental_agreement', 'passport_registration' and 'temporary_registration' types. Files can be decrypted and verified using the accompanying EncryptedCredentials."""
front_side: Optional[PassportFile] = None
"""Encrypted file with the front side of the document, provided by the user. Available for 'passport', 'driver_license', 'identity_card' and 'internal_passport'. The file can be decrypted and verified using the accompanying EncryptedCredentials."""
reverse_side: Optional[PassportFile] = None
"""Encrypted file with the reverse side of the document, provided by the user. Available for 'driver_license' and 'identity_card'. The file can be decrypted and verified using the accompanying EncryptedCredentials."""
selfie: Optional[PassportFile] = None
"""Encrypted file with the selfie of the user holding a document, provided by the user; available for 'passport', 'driver_license', 'identity_card' and 'internal_passport'. The file can be decrypted and verified using the accompanying EncryptedCredentials."""
translation: Optional[List[PassportFile]] = None
"""Array of encrypted files with translated versions of documents provided by the user. Available if requested for 'passport', 'driver_license', 'identity_card', 'internal_passport', 'utility_bill', 'bank_statement', 'rental_agreement', 'passport_registration' and 'temporary_registration' types. Files can be decrypted and verified using the accompanying EncryptedCredentials."""

21
aiogram/api/types/file.py Normal file
View file

@ -0,0 +1,21 @@
from __future__ import annotations
from typing import Optional
from .base import TelegramObject
class File(TelegramObject):
"""
This object represents a file ready to be downloaded. The file can be downloaded via the link https://api.telegram.org/file/bot<token>/<file_path>. It is guaranteed that the link will be valid for at least 1 hour. When the link expires, a new one can be requested by calling getFile.
Maximum file size to download is 20 MB
Source: https://core.telegram.org/bots/api#file
"""
file_id: str
"""Identifier for this file"""
file_size: Optional[int] = None
"""File size, if known"""
file_path: Optional[str] = None
"""File path. Use https://api.telegram.org/file/bot<token>/<file_path> to get the file."""

View file

@ -0,0 +1,23 @@
from __future__ import annotations
from typing import Optional
from .base import TelegramObject
class ForceReply(TelegramObject):
"""
Upon receiving a message with this object, Telegram clients will display a reply interface to the user (act as if the user has selected the bots message and tapped Reply'). This can be extremely useful if you want to create user-friendly step-by-step interfaces without having to sacrifice privacy mode.
Example: A poll bot for groups runs in privacy mode (only receives commands, replies to its messages and mentions). There could be two ways to create a new poll:
Explain the user how to send a command with parameters (e.g. /newpoll question answer1 answer2). May be appealing for hardcore users but lacks modern day polish.
Guide the user through a step-by-step process. Please send me your question, Cool, now lets add the first answer option, Great. Keep adding answer options, then send /done when youre ready.
The last option is definitely more attractive. And if you use ForceReply in your bots questions, it will receive the users answers even if it only receives replies, commands and mentions without any extra work for the user.
Source: https://core.telegram.org/bots/api#forcereply
"""
force_reply: bool
"""Shows reply interface to the user, as if they manually selected the bots message and tapped Reply'"""
selective: Optional[bool] = None
"""Use this parameter if you want to force reply from specific users only. Targets: 1) users that are @mentioned in the text of the Message object; 2) if the bot's message is a reply (has reply_to_message_id), sender of the original message."""

31
aiogram/api/types/game.py Normal file
View file

@ -0,0 +1,31 @@
from __future__ import annotations
from typing import TYPE_CHECKING, List, Optional
from .base import TelegramObject
if TYPE_CHECKING:
from .photo_size import PhotoSize
from .animation import Animation
from .message_entity import MessageEntity
class Game(TelegramObject):
"""
This object represents a game. Use BotFather to create and edit games, their short names will act as unique identifiers.
Source: https://core.telegram.org/bots/api#game
"""
title: str
"""Title of the game"""
description: str
"""Description of the game"""
photo: List[PhotoSize]
"""Photo that will be displayed in the game message in chats."""
text: Optional[str] = None
"""Brief description of the game or high scores included in the game message. Can be automatically edited to include current high scores for the game when the bot calls setGameScore, or manually edited using editMessageText. 0-4096 characters."""
text_entities: Optional[List[MessageEntity]] = None
"""Special entities that appear in text, such as usernames, URLs, bot commands, etc."""
animation: Optional[Animation] = None
"""Animation that will be displayed in the game message in chats. Upload via BotFather"""

View file

@ -0,0 +1,25 @@
from __future__ import annotations
from typing import TYPE_CHECKING
from .base import TelegramObject
if TYPE_CHECKING:
from .user import User
class GameHighScore(TelegramObject):
"""
This object represents one row of the high scores table for a game.
And thats about all weve got for now.
If you've got any questions, please check out our Bot FAQ
Source: https://core.telegram.org/bots/api#gamehighscore
"""
position: int
"""Position in high score table for the game"""
user: User
"""User"""
score: int
"""Score"""

View file

@ -0,0 +1,42 @@
from __future__ import annotations
from typing import TYPE_CHECKING, Optional
from .base import TelegramObject
if TYPE_CHECKING:
from .callback_game import CallbackGame
from .login_url import LoginUrl
class InlineKeyboardButton(TelegramObject):
"""
This object represents one button of an inline keyboard. You must use exactly one of the optional fields.
Source: https://core.telegram.org/bots/api#inlinekeyboardbutton
"""
text: str
"""Label text on the button"""
url: Optional[str] = None
"""HTTP or tg:// url to be opened when button is pressed"""
login_url: Optional[LoginUrl] = None
"""An HTTP URL used to automatically authorize the user. Can be used as a replacement for the Telegram Login Widget."""
callback_data: Optional[str] = None
"""Data to be sent in a callback query to the bot when button is pressed, 1-64 bytes"""
switch_inline_query: Optional[str] = None
"""If set, pressing the button will prompt the user to select one of their chats, open that chat and insert the bots username and the specified inline query in the input field. Can be empty, in which case just the bots username will be inserted.
Note: This offers an easy way for users to start using your bot in inline mode when they are currently in a private chat with it. Especially useful when combined with switch_pm actions in this case the user will be automatically returned to the chat they switched from, skipping the chat selection screen."""
switch_inline_query_current_chat: Optional[str] = None
"""If set, pressing the button will insert the bots username and the specified inline query in the current chat's input field. Can be empty, in which case only the bots username will be inserted.
This offers a quick way for the user to open your bot in inline mode in the same chat good for selecting something from multiple options."""
callback_game: Optional[CallbackGame] = None
"""Description of the game that will be launched when the user presses the button.
NOTE: This type of button must always be the first button in the first row."""
pay: Optional[bool] = None
"""Specify True, to send a Pay button.
NOTE: This type of button must always be the first button in the first row."""

View file

@ -0,0 +1,20 @@
from __future__ import annotations
from typing import TYPE_CHECKING, List
from .base import TelegramObject
if TYPE_CHECKING:
from .inline_keyboard_button import InlineKeyboardButton
class InlineKeyboardMarkup(TelegramObject):
"""
This object represents an inline keyboard that appears right next to the message it belongs to.
Note: This will only work in Telegram versions released after 9 April, 2016. Older clients will display unsupported message.
Source: https://core.telegram.org/bots/api#inlinekeyboardmarkup
"""
inline_keyboard: List[List[InlineKeyboardButton]]
"""Array of button rows, each represented by an Array of InlineKeyboardButton objects"""

View file

@ -0,0 +1,30 @@
from __future__ import annotations
from typing import TYPE_CHECKING, Optional
from pydantic import Field
from .base import TelegramObject
if TYPE_CHECKING:
from .location import Location
from .user import User
class InlineQuery(TelegramObject):
"""
This object represents an incoming inline query. When the user sends an empty query, your bot could return some default or trending results.
Source: https://core.telegram.org/bots/api#inlinequery
"""
id: str
"""Unique identifier for this query"""
from_user: User = Field(..., alias="from")
"""Sender"""
query: str
"""Text of the query (up to 512 characters)"""
offset: str
"""Offset of the results to be returned, can be controlled by the bot"""
location: Optional[Location] = None
"""Sender location, only for bots that request user location"""

View file

@ -0,0 +1,31 @@
from __future__ import annotations
from .base import TelegramObject
class InlineQueryResult(TelegramObject):
"""
This object represents one result of an inline query. Telegram clients currently support results of the following 20 types:
- InlineQueryResultCachedAudio
- InlineQueryResultCachedDocument
- InlineQueryResultCachedGif
- InlineQueryResultCachedMpeg4Gif
- InlineQueryResultCachedPhoto
- InlineQueryResultCachedSticker
- InlineQueryResultCachedVideo
- InlineQueryResultCachedVoice
- InlineQueryResultArticle
- InlineQueryResultAudio
- InlineQueryResultContact
- InlineQueryResultGame
- InlineQueryResultDocument
- InlineQueryResultGif
- InlineQueryResultLocation
- InlineQueryResultMpeg4Gif
- InlineQueryResultPhoto
- InlineQueryResultVenue
- InlineQueryResultVideo
- InlineQueryResultVoice
Source: https://core.telegram.org/bots/api#inlinequeryresult
"""

View file

@ -0,0 +1,42 @@
from __future__ import annotations
from typing import TYPE_CHECKING, Optional
from pydantic import Field
from .inline_query_result import InlineQueryResult
if TYPE_CHECKING:
from .inline_keyboard_markup import InlineKeyboardMarkup
from .input_message_content import InputMessageContent
class InlineQueryResultArticle(InlineQueryResult):
"""
Represents a link to an article or web page.
Source: https://core.telegram.org/bots/api#inlinequeryresultarticle
"""
type: str = Field("article", const=True)
"""Type of the result, must be article"""
id: str
"""Unique identifier for this result, 1-64 Bytes"""
title: str
"""Title of the result"""
input_message_content: InputMessageContent
"""Content of the message to be sent"""
reply_markup: Optional[InlineKeyboardMarkup] = None
"""Inline keyboard attached to the message"""
url: Optional[str] = None
"""URL of the result"""
hide_url: Optional[bool] = None
"""Pass True, if you don't want the URL to be shown in the message"""
description: Optional[str] = None
"""Short description of the result"""
thumb_url: Optional[str] = None
"""Url of the thumbnail for the result"""
thumb_width: Optional[int] = None
"""Thumbnail width"""
thumb_height: Optional[int] = None
"""Thumbnail height"""

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