diff --git a/aiogram/_telegram/__init__.py b/aiogram/_telegram/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/aiogram/_telegram/types.py b/aiogram/_telegram/types.py new file mode 100644 index 00000000..13c7d976 --- /dev/null +++ b/aiogram/_telegram/types.py @@ -0,0 +1,2793 @@ +""" +!!! DO NOT EDIT THIS FILE !!! +This file is autogenerated from Docs of Telegram Bot API at 2019-06-30 19:48:06 UTC +""" +import typing + +import pydantic + +from aiogram import types + +__all__ = [ + "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", + "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", + "Games", + "Game", + "CallbackGame", + "GameHighScore", +] + + +# %% Region: 'Getting updates' +""" +There are two mutually exclusive ways of receiving updates for your bot — the getUpdates method on one hand and Webhooks on the other. Incoming updates are stored on the server until the bot receives them either way, but they will not be kept longer than 24 hours. +Regardless of which option you choose, you will receive JSON-serialized Update objects as a result. + +link: https://core.telegram.org/bots/api#getting-updates +""" + + +class Update(pydantic.BaseModel): + """ + This object represents an incoming update. + At most one of the optional parameters can be present in any given update. + + Source: https://core.telegram.org/bots/api#update + """ + + update_id: int + """The update‘s unique identifier. Update identifiers start from a certain positive number and increase sequentially. This ID becomes especially handy if you’re using Webhooks, since it allows you to ignore repeated updates or to restore the correct update sequence, should they get out of order. If there are no new updates for at least a week, then identifier of the next update will be chosen randomly instead of sequentially.""" + + message: types.Message = None + """New incoming message of any kind — text, photo, sticker, etc.""" + + edited_message: types.Message = None + """New version of a message that is known to the bot and was edited""" + + channel_post: types.Message = None + """New incoming channel post of any kind — text, photo, sticker, etc.""" + + edited_channel_post: types.Message = None + """New version of a channel post that is known to the bot and was edited""" + + inline_query: types.InlineQuery = None + """New incoming inline query""" + + chosen_inline_result: types.ChosenInlineResult = None + """The result of an inline query that was chosen by a user and sent to their chat partner. Please see our documentation on the feedback collecting for details on how to enable these updates for your bot.""" + + callback_query: types.CallbackQuery = None + """New incoming callback query""" + + shipping_query: types.ShippingQuery = None + """New incoming shipping query. Only for invoices with flexible price""" + + pre_checkout_query: types.PreCheckoutQuery = None + """New incoming pre-checkout query. Contains full information about checkout""" + + poll: types.Poll = None + """New poll state. Bots receive only updates about stopped polls and polls, which are sent by the bot""" + + +class WebhookInfo(pydantic.BaseModel): + """ + Contains information about the current status of a webhook. + + Source: https://core.telegram.org/bots/api#webhookinfo + """ + + url: str + """Webhook URL, may be empty if webhook is not set up""" + + has_custom_certificate: bool + """True, if a custom certificate was provided for webhook certificate checks""" + + pending_update_count: int + """Number of updates awaiting delivery""" + + last_error_date: int = None + """Unix time for the most recent error that happened when trying to deliver an update via webhook""" + + last_error_message: str = None + """Error message in human-readable format for the most recent error that happened when trying to deliver an update via webhook""" + + max_connections: int = None + """Maximum allowed number of simultaneous HTTPS connections to the webhook for update delivery""" + + allowed_updates: typing.List[str] = None + """A list of update types the bot is subscribed to. Defaults to all update types""" + + +# %% End of region 'Getting updates' + +# %% Region: 'Available types' +""" +All types used in the Bot API responses are represented as JSON-objects. +It is safe to use 32-bit signed integers for storing all Integer fields unless otherwise noted. +Optional fields may be not returned when irrelevant. + +link: https://core.telegram.org/bots/api#available-types +""" + + +class User(pydantic.BaseModel): + """ + This object represents a Telegram user or bot. + + Source: https://core.telegram.org/bots/api#user + """ + + id: int + """Unique identifier for this user or bot""" + + is_bot: bool + """True, if this user is a bot""" + + first_name: str + """User‘s or bot’s first name""" + + last_name: str = None + """User‘s or bot’s last name""" + + username: str = None + """User‘s or bot’s username""" + + language_code: str = None + """IETF language tag of the user's language""" + + +class Chat(pydantic.BaseModel): + """ + 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: str = None + """Title, for supergroups, channels and group chats""" + + username: str = None + """Username, for private chats, supergroups and channels if available""" + + first_name: str = None + """First name of the other party in a private chat""" + + last_name: str = None + """Last name of the other party in a private chat""" + + all_members_are_administrators: bool = None + """True if a group has ‘All Members Are Admins’ enabled.""" + + photo: types.ChatPhoto = None + """Chat photo. Returned only in getChat.""" + + description: str = None + """Description, for supergroups and channel chats. Returned only in getChat.""" + + invite_link: str = None + """Chat invite link, for 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: types.Message = None + """Pinned message, for groups, supergroups and channels. Returned only in getChat.""" + + sticker_set_name: str = None + """For supergroups, name of group sticker set. Returned only in getChat.""" + + can_set_sticker_set: bool = None + """True, if the bot can change the group sticker set. Returned only in getChat.""" + + +class Message(pydantic.BaseModel): + """ + This object represents a message. + + Source: https://core.telegram.org/bots/api#message + """ + + message_id: int + """Unique message identifier inside this chat""" + + from_user: types.User = pydantic.Schema(None, alias="from") + """Sender, empty for messages sent to channels""" + + date: int + """Date the message was sent in Unix time""" + + chat: types.Chat + """Conversation the message belongs to""" + + forward_from: types.User = None + """For forwarded messages, sender of the original message""" + + forward_from_chat: types.Chat = None + """For messages forwarded from channels, information about the original channel""" + + forward_from_message_id: int = None + """For messages forwarded from channels, identifier of the original message in the channel""" + + forward_signature: str = None + """For messages forwarded from channels, signature of the post author if present""" + + forward_sender_name: str = None + """Sender's name for messages forwarded from users who disallow adding a link to their account in forwarded messages""" + + forward_date: int = None + """For forwarded messages, date the original message was sent in Unix time""" + + reply_to_message: types.Message = None + """For replies, the original message. Note that the Message object in this field will not contain further reply_to_message fields even if it itself is a reply.""" + + edit_date: int = None + """Date the message was last edited in Unix time""" + + media_group_id: str = None + """The unique identifier of a media message group this message belongs to""" + + author_signature: str = None + """Signature of the post author for messages in channels""" + + text: str = None + """For text messages, the actual UTF-8 text of the message, 0-4096 characters.""" + + entities: typing.List[types.MessageEntity] = None + """For text messages, special entities like usernames, URLs, bot commands, etc. that appear in the text""" + + caption_entities: typing.List[types.MessageEntity] = None + """For messages with a caption, special entities like usernames, URLs, bot commands, etc. that appear in the caption""" + + audio: types.Audio = None + """Message is an audio file, information about the file""" + + document: types.Document = None + """Message is a general file, information about the file""" + + animation: types.Animation = None + """Message is an animation, information about the animation. For backward compatibility, when this field is set, the document field will also be set""" + + game: types.Game = None + """Message is a game, information about the game.""" + + photo: typing.List[types.PhotoSize] = None + """Message is a photo, available sizes of the photo""" + + sticker: types.Sticker = None + """Message is a sticker, information about the sticker""" + + video: types.Video = None + """Message is a video, information about the video""" + + voice: types.Voice = None + """Message is a voice message, information about the file""" + + video_note: types.VideoNote = None + """Message is a video note, information about the video message""" + + caption: str = None + """Caption for the animation, audio, document, photo, video or voice, 0-1024 characters""" + + contact: types.Contact = None + """Message is a shared contact, information about the contact""" + + location: types.Location = None + """Message is a shared location, information about the location""" + + venue: types.Venue = None + """Message is a venue, information about the venue""" + + poll: types.Poll = None + """Message is a native poll, information about the poll""" + + new_chat_members: typing.List[types.User] = None + """New members that were added to the group or supergroup and information about them (the bot itself may be one of these members)""" + + left_chat_member: types.User = None + """A member was removed from the group, information about them (this member may be the bot itself)""" + + new_chat_title: str = None + """A chat title was changed to this value""" + + new_chat_photo: typing.List[types.PhotoSize] = None + """A chat photo was change to this value""" + + delete_chat_photo: bool = None + """Service message: the chat photo was deleted""" + + group_chat_created: bool = None + """Service message: the group has been created""" + + supergroup_chat_created: bool = None + """Service message: the supergroup has been created. This field can‘t be received in a message coming through updates, because bot can’t be a member of a supergroup when it is created. It can only be found in reply_to_message if someone replies to a very first message in a directly created supergroup.""" + + channel_chat_created: bool = None + """Service message: the channel has been created. This field can‘t be received in a message coming through updates, because bot can’t be a member of a channel when it is created. It can only be found in reply_to_message if someone replies to a very first message in a channel.""" + + migrate_to_chat_id: int = None + """The group has been migrated to a supergroup with the specified identifier. 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.""" + + migrate_from_chat_id: int = None + """The supergroup has been migrated from a group with the specified identifier. 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.""" + + pinned_message: types.Message = None + """Specified message was pinned. Note that the Message object in this field will not contain further reply_to_message fields even if it is itself a reply.""" + + invoice: types.Invoice = None + """Message is an invoice for a payment, information about the invoice.""" + + successful_payment: types.SuccessfulPayment = None + """Message is a service message about a successful payment, information about the payment.""" + + connected_website: str = None + """The domain name of the website on which the user has logged in.""" + + passport_data: types.PassportData = None + """Telegram Passport data""" + + reply_markup: types.InlineKeyboardMarkup = None + """Inline keyboard attached to the message. login_url buttons are represented as ordinary url buttons.""" + + +class MessageEntity(pydantic.BaseModel): + """ + This object represents one special entity in a text message. For example, hashtags, usernames, URLs, etc. + + Source: https://core.telegram.org/bots/api#messageentity + """ + + type: str + """Type of the entity. Can be mention (@username), hashtag, cashtag, bot_command, url, email, phone_number, bold (bold text), italic (italic text), code (monowidth string), pre (monowidth block), text_link (for clickable text URLs), text_mention (for users without usernames)""" + + offset: int + """Offset in UTF-16 code units to the start of the entity""" + + length: int + """Length of the entity in UTF-16 code units""" + + url: str = None + """For 'text_link' only, url that will be opened after user taps on the text""" + + user: types.User = None + """For 'text_mention' only, the mentioned user""" + + +class PhotoSize(pydantic.BaseModel): + """ + This object represents one size of a photo or a file / sticker thumbnail. + + Source: https://core.telegram.org/bots/api#photosize + """ + + file_id: str + """Unique identifier for this file""" + + width: int + """Photo width""" + + height: int + """Photo height""" + + file_size: int = None + """File size""" + + +class Audio(pydantic.BaseModel): + """ + 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 + """Unique identifier for this file""" + + duration: int + """Duration of the audio in seconds as defined by sender""" + + performer: str = None + """Performer of the audio as defined by sender or by audio tags""" + + title: str = None + """Title of the audio as defined by sender or by audio tags""" + + mime_type: str = None + """MIME type of the file as defined by sender""" + + file_size: int = None + """File size""" + + thumb: types.PhotoSize = None + """Thumbnail of the album cover to which the music file belongs""" + + +class Document(pydantic.BaseModel): + """ + 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 + """Unique file identifier""" + + thumb: types.PhotoSize = None + """Document thumbnail as defined by sender""" + + file_name: str = None + """Original filename as defined by sender""" + + mime_type: str = None + """MIME type of the file as defined by sender""" + + file_size: int = None + """File size""" + + +class Video(pydantic.BaseModel): + """ + This object represents a video file. + + Source: https://core.telegram.org/bots/api#video + """ + + file_id: str + """Unique 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: types.PhotoSize = None + """Video thumbnail""" + + mime_type: str = None + """Mime type of a file as defined by sender""" + + file_size: int = None + """File size""" + + +class Animation(pydantic.BaseModel): + """ + 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 + """Unique file identifier""" + + 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: types.PhotoSize = None + """Animation thumbnail as defined by sender""" + + file_name: str = None + """Original animation filename as defined by sender""" + + mime_type: str = None + """MIME type of the file as defined by sender""" + + file_size: int = None + """File size""" + + +class Voice(pydantic.BaseModel): + """ + This object represents a voice note. + + Source: https://core.telegram.org/bots/api#voice + """ + + file_id: str + """Unique identifier for this file""" + + duration: int + """Duration of the audio in seconds as defined by sender""" + + mime_type: str = None + """MIME type of the file as defined by sender""" + + file_size: int = None + """File size""" + + +class VideoNote(pydantic.BaseModel): + """ + This object represents a video message (available in Telegram apps as of v.4.0). + + Source: https://core.telegram.org/bots/api#videonote + """ + + file_id: str + """Unique identifier for this file""" + + length: int + """Video width and height (diameter of the video message) as defined by sender""" + + duration: int + """Duration of the video in seconds as defined by sender""" + + thumb: types.PhotoSize = None + """Video thumbnail""" + + file_size: int = None + """File size""" + + +class Contact(pydantic.BaseModel): + """ + 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: str = None + """Contact's last name""" + + user_id: int = None + """Contact's user identifier in Telegram""" + + vcard: str = None + """Additional data about the contact in the form of a vCard""" + + +class Location(pydantic.BaseModel): + """ + This object represents a point on the map. + + Source: https://core.telegram.org/bots/api#location + """ + + longitude: float + """Longitude as defined by sender""" + + latitude: float + """Latitude as defined by sender""" + + +class Venue(pydantic.BaseModel): + """ + This object represents a venue. + + Source: https://core.telegram.org/bots/api#venue + """ + + location: types.Location + """Venue location""" + + title: str + """Name of the venue""" + + address: str + """Address of the venue""" + + foursquare_id: str = None + """Foursquare identifier of the venue""" + + foursquare_type: str = None + """Foursquare type of the venue. (For example, 'arts_entertainment/default', 'arts_entertainment/aquarium' or 'food/icecream'.)""" + + +class PollOption(pydantic.BaseModel): + """ + This object contains information about one answer option in a poll. + + Source: https://core.telegram.org/bots/api#polloption + """ + + text: str + """Option text, 1-100 characters""" + + voter_count: int + """Number of users that voted for this option""" + + +class Poll(pydantic.BaseModel): + """ + This object contains information about a poll. + + Source: https://core.telegram.org/bots/api#poll + """ + + id: str + """Unique poll identifier""" + + question: str + """Poll question, 1-255 characters""" + + options: typing.List[types.PollOption] + """List of poll options""" + + is_closed: bool + """True, if the poll is closed""" + + +class UserProfilePhotos(pydantic.BaseModel): + """ + This object represent a user's profile pictures. + + Source: https://core.telegram.org/bots/api#userprofilephotos + """ + + total_count: int + """Total number of profile pictures the target user has""" + + photos: typing.List[typing.List[types.PhotoSize]] + """Requested profile pictures (in up to 4 sizes each)""" + + +class File(pydantic.BaseModel): + """ + This object represents a file ready to be downloaded. The file can be downloaded via the link https://api.telegram.org/file/bot/. 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 + """Unique identifier for this file""" + + file_size: int = None + """File size, if known""" + + file_path: str = None + """File path. Use https://api.telegram.org/file/bot/ to get the file.""" + + +class ReplyKeyboardMarkup(pydantic.BaseModel): + """ + This object represents a custom keyboard with reply options (see Introduction to bots for details and examples). + + Source: https://core.telegram.org/bots/api#replykeyboardmarkup + """ + + keyboard: typing.List[typing.List[types.KeyboardButton]] + """Array of button rows, each represented by an Array of KeyboardButton objects""" + + resize_keyboard: bool = None + """Requests clients to resize the keyboard vertically for optimal fit (e.g., make the keyboard smaller if there are just two rows of buttons). Defaults to false, in which case the custom keyboard is always of the same height as the app's standard keyboard.""" + + one_time_keyboard: bool = None + """Requests clients to hide the keyboard as soon as it's been used. The keyboard will still be available, but clients will automatically display the usual letter-keyboard in the chat – the user can press a special button in the input field to see the custom keyboard again. Defaults to false.""" + + selective: bool = None + """Use this parameter if you want to show the keyboard to 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. + + Example: A user requests to change the bot‘s language, bot replies to the request with a keyboard to select the new language. Other users in the group don’t see the keyboard.""" + + +class KeyboardButton(pydantic.BaseModel): + """ + This object represents one button of the reply keyboard. For simple text buttons String can be used instead of this object to specify text of the button. Optional fields are mutually exclusive. + Note: request_contact and request_location options will only work in Telegram versions released after 9 April, 2016. Older clients will ignore them. + + Source: https://core.telegram.org/bots/api#keyboardbutton + """ + + text: str + """Text of the button. If none of the optional fields are used, it will be sent as a message when the button is pressed""" + + request_contact: bool = None + """If True, the user's phone number will be sent as a contact when the button is pressed. Available in private chats only""" + + request_location: bool = None + """If True, the user's current location will be sent when the button is pressed. Available in private chats only""" + + +class ReplyKeyboardRemove(pydantic.BaseModel): + """ + Upon receiving a message with this object, Telegram clients will remove the current custom keyboard and display the default letter-keyboard. By default, custom keyboards are displayed until a new keyboard is sent by a bot. An exception is made for one-time keyboards that are hidden immediately after the user presses a button (see ReplyKeyboardMarkup). + + Source: https://core.telegram.org/bots/api#replykeyboardremove + """ + + remove_keyboard: bool + """Requests clients to remove the custom keyboard (user will not be able to summon this keyboard; if you want to hide the keyboard from sight but keep it accessible, use one_time_keyboard in ReplyKeyboardMarkup)""" + + selective: bool = None + """Use this parameter if you want to remove the keyboard for 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. + + Example: A user votes in a poll, bot returns confirmation message in reply to the vote and removes the keyboard for that user, while still showing the keyboard with poll options to users who haven't voted yet.""" + + +class InlineKeyboardMarkup(pydantic.BaseModel): + """ + 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: typing.List[typing.List[types.InlineKeyboardButton]] + """Array of button rows, each represented by an Array of InlineKeyboardButton objects""" + + +class InlineKeyboardButton(pydantic.BaseModel): + """ + 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: str = None + """HTTP or tg:// url to be opened when button is pressed""" + + login_url: types.LoginUrl = None + """An HTTP URL used to automatically authorize the user. Can be used as a replacement for the Telegram Login Widget.""" + + callback_data: str = None + """Data to be sent in a callback query to the bot when button is pressed, 1-64 bytes""" + + switch_inline_query: str = None + """If set, pressing the button will prompt the user to select one of their chats, open that chat and insert the bot‘s username and the specified inline query in the input field. Can be empty, in which case just the bot’s 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: str = None + """If set, pressing the button will insert the bot‘s username and the specified inline query in the current chat's input field. Can be empty, in which case only the bot’s 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: types.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: bool = None + """Specify True, to send a Pay button. + + NOTE: This type of button must always be the first button in the first row.""" + + +class LoginUrl(pydantic.BaseModel): + """ + This object represents a parameter of the inline keyboard button used to automatically authorize a user. Serves as a great replacement for the Telegram Login Widget when the user is coming from Telegram. All the user needs to do is tap/click a button and confirm that they want to log in: + Telegram apps support these buttons as of version 5.7. + Sample bot: @discussbot + + Source: https://core.telegram.org/bots/api#loginurl + """ + + url: str + """An HTTP URL to be opened with user authorization data added to the query string when the button is pressed. If the user refuses to provide authorization data, the original URL without information about the user will be opened. The data added is the same as described in Receiving authorization data. + + NOTE: You must always check the hash of the received data to verify the authentication and the integrity of the data as described in Checking authorization.""" + + forward_text: str = None + """New text of the button in forwarded messages.""" + + bot_username: str = None + """Username of a bot, which will be used for user authorization. See Setting up a bot for more details. If not specified, the current bot's username will be assumed. The url's domain must be the same as the domain linked with the bot. See Linking your domain to the bot for more details.""" + + request_write_access: bool = None + """Pass True to request the permission for your bot to send messages to the user.""" + + +class CallbackQuery(pydantic.BaseModel): + """ + 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: types.User = pydantic.Schema(..., alias="from") + """Sender""" + + message: types.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: str = None + """Identifier of the message sent via the bot in inline mode, that originated the query.""" + + 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.""" + + data: str = None + """Data associated with the callback button. Be aware that a bad client can send arbitrary data in this field.""" + + game_short_name: str = None + """Short name of a Game to be returned, serves as the unique identifier for the game""" + + +class ForceReply(pydantic.BaseModel): + """ + 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 bot‘s 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 let’s add the first answer option‘, ’Great. Keep adding answer options, then send /done when you‘re ready’. + The last option is definitely more attractive. And if you use ForceReply in your bot‘s questions, it will receive the user’s 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 bot‘s message and tapped ’Reply'""" + + selective: 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.""" + + +class ChatPhoto(pydantic.BaseModel): + """ + This object represents a chat photo. + + Source: https://core.telegram.org/bots/api#chatphoto + """ + + small_file_id: str + """Unique file identifier of small (160x160) chat photo. This file_id can be used only for photo download.""" + + big_file_id: str + """Unique file identifier of big (640x640) chat photo. This file_id can be used only for photo download.""" + + +class ChatMember(pydantic.BaseModel): + """ + This object contains information about one member of a chat. + + Source: https://core.telegram.org/bots/api#chatmember + """ + + user: types.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: int = None + """Restricted and kicked only. Date when restrictions will be lifted for this user, unix time""" + + can_be_edited: bool = None + """Administrators only. True, if the bot is allowed to edit administrator privileges of that user""" + + can_change_info: bool = None + """Administrators only. True, if the administrator can change the chat title, photo and other settings""" + + can_post_messages: bool = None + """Administrators only. True, if the administrator can post in the channel, channels only""" + + can_edit_messages: bool = None + """Administrators only. True, if the administrator can edit messages of other users and can pin messages, channels only""" + + can_delete_messages: bool = None + """Administrators only. True, if the administrator can delete messages of other users""" + + can_invite_users: bool = None + """Administrators only. True, if the administrator can invite new users to the chat""" + + can_restrict_members: bool = None + """Administrators only. True, if the administrator can restrict, ban or unban chat members""" + + can_pin_messages: bool = None + """Administrators only. True, if the administrator can pin messages, groups and supergroups only""" + + can_promote_members: 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)""" + + is_member: bool = None + """Restricted only. True, if the user is a member of the chat at the moment of the request""" + + can_send_messages: bool = None + """Restricted only. True, if the user can send text messages, contacts, locations and venues""" + + can_send_media_messages: bool = None + """Restricted only. True, if the user can send audios, documents, photos, videos, video notes and voice notes, implies can_send_messages""" + + can_send_other_messages: bool = None + """Restricted only. True, if the user can send animations, games, stickers and use inline bots, implies can_send_media_messages""" + + can_add_web_page_previews: bool = None + """Restricted only. True, if user may add web page previews to his messages, implies can_send_media_messages""" + + +class ResponseParameters(pydantic.BaseModel): + """ + Contains information about why a request was unsuccessful. + + Source: https://core.telegram.org/bots/api#responseparameters + """ + + migrate_to_chat_id: int = None + """The group has been migrated to a supergroup with the specified identifier. 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.""" + + retry_after: int = None + """In case of exceeding flood control, the number of seconds left to wait before the request can be repeated""" + + +class InputMedia(pydantic.BaseModel): + """ + This object represents the content of a media message to be sent. It should be one of + - InputMediaAnimation + - InputMediaDocument + - InputMediaAudio + - InputMediaPhoto + - InputMediaVideo + + Source: https://core.telegram.org/bots/api#inputmedia + """ + + pass + + +class InputMediaPhoto(pydantic.BaseModel): + """ + Represents a photo to be sent. + + Source: https://core.telegram.org/bots/api#inputmediaphoto + """ + + type: str + """Type of the result, must be photo""" + + media: str + """File to send. Pass a file_id to send a file that exists on the Telegram servers (recommended), pass an HTTP URL for Telegram to get a file from the Internet, or pass 'attach://' to upload a new one using multipart/form-data under name.""" + + caption: str = None + """Caption of the photo to be sent, 0-1024 characters""" + + parse_mode: 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.""" + + +class InputMediaVideo(pydantic.BaseModel): + """ + Represents a video to be sent. + + Source: https://core.telegram.org/bots/api#inputmediavideo + """ + + type: str + """Type of the result, must be video""" + + media: str + """File to send. Pass a file_id to send a file that exists on the Telegram servers (recommended), pass an HTTP URL for Telegram to get a file from the Internet, or pass 'attach://' to upload a new one using multipart/form-data under name.""" + + thumb: typing.Optional[types.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 thumbnail‘s width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can’t be reused and can be only uploaded as a new file, so you can pass 'attach://' if the thumbnail was uploaded using multipart/form-data under .""" + + caption: str = None + """Caption of the video to be sent, 0-1024 characters""" + + parse_mode: 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.""" + + width: int = None + """Video width""" + + height: int = None + """Video height""" + + duration: int = None + """Video duration""" + + supports_streaming: bool = None + """Pass True, if the uploaded video is suitable for streaming""" + + +class InputMediaAnimation(pydantic.BaseModel): + """ + Represents an animation file (GIF or H.264/MPEG-4 AVC video without sound) to be sent. + + Source: https://core.telegram.org/bots/api#inputmediaanimation + """ + + type: str + """Type of the result, must be animation""" + + media: str + """File to send. Pass a file_id to send a file that exists on the Telegram servers (recommended), pass an HTTP URL for Telegram to get a file from the Internet, or pass 'attach://' to upload a new one using multipart/form-data under name.""" + + thumb: typing.Optional[types.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 thumbnail‘s width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can’t be reused and can be only uploaded as a new file, so you can pass 'attach://' if the thumbnail was uploaded using multipart/form-data under .""" + + caption: str = None + """Caption of the animation to be sent, 0-1024 characters""" + + parse_mode: 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.""" + + width: int = None + """Animation width""" + + height: int = None + """Animation height""" + + duration: int = None + """Animation duration""" + + +class InputMediaAudio(pydantic.BaseModel): + """ + Represents an audio file to be treated as music to be sent. + + Source: https://core.telegram.org/bots/api#inputmediaaudio + """ + + type: str + """Type of the result, must be audio""" + + media: str + """File to send. Pass a file_id to send a file that exists on the Telegram servers (recommended), pass an HTTP URL for Telegram to get a file from the Internet, or pass 'attach://' to upload a new one using multipart/form-data under name.""" + + thumb: typing.Optional[types.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 thumbnail‘s width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can’t be reused and can be only uploaded as a new file, so you can pass 'attach://' if the thumbnail was uploaded using multipart/form-data under .""" + + caption: str = None + """Caption of the audio to be sent, 0-1024 characters""" + + parse_mode: 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: int = None + """Duration of the audio in seconds""" + + performer: str = None + """Performer of the audio""" + + title: str = None + """Title of the audio""" + + +class InputMediaDocument(pydantic.BaseModel): + """ + Represents a general file to be sent. + + Source: https://core.telegram.org/bots/api#inputmediadocument + """ + + type: str + """Type of the result, must be document""" + + media: str + """File to send. Pass a file_id to send a file that exists on the Telegram servers (recommended), pass an HTTP URL for Telegram to get a file from the Internet, or pass 'attach://' to upload a new one using multipart/form-data under name.""" + + thumb: typing.Optional[types.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 thumbnail‘s width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can’t be reused and can be only uploaded as a new file, so you can pass 'attach://' if the thumbnail was uploaded using multipart/form-data under .""" + + caption: str = None + """Caption of the document to be sent, 0-1024 characters""" + + parse_mode: 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.""" + + +class InputFile(pydantic.BaseModel): + """ + This object represents the contents of a file to be uploaded. Must be posted using multipart/form-data in the usual way that files are uploaded via the browser. + + Source: https://core.telegram.org/bots/api#inputfile + """ + + pass + + +# %% End of region 'Available types' + +# %% Region: 'Available methods' +""" +All methods in the Bot API are case-insensitive. We support GET and POST HTTP methods. Use either URL query string or application/json or application/x-www-form-urlencoded or multipart/form-data for passing parameters in Bot API requests. +On successful call, a JSON-object containing the result will be returned. + +link: https://core.telegram.org/bots/api#available-methods +""" + +# %% End of region 'Available methods' + +# %% Region: 'Updating messages' +""" +The following methods allow you to change an existing message in the message history instead of sending a new one with a result of an action. This is most useful for messages with inline keyboards using callback queries, but can also help reduce clutter in conversations with regular chat bots. +Please note, that it is currently only possible to edit messages without reply_markup or with inline keyboards. + +link: https://core.telegram.org/bots/api#updating-messages +""" + +# %% End of region 'Updating messages' + +# %% Region: 'Stickers' +""" +The following methods and objects allow your bot to handle stickers and sticker sets. + +link: https://core.telegram.org/bots/api#stickers +""" + + +class Sticker(pydantic.BaseModel): + """ + This object represents a sticker. + + Source: https://core.telegram.org/bots/api#sticker + """ + + file_id: str + """Unique identifier for this file""" + + width: int + """Sticker width""" + + height: int + """Sticker height""" + + thumb: types.PhotoSize = None + """Sticker thumbnail in the .webp or .jpg format""" + + emoji: str = None + """Emoji associated with the sticker""" + + set_name: str = None + """Name of the sticker set to which the sticker belongs""" + + mask_position: types.MaskPosition = None + """For mask stickers, the position where the mask should be placed""" + + file_size: int = None + """File size""" + + +class StickerSet(pydantic.BaseModel): + """ + This object represents a sticker set. + + Source: https://core.telegram.org/bots/api#stickerset + """ + + name: str + """Sticker set name""" + + title: str + """Sticker set title""" + + contains_masks: bool + """True, if the sticker set contains masks""" + + stickers: typing.List[types.Sticker] + """List of all set stickers""" + + +class MaskPosition(pydantic.BaseModel): + """ + This object describes the position on faces where a mask should be placed by default. + + Source: https://core.telegram.org/bots/api#maskposition + """ + + point: str + """The part of the face relative to which the mask should be placed. One of 'forehead', 'eyes', 'mouth', or 'chin'.""" + + x_shift: float + """Shift by X-axis measured in widths of the mask scaled to the face size, from left to right. For example, choosing -1.0 will place mask just to the left of the default mask position.""" + + y_shift: float + """Shift by Y-axis measured in heights of the mask scaled to the face size, from top to bottom. For example, 1.0 will place the mask just below the default mask position.""" + + scale: float + """Mask scaling coefficient. For example, 2.0 means double size.""" + + +# %% End of region 'Stickers' + +# %% Region: 'Inline mode' +""" +The following methods and objects allow your bot to work in inline mode. +Please see our Introduction to Inline bots for more details. +To enable this option, send the /setinline command to @BotFather and provide the placeholder text that the user will see in the input field after typing your bot’s name. + +link: https://core.telegram.org/bots/api#inline-mode +""" + + +class InlineQuery(pydantic.BaseModel): + """ + 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: types.User = pydantic.Schema(..., alias="from") + """Sender""" + + location: types.Location = None + """Sender location, only for bots that request user location""" + + 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""" + + +class InlineQueryResult(pydantic.BaseModel): + """ + 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 + """ + + pass + + +class InlineQueryResultArticle(pydantic.BaseModel): + """ + Represents a link to an article or web page. + + Source: https://core.telegram.org/bots/api#inlinequeryresultarticle + """ + + type: str + """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: types.InputMessageContent + """Content of the message to be sent""" + + reply_markup: types.InlineKeyboardMarkup = None + """Inline keyboard attached to the message""" + + url: str = None + """URL of the result""" + + hide_url: bool = None + """Pass True, if you don't want the URL to be shown in the message""" + + description: str = None + """Short description of the result""" + + thumb_url: str = None + """Url of the thumbnail for the result""" + + thumb_width: int = None + """Thumbnail width""" + + thumb_height: int = None + """Thumbnail height""" + + +class InlineQueryResultPhoto(pydantic.BaseModel): + """ + Represents a link to a photo. By default, this photo will be sent by the user with optional caption. Alternatively, you can use input_message_content to send a message with the specified content instead of the photo. + + Source: https://core.telegram.org/bots/api#inlinequeryresultphoto + """ + + type: str + """Type of the result, must be photo""" + + id: str + """Unique identifier for this result, 1-64 bytes""" + + photo_url: str + """A valid URL of the photo. Photo must be in jpeg format. Photo size must not exceed 5MB""" + + thumb_url: str + """URL of the thumbnail for the photo""" + + photo_width: int = None + """Width of the photo""" + + photo_height: int = None + """Height of the photo""" + + title: str = None + """Title for the result""" + + description: str = None + """Short description of the result""" + + caption: str = None + """Caption of the photo to be sent, 0-1024 characters""" + + parse_mode: 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: types.InlineKeyboardMarkup = None + """Inline keyboard attached to the message""" + + input_message_content: types.InputMessageContent = None + """Content of the message to be sent instead of the photo""" + + +class InlineQueryResultGif(pydantic.BaseModel): + """ + Represents a link to an animated GIF file. By default, this animated GIF file will be sent by the user with optional caption. Alternatively, you can use input_message_content to send a message with the specified content instead of the animation. + + Source: https://core.telegram.org/bots/api#inlinequeryresultgif + """ + + type: str + """Type of the result, must be gif""" + + id: str + """Unique identifier for this result, 1-64 bytes""" + + gif_url: str + """A valid URL for the GIF file. File size must not exceed 1MB""" + + gif_width: int = None + """Width of the GIF""" + + gif_height: int = None + """Height of the GIF""" + + gif_duration: int = None + """Duration of the GIF""" + + thumb_url: str + """URL of the static thumbnail for the result (jpeg or gif)""" + + title: str = None + """Title for the result""" + + caption: str = None + """Caption of the GIF file to be sent, 0-1024 characters""" + + parse_mode: 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: types.InlineKeyboardMarkup = None + """Inline keyboard attached to the message""" + + input_message_content: types.InputMessageContent = None + """Content of the message to be sent instead of the GIF animation""" + + +class InlineQueryResultMpeg4Gif(pydantic.BaseModel): + """ + Represents a link to a video animation (H.264/MPEG-4 AVC video without sound). By default, this animated MPEG-4 file will be sent by the user with optional caption. Alternatively, you can use input_message_content to send a message with the specified content instead of the animation. + + Source: https://core.telegram.org/bots/api#inlinequeryresultmpeg4gif + """ + + type: str + """Type of the result, must be mpeg4_gif""" + + id: str + """Unique identifier for this result, 1-64 bytes""" + + mpeg4_url: str + """A valid URL for the MP4 file. File size must not exceed 1MB""" + + mpeg4_width: int = None + """Video width""" + + mpeg4_height: int = None + """Video height""" + + mpeg4_duration: int = None + """Video duration""" + + thumb_url: str + """URL of the static thumbnail (jpeg or gif) for the result""" + + title: str = None + """Title for the result""" + + caption: str = None + """Caption of the MPEG-4 file to be sent, 0-1024 characters""" + + parse_mode: 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: types.InlineKeyboardMarkup = None + """Inline keyboard attached to the message""" + + input_message_content: types.InputMessageContent = None + """Content of the message to be sent instead of the video animation""" + + +class InlineQueryResultVideo(pydantic.BaseModel): + """ + Represents a link to a page containing an embedded video player or a video file. By default, this video file will be sent by the user with an optional caption. Alternatively, you can use input_message_content to send a message with the specified content instead of the video. + If an InlineQueryResultVideo message contains an embedded video (e.g., YouTube), you must replace its content using input_message_content. + + Source: https://core.telegram.org/bots/api#inlinequeryresultvideo + """ + + type: str + """Type of the result, must be video""" + + id: str + """Unique identifier for this result, 1-64 bytes""" + + video_url: str + """A valid URL for the embedded video player or video file""" + + mime_type: str + """Mime type of the content of video url, 'text/html' or 'video/mp4'""" + + thumb_url: str + """URL of the thumbnail (jpeg only) for the video""" + + title: str + """Title for the result""" + + caption: str = None + """Caption of the video to be sent, 0-1024 characters""" + + parse_mode: 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.""" + + video_width: int = None + """Video width""" + + video_height: int = None + """Video height""" + + video_duration: int = None + """Video duration in seconds""" + + description: str = None + """Short description of the result""" + + reply_markup: types.InlineKeyboardMarkup = None + """Inline keyboard attached to the message""" + + input_message_content: types.InputMessageContent = None + """Content of the message to be sent instead of the video. This field is required if InlineQueryResultVideo is used to send an HTML-page as a result (e.g., a YouTube video).""" + + +class InlineQueryResultAudio(pydantic.BaseModel): + """ + Represents a link to an mp3 audio file. By default, this audio file will be sent by the user. Alternatively, you can use input_message_content to send a message with the specified content instead of the audio. + Note: This will only work in Telegram versions released after 9 April, 2016. Older clients will ignore them. + + Source: https://core.telegram.org/bots/api#inlinequeryresultaudio + """ + + type: str + """Type of the result, must be audio""" + + id: str + """Unique identifier for this result, 1-64 bytes""" + + audio_url: str + """A valid URL for the audio file""" + + title: str + """Title""" + + caption: str = None + """Caption, 0-1024 characters""" + + parse_mode: 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.""" + + performer: str = None + """Performer""" + + audio_duration: int = None + """Audio duration in seconds""" + + reply_markup: types.InlineKeyboardMarkup = None + """Inline keyboard attached to the message""" + + input_message_content: types.InputMessageContent = None + """Content of the message to be sent instead of the audio""" + + +class InlineQueryResultVoice(pydantic.BaseModel): + """ + Represents a link to a voice recording in an .ogg container encoded with OPUS. By default, this voice recording will be sent by the user. Alternatively, you can use input_message_content to send a message with the specified content instead of the the voice message. + Note: This will only work in Telegram versions released after 9 April, 2016. Older clients will ignore them. + + Source: https://core.telegram.org/bots/api#inlinequeryresultvoice + """ + + type: str + """Type of the result, must be voice""" + + id: str + """Unique identifier for this result, 1-64 bytes""" + + voice_url: str + """A valid URL for the voice recording""" + + title: str + """Recording title""" + + caption: str = None + """Caption, 0-1024 characters""" + + parse_mode: 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.""" + + voice_duration: int = None + """Recording duration in seconds""" + + reply_markup: types.InlineKeyboardMarkup = None + """Inline keyboard attached to the message""" + + input_message_content: types.InputMessageContent = None + """Content of the message to be sent instead of the voice recording""" + + +class InlineQueryResultDocument(pydantic.BaseModel): + """ + Represents a link to a file. By default, this file will be sent by the user with an optional caption. Alternatively, you can use input_message_content to send a message with the specified content instead of the file. Currently, only .PDF and .ZIP files can be sent using this method. + Note: This will only work in Telegram versions released after 9 April, 2016. Older clients will ignore them. + + Source: https://core.telegram.org/bots/api#inlinequeryresultdocument + """ + + type: str + """Type of the result, must be document""" + + id: str + """Unique identifier for this result, 1-64 bytes""" + + title: str + """Title for the result""" + + caption: str = None + """Caption of the document to be sent, 0-1024 characters""" + + parse_mode: 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.""" + + document_url: str + """A valid URL for the file""" + + mime_type: str + """Mime type of the content of the file, either 'application/pdf' or 'application/zip'""" + + description: str = None + """Short description of the result""" + + reply_markup: types.InlineKeyboardMarkup = None + """Inline keyboard attached to the message""" + + input_message_content: types.InputMessageContent = None + """Content of the message to be sent instead of the file""" + + thumb_url: str = None + """URL of the thumbnail (jpeg only) for the file""" + + thumb_width: int = None + """Thumbnail width""" + + thumb_height: int = None + """Thumbnail height""" + + +class InlineQueryResultLocation(pydantic.BaseModel): + """ + Represents a location on a map. By default, the location will be sent by the user. Alternatively, you can use input_message_content to send a message with the specified content instead of the location. + Note: This will only work in Telegram versions released after 9 April, 2016. Older clients will ignore them. + + Source: https://core.telegram.org/bots/api#inlinequeryresultlocation + """ + + type: str + """Type of the result, must be location""" + + id: str + """Unique identifier for this result, 1-64 Bytes""" + + latitude: float + """Location latitude in degrees""" + + longitude: float + """Location longitude in degrees""" + + title: str + """Location title""" + + live_period: int = None + """Period in seconds for which the location can be updated, should be between 60 and 86400.""" + + reply_markup: types.InlineKeyboardMarkup = None + """Inline keyboard attached to the message""" + + input_message_content: types.InputMessageContent = None + """Content of the message to be sent instead of the location""" + + thumb_url: str = None + """Url of the thumbnail for the result""" + + thumb_width: int = None + """Thumbnail width""" + + thumb_height: int = None + """Thumbnail height""" + + +class InlineQueryResultVenue(pydantic.BaseModel): + """ + Represents a venue. By default, the venue will be sent by the user. Alternatively, you can use input_message_content to send a message with the specified content instead of the venue. + Note: This will only work in Telegram versions released after 9 April, 2016. Older clients will ignore them. + + Source: https://core.telegram.org/bots/api#inlinequeryresultvenue + """ + + type: str + """Type of the result, must be venue""" + + id: str + """Unique identifier for this result, 1-64 Bytes""" + + latitude: float + """Latitude of the venue location in degrees""" + + longitude: float + """Longitude of the venue location in degrees""" + + title: str + """Title of the venue""" + + address: str + """Address of the venue""" + + foursquare_id: str = None + """Foursquare identifier of the venue if known""" + + foursquare_type: str = None + """Foursquare type of the venue, if known. (For example, 'arts_entertainment/default', 'arts_entertainment/aquarium' or 'food/icecream'.)""" + + reply_markup: types.InlineKeyboardMarkup = None + """Inline keyboard attached to the message""" + + input_message_content: types.InputMessageContent = None + """Content of the message to be sent instead of the venue""" + + thumb_url: str = None + """Url of the thumbnail for the result""" + + thumb_width: int = None + """Thumbnail width""" + + thumb_height: int = None + """Thumbnail height""" + + +class InlineQueryResultContact(pydantic.BaseModel): + """ + Represents a contact with a phone number. By default, this contact will be sent by the user. Alternatively, you can use input_message_content to send a message with the specified content instead of the contact. + Note: This will only work in Telegram versions released after 9 April, 2016. Older clients will ignore them. + + Source: https://core.telegram.org/bots/api#inlinequeryresultcontact + """ + + type: str + """Type of the result, must be contact""" + + id: str + """Unique identifier for this result, 1-64 Bytes""" + + phone_number: str + """Contact's phone number""" + + first_name: str + """Contact's first name""" + + last_name: str = None + """Contact's last name""" + + vcard: str = None + """Additional data about the contact in the form of a vCard, 0-2048 bytes""" + + reply_markup: types.InlineKeyboardMarkup = None + """Inline keyboard attached to the message""" + + input_message_content: types.InputMessageContent = None + """Content of the message to be sent instead of the contact""" + + thumb_url: str = None + """Url of the thumbnail for the result""" + + thumb_width: int = None + """Thumbnail width""" + + thumb_height: int = None + """Thumbnail height""" + + +class InlineQueryResultGame(pydantic.BaseModel): + """ + Represents a Game. + Note: This will only work in Telegram versions released after October 1, 2016. Older clients will not display any inline results if a game result is among them. + + Source: https://core.telegram.org/bots/api#inlinequeryresultgame + """ + + type: str + """Type of the result, must be game""" + + id: str + """Unique identifier for this result, 1-64 bytes""" + + game_short_name: str + """Short name of the game""" + + reply_markup: types.InlineKeyboardMarkup = None + """Inline keyboard attached to the message""" + + +class InlineQueryResultCachedPhoto(pydantic.BaseModel): + """ + Represents a link to a photo stored on the Telegram servers. By default, this photo will be sent by the user with an optional caption. Alternatively, you can use input_message_content to send a message with the specified content instead of the photo. + + Source: https://core.telegram.org/bots/api#inlinequeryresultcachedphoto + """ + + type: str + """Type of the result, must be photo""" + + id: str + """Unique identifier for this result, 1-64 bytes""" + + photo_file_id: str + """A valid file identifier of the photo""" + + title: str = None + """Title for the result""" + + description: str = None + """Short description of the result""" + + caption: str = None + """Caption of the photo to be sent, 0-1024 characters""" + + parse_mode: 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: types.InlineKeyboardMarkup = None + """Inline keyboard attached to the message""" + + input_message_content: types.InputMessageContent = None + """Content of the message to be sent instead of the photo""" + + +class InlineQueryResultCachedGif(pydantic.BaseModel): + """ + Represents a link to an animated GIF file stored on the Telegram servers. By default, this animated GIF file will be sent by the user with an optional caption. Alternatively, you can use input_message_content to send a message with specified content instead of the animation. + + Source: https://core.telegram.org/bots/api#inlinequeryresultcachedgif + """ + + type: str + """Type of the result, must be gif""" + + id: str + """Unique identifier for this result, 1-64 bytes""" + + gif_file_id: str + """A valid file identifier for the GIF file""" + + title: str = None + """Title for the result""" + + caption: str = None + """Caption of the GIF file to be sent, 0-1024 characters""" + + parse_mode: 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: types.InlineKeyboardMarkup = None + """Inline keyboard attached to the message""" + + input_message_content: types.InputMessageContent = None + """Content of the message to be sent instead of the GIF animation""" + + +class InlineQueryResultCachedMpeg4Gif(pydantic.BaseModel): + """ + Represents a link to a video animation (H.264/MPEG-4 AVC video without sound) stored on the Telegram servers. By default, this animated MPEG-4 file will be sent by the user with an optional caption. Alternatively, you can use input_message_content to send a message with the specified content instead of the animation. + + Source: https://core.telegram.org/bots/api#inlinequeryresultcachedmpeg4gif + """ + + type: str + """Type of the result, must be mpeg4_gif""" + + id: str + """Unique identifier for this result, 1-64 bytes""" + + mpeg4_file_id: str + """A valid file identifier for the MP4 file""" + + title: str = None + """Title for the result""" + + caption: str = None + """Caption of the MPEG-4 file to be sent, 0-1024 characters""" + + parse_mode: 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: types.InlineKeyboardMarkup = None + """Inline keyboard attached to the message""" + + input_message_content: types.InputMessageContent = None + """Content of the message to be sent instead of the video animation""" + + +class InlineQueryResultCachedSticker(pydantic.BaseModel): + """ + Represents a link to a sticker stored on the Telegram servers. By default, this sticker will be sent by the user. Alternatively, you can use input_message_content to send a message with the specified content instead of the sticker. + Note: This will only work in Telegram versions released after 9 April, 2016. Older clients will ignore them. + + Source: https://core.telegram.org/bots/api#inlinequeryresultcachedsticker + """ + + type: str + """Type of the result, must be sticker""" + + id: str + """Unique identifier for this result, 1-64 bytes""" + + sticker_file_id: str + """A valid file identifier of the sticker""" + + reply_markup: types.InlineKeyboardMarkup = None + """Inline keyboard attached to the message""" + + input_message_content: types.InputMessageContent = None + """Content of the message to be sent instead of the sticker""" + + +class InlineQueryResultCachedDocument(pydantic.BaseModel): + """ + Represents a link to a file stored on the Telegram servers. By default, this file will be sent by the user with an optional caption. Alternatively, you can use input_message_content to send a message with the specified content instead of the file. + Note: This will only work in Telegram versions released after 9 April, 2016. Older clients will ignore them. + + Source: https://core.telegram.org/bots/api#inlinequeryresultcacheddocument + """ + + type: str + """Type of the result, must be document""" + + id: str + """Unique identifier for this result, 1-64 bytes""" + + title: str + """Title for the result""" + + document_file_id: str + """A valid file identifier for the file""" + + description: str = None + """Short description of the result""" + + caption: str = None + """Caption of the document to be sent, 0-1024 characters""" + + parse_mode: 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: types.InlineKeyboardMarkup = None + """Inline keyboard attached to the message""" + + input_message_content: types.InputMessageContent = None + """Content of the message to be sent instead of the file""" + + +class InlineQueryResultCachedVideo(pydantic.BaseModel): + """ + Represents a link to a video file stored on the Telegram servers. By default, this video file will be sent by the user with an optional caption. Alternatively, you can use input_message_content to send a message with the specified content instead of the video. + + Source: https://core.telegram.org/bots/api#inlinequeryresultcachedvideo + """ + + type: str + """Type of the result, must be video""" + + id: str + """Unique identifier for this result, 1-64 bytes""" + + video_file_id: str + """A valid file identifier for the video file""" + + title: str + """Title for the result""" + + description: str = None + """Short description of the result""" + + caption: str = None + """Caption of the video to be sent, 0-1024 characters""" + + parse_mode: 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: types.InlineKeyboardMarkup = None + """Inline keyboard attached to the message""" + + input_message_content: types.InputMessageContent = None + """Content of the message to be sent instead of the video""" + + +class InlineQueryResultCachedVoice(pydantic.BaseModel): + """ + Represents a link to a voice message stored on the Telegram servers. By default, this voice message will be sent by the user. Alternatively, you can use input_message_content to send a message with the specified content instead of the voice message. + Note: This will only work in Telegram versions released after 9 April, 2016. Older clients will ignore them. + + Source: https://core.telegram.org/bots/api#inlinequeryresultcachedvoice + """ + + type: str + """Type of the result, must be voice""" + + id: str + """Unique identifier for this result, 1-64 bytes""" + + voice_file_id: str + """A valid file identifier for the voice message""" + + title: str + """Voice message title""" + + caption: str = None + """Caption, 0-1024 characters""" + + parse_mode: 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: types.InlineKeyboardMarkup = None + """Inline keyboard attached to the message""" + + input_message_content: types.InputMessageContent = None + """Content of the message to be sent instead of the voice message""" + + +class InlineQueryResultCachedAudio(pydantic.BaseModel): + """ + Represents a link to an mp3 audio file stored on the Telegram servers. By default, this audio file will be sent by the user. Alternatively, you can use input_message_content to send a message with the specified content instead of the audio. + Note: This will only work in Telegram versions released after 9 April, 2016. Older clients will ignore them. + + Source: https://core.telegram.org/bots/api#inlinequeryresultcachedaudio + """ + + type: str + """Type of the result, must be audio""" + + id: str + """Unique identifier for this result, 1-64 bytes""" + + audio_file_id: str + """A valid file identifier for the audio file""" + + caption: str = None + """Caption, 0-1024 characters""" + + parse_mode: 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: types.InlineKeyboardMarkup = None + """Inline keyboard attached to the message""" + + input_message_content: types.InputMessageContent = None + """Content of the message to be sent instead of the audio""" + + +class InputMessageContent(pydantic.BaseModel): + """ + This object represents the content of a message to be sent as a result of an inline query. Telegram clients currently support the following 4 types: + - InputTextMessageContent + - InputLocationMessageContent + - InputVenueMessageContent + - InputContactMessageContent + + Source: https://core.telegram.org/bots/api#inputmessagecontent + """ + + pass + + +class InputTextMessageContent(pydantic.BaseModel): + """ + Represents the content of a text message to be sent as the result of an inline query. + + Source: https://core.telegram.org/bots/api#inputtextmessagecontent + """ + + message_text: str + """Text of the message to be sent, 1-4096 characters""" + + parse_mode: 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: bool = None + """Disables link previews for links in the sent message""" + + +class InputLocationMessageContent(pydantic.BaseModel): + """ + Represents the content of a location message to be sent as the result of an inline query. + + Source: https://core.telegram.org/bots/api#inputlocationmessagecontent + """ + + latitude: float + """Latitude of the location in degrees""" + + longitude: float + """Longitude of the location in degrees""" + + live_period: int = None + """Period in seconds for which the location can be updated, should be between 60 and 86400.""" + + +class InputVenueMessageContent(pydantic.BaseModel): + """ + Represents the content of a venue message to be sent as the result of an inline query. + + Source: https://core.telegram.org/bots/api#inputvenuemessagecontent + """ + + latitude: float + """Latitude of the venue in degrees""" + + longitude: float + """Longitude of the venue in degrees""" + + title: str + """Name of the venue""" + + address: str + """Address of the venue""" + + foursquare_id: str = None + """Foursquare identifier of the venue, if known""" + + foursquare_type: str = None + """Foursquare type of the venue, if known. (For example, 'arts_entertainment/default', 'arts_entertainment/aquarium' or 'food/icecream'.)""" + + +class InputContactMessageContent(pydantic.BaseModel): + """ + Represents the content of a contact message to be sent as the result of an inline query. + + Source: https://core.telegram.org/bots/api#inputcontactmessagecontent + """ + + phone_number: str + """Contact's phone number""" + + first_name: str + """Contact's first name""" + + last_name: str = None + """Contact's last name""" + + vcard: str = None + """Additional data about the contact in the form of a vCard, 0-2048 bytes""" + + +class ChosenInlineResult(pydantic.BaseModel): + """ + 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: types.User = pydantic.Schema(..., alias="from") + """The user that chose the result""" + + location: types.Location = None + """Sender location, only for bots that require user location""" + + inline_message_id: 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.""" + + query: str + """The query that was used to obtain the result""" + + +# %% End of region 'Inline mode' + +# %% Region: 'Payments' +""" +Your bot can accept payments from Telegram users. Please see the introduction to payments for more details on the process and how to set up payments for your bot. Please note that users will need Telegram v.4.0 or higher to use payments (released on May 18, 2017). + +link: https://core.telegram.org/bots/api#payments +""" + + +class LabeledPrice(pydantic.BaseModel): + """ + This object represents a portion of the price for goods or services. + + Source: https://core.telegram.org/bots/api#labeledprice + """ + + label: str + """Portion label""" + + amount: int + """Price of the product in the smallest units of the currency (integer, not float/double). For example, for a price of US$ 1.45 pass amount = 145. See the exp parameter in currencies.json, it shows the number of digits past the decimal point for each currency (2 for the majority of currencies).""" + + +class Invoice(pydantic.BaseModel): + """ + This object contains basic information about an invoice. + + Source: https://core.telegram.org/bots/api#invoice + """ + + title: str + """Product name""" + + description: str + """Product description""" + + start_parameter: str + """Unique bot deep-linking parameter that can be used to generate this invoice""" + + currency: str + """Three-letter ISO 4217 currency code""" + + total_amount: int + """Total price in the smallest units of the currency (integer, not float/double). For example, for a price of US$ 1.45 pass amount = 145. See the exp parameter in currencies.json, it shows the number of digits past the decimal point for each currency (2 for the majority of currencies).""" + + +class ShippingAddress(pydantic.BaseModel): + """ + This object represents a shipping address. + + Source: https://core.telegram.org/bots/api#shippingaddress + """ + + country_code: str + """ISO 3166-1 alpha-2 country code""" + + state: str + """State, if applicable""" + + city: str + """City""" + + street_line1: str + """First line for the address""" + + street_line2: str + """Second line for the address""" + + post_code: str + """Address post code""" + + +class OrderInfo(pydantic.BaseModel): + """ + This object represents information about an order. + + Source: https://core.telegram.org/bots/api#orderinfo + """ + + name: str = None + """User name""" + + phone_number: str = None + """User's phone number""" + + email: str = None + """User email""" + + shipping_address: types.ShippingAddress = None + """User shipping address""" + + +class ShippingOption(pydantic.BaseModel): + """ + This object represents one shipping option. + + Source: https://core.telegram.org/bots/api#shippingoption + """ + + id: str + """Shipping option identifier""" + + title: str + """Option title""" + + prices: typing.List[types.LabeledPrice] + """List of price portions""" + + +class SuccessfulPayment(pydantic.BaseModel): + """ + This object contains basic information about a successful payment. + + Source: https://core.telegram.org/bots/api#successfulpayment + """ + + currency: str + """Three-letter ISO 4217 currency code""" + + total_amount: int + """Total price in the smallest units of the currency (integer, not float/double). For example, for a price of US$ 1.45 pass amount = 145. See the exp parameter in currencies.json, it shows the number of digits past the decimal point for each currency (2 for the majority of currencies).""" + + invoice_payload: str + """Bot specified invoice payload""" + + shipping_option_id: str = None + """Identifier of the shipping option chosen by the user""" + + order_info: types.OrderInfo = None + """Order info provided by the user""" + + telegram_payment_charge_id: str + """Telegram payment identifier""" + + provider_payment_charge_id: str + """Provider payment identifier""" + + +class ShippingQuery(pydantic.BaseModel): + """ + This object contains information about an incoming shipping query. + + Source: https://core.telegram.org/bots/api#shippingquery + """ + + id: str + """Unique query identifier""" + + from_user: types.User = pydantic.Schema(..., alias="from") + """User who sent the query""" + + invoice_payload: str + """Bot specified invoice payload""" + + shipping_address: types.ShippingAddress + """User specified shipping address""" + + +class PreCheckoutQuery(pydantic.BaseModel): + """ + This object contains information about an incoming pre-checkout query. + + Source: https://core.telegram.org/bots/api#precheckoutquery + """ + + id: str + """Unique query identifier""" + + from_user: types.User = pydantic.Schema(..., alias="from") + """User who sent the query""" + + currency: str + """Three-letter ISO 4217 currency code""" + + total_amount: int + """Total price in the smallest units of the currency (integer, not float/double). For example, for a price of US$ 1.45 pass amount = 145. See the exp parameter in currencies.json, it shows the number of digits past the decimal point for each currency (2 for the majority of currencies).""" + + invoice_payload: str + """Bot specified invoice payload""" + + shipping_option_id: str = None + """Identifier of the shipping option chosen by the user""" + + order_info: types.OrderInfo = None + """Order info provided by the user""" + + +# %% End of region 'Payments' + +# %% Region: 'Telegram Passport' +""" +Telegram Passport is a unified authorization method for services that require personal identification. Users can upload their documents once, then instantly share their data with services that require real-world ID (finance, ICOs, etc.). Please see the manual for details. + +link: https://core.telegram.org/bots/api#telegram-passport +""" + + +class PassportData(pydantic.BaseModel): + """ + Contains information about Telegram Passport data shared with the bot by the user. + + Source: https://core.telegram.org/bots/api#passportdata + """ + + data: typing.List[types.EncryptedPassportElement] + """Array with information about documents and other Telegram Passport elements that was shared with the bot""" + + credentials: types.EncryptedCredentials + """Encrypted credentials required to decrypt the data""" + + +class PassportFile(pydantic.BaseModel): + """ + This object represents a file uploaded to Telegram Passport. Currently all Telegram Passport files are in JPEG format when decrypted and don't exceed 10MB. + + Source: https://core.telegram.org/bots/api#passportfile + """ + + file_id: str + """Unique identifier for this file""" + + file_size: int + """File size""" + + file_date: int + """Unix time when the file was uploaded""" + + +class EncryptedPassportElement(pydantic.BaseModel): + """ + 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'.""" + + data: 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: str = None + """User's verified phone number, available only for 'phone_number' type""" + + email: str = None + """User's verified email address, available only for 'email' type""" + + files: typing.List[types.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: types.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: types.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: types.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: typing.List[types.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.""" + + hash: str + """Base64-encoded element hash for using in PassportElementErrorUnspecified""" + + +class EncryptedCredentials(pydantic.BaseModel): + """ + 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""" + + +class PassportElementError(pydantic.BaseModel): + """ + This object represents an error in the Telegram Passport element which was submitted that should be resolved by the user. It should be one of: + - PassportElementErrorDataField + - PassportElementErrorFrontSide + - PassportElementErrorReverseSide + - PassportElementErrorSelfie + - PassportElementErrorFile + - PassportElementErrorFiles + - PassportElementErrorTranslationFile + - PassportElementErrorTranslationFiles + - PassportElementErrorUnspecified + + Source: https://core.telegram.org/bots/api#passportelementerror + """ + + pass + + +class PassportElementErrorDataField(pydantic.BaseModel): + """ + Represents an issue in one of the data fields that was provided by the user. The error is considered resolved when the field's value changes. + + Source: https://core.telegram.org/bots/api#passportelementerrordatafield + """ + + source: str + """Error source, must be data""" + + type: str + """The section of the user's Telegram Passport which has the error, one of 'personal_details', 'passport', 'driver_license', 'identity_card', 'internal_passport', 'address'""" + + field_name: str + """Name of the data field which has the error""" + + data_hash: str + """Base64-encoded data hash""" + + message: str + """Error message""" + + +class PassportElementErrorFrontSide(pydantic.BaseModel): + """ + Represents an issue with the front side of a document. The error is considered resolved when the file with the front side of the document changes. + + Source: https://core.telegram.org/bots/api#passportelementerrorfrontside + """ + + source: str + """Error source, must be front_side""" + + type: str + """The section of the user's Telegram Passport which has the issue, one of 'passport', 'driver_license', 'identity_card', 'internal_passport'""" + + file_hash: str + """Base64-encoded hash of the file with the front side of the document""" + + message: str + """Error message""" + + +class PassportElementErrorReverseSide(pydantic.BaseModel): + """ + Represents an issue with the reverse side of a document. The error is considered resolved when the file with reverse side of the document changes. + + Source: https://core.telegram.org/bots/api#passportelementerrorreverseside + """ + + source: str + """Error source, must be reverse_side""" + + type: str + """The section of the user's Telegram Passport which has the issue, one of 'driver_license', 'identity_card'""" + + file_hash: str + """Base64-encoded hash of the file with the reverse side of the document""" + + message: str + """Error message""" + + +class PassportElementErrorSelfie(pydantic.BaseModel): + """ + Represents an issue with the selfie with a document. The error is considered resolved when the file with the selfie changes. + + Source: https://core.telegram.org/bots/api#passportelementerrorselfie + """ + + source: str + """Error source, must be selfie""" + + type: str + """The section of the user's Telegram Passport which has the issue, one of 'passport', 'driver_license', 'identity_card', 'internal_passport'""" + + file_hash: str + """Base64-encoded hash of the file with the selfie""" + + message: str + """Error message""" + + +class PassportElementErrorFile(pydantic.BaseModel): + """ + Represents an issue with a document scan. The error is considered resolved when the file with the document scan changes. + + Source: https://core.telegram.org/bots/api#passportelementerrorfile + """ + + source: str + """Error source, must be file""" + + type: str + """The section of the user's Telegram Passport which has the issue, one of 'utility_bill', 'bank_statement', 'rental_agreement', 'passport_registration', 'temporary_registration'""" + + file_hash: str + """Base64-encoded file hash""" + + message: str + """Error message""" + + +class PassportElementErrorFiles(pydantic.BaseModel): + """ + Represents an issue with a list of scans. The error is considered resolved when the list of files containing the scans changes. + + Source: https://core.telegram.org/bots/api#passportelementerrorfiles + """ + + source: str + """Error source, must be files""" + + type: str + """The section of the user's Telegram Passport which has the issue, one of 'utility_bill', 'bank_statement', 'rental_agreement', 'passport_registration', 'temporary_registration'""" + + file_hashes: typing.List[str] + """List of base64-encoded file hashes""" + + message: str + """Error message""" + + +class PassportElementErrorTranslationFile(pydantic.BaseModel): + """ + Represents an issue with one of the files that constitute the translation of a document. The error is considered resolved when the file changes. + + Source: https://core.telegram.org/bots/api#passportelementerrortranslationfile + """ + + source: str + """Error source, must be translation_file""" + + type: str + """Type of element of the user's Telegram Passport which has the issue, one of 'passport', 'driver_license', 'identity_card', 'internal_passport', 'utility_bill', 'bank_statement', 'rental_agreement', 'passport_registration', 'temporary_registration'""" + + file_hash: str + """Base64-encoded file hash""" + + message: str + """Error message""" + + +class PassportElementErrorTranslationFiles(pydantic.BaseModel): + """ + Represents an issue with the translated version of a document. The error is considered resolved when a file with the document translation change. + + Source: https://core.telegram.org/bots/api#passportelementerrortranslationfiles + """ + + source: str + """Error source, must be translation_files""" + + type: str + """Type of element of the user's Telegram Passport which has the issue, one of 'passport', 'driver_license', 'identity_card', 'internal_passport', 'utility_bill', 'bank_statement', 'rental_agreement', 'passport_registration', 'temporary_registration'""" + + file_hashes: typing.List[str] + """List of base64-encoded file hashes""" + + message: str + """Error message""" + + +class PassportElementErrorUnspecified(pydantic.BaseModel): + """ + Represents an issue in an unspecified place. The error is considered resolved when new data is added. + + Source: https://core.telegram.org/bots/api#passportelementerrorunspecified + """ + + source: str + """Error source, must be unspecified""" + + type: str + """Type of element of the user's Telegram Passport which has the issue""" + + element_hash: str + """Base64-encoded element hash""" + + message: str + """Error message""" + + +# %% End of region 'Telegram Passport' + +# %% Region: 'Games' +""" +link: https://core.telegram.org/bots/api#games +""" + + +class Games(pydantic.BaseModel): + """ + Your bot can offer users HTML5 games to play solo or to compete against each other in groups and one-on-one chats. Create games via @BotFather using the /newgame command. Please note that this kind of power requires responsibility: you will need to accept the terms for each game that your bots will be offering. + - Games are a new type of content on Telegram, represented by the Game and InlineQueryResultGame objects. + - Once you've created a game via BotFather, you can send games to chats as regular messages using the sendGame method, or use inline mode with InlineQueryResultGame. + - If you send the game message without any buttons, it will automatically have a 'Play GameName' button. When this button is pressed, your bot gets a CallbackQuery with the game_short_name of the requested game. You provide the correct URL for this particular user and the app opens the game in the in-app browser. + - You can manually add multiple buttons to your game message. Please note that the first button in the first row must always launch the game, using the field callback_game in InlineKeyboardButton. You can add extra buttons according to taste: e.g., for a description of the rules, or to open the game's official community. + - To make your game more attractive, you can upload a GIF animation that demostrates the game to the users via BotFather (see Lumberjack for example). + - A game message will also display high scores for the current chat. Use setGameScore to post high scores to the chat with the game, add the edit_message parameter to automatically update the message with the current scoreboard. + - Use getGameHighScores to get data for in-game high score tables. + - You can also add an extra sharing button for users to share their best score to different chats. + - For examples of what can be done using this new stuff, check the @gamebot and @gamee bots. + + Source: https://core.telegram.org/bots/api#games + """ + + pass + + +class Game(pydantic.BaseModel): + """ + 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: typing.List[types.PhotoSize] + """Photo that will be displayed in the game message in chats.""" + + text: 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: typing.List[types.MessageEntity] = None + """Special entities that appear in text, such as usernames, URLs, bot commands, etc.""" + + animation: types.Animation = None + """Animation that will be displayed in the game message in chats. Upload via BotFather""" + + +class CallbackGame(pydantic.BaseModel): + """ + A placeholder, currently holds no information. Use BotFather to set up your game. + + Source: https://core.telegram.org/bots/api#callbackgame + """ + + pass + + +class GameHighScore(pydantic.BaseModel): + """ + This object represents one row of the high scores table for a game. + And that‘s about all we’ve 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: types.User + """User""" + + score: int + """Score""" + + +# %% End of region 'Games' diff --git a/dev_requirements.txt b/dev_requirements.txt index 79adc949..b746e5fc 100644 --- a/dev_requirements.txt +++ b/dev_requirements.txt @@ -15,3 +15,5 @@ sphinx-rtd-theme>=0.4.3 sphinxcontrib-programoutput>=0.14 aiohttp-socks>=0.2.2 rethinkdb>=2.4.1 +lxml==4.3.4 +requests==2.22.0 diff --git a/generator/__init__.py b/generator/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/generator/__main__.py b/generator/__main__.py new file mode 100644 index 00000000..5b846972 --- /dev/null +++ b/generator/__main__.py @@ -0,0 +1,7 @@ +import logging +import sys + +from generator.cli import main + +if __name__ == "__main__": + sys.exit(main(sys.argv)) diff --git a/generator/cli.py b/generator/cli.py new file mode 100644 index 00000000..e2263073 --- /dev/null +++ b/generator/cli.py @@ -0,0 +1,22 @@ +import logging +import pathlib +import sys +import typing + +from generator.generator import Generator +from generator.parser import Parser + +script_path = pathlib.Path(__file__).parent +out_dir = script_path.parent / "aiogram" / "_telegram" + + +def main(argv: typing.List[str]) -> int: + logging.basicConfig(level=logging.ERROR, stream=sys.stdout) + parser = Parser() + parser.parse() + generator = Generator(parser) + + with (out_dir / "types.py").open("w") as f: + f.write(generator.render_types()) + + return 0 diff --git a/generator/consts.py b/generator/consts.py new file mode 100644 index 00000000..f5fa22ca --- /dev/null +++ b/generator/consts.py @@ -0,0 +1,32 @@ +import re + +DOCS_URL = "https://core.telegram.org/bots/api" + +RE_FLAGS = re.IGNORECASE +ANCHOR_HEADER_PATTERN = re.compile(r"^h([34])$") +RETURN_PATTERNS = [ + re.compile(r"(?PArray of [a-z]+) objects", flags=RE_FLAGS), + re.compile(r"a (?P[a-z]+) object", flags=RE_FLAGS), + re.compile(r"Returns (?P[a-z]+) on success", flags=RE_FLAGS), + re.compile(r"(?P[a-z]+) on success", flags=RE_FLAGS), + re.compile( + r"(?P[a-z]+) is returned, otherwise (?P[a-zA-Z]+) is returned", flags=RE_FLAGS + ), + re.compile( + r"returns the edited (?P[a-z]+), otherwise returns (?P[a-zA-Z]+)", + flags=RE_FLAGS, + ), + re.compile(r"(?P[a-z]+) is returned", flags=RE_FLAGS), + re.compile(r"Returns (?P[a-z]+)", flags=RE_FLAGS), +] +BUILTIN_TYPES = { + "String": "str", + "Integer": "int", + "Float": "float", + "Boolean": "bool", + "InputFile": "types.InputFile", +} +READ_MORE_PATTERN = re.compile( + r" ((More info on|More about)([\W\w]+»)|»)", flags=re.MULTILINE & re.IGNORECASE +) +SYMBOLS_MAP = {"“": "'", "”": "'"} diff --git a/generator/generator.py b/generator/generator.py new file mode 100644 index 00000000..df425d6d --- /dev/null +++ b/generator/generator.py @@ -0,0 +1,34 @@ +import datetime +import pathlib + +import black +import jinja2 + +from generator.parser import Parser + +templates_dir: pathlib.Path = pathlib.Path(__file__).parent / "templates" + + +class Generator: + def __init__(self, parser: Parser): + self.parser = parser + self.env = jinja2.Environment(loader=jinja2.FileSystemLoader(searchpath=[templates_dir])) + + @property + def context(self): + return { + "groups": self.parser.groups, + "timestamp": datetime.datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S UTC"), + } + + def _render_template(self, template: str) -> str: + template = self.env.get_template(template) + content = template.render(self.context) + return content + + def _reformat_code(self, code: str) -> str: + return black.format_str(code, mode=black.FileMode()) + + def render_types(self): + content = self._render_template("types.py.jinja2") + return self._reformat_code(content) diff --git a/generator/normalizers.py b/generator/normalizers.py new file mode 100644 index 00000000..c92f9e8e --- /dev/null +++ b/generator/normalizers.py @@ -0,0 +1,85 @@ +import functools + +from generator.consts import BUILTIN_TYPES, RETURN_PATTERNS, READ_MORE_PATTERN, SYMBOLS_MAP + + +def normalize_description(text: str) -> str: + for bad, good in SYMBOLS_MAP.items(): + text = text.replace(bad, good) + text = READ_MORE_PATTERN.sub("", text) + text.strip() + return text + + +def normalize_annotation(item: dict): + for key in list(item.keys()): + item[key.lower()] = item.pop(key) + + item["description"] = normalize_description(item["description"]) + + +def normalize_method_annotation(item: dict): + normalize_annotation(item) + item["required"] = {"Optional": False, "Yes": True}[item["required"]] + item["name"] = item.pop("parameter") + + +def normalize_type_annotation(item: dict): + normalize_annotation(item) + + item["name"] = item.pop("field") + + if item["description"].startswith("Optional"): + item["required"] = False + item["description"] = item["description"][10:] + else: + item["required"] = True + + +@functools.lru_cache() +def normalize_type(string, required=True): + if not string: + return "typing.Any" + + union = "typing.Union" if required else "typing.Optional" + + lower = string.lower() + split = lower.split() + + if split[0] == "array": + new_string = string[lower.index("of") + 2 :].strip() + return f"typing.List[{normalize_type(new_string)}]" + if "or" in split: + split_types = string.split(" or ") + norm_str = ", ".join(map(normalize_type, map(str.strip, split_types))) + return f"{union}[{norm_str}]" + if "number" in lower: + return normalize_type(string.replace("number", "").strip()) + if lower in ["true", "false"]: + return "bool" + if string not in BUILTIN_TYPES and string[0].isupper(): + return f"types.{string}" + elif string in BUILTIN_TYPES: + return BUILTIN_TYPES[string] + return "typing.Any" + + +@functools.lru_cache() +def get_returning(description): + parts = list(filter(lambda item: "return" in item.lower(), description.split("."))) + if not parts: + return "typing.Any", "" + sentence = ". ".join(map(str.strip, parts)) + return_type = None + + for pattern in RETURN_PATTERNS: + temp = pattern.search(sentence) + if temp: + return_type = temp.group("type") + if "other" in temp.groupdict(): + otherwise = temp.group("other") + return_type += f" or {otherwise}" + if return_type: + break + + return return_type, sentence + "." diff --git a/generator/parser.py b/generator/parser.py new file mode 100644 index 00000000..c5150e51 --- /dev/null +++ b/generator/parser.py @@ -0,0 +1,134 @@ +import logging + +import requests +from lxml import html +from lxml.html import HtmlElement + +from generator.consts import DOCS_URL, ANCHOR_HEADER_PATTERN +from generator.normalizers import ( + normalize_type_annotation, + normalize_method_annotation, + normalize_description, +) +from generator.structures import Group, Entity, Annotation + +log = logging.getLogger(__name__) + + +class Parser: + def __init__(self): + self.docs = self.load(DOCS_URL) + self.groups = [] + + @staticmethod + def load_page(url: str) -> str: + log.info("Load page %r", url) + response = requests.get(url) + response.raise_for_status() + return response.text + + @staticmethod + def to_html(content: str, url: str) -> HtmlElement: + page = html.fromstring(content, url) + + for br in page.xpath("*//br"): + br.tail = "\n" + br.tail if br.tail else "\n" + + return page + + def load(self, url: str) -> HtmlElement: + content = self.load_page(url) + return self.to_html(content, url) + + def optimize_group(self, group: Group): + if not group.childs: + log.warning("Remove empty %s", group) + self.groups.remove(group) + return + + if not group.childs[0].annotations: + log.warning("Update group %r description from first child element", group.title) + group.description = group.childs[0].description + group.childs.pop(0) + + def parse(self): + self.groups.clear() + + group = None + + for item in self.docs.xpath("//a[@class='anchor']"): # type: HtmlElement + parent_tag: HtmlElement = item.getparent() + anchor_name = item.get("name", None) + matches = ANCHOR_HEADER_PATTERN.match(parent_tag.tag) + if not matches or not anchor_name: + continue + level = int(matches.group(1)) + title = item.tail + + if level == 3: + if group: + self.optimize_group(group) + + log.info("Parse group %r (#%s)", title, anchor_name) + group = Group(title=title, anchor=anchor_name) + self.groups.append(group) + + if level == 4 and len(title.split()) > 1: + continue + + elif anchor_name not in ["recent-changes", "authorizing-your-bot", "making-requests"]: + child = self._parse_child(parent_tag, anchor_name) + group.childs.append(child) + + return self.groups + + def _parse_child(self, start_tag: HtmlElement, anchor: str): + name = start_tag.text_content() + description = [] + annotations = [] + + is_method = name[0].islower() + + log.info("Parse block: %r (#%s)", name, anchor) + + for item in self._parse_tags_group(start_tag): + if item.tag == "table": + for raw in self._parse_table(item): + if is_method: + normalize_method_annotation(raw) + else: + normalize_type_annotation(raw) + annotations.append(Annotation(**raw)) + + elif item.tag == "p": + description.extend(item.text_content().splitlines()) + elif item.tag == "blockquote": + description.extend(self._parse_blockquote(item)) + elif item.tag == "ul": + description.extend(self._parse_list(item)) + + description = normalize_description("\n".join(description)) + block = Entity(anchor=anchor, name=name, description=description, annotations=annotations) + log.info("%s", block) + return block + + def _parse_tags_group(self, start_tag: HtmlElement): + tag: HtmlElement = start_tag.getnext() + while tag is not None and tag.tag not in ["h3", "h4"]: + yield tag + tag: HtmlElement = tag.getnext() + + def _parse_table(self, table: HtmlElement): + head, body = table.getchildren() # type: HtmlElement, HtmlElement + header = [item.text_content() for item in head.getchildren()[0]] + + for body_item in body: + yield {k: v for k, v in zip(header, [item.text_content() for item in body_item])} + + def _parse_blockquote(self, blockquote: HtmlElement): + for item in blockquote.getchildren(): + yield from item.text_content().splitlines() + + def _parse_list(self, data: HtmlElement): + for item in data.getchildren(): + yield " - " + item.text_content() diff --git a/generator/structures.py b/generator/structures.py new file mode 100644 index 00000000..8d240d9d --- /dev/null +++ b/generator/structures.py @@ -0,0 +1,90 @@ +from __future__ import annotations + +import typing +from dataclasses import dataclass, field + +from generator.normalizers import normalize_type, get_returning + + +@dataclass +class Annotation: + name: str + type: str + description: str + required: bool = True + + @property + def python_name(self): + if self.name == "from": + return "from_user" + return self.name + + @property + def python_type(self) -> str: + return normalize_type(self.type, self.required) + + @property + def python_argument(self): + result = f"{self.python_name}: {self.python_type}" + + value = "" if self.required else "None" + if self.name == "from": + value = f"pydantic.Schema({value or '...'}, alias=\"from\")" + + if value: + result += f" = {value}" + return result + + +@dataclass +class Entity: + name: str + anchor: str + description: str = None + annotations: typing.List[Annotation] = field(default_factory=list) + + @property + def is_method(self) -> bool: + return self.name[0].islower() + + @property + def is_type(self) -> bool: + return not self.is_method + + @property + def python_name(self) -> str: + return self.name + + def _get_returning(self): + if self.is_type: + return self.name, "" + + return get_returning(self.description) + + @property + def returning(self): + return self._get_returning()[1] + + @property + def returning_type(self): + return self._get_returning()[0] + + @property + def python_returning_type(self): + return normalize_type(self.returning_type) + + +@dataclass +class Group: + title: str + anchor: str + description: str = None + childs: typing.List[Entity] = field(default_factory=list) + + @property + def has_methods(self): + return any(entity.is_method for entity in self.childs) + + @property + def has_types(self): + return any(entity.is_method for entity in self.childs) diff --git a/generator/templates/type.py.jinja2 b/generator/templates/type.py.jinja2 new file mode 100644 index 00000000..5b5a6f72 --- /dev/null +++ b/generator/templates/type.py.jinja2 @@ -0,0 +1,12 @@ +class {{ entity.python_name }}(pydantic.BaseModel): + """ + {{ entity.description|indent(width=4) }} + + Source: https://core.telegram.org/bots/api#{{ entity.anchor }} + """ +{% for annotation in entity.annotations %} + {{ annotation.python_argument }} + """{{ annotation.description|indent(width=4) }}""" +{% else %} + pass +{% endfor %} diff --git a/generator/templates/types.py.jinja2 b/generator/templates/types.py.jinja2 new file mode 100644 index 00000000..cd5cd73a --- /dev/null +++ b/generator/templates/types.py.jinja2 @@ -0,0 +1,20 @@ +""" +!!! DO NOT EDIT THIS FILE !!! +This file is autogenerated from Docs of Telegram Bot API at {{ timestamp }} +""" +import typing + +import pydantic + +from aiogram import types + +__all__ = [ +{% for group in groups %}{% for entity in group.childs %}{% if entity.is_type %} + "{{ entity.python_name }}", +{% endif %}{% endfor %}{% endfor %} +] + + +{% for group in groups %} +{% include 'types_group.py.jinja2' %} +{% endfor %} diff --git a/generator/templates/types_group.py.jinja2 b/generator/templates/types_group.py.jinja2 new file mode 100644 index 00000000..d25fda26 --- /dev/null +++ b/generator/templates/types_group.py.jinja2 @@ -0,0 +1,10 @@ +# %% Region: '{{ group.title }}' +"""{% if group.description %} +{{ group.description }} +{% endif %} +link: https://core.telegram.org/bots/api#{{ group.anchor }} +""" +{% for entity in group.childs %}{% if entity.is_type %} +{% include 'type.py.jinja2' %} +{% endif %}{% endfor %} +# %% End of region '{{ group.title }}' diff --git a/setup.py b/setup.py index 0dde5602..1db97490 100755 --- a/setup.py +++ b/setup.py @@ -63,7 +63,7 @@ def get_requirements(filename=None): setup( name="aiogram", version=get_version(), - packages=find_packages(exclude=("tests", "tests.*", "examples.*", "docs")), + packages=find_packages(exclude=("tests", "tests.*", "examples.*", "docs", "generator")), url="https://github.com/aiogram/aiogram", license="MIT", author="Alex Root Junior",