init commit
Some checks failed
continuous-integration/drone Build is failing

This commit is contained in:
2025-09-04 01:51:59 +09:00
commit aca280b64d
1841 changed files with 753304 additions and 0 deletions

View File

@@ -0,0 +1,619 @@
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2025
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser Public License for more details.
#
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""A library that provides a Python interface to the Telegram Bot API"""
__author__ = "devs@python-telegram-bot.org"
__all__ = (
"AcceptedGiftTypes",
"AffiliateInfo",
"Animation",
"Audio",
"BackgroundFill",
"BackgroundFillFreeformGradient",
"BackgroundFillGradient",
"BackgroundFillSolid",
"BackgroundType",
"BackgroundTypeChatTheme",
"BackgroundTypeFill",
"BackgroundTypePattern",
"BackgroundTypeWallpaper",
"Birthdate",
"Bot",
"BotCommand",
"BotCommandScope",
"BotCommandScopeAllChatAdministrators",
"BotCommandScopeAllGroupChats",
"BotCommandScopeAllPrivateChats",
"BotCommandScopeChat",
"BotCommandScopeChatAdministrators",
"BotCommandScopeChatMember",
"BotCommandScopeDefault",
"BotDescription",
"BotName",
"BotShortDescription",
"BusinessBotRights",
"BusinessConnection",
"BusinessIntro",
"BusinessLocation",
"BusinessMessagesDeleted",
"BusinessOpeningHours",
"BusinessOpeningHoursInterval",
"CallbackGame",
"CallbackQuery",
"Chat",
"ChatAdministratorRights",
"ChatBackground",
"ChatBoost",
"ChatBoostAdded",
"ChatBoostRemoved",
"ChatBoostSource",
"ChatBoostSourceGiftCode",
"ChatBoostSourceGiveaway",
"ChatBoostSourcePremium",
"ChatBoostUpdated",
"ChatFullInfo",
"ChatInviteLink",
"ChatJoinRequest",
"ChatLocation",
"ChatMember",
"ChatMemberAdministrator",
"ChatMemberBanned",
"ChatMemberLeft",
"ChatMemberMember",
"ChatMemberOwner",
"ChatMemberRestricted",
"ChatMemberUpdated",
"ChatPermissions",
"ChatPhoto",
"ChatShared",
"Checklist",
"ChecklistTask",
"ChecklistTasksAdded",
"ChecklistTasksDone",
"ChosenInlineResult",
"Contact",
"CopyTextButton",
"Credentials",
"DataCredentials",
"Dice",
"DirectMessagePriceChanged",
"Document",
"EncryptedCredentials",
"EncryptedPassportElement",
"ExternalReplyInfo",
"File",
"FileCredentials",
"ForceReply",
"ForumTopic",
"ForumTopicClosed",
"ForumTopicCreated",
"ForumTopicEdited",
"ForumTopicReopened",
"Game",
"GameHighScore",
"GeneralForumTopicHidden",
"GeneralForumTopicUnhidden",
"Gift",
"GiftInfo",
"Gifts",
"Giveaway",
"GiveawayCompleted",
"GiveawayCreated",
"GiveawayWinners",
"IdDocumentData",
"InaccessibleMessage",
"InlineKeyboardButton",
"InlineKeyboardMarkup",
"InlineQuery",
"InlineQueryResult",
"InlineQueryResultArticle",
"InlineQueryResultAudio",
"InlineQueryResultCachedAudio",
"InlineQueryResultCachedDocument",
"InlineQueryResultCachedGif",
"InlineQueryResultCachedMpeg4Gif",
"InlineQueryResultCachedPhoto",
"InlineQueryResultCachedSticker",
"InlineQueryResultCachedVideo",
"InlineQueryResultCachedVoice",
"InlineQueryResultContact",
"InlineQueryResultDocument",
"InlineQueryResultGame",
"InlineQueryResultGif",
"InlineQueryResultLocation",
"InlineQueryResultMpeg4Gif",
"InlineQueryResultPhoto",
"InlineQueryResultVenue",
"InlineQueryResultVideo",
"InlineQueryResultVoice",
"InlineQueryResultsButton",
"InputChecklist",
"InputChecklistTask",
"InputContactMessageContent",
"InputFile",
"InputInvoiceMessageContent",
"InputLocationMessageContent",
"InputMedia",
"InputMediaAnimation",
"InputMediaAudio",
"InputMediaDocument",
"InputMediaPhoto",
"InputMediaVideo",
"InputMessageContent",
"InputPaidMedia",
"InputPaidMediaPhoto",
"InputPaidMediaVideo",
"InputPollOption",
"InputProfilePhoto",
"InputProfilePhotoAnimated",
"InputProfilePhotoStatic",
"InputSticker",
"InputStoryContent",
"InputStoryContentPhoto",
"InputStoryContentVideo",
"InputTextMessageContent",
"InputVenueMessageContent",
"Invoice",
"KeyboardButton",
"KeyboardButtonPollType",
"KeyboardButtonRequestChat",
"KeyboardButtonRequestUsers",
"LabeledPrice",
"LinkPreviewOptions",
"Location",
"LocationAddress",
"LoginUrl",
"MaskPosition",
"MaybeInaccessibleMessage",
"MenuButton",
"MenuButtonCommands",
"MenuButtonDefault",
"MenuButtonWebApp",
"Message",
"MessageAutoDeleteTimerChanged",
"MessageEntity",
"MessageId",
"MessageOrigin",
"MessageOriginChannel",
"MessageOriginChat",
"MessageOriginHiddenUser",
"MessageOriginUser",
"MessageReactionCountUpdated",
"MessageReactionUpdated",
"OrderInfo",
"OwnedGift",
"OwnedGiftRegular",
"OwnedGiftUnique",
"OwnedGifts",
"PaidMedia",
"PaidMediaInfo",
"PaidMediaPhoto",
"PaidMediaPreview",
"PaidMediaPurchased",
"PaidMediaVideo",
"PaidMessagePriceChanged",
"PassportData",
"PassportElementError",
"PassportElementErrorDataField",
"PassportElementErrorFile",
"PassportElementErrorFiles",
"PassportElementErrorFrontSide",
"PassportElementErrorReverseSide",
"PassportElementErrorSelfie",
"PassportElementErrorTranslationFile",
"PassportElementErrorTranslationFiles",
"PassportElementErrorUnspecified",
"PassportFile",
"PersonalDetails",
"PhotoSize",
"Poll",
"PollAnswer",
"PollOption",
"PreCheckoutQuery",
"PreparedInlineMessage",
"ProximityAlertTriggered",
"ReactionCount",
"ReactionType",
"ReactionTypeCustomEmoji",
"ReactionTypeEmoji",
"ReactionTypePaid",
"RefundedPayment",
"ReplyKeyboardMarkup",
"ReplyKeyboardRemove",
"ReplyParameters",
"ResidentialAddress",
"RevenueWithdrawalState",
"RevenueWithdrawalStateFailed",
"RevenueWithdrawalStatePending",
"RevenueWithdrawalStateSucceeded",
"SecureData",
"SecureValue",
"SentWebAppMessage",
"SharedUser",
"ShippingAddress",
"ShippingOption",
"ShippingQuery",
"StarAmount",
"StarTransaction",
"StarTransactions",
"Sticker",
"StickerSet",
"Story",
"StoryArea",
"StoryAreaPosition",
"StoryAreaType",
"StoryAreaTypeLink",
"StoryAreaTypeLocation",
"StoryAreaTypeSuggestedReaction",
"StoryAreaTypeUniqueGift",
"StoryAreaTypeWeather",
"SuccessfulPayment",
"SwitchInlineQueryChosenChat",
"TelegramObject",
"TextQuote",
"TransactionPartner",
"TransactionPartnerAffiliateProgram",
"TransactionPartnerChat",
"TransactionPartnerFragment",
"TransactionPartnerOther",
"TransactionPartnerTelegramAds",
"TransactionPartnerTelegramApi",
"TransactionPartnerUser",
"UniqueGift",
"UniqueGiftBackdrop",
"UniqueGiftBackdropColors",
"UniqueGiftInfo",
"UniqueGiftModel",
"UniqueGiftSymbol",
"Update",
"User",
"UserChatBoosts",
"UserProfilePhotos",
"UsersShared",
"Venue",
"Video",
"VideoChatEnded",
"VideoChatParticipantsInvited",
"VideoChatScheduled",
"VideoChatStarted",
"VideoNote",
"Voice",
"WebAppData",
"WebAppInfo",
"WebhookInfo",
"WriteAccessAllowed",
"__bot_api_version__",
"__bot_api_version_info__",
"__version__",
"__version_info__",
"constants",
"error",
"helpers",
"request",
"warnings",
)
from telegram._inputchecklist import InputChecklist, InputChecklistTask
from telegram._payment.stars.staramount import StarAmount
from telegram._payment.stars.startransactions import StarTransaction, StarTransactions
from telegram._payment.stars.transactionpartner import (
TransactionPartner,
TransactionPartnerAffiliateProgram,
TransactionPartnerChat,
TransactionPartnerFragment,
TransactionPartnerOther,
TransactionPartnerTelegramAds,
TransactionPartnerTelegramApi,
TransactionPartnerUser,
)
from . import _version, constants, error, helpers, request, warnings
from ._birthdate import Birthdate
from ._bot import Bot
from ._botcommand import BotCommand
from ._botcommandscope import (
BotCommandScope,
BotCommandScopeAllChatAdministrators,
BotCommandScopeAllGroupChats,
BotCommandScopeAllPrivateChats,
BotCommandScopeChat,
BotCommandScopeChatAdministrators,
BotCommandScopeChatMember,
BotCommandScopeDefault,
)
from ._botdescription import BotDescription, BotShortDescription
from ._botname import BotName
from ._business import (
BusinessBotRights,
BusinessConnection,
BusinessIntro,
BusinessLocation,
BusinessMessagesDeleted,
BusinessOpeningHours,
BusinessOpeningHoursInterval,
)
from ._callbackquery import CallbackQuery
from ._chat import Chat
from ._chatadministratorrights import ChatAdministratorRights
from ._chatbackground import (
BackgroundFill,
BackgroundFillFreeformGradient,
BackgroundFillGradient,
BackgroundFillSolid,
BackgroundType,
BackgroundTypeChatTheme,
BackgroundTypeFill,
BackgroundTypePattern,
BackgroundTypeWallpaper,
ChatBackground,
)
from ._chatboost import (
ChatBoost,
ChatBoostAdded,
ChatBoostRemoved,
ChatBoostSource,
ChatBoostSourceGiftCode,
ChatBoostSourceGiveaway,
ChatBoostSourcePremium,
ChatBoostUpdated,
UserChatBoosts,
)
from ._chatfullinfo import ChatFullInfo
from ._chatinvitelink import ChatInviteLink
from ._chatjoinrequest import ChatJoinRequest
from ._chatlocation import ChatLocation
from ._chatmember import (
ChatMember,
ChatMemberAdministrator,
ChatMemberBanned,
ChatMemberLeft,
ChatMemberMember,
ChatMemberOwner,
ChatMemberRestricted,
)
from ._chatmemberupdated import ChatMemberUpdated
from ._chatpermissions import ChatPermissions
from ._checklists import Checklist, ChecklistTask, ChecklistTasksAdded, ChecklistTasksDone
from ._choseninlineresult import ChosenInlineResult
from ._copytextbutton import CopyTextButton
from ._dice import Dice
from ._directmessagepricechanged import DirectMessagePriceChanged
from ._files._inputstorycontent import (
InputStoryContent,
InputStoryContentPhoto,
InputStoryContentVideo,
)
from ._files.animation import Animation
from ._files.audio import Audio
from ._files.chatphoto import ChatPhoto
from ._files.contact import Contact
from ._files.document import Document
from ._files.file import File
from ._files.inputfile import InputFile
from ._files.inputmedia import (
InputMedia,
InputMediaAnimation,
InputMediaAudio,
InputMediaDocument,
InputMediaPhoto,
InputMediaVideo,
InputPaidMedia,
InputPaidMediaPhoto,
InputPaidMediaVideo,
)
from ._files.inputprofilephoto import (
InputProfilePhoto,
InputProfilePhotoAnimated,
InputProfilePhotoStatic,
)
from ._files.inputsticker import InputSticker
from ._files.location import Location
from ._files.photosize import PhotoSize
from ._files.sticker import MaskPosition, Sticker, StickerSet
from ._files.venue import Venue
from ._files.video import Video
from ._files.videonote import VideoNote
from ._files.voice import Voice
from ._forcereply import ForceReply
from ._forumtopic import (
ForumTopic,
ForumTopicClosed,
ForumTopicCreated,
ForumTopicEdited,
ForumTopicReopened,
GeneralForumTopicHidden,
GeneralForumTopicUnhidden,
)
from ._games.callbackgame import CallbackGame
from ._games.game import Game
from ._games.gamehighscore import GameHighScore
from ._gifts import AcceptedGiftTypes, Gift, GiftInfo, Gifts
from ._giveaway import Giveaway, GiveawayCompleted, GiveawayCreated, GiveawayWinners
from ._inline.inlinekeyboardbutton import InlineKeyboardButton
from ._inline.inlinekeyboardmarkup import InlineKeyboardMarkup
from ._inline.inlinequery import InlineQuery
from ._inline.inlinequeryresult import InlineQueryResult
from ._inline.inlinequeryresultarticle import InlineQueryResultArticle
from ._inline.inlinequeryresultaudio import InlineQueryResultAudio
from ._inline.inlinequeryresultcachedaudio import InlineQueryResultCachedAudio
from ._inline.inlinequeryresultcacheddocument import InlineQueryResultCachedDocument
from ._inline.inlinequeryresultcachedgif import InlineQueryResultCachedGif
from ._inline.inlinequeryresultcachedmpeg4gif import InlineQueryResultCachedMpeg4Gif
from ._inline.inlinequeryresultcachedphoto import InlineQueryResultCachedPhoto
from ._inline.inlinequeryresultcachedsticker import InlineQueryResultCachedSticker
from ._inline.inlinequeryresultcachedvideo import InlineQueryResultCachedVideo
from ._inline.inlinequeryresultcachedvoice import InlineQueryResultCachedVoice
from ._inline.inlinequeryresultcontact import InlineQueryResultContact
from ._inline.inlinequeryresultdocument import InlineQueryResultDocument
from ._inline.inlinequeryresultgame import InlineQueryResultGame
from ._inline.inlinequeryresultgif import InlineQueryResultGif
from ._inline.inlinequeryresultlocation import InlineQueryResultLocation
from ._inline.inlinequeryresultmpeg4gif import InlineQueryResultMpeg4Gif
from ._inline.inlinequeryresultphoto import InlineQueryResultPhoto
from ._inline.inlinequeryresultsbutton import InlineQueryResultsButton
from ._inline.inlinequeryresultvenue import InlineQueryResultVenue
from ._inline.inlinequeryresultvideo import InlineQueryResultVideo
from ._inline.inlinequeryresultvoice import InlineQueryResultVoice
from ._inline.inputcontactmessagecontent import InputContactMessageContent
from ._inline.inputinvoicemessagecontent import InputInvoiceMessageContent
from ._inline.inputlocationmessagecontent import InputLocationMessageContent
from ._inline.inputmessagecontent import InputMessageContent
from ._inline.inputtextmessagecontent import InputTextMessageContent
from ._inline.inputvenuemessagecontent import InputVenueMessageContent
from ._inline.preparedinlinemessage import PreparedInlineMessage
from ._keyboardbutton import KeyboardButton
from ._keyboardbuttonpolltype import KeyboardButtonPollType
from ._keyboardbuttonrequest import KeyboardButtonRequestChat, KeyboardButtonRequestUsers
from ._linkpreviewoptions import LinkPreviewOptions
from ._loginurl import LoginUrl
from ._menubutton import MenuButton, MenuButtonCommands, MenuButtonDefault, MenuButtonWebApp
from ._message import InaccessibleMessage, MaybeInaccessibleMessage, Message
from ._messageautodeletetimerchanged import MessageAutoDeleteTimerChanged
from ._messageentity import MessageEntity
from ._messageid import MessageId
from ._messageorigin import (
MessageOrigin,
MessageOriginChannel,
MessageOriginChat,
MessageOriginHiddenUser,
MessageOriginUser,
)
from ._messagereactionupdated import MessageReactionCountUpdated, MessageReactionUpdated
from ._ownedgift import OwnedGift, OwnedGiftRegular, OwnedGifts, OwnedGiftUnique
from ._paidmedia import (
PaidMedia,
PaidMediaInfo,
PaidMediaPhoto,
PaidMediaPreview,
PaidMediaPurchased,
PaidMediaVideo,
)
from ._paidmessagepricechanged import PaidMessagePriceChanged
from ._passport.credentials import (
Credentials,
DataCredentials,
EncryptedCredentials,
FileCredentials,
SecureData,
SecureValue,
)
from ._passport.data import IdDocumentData, PersonalDetails, ResidentialAddress
from ._passport.encryptedpassportelement import EncryptedPassportElement
from ._passport.passportdata import PassportData
from ._passport.passportelementerrors import (
PassportElementError,
PassportElementErrorDataField,
PassportElementErrorFile,
PassportElementErrorFiles,
PassportElementErrorFrontSide,
PassportElementErrorReverseSide,
PassportElementErrorSelfie,
PassportElementErrorTranslationFile,
PassportElementErrorTranslationFiles,
PassportElementErrorUnspecified,
)
from ._passport.passportfile import PassportFile
from ._payment.invoice import Invoice
from ._payment.labeledprice import LabeledPrice
from ._payment.orderinfo import OrderInfo
from ._payment.precheckoutquery import PreCheckoutQuery
from ._payment.refundedpayment import RefundedPayment
from ._payment.shippingaddress import ShippingAddress
from ._payment.shippingoption import ShippingOption
from ._payment.shippingquery import ShippingQuery
from ._payment.stars.affiliateinfo import AffiliateInfo
from ._payment.stars.revenuewithdrawalstate import (
RevenueWithdrawalState,
RevenueWithdrawalStateFailed,
RevenueWithdrawalStatePending,
RevenueWithdrawalStateSucceeded,
)
from ._payment.successfulpayment import SuccessfulPayment
from ._poll import InputPollOption, Poll, PollAnswer, PollOption
from ._proximityalerttriggered import ProximityAlertTriggered
from ._reaction import (
ReactionCount,
ReactionType,
ReactionTypeCustomEmoji,
ReactionTypeEmoji,
ReactionTypePaid,
)
from ._reply import ExternalReplyInfo, ReplyParameters, TextQuote
from ._replykeyboardmarkup import ReplyKeyboardMarkup
from ._replykeyboardremove import ReplyKeyboardRemove
from ._sentwebappmessage import SentWebAppMessage
from ._shared import ChatShared, SharedUser, UsersShared
from ._story import Story
from ._storyarea import (
LocationAddress,
StoryArea,
StoryAreaPosition,
StoryAreaType,
StoryAreaTypeLink,
StoryAreaTypeLocation,
StoryAreaTypeSuggestedReaction,
StoryAreaTypeUniqueGift,
StoryAreaTypeWeather,
)
from ._switchinlinequerychosenchat import SwitchInlineQueryChosenChat
from ._telegramobject import TelegramObject
from ._uniquegift import (
UniqueGift,
UniqueGiftBackdrop,
UniqueGiftBackdropColors,
UniqueGiftInfo,
UniqueGiftModel,
UniqueGiftSymbol,
)
from ._update import Update
from ._user import User
from ._userprofilephotos import UserProfilePhotos
from ._videochat import (
VideoChatEnded,
VideoChatParticipantsInvited,
VideoChatScheduled,
VideoChatStarted,
)
from ._webappdata import WebAppData
from ._webappinfo import WebAppInfo
from ._webhookinfo import WebhookInfo
from ._writeaccessallowed import WriteAccessAllowed
#: :obj:`str`: The version of the `python-telegram-bot` library as string.
#: To get detailed information about the version number, please use :data:`__version_info__`
#: instead.
__version__: str = _version.__version__
#: :class:`typing.NamedTuple`: A tuple containing the five components of the version number:
#: `major`, `minor`, `micro`, `releaselevel`, and `serial`.
#: All values except `releaselevel` are integers.
#: The release level is ``'alpha'``, ``'beta'``, ``'candidate'``, or ``'final'``.
#: The components can also be accessed by name, so ``__version_info__[0]`` is equivalent to
#: ``__version_info__.major`` and so on.
#:
#: .. versionadded:: 20.0
__version_info__: _version.Version = _version.__version_info__
#: :obj:`str`: Shortcut for :const:`telegram.constants.BOT_API_VERSION`.
#:
#: .. versionchanged:: 20.0
#: This constant was previously named ``bot_api_version``.
__bot_api_version__: str = constants.BOT_API_VERSION
#: :class:`typing.NamedTuple`: Shortcut for :const:`telegram.constants.BOT_API_VERSION_INFO`.
#:
#: .. versionadded:: 20.0
__bot_api_version_info__: constants._BotAPIVersion = constants.BOT_API_VERSION_INFO

View File

@@ -0,0 +1,54 @@
# !/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2025
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser Public License for more details.
#
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
# pylint: disable=missing-module-docstring
# ruff: noqa: T201, D100, S607
import subprocess
import sys
from typing import Optional
from . import __version__ as telegram_ver
from .constants import BOT_API_VERSION
def _git_revision() -> Optional[str]:
try:
output = subprocess.check_output(
["git", "describe", "--long", "--tags"], stderr=subprocess.STDOUT
)
except (subprocess.SubprocessError, OSError):
return None
return output.decode().strip()
def print_ver_info() -> None:
"""Prints version information for python-telegram-bot, the Bot API and Python."""
git_revision = _git_revision()
print(f"python-telegram-bot {telegram_ver}" + (f" ({git_revision})" if git_revision else ""))
print(f"Bot API {BOT_API_VERSION}")
sys_version = sys.version.replace("\n", " ")
print(f"Python {sys_version}")
def main() -> None:
"""Prints version information for python-telegram-bot, the Bot API and Python."""
print_ver_info()
if __name__ == "__main__":
main()

View File

@@ -0,0 +1,92 @@
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2025
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser Public License for more details.
#
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents a Telegram Birthday."""
import datetime as dtm
from typing import Optional
from telegram._telegramobject import TelegramObject
from telegram._utils.types import JSONDict
class Birthdate(TelegramObject):
"""
This object describes the birthdate of a user.
Objects of this class are comparable in terms of equality. Two objects of this class are
considered equal, if their :attr:`day`, and :attr:`month` are equal.
.. versionadded:: 21.1
Args:
day (:obj:`int`): Day of the user's birth; 1-31.
month (:obj:`int`): Month of the user's birth; 1-12.
year (:obj:`int`, optional): Year of the user's birth.
Attributes:
day (:obj:`int`): Day of the user's birth; 1-31.
month (:obj:`int`): Month of the user's birth; 1-12.
year (:obj:`int`): Optional. Year of the user's birth.
"""
__slots__ = ("day", "month", "year")
def __init__(
self,
day: int,
month: int,
year: Optional[int] = None,
*,
api_kwargs: Optional[JSONDict] = None,
):
super().__init__(api_kwargs=api_kwargs)
# Required
self.day: int = day
self.month: int = month
# Optional
self.year: Optional[int] = year
self._id_attrs = (
self.day,
self.month,
)
self._freeze()
def to_date(self, year: Optional[int] = None) -> dtm.date:
"""Return the birthdate as a date object.
.. versionchanged:: 21.2
Now returns a :obj:`datetime.date` object instead of a :obj:`datetime.datetime` object,
as was originally intended.
Args:
year (:obj:`int`, optional): The year to use. Required, if the :attr:`year` was not
present.
Returns:
:obj:`datetime.date`: The birthdate as a date object.
"""
if self.year is None and year is None:
raise ValueError(
"The `year` argument is required if the `year` attribute was not present."
)
return dtm.date(year or self.year, self.month, self.day) # type: ignore[arg-type]

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,83 @@
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2025
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser Public License for more details.
#
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents a Telegram Bot Command."""
from typing import Final, Optional
from telegram import constants
from telegram._telegramobject import TelegramObject
from telegram._utils.types import JSONDict
class BotCommand(TelegramObject):
"""
This object represents a bot command.
Objects of this class are comparable in terms of equality. Two objects of this class are
considered equal, if their :attr:`command` and :attr:`description` are equal.
Args:
command (:obj:`str`): Text of the command; :tg-const:`telegram.BotCommand.MIN_COMMAND`-
:tg-const:`telegram.BotCommand.MAX_COMMAND` characters. Can contain only lowercase
English letters, digits and underscores.
description (:obj:`str`): Description of the command;
:tg-const:`telegram.BotCommand.MIN_DESCRIPTION`-
:tg-const:`telegram.BotCommand.MAX_DESCRIPTION` characters.
Attributes:
command (:obj:`str`): Text of the command; :tg-const:`telegram.BotCommand.MIN_COMMAND`-
:tg-const:`telegram.BotCommand.MAX_COMMAND` characters. Can contain only lowercase
English letters, digits and underscores.
description (:obj:`str`): Description of the command;
:tg-const:`telegram.BotCommand.MIN_DESCRIPTION`-
:tg-const:`telegram.BotCommand.MAX_DESCRIPTION` characters.
"""
__slots__ = ("command", "description")
def __init__(self, command: str, description: str, *, api_kwargs: Optional[JSONDict] = None):
super().__init__(api_kwargs=api_kwargs)
self.command: str = command
self.description: str = description
self._id_attrs = (self.command, self.description)
self._freeze()
MIN_COMMAND: Final[int] = constants.BotCommandLimit.MIN_COMMAND
""":const:`telegram.constants.BotCommandLimit.MIN_COMMAND`
.. versionadded:: 20.0
"""
MAX_COMMAND: Final[int] = constants.BotCommandLimit.MAX_COMMAND
""":const:`telegram.constants.BotCommandLimit.MAX_COMMAND`
.. versionadded:: 20.0
"""
MIN_DESCRIPTION: Final[int] = constants.BotCommandLimit.MIN_DESCRIPTION
""":const:`telegram.constants.BotCommandLimit.MIN_DESCRIPTION`
.. versionadded:: 20.0
"""
MAX_DESCRIPTION: Final[int] = constants.BotCommandLimit.MAX_DESCRIPTION
""":const:`telegram.constants.BotCommandLimit.MAX_DESCRIPTION`
.. versionadded:: 20.0
"""

View File

@@ -0,0 +1,268 @@
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2025
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser Public License for more details.
#
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
# pylint: disable=redefined-builtin
"""This module contains objects representing Telegram bot command scopes."""
from typing import TYPE_CHECKING, Final, Optional, Union
from telegram import constants
from telegram._telegramobject import TelegramObject
from telegram._utils import enum
from telegram._utils.types import JSONDict
if TYPE_CHECKING:
from telegram import Bot
class BotCommandScope(TelegramObject):
"""Base class for objects that represent the scope to which bot commands are applied.
Currently, the following 7 scopes are supported:
* :class:`telegram.BotCommandScopeDefault`
* :class:`telegram.BotCommandScopeAllPrivateChats`
* :class:`telegram.BotCommandScopeAllGroupChats`
* :class:`telegram.BotCommandScopeAllChatAdministrators`
* :class:`telegram.BotCommandScopeChat`
* :class:`telegram.BotCommandScopeChatAdministrators`
* :class:`telegram.BotCommandScopeChatMember`
Objects of this class are comparable in terms of equality. Two objects of this class are
considered equal, if their :attr:`type` is equal. For subclasses with additional attributes,
the notion of equality is overridden.
Note:
Please see the `official docs`_ on how Telegram determines which commands to display.
.. _`official docs`: https://core.telegram.org/bots/api#determining-list-of-commands
.. versionadded:: 13.7
Args:
type (:obj:`str`): Scope type.
Attributes:
type (:obj:`str`): Scope type.
"""
__slots__ = ("type",)
DEFAULT: Final[str] = constants.BotCommandScopeType.DEFAULT
""":const:`telegram.constants.BotCommandScopeType.DEFAULT`"""
ALL_PRIVATE_CHATS: Final[str] = constants.BotCommandScopeType.ALL_PRIVATE_CHATS
""":const:`telegram.constants.BotCommandScopeType.ALL_PRIVATE_CHATS`"""
ALL_GROUP_CHATS: Final[str] = constants.BotCommandScopeType.ALL_GROUP_CHATS
""":const:`telegram.constants.BotCommandScopeType.ALL_GROUP_CHATS`"""
ALL_CHAT_ADMINISTRATORS: Final[str] = constants.BotCommandScopeType.ALL_CHAT_ADMINISTRATORS
""":const:`telegram.constants.BotCommandScopeType.ALL_CHAT_ADMINISTRATORS`"""
CHAT: Final[str] = constants.BotCommandScopeType.CHAT
""":const:`telegram.constants.BotCommandScopeType.CHAT`"""
CHAT_ADMINISTRATORS: Final[str] = constants.BotCommandScopeType.CHAT_ADMINISTRATORS
""":const:`telegram.constants.BotCommandScopeType.CHAT_ADMINISTRATORS`"""
CHAT_MEMBER: Final[str] = constants.BotCommandScopeType.CHAT_MEMBER
""":const:`telegram.constants.BotCommandScopeType.CHAT_MEMBER`"""
def __init__(self, type: str, *, api_kwargs: Optional[JSONDict] = None):
super().__init__(api_kwargs=api_kwargs)
self.type: str = enum.get_member(constants.BotCommandScopeType, type, type)
self._id_attrs = (self.type,)
self._freeze()
@classmethod
def de_json(cls, data: JSONDict, bot: Optional["Bot"] = None) -> "BotCommandScope":
"""Converts JSON data to the appropriate :class:`BotCommandScope` object, i.e. takes
care of selecting the correct subclass.
Args:
data (dict[:obj:`str`, ...]): The JSON data.
bot (:class:`telegram.Bot`, optional): The bot associated with this object. Defaults to
:obj:`None`, in which case shortcut methods will not be available.
.. versionchanged:: 21.4
:paramref:`bot` is now optional and defaults to :obj:`None`
Returns:
The Telegram object.
"""
data = cls._parse_data(data)
_class_mapping: dict[str, type[BotCommandScope]] = {
cls.DEFAULT: BotCommandScopeDefault,
cls.ALL_PRIVATE_CHATS: BotCommandScopeAllPrivateChats,
cls.ALL_GROUP_CHATS: BotCommandScopeAllGroupChats,
cls.ALL_CHAT_ADMINISTRATORS: BotCommandScopeAllChatAdministrators,
cls.CHAT: BotCommandScopeChat,
cls.CHAT_ADMINISTRATORS: BotCommandScopeChatAdministrators,
cls.CHAT_MEMBER: BotCommandScopeChatMember,
}
if cls is BotCommandScope and data.get("type") in _class_mapping:
return _class_mapping[data.pop("type")].de_json(data=data, bot=bot)
return super().de_json(data=data, bot=bot)
class BotCommandScopeDefault(BotCommandScope):
"""Represents the default scope of bot commands. Default commands are used if no commands with
a `narrower scope`_ are specified for the user.
.. _`narrower scope`: https://core.telegram.org/bots/api#determining-list-of-commands
.. versionadded:: 13.7
Attributes:
type (:obj:`str`): Scope type :tg-const:`telegram.BotCommandScope.DEFAULT`.
"""
__slots__ = ()
def __init__(self, *, api_kwargs: Optional[JSONDict] = None):
super().__init__(type=BotCommandScope.DEFAULT, api_kwargs=api_kwargs)
self._freeze()
class BotCommandScopeAllPrivateChats(BotCommandScope):
"""Represents the scope of bot commands, covering all private chats.
.. versionadded:: 13.7
Attributes:
type (:obj:`str`): Scope type :tg-const:`telegram.BotCommandScope.ALL_PRIVATE_CHATS`.
"""
__slots__ = ()
def __init__(self, *, api_kwargs: Optional[JSONDict] = None):
super().__init__(type=BotCommandScope.ALL_PRIVATE_CHATS, api_kwargs=api_kwargs)
self._freeze()
class BotCommandScopeAllGroupChats(BotCommandScope):
"""Represents the scope of bot commands, covering all group and supergroup chats.
.. versionadded:: 13.7
Attributes:
type (:obj:`str`): Scope type :tg-const:`telegram.BotCommandScope.ALL_GROUP_CHATS`.
"""
__slots__ = ()
def __init__(self, *, api_kwargs: Optional[JSONDict] = None):
super().__init__(type=BotCommandScope.ALL_GROUP_CHATS, api_kwargs=api_kwargs)
self._freeze()
class BotCommandScopeAllChatAdministrators(BotCommandScope):
"""Represents the scope of bot commands, covering all group and supergroup chat administrators.
.. versionadded:: 13.7
Attributes:
type (:obj:`str`): Scope type :tg-const:`telegram.BotCommandScope.ALL_CHAT_ADMINISTRATORS`.
"""
__slots__ = ()
def __init__(self, *, api_kwargs: Optional[JSONDict] = None):
super().__init__(type=BotCommandScope.ALL_CHAT_ADMINISTRATORS, api_kwargs=api_kwargs)
self._freeze()
class BotCommandScopeChat(BotCommandScope):
"""Represents the scope of bot commands, covering a specific chat.
Objects of this class are comparable in terms of equality. Two objects of this class are
considered equal, if their :attr:`type` and :attr:`chat_id` are equal.
.. versionadded:: 13.7
Args:
chat_id (:obj:`str` | :obj:`int`): |chat_id_group|
Attributes:
type (:obj:`str`): Scope type :tg-const:`telegram.BotCommandScope.CHAT`.
chat_id (:obj:`str` | :obj:`int`): |chat_id_group|
"""
__slots__ = ("chat_id",)
def __init__(self, chat_id: Union[str, int], *, api_kwargs: Optional[JSONDict] = None):
super().__init__(type=BotCommandScope.CHAT, api_kwargs=api_kwargs)
with self._unfrozen():
self.chat_id: Union[str, int] = (
chat_id if isinstance(chat_id, str) and chat_id.startswith("@") else int(chat_id)
)
self._id_attrs = (self.type, self.chat_id)
class BotCommandScopeChatAdministrators(BotCommandScope):
"""Represents the scope of bot commands, covering all administrators of a specific group or
supergroup chat.
Objects of this class are comparable in terms of equality. Two objects of this class are
considered equal, if their :attr:`type` and :attr:`chat_id` are equal.
.. versionadded:: 13.7
Args:
chat_id (:obj:`str` | :obj:`int`): |chat_id_group|
Attributes:
type (:obj:`str`): Scope type :tg-const:`telegram.BotCommandScope.CHAT_ADMINISTRATORS`.
chat_id (:obj:`str` | :obj:`int`): |chat_id_group|
"""
__slots__ = ("chat_id",)
def __init__(self, chat_id: Union[str, int], *, api_kwargs: Optional[JSONDict] = None):
super().__init__(type=BotCommandScope.CHAT_ADMINISTRATORS, api_kwargs=api_kwargs)
with self._unfrozen():
self.chat_id: Union[str, int] = (
chat_id if isinstance(chat_id, str) and chat_id.startswith("@") else int(chat_id)
)
self._id_attrs = (self.type, self.chat_id)
class BotCommandScopeChatMember(BotCommandScope):
"""Represents the scope of bot commands, covering a specific member of a group or supergroup
chat.
Objects of this class are comparable in terms of equality. Two objects of this class are
considered equal, if their :attr:`type`, :attr:`chat_id` and :attr:`user_id` are equal.
.. versionadded:: 13.7
Args:
chat_id (:obj:`str` | :obj:`int`): |chat_id_group|
user_id (:obj:`int`): Unique identifier of the target user.
Attributes:
type (:obj:`str`): Scope type :tg-const:`telegram.BotCommandScope.CHAT_MEMBER`.
chat_id (:obj:`str` | :obj:`int`): |chat_id_group|
user_id (:obj:`int`): Unique identifier of the target user.
"""
__slots__ = ("chat_id", "user_id")
def __init__(
self, chat_id: Union[str, int], user_id: int, *, api_kwargs: Optional[JSONDict] = None
):
super().__init__(type=BotCommandScope.CHAT_MEMBER, api_kwargs=api_kwargs)
with self._unfrozen():
self.chat_id: Union[str, int] = (
chat_id if isinstance(chat_id, str) and chat_id.startswith("@") else int(chat_id)
)
self.user_id: int = user_id
self._id_attrs = (self.type, self.chat_id, self.user_id)

View File

@@ -0,0 +1,77 @@
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2025
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser Public License for more details.
#
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains two objects that represent a Telegram bots (short) description."""
from typing import Optional
from telegram._telegramobject import TelegramObject
from telegram._utils.types import JSONDict
class BotDescription(TelegramObject):
"""This object represents the bot's description.
Objects of this class are comparable in terms of equality. Two objects of this class are
considered equal, if their :attr:`description` is equal.
.. versionadded:: 20.2
Args:
description (:obj:`str`): The bot's description.
Attributes:
description (:obj:`str`): The bot's description.
"""
__slots__ = ("description",)
def __init__(self, description: str, *, api_kwargs: Optional[JSONDict] = None):
super().__init__(api_kwargs=api_kwargs)
self.description: str = description
self._id_attrs = (self.description,)
self._freeze()
class BotShortDescription(TelegramObject):
"""This object represents the bot's short description.
Objects of this class are comparable in terms of equality. Two objects of this class are
considered equal, if their :attr:`short_description` is equal.
.. versionadded:: 20.2
Args:
short_description (:obj:`str`): The bot's short description.
Attributes:
short_description (:obj:`str`): The bot's short description.
"""
__slots__ = ("short_description",)
def __init__(self, short_description: str, *, api_kwargs: Optional[JSONDict] = None):
super().__init__(api_kwargs=api_kwargs)
self.short_description: str = short_description
self._id_attrs = (self.short_description,)
self._freeze()

View File

@@ -0,0 +1,54 @@
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2025
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser Public License for more details.
#
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represent a Telegram bots name."""
from typing import Final, Optional
from telegram import constants
from telegram._telegramobject import TelegramObject
from telegram._utils.types import JSONDict
class BotName(TelegramObject):
"""This object represents the bot's name.
Objects of this class are comparable in terms of equality. Two objects of this class are
considered equal, if their :attr:`name` is equal.
.. versionadded:: 20.3
Args:
name (:obj:`str`): The bot's name.
Attributes:
name (:obj:`str`): The bot's name.
"""
__slots__ = ("name",)
def __init__(self, name: str, *, api_kwargs: Optional[JSONDict] = None):
super().__init__(api_kwargs=api_kwargs)
self.name: str = name
self._id_attrs = (self.name,)
self._freeze()
MAX_LENGTH: Final[int] = constants.BotNameLimit.MAX_NAME_LENGTH
""":const:`telegram.constants.BotNameLimit.MAX_NAME_LENGTH`"""

View File

@@ -0,0 +1,582 @@
#!/usr/bin/env python
# pylint: disable=redefined-builtin
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2025
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser Public License for more details.
#
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]
"""This module contains the Telegram Business related classes."""
import datetime as dtm
from collections.abc import Sequence
from typing import TYPE_CHECKING, Optional
from telegram._chat import Chat
from telegram._files.location import Location
from telegram._files.sticker import Sticker
from telegram._telegramobject import TelegramObject
from telegram._user import User
from telegram._utils.argumentparsing import de_json_optional, de_list_optional, parse_sequence_arg
from telegram._utils.datetime import extract_tzinfo_from_defaults, from_timestamp
from telegram._utils.types import JSONDict
if TYPE_CHECKING:
from telegram import Bot
class BusinessBotRights(TelegramObject):
"""
This object represents the rights of a business bot.
Objects of this class are comparable in terms of equality.
Two objects of this class are considered equal, if all their attributes are equal.
.. versionadded:: 22.1
Args:
can_reply (:obj:`bool`, optional): True, if the bot can send and edit messages in the
private chats that had incoming messages in the last 24 hours.
can_read_messages (:obj:`bool`, optional): True, if the bot can mark incoming private
messages as read.
can_delete_sent_messages (:obj:`bool`, optional): True, if the bot can delete messages
sent by the bot.
can_delete_all_messages (:obj:`bool`, optional): True, if the bot can delete all private
messages in managed chats.
can_edit_name (:obj:`bool`, optional): True, if the bot can edit the first and last name
of the business account.
can_edit_bio (:obj:`bool`, optional): True, if the bot can edit the bio of the
business account.
can_edit_profile_photo (:obj:`bool`, optional): True, if the bot can edit the profile
photo of the business account.
can_edit_username (:obj:`bool`, optional): True, if the bot can edit the username of the
business account.
can_change_gift_settings (:obj:`bool`, optional): True, if the bot can change the privacy
settings pertaining to gifts for the business account.
can_view_gifts_and_stars (:obj:`bool`, optional): True, if the bot can view gifts and the
amount of Telegram Stars owned by the business account.
can_convert_gifts_to_stars (:obj:`bool`, optional): True, if the bot can convert regular
gifts owned by the business account to Telegram Stars.
can_transfer_and_upgrade_gifts (:obj:`bool`, optional): True, if the bot can transfer and
upgrade gifts owned by the business account.
can_transfer_stars (:obj:`bool`, optional): True, if the bot can transfer Telegram Stars
received by the business account to its own account, or use them to upgrade and
transfer gifts.
can_manage_stories (:obj:`bool`, optional): True, if the bot can post, edit and delete
stories on behalf of the business account.
Attributes:
can_reply (:obj:`bool`): Optional. True, if the bot can send and edit messages in the
private chats that had incoming messages in the last 24 hours.
can_read_messages (:obj:`bool`): Optional. True, if the bot can mark incoming private
messages as read.
can_delete_sent_messages (:obj:`bool`): Optional. True, if the bot can delete messages
sent by the bot.
can_delete_all_messages (:obj:`bool`): Optional. True, if the bot can delete all private
messages in managed chats.
can_edit_name (:obj:`bool`): Optional. True, if the bot can edit the first and last name
of the business account.
can_edit_bio (:obj:`bool`): Optional. True, if the bot can edit the bio of the
business account.
can_edit_profile_photo (:obj:`bool`): Optional. True, if the bot can edit the profile
photo of the business account.
can_edit_username (:obj:`bool`): Optional. True, if the bot can edit the username of the
business account.
can_change_gift_settings (:obj:`bool`): Optional. True, if the bot can change the privacy
settings pertaining to gifts for the business account.
can_view_gifts_and_stars (:obj:`bool`): Optional. True, if the bot can view gifts and the
amount of Telegram Stars owned by the business account.
can_convert_gifts_to_stars (:obj:`bool`): Optional. True, if the bot can convert regular
gifts owned by the business account to Telegram Stars.
can_transfer_and_upgrade_gifts (:obj:`bool`): Optional. True, if the bot can transfer and
upgrade gifts owned by the business account.
can_transfer_stars (:obj:`bool`): Optional. True, if the bot can transfer Telegram Stars
received by the business account to its own account, or use them to upgrade and
transfer gifts.
can_manage_stories (:obj:`bool`): Optional. True, if the bot can post, edit and delete
stories on behalf of the business account.
"""
__slots__ = (
"can_change_gift_settings",
"can_convert_gifts_to_stars",
"can_delete_all_messages",
"can_delete_sent_messages",
"can_edit_bio",
"can_edit_name",
"can_edit_profile_photo",
"can_edit_username",
"can_manage_stories",
"can_read_messages",
"can_reply",
"can_transfer_and_upgrade_gifts",
"can_transfer_stars",
"can_view_gifts_and_stars",
)
def __init__(
self,
can_reply: Optional[bool] = None,
can_read_messages: Optional[bool] = None,
can_delete_sent_messages: Optional[bool] = None,
can_delete_all_messages: Optional[bool] = None,
can_edit_name: Optional[bool] = None,
can_edit_bio: Optional[bool] = None,
can_edit_profile_photo: Optional[bool] = None,
can_edit_username: Optional[bool] = None,
can_change_gift_settings: Optional[bool] = None,
can_view_gifts_and_stars: Optional[bool] = None,
can_convert_gifts_to_stars: Optional[bool] = None,
can_transfer_and_upgrade_gifts: Optional[bool] = None,
can_transfer_stars: Optional[bool] = None,
can_manage_stories: Optional[bool] = None,
*,
api_kwargs: Optional[JSONDict] = None,
):
super().__init__(api_kwargs=api_kwargs)
self.can_reply: Optional[bool] = can_reply
self.can_read_messages: Optional[bool] = can_read_messages
self.can_delete_sent_messages: Optional[bool] = can_delete_sent_messages
self.can_delete_all_messages: Optional[bool] = can_delete_all_messages
self.can_edit_name: Optional[bool] = can_edit_name
self.can_edit_bio: Optional[bool] = can_edit_bio
self.can_edit_profile_photo: Optional[bool] = can_edit_profile_photo
self.can_edit_username: Optional[bool] = can_edit_username
self.can_change_gift_settings: Optional[bool] = can_change_gift_settings
self.can_view_gifts_and_stars: Optional[bool] = can_view_gifts_and_stars
self.can_convert_gifts_to_stars: Optional[bool] = can_convert_gifts_to_stars
self.can_transfer_and_upgrade_gifts: Optional[bool] = can_transfer_and_upgrade_gifts
self.can_transfer_stars: Optional[bool] = can_transfer_stars
self.can_manage_stories: Optional[bool] = can_manage_stories
self._id_attrs = (
self.can_reply,
self.can_read_messages,
self.can_delete_sent_messages,
self.can_delete_all_messages,
self.can_edit_name,
self.can_edit_bio,
self.can_edit_profile_photo,
self.can_edit_username,
self.can_change_gift_settings,
self.can_view_gifts_and_stars,
self.can_convert_gifts_to_stars,
self.can_transfer_and_upgrade_gifts,
self.can_transfer_stars,
self.can_manage_stories,
)
self._freeze()
class BusinessConnection(TelegramObject):
"""
Describes the connection of the bot with a business account.
Objects of this class are comparable in terms of equality. Two objects of this class are
considered equal if their :attr:`id`, :attr:`user`, :attr:`user_chat_id`, :attr:`date`,
:attr:`rights`, and :attr:`is_enabled` are equal.
.. versionadded:: 21.1
.. versionchanged:: 22.1
Equality comparison now considers :attr:`rights` instead of ``can_reply``.
.. versionremoved:: 22.3
Removed argument and attribute ``can_reply`` deprecated by API 9.0.
Args:
id (:obj:`str`): Unique identifier of the business connection.
user (:class:`telegram.User`): Business account user that created the business connection.
user_chat_id (:obj:`int`): Identifier of a private chat with the user who created the
business connection.
date (:obj:`datetime.datetime`): Date the connection was established in Unix time.
is_enabled (:obj:`bool`): True, if the connection is active.
rights (:class:`BusinessBotRights`, optional): Rights of the business bot.
.. versionadded:: 22.1
Attributes:
id (:obj:`str`): Unique identifier of the business connection.
user (:class:`telegram.User`): Business account user that created the business connection.
user_chat_id (:obj:`int`): Identifier of a private chat with the user who created the
business connection.
date (:obj:`datetime.datetime`): Date the connection was established in Unix time.
is_enabled (:obj:`bool`): True, if the connection is active.
rights (:class:`BusinessBotRights`): Optional. Rights of the business bot.
.. versionadded:: 22.1
"""
__slots__ = (
"date",
"id",
"is_enabled",
"rights",
"user",
"user_chat_id",
)
def __init__(
self,
id: str,
user: "User",
user_chat_id: int,
date: dtm.datetime,
is_enabled: bool,
rights: Optional[BusinessBotRights] = None,
*,
api_kwargs: Optional[JSONDict] = None,
):
super().__init__(api_kwargs=api_kwargs)
self.id: str = id
self.user: User = user
self.user_chat_id: int = user_chat_id
self.date: dtm.datetime = date
self.is_enabled: bool = is_enabled
self.rights: Optional[BusinessBotRights] = rights
self._id_attrs = (
self.id,
self.user,
self.user_chat_id,
self.date,
self.rights,
self.is_enabled,
)
self._freeze()
@classmethod
def de_json(cls, data: JSONDict, bot: Optional["Bot"] = None) -> "BusinessConnection":
"""See :meth:`telegram.TelegramObject.de_json`."""
data = cls._parse_data(data)
# Get the local timezone from the bot if it has defaults
loc_tzinfo = extract_tzinfo_from_defaults(bot)
data["date"] = from_timestamp(data.get("date"), tzinfo=loc_tzinfo)
data["user"] = de_json_optional(data.get("user"), User, bot)
data["rights"] = de_json_optional(data.get("rights"), BusinessBotRights, bot)
return super().de_json(data=data, bot=bot)
class BusinessMessagesDeleted(TelegramObject):
"""
This object is received when messages are deleted from a connected business account.
Objects of this class are comparable in terms of equality. Two objects of this class are
considered equal if their :attr:`business_connection_id`, :attr:`message_ids`, and
:attr:`chat` are equal.
.. versionadded:: 21.1
Args:
business_connection_id (:obj:`str`): Unique identifier of the business connection.
chat (:class:`telegram.Chat`): Information about a chat in the business account. The bot
may not have access to the chat or the corresponding user.
message_ids (Sequence[:obj:`int`]): A list of identifiers of the deleted messages in the
chat of the business account.
Attributes:
business_connection_id (:obj:`str`): Unique identifier of the business connection.
chat (:class:`telegram.Chat`): Information about a chat in the business account. The bot
may not have access to the chat or the corresponding user.
message_ids (tuple[:obj:`int`]): A list of identifiers of the deleted messages in the
chat of the business account.
"""
__slots__ = (
"business_connection_id",
"chat",
"message_ids",
)
def __init__(
self,
business_connection_id: str,
chat: Chat,
message_ids: Sequence[int],
*,
api_kwargs: Optional[JSONDict] = None,
):
super().__init__(api_kwargs=api_kwargs)
self.business_connection_id: str = business_connection_id
self.chat: Chat = chat
self.message_ids: tuple[int, ...] = parse_sequence_arg(message_ids)
self._id_attrs = (
self.business_connection_id,
self.chat,
self.message_ids,
)
self._freeze()
@classmethod
def de_json(cls, data: JSONDict, bot: Optional["Bot"] = None) -> "BusinessMessagesDeleted":
"""See :meth:`telegram.TelegramObject.de_json`."""
data = cls._parse_data(data)
data["chat"] = de_json_optional(data.get("chat"), Chat, bot)
return super().de_json(data=data, bot=bot)
class BusinessIntro(TelegramObject):
"""
This object contains information about the start page settings of a Telegram Business account.
Objects of this class are comparable in terms of equality.
Two objects of this class are considered equal, if their
:attr:`title`, :attr:`message` and :attr:`sticker` are equal.
.. versionadded:: 21.1
Args:
title (:obj:`str`, optional): Title text of the business intro.
message (:obj:`str`, optional): Message text of the business intro.
sticker (:class:`telegram.Sticker`, optional): Sticker of the business intro.
Attributes:
title (:obj:`str`): Optional. Title text of the business intro.
message (:obj:`str`): Optional. Message text of the business intro.
sticker (:class:`telegram.Sticker`): Optional. Sticker of the business intro.
"""
__slots__ = (
"message",
"sticker",
"title",
)
def __init__(
self,
title: Optional[str] = None,
message: Optional[str] = None,
sticker: Optional[Sticker] = None,
*,
api_kwargs: Optional[JSONDict] = None,
):
super().__init__(api_kwargs=api_kwargs)
self.title: Optional[str] = title
self.message: Optional[str] = message
self.sticker: Optional[Sticker] = sticker
self._id_attrs = (self.title, self.message, self.sticker)
self._freeze()
@classmethod
def de_json(cls, data: JSONDict, bot: Optional["Bot"] = None) -> "BusinessIntro":
"""See :meth:`telegram.TelegramObject.de_json`."""
data = cls._parse_data(data)
data["sticker"] = de_json_optional(data.get("sticker"), Sticker, bot)
return super().de_json(data=data, bot=bot)
class BusinessLocation(TelegramObject):
"""
This object contains information about the location of a Telegram Business account.
Objects of this class are comparable in terms of equality.
Two objects of this class are considered equal, if their
:attr:`address` is equal.
.. versionadded:: 21.1
Args:
address (:obj:`str`): Address of the business.
location (:class:`telegram.Location`, optional): Location of the business.
Attributes:
address (:obj:`str`): Address of the business.
location (:class:`telegram.Location`): Optional. Location of the business.
"""
__slots__ = (
"address",
"location",
)
def __init__(
self,
address: str,
location: Optional[Location] = None,
*,
api_kwargs: Optional[JSONDict] = None,
):
super().__init__(api_kwargs=api_kwargs)
self.address: str = address
self.location: Optional[Location] = location
self._id_attrs = (self.address,)
self._freeze()
@classmethod
def de_json(cls, data: JSONDict, bot: Optional["Bot"] = None) -> "BusinessLocation":
"""See :meth:`telegram.TelegramObject.de_json`."""
data = cls._parse_data(data)
data["location"] = de_json_optional(data.get("location"), Location, bot)
return super().de_json(data=data, bot=bot)
class BusinessOpeningHoursInterval(TelegramObject):
"""
This object describes an interval of time during which a business is open.
Objects of this class are comparable in terms of equality.
Two objects of this class are considered equal, if their
:attr:`opening_minute` and :attr:`closing_minute` are equal.
.. versionadded:: 21.1
Examples:
A day has (24 * 60 =) 1440 minutes, a week has (7 * 1440 =) 10080 minutes.
Starting the the minute's sequence from Monday, example values of
:attr:`opening_minute`, :attr:`closing_minute` will map to the following day times:
* Monday - 8am to 8:30pm:
- ``opening_minute = 480`` :guilabel:`8 * 60`
- ``closing_minute = 1230`` :guilabel:`20 * 60 + 30`
* Tuesday - 24 hours:
- ``opening_minute = 1440`` :guilabel:`24 * 60`
- ``closing_minute = 2879`` :guilabel:`2 * 24 * 60 - 1`
* Sunday - 12am - 11:58pm:
- ``opening_minute = 8640`` :guilabel:`6 * 24 * 60`
- ``closing_minute = 10078`` :guilabel:`7 * 24 * 60 - 2`
Args:
opening_minute (:obj:`int`): The minute's sequence number in a week, starting on Monday,
marking the start of the time interval during which the business is open;
0 - 7 * 24 * 60.
closing_minute (:obj:`int`): The minute's
sequence number in a week, starting on Monday, marking the end of the time interval
during which the business is open; 0 - 8 * 24 * 60
Attributes:
opening_minute (:obj:`int`): The minute's sequence number in a week, starting on Monday,
marking the start of the time interval during which the business is open;
0 - 7 * 24 * 60.
closing_minute (:obj:`int`): The minute's
sequence number in a week, starting on Monday, marking the end of the time interval
during which the business is open; 0 - 8 * 24 * 60
"""
__slots__ = ("_closing_time", "_opening_time", "closing_minute", "opening_minute")
def __init__(
self,
opening_minute: int,
closing_minute: int,
*,
api_kwargs: Optional[JSONDict] = None,
):
super().__init__(api_kwargs=api_kwargs)
self.opening_minute: int = opening_minute
self.closing_minute: int = closing_minute
self._opening_time: Optional[tuple[int, int, int]] = None
self._closing_time: Optional[tuple[int, int, int]] = None
self._id_attrs = (self.opening_minute, self.closing_minute)
self._freeze()
def _parse_minute(self, minute: int) -> tuple[int, int, int]:
return (minute // 1440, minute % 1440 // 60, minute % 1440 % 60)
@property
def opening_time(self) -> tuple[int, int, int]:
"""Convenience attribute. A :obj:`tuple` parsed from :attr:`opening_minute`. It contains
the `weekday`, `hour` and `minute` in the same ranges as :attr:`datetime.datetime.weekday`,
:attr:`datetime.datetime.hour` and :attr:`datetime.datetime.minute`
Returns:
tuple[:obj:`int`, :obj:`int`, :obj:`int`]:
"""
if self._opening_time is None:
self._opening_time = self._parse_minute(self.opening_minute)
return self._opening_time
@property
def closing_time(self) -> tuple[int, int, int]:
"""Convenience attribute. A :obj:`tuple` parsed from :attr:`closing_minute`. It contains
the `weekday`, `hour` and `minute` in the same ranges as :attr:`datetime.datetime.weekday`,
:attr:`datetime.datetime.hour` and :attr:`datetime.datetime.minute`
Returns:
tuple[:obj:`int`, :obj:`int`, :obj:`int`]:
"""
if self._closing_time is None:
self._closing_time = self._parse_minute(self.closing_minute)
return self._closing_time
class BusinessOpeningHours(TelegramObject):
"""
This object describes the opening hours of a business.
Objects of this class are comparable in terms of equality.
Two objects of this class are considered equal, if their
:attr:`time_zone_name` and :attr:`opening_hours` are equal.
.. versionadded:: 21.1
Args:
time_zone_name (:obj:`str`): Unique name of the time zone for which the opening
hours are defined.
opening_hours (Sequence[:class:`telegram.BusinessOpeningHoursInterval`]): List of
time intervals describing business opening hours.
Attributes:
time_zone_name (:obj:`str`): Unique name of the time zone for which the opening
hours are defined.
opening_hours (Sequence[:class:`telegram.BusinessOpeningHoursInterval`]): List of
time intervals describing business opening hours.
"""
__slots__ = ("opening_hours", "time_zone_name")
def __init__(
self,
time_zone_name: str,
opening_hours: Sequence[BusinessOpeningHoursInterval],
*,
api_kwargs: Optional[JSONDict] = None,
):
super().__init__(api_kwargs=api_kwargs)
self.time_zone_name: str = time_zone_name
self.opening_hours: Sequence[BusinessOpeningHoursInterval] = parse_sequence_arg(
opening_hours
)
self._id_attrs = (self.time_zone_name, self.opening_hours)
self._freeze()
@classmethod
def de_json(cls, data: JSONDict, bot: Optional["Bot"] = None) -> "BusinessOpeningHours":
"""See :meth:`telegram.TelegramObject.de_json`."""
data = cls._parse_data(data)
data["opening_hours"] = de_list_optional(
data.get("opening_hours"), BusinessOpeningHoursInterval, bot
)
return super().de_json(data=data, bot=bot)

View File

@@ -0,0 +1,931 @@
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2025
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser Public License for more details.
#
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
# pylint: disable=redefined-builtin
"""This module contains an object that represents a Telegram CallbackQuery"""
from collections.abc import Sequence
from typing import TYPE_CHECKING, Final, Optional, Union
from telegram import constants
from telegram._files.location import Location
from telegram._inputchecklist import InputChecklist
from telegram._message import MaybeInaccessibleMessage, Message
from telegram._telegramobject import TelegramObject
from telegram._user import User
from telegram._utils.argumentparsing import de_json_optional
from telegram._utils.defaultvalue import DEFAULT_NONE
from telegram._utils.types import JSONDict, ODVInput, ReplyMarkup, TimePeriod
if TYPE_CHECKING:
from telegram import (
Bot,
GameHighScore,
InlineKeyboardMarkup,
InputMedia,
LinkPreviewOptions,
MessageEntity,
MessageId,
ReplyParameters,
)
class CallbackQuery(TelegramObject):
"""
This object represents an incoming callback query from a callback button in an inline keyboard.
If the button that originated the query was attached to a message sent by the bot, the field
:attr:`message` will be present. If the button was attached to a message sent via the bot (in
inline mode), the field :attr:`inline_message_id` will be present.
Objects of this class are comparable in terms of equality. Two objects of this class are
considered equal, if their :attr:`id` is equal.
Note:
* In Python :keyword:`from` is a reserved word. Use :paramref:`from_user` instead.
* Exactly one of the fields :attr:`data` or :attr:`game_short_name` will be present.
* After the user presses an inline button, Telegram clients will display a progress bar
until you call :attr:`answer`. It is, therefore, necessary to react
by calling :attr:`telegram.Bot.answer_callback_query` even if no notification to the user
is needed (e.g., without specifying any of the optional parameters).
* If you're using :attr:`telegram.ext.ExtBot.callback_data_cache`, :attr:`data` may be
an instance
of :class:`telegram.ext.InvalidCallbackData`. This will be the case, if the data
associated with the button triggering the :class:`telegram.CallbackQuery` was already
deleted or if :attr:`data` was manipulated by a malicious client.
.. versionadded:: 13.6
Args:
id (:obj:`str`): Unique identifier for this query.
from_user (:class:`telegram.User`): Sender.
chat_instance (:obj:`str`): Global identifier, uniquely corresponding to the chat to which
the message with the callback button was sent. Useful for high scores in games.
message (:class:`telegram.MaybeInaccessibleMessage`, optional): Message sent by the bot
with the callback button that originated the query.
.. versionchanged:: 20.8
Accept objects of type :class:`telegram.MaybeInaccessibleMessage` since Bot API 7.0.
data (:obj:`str`, optional): Data associated with the callback button. Be aware that the
message, which originated the query, can contain no callback buttons with this data.
inline_message_id (:obj:`str`, optional): Identifier of the message sent via the bot in
inline mode, that originated the query.
game_short_name (:obj:`str`, optional): Short name of a Game to be returned, serves as
the unique identifier for the game.
Attributes:
id (:obj:`str`): Unique identifier for this query.
from_user (:class:`telegram.User`): Sender.
chat_instance (:obj:`str`): Global identifier, uniquely corresponding to the chat to which
the message with the callback button was sent. Useful for high scores in games.
message (:class:`telegram.MaybeInaccessibleMessage`): Optional. Message sent by the bot
with the callback button that originated the query.
.. versionchanged:: 20.8
Objects may be of type :class:`telegram.MaybeInaccessibleMessage` since Bot API
7.0.
data (:obj:`str` | :obj:`object`): Optional. Data associated with the callback button.
Be aware that the message, which originated the query, can contain no callback buttons
with this data.
Tip:
The value here is the same as the value passed in
:paramref:`telegram.InlineKeyboardButton.callback_data`.
inline_message_id (:obj:`str`): Optional. Identifier of the message sent via the bot in
inline mode, that originated the query.
game_short_name (:obj:`str`): Optional. Short name of a Game to be returned, serves as
the unique identifier for the game.
"""
__slots__ = (
"chat_instance",
"data",
"from_user",
"game_short_name",
"id",
"inline_message_id",
"message",
)
def __init__(
self,
id: str,
from_user: User,
chat_instance: str,
message: Optional[MaybeInaccessibleMessage] = None,
data: Optional[str] = None,
inline_message_id: Optional[str] = None,
game_short_name: Optional[str] = None,
*,
api_kwargs: Optional[JSONDict] = None,
):
super().__init__(api_kwargs=api_kwargs)
# Required
self.id: str = id
self.from_user: User = from_user
self.chat_instance: str = chat_instance
# Optionals
self.message: Optional[MaybeInaccessibleMessage] = message
self.data: Optional[str] = data
self.inline_message_id: Optional[str] = inline_message_id
self.game_short_name: Optional[str] = game_short_name
self._id_attrs = (self.id,)
self._freeze()
@classmethod
def de_json(cls, data: JSONDict, bot: Optional["Bot"] = None) -> "CallbackQuery":
"""See :meth:`telegram.TelegramObject.de_json`."""
data = cls._parse_data(data)
data["from_user"] = de_json_optional(data.pop("from", None), User, bot)
data["message"] = de_json_optional(data.get("message"), Message, bot)
return super().de_json(data=data, bot=bot)
async def answer(
self,
text: Optional[str] = None,
show_alert: Optional[bool] = None,
url: Optional[str] = None,
cache_time: Optional[TimePeriod] = None,
*,
read_timeout: ODVInput[float] = DEFAULT_NONE,
write_timeout: ODVInput[float] = DEFAULT_NONE,
connect_timeout: ODVInput[float] = DEFAULT_NONE,
pool_timeout: ODVInput[float] = DEFAULT_NONE,
api_kwargs: Optional[JSONDict] = None,
) -> bool:
"""Shortcut for::
await bot.answer_callback_query(update.callback_query.id, *args, **kwargs)
For the documentation of the arguments, please see
:meth:`telegram.Bot.answer_callback_query`.
Returns:
:obj:`bool`: On success, :obj:`True` is returned.
"""
return await self.get_bot().answer_callback_query(
callback_query_id=self.id,
text=text,
show_alert=show_alert,
url=url,
cache_time=cache_time,
read_timeout=read_timeout,
write_timeout=write_timeout,
connect_timeout=connect_timeout,
pool_timeout=pool_timeout,
api_kwargs=api_kwargs,
)
def _get_message(self, action: str = "edit") -> Message:
"""Helper method to get the message for the shortcut methods. Must be called only
if :attr:`inline_message_id` is *not* set.
"""
if not isinstance(self.message, Message):
raise TypeError(f"Cannot {action} an inaccessible message")
return self.message
async def edit_message_text(
self,
text: str,
parse_mode: ODVInput[str] = DEFAULT_NONE,
reply_markup: Optional["InlineKeyboardMarkup"] = None,
entities: Optional[Sequence["MessageEntity"]] = None,
link_preview_options: ODVInput["LinkPreviewOptions"] = DEFAULT_NONE,
*,
disable_web_page_preview: Optional[bool] = None,
read_timeout: ODVInput[float] = DEFAULT_NONE,
write_timeout: ODVInput[float] = DEFAULT_NONE,
connect_timeout: ODVInput[float] = DEFAULT_NONE,
pool_timeout: ODVInput[float] = DEFAULT_NONE,
api_kwargs: Optional[JSONDict] = None,
) -> Union[Message, bool]:
"""Shortcut for either::
await update.callback_query.message.edit_text(*args, **kwargs)
or::
await bot.edit_message_text(
inline_message_id=update.callback_query.inline_message_id, *args, **kwargs,
)
For the documentation of the arguments, please see
:meth:`telegram.Bot.edit_message_text` and :meth:`telegram.Message.edit_text`.
.. versionchanged:: 20.8
Raises :exc:`TypeError` if :attr:`message` is not accessible.
Returns:
:class:`telegram.Message`: On success, if edited message is sent by the bot, the
edited Message is returned, otherwise :obj:`True` is returned.
Raises:
:exc:`TypeError` if :attr:`message` is not accessible.
"""
if self.inline_message_id:
return await self.get_bot().edit_message_text(
inline_message_id=self.inline_message_id,
text=text,
parse_mode=parse_mode,
disable_web_page_preview=disable_web_page_preview,
link_preview_options=link_preview_options,
reply_markup=reply_markup,
read_timeout=read_timeout,
write_timeout=write_timeout,
connect_timeout=connect_timeout,
pool_timeout=pool_timeout,
api_kwargs=api_kwargs,
entities=entities,
chat_id=None,
message_id=None,
# inline messages can not be sent on behalf of a bcid
business_connection_id=None,
)
return await self._get_message().edit_text(
text=text,
parse_mode=parse_mode,
disable_web_page_preview=disable_web_page_preview,
link_preview_options=link_preview_options,
reply_markup=reply_markup,
read_timeout=read_timeout,
write_timeout=write_timeout,
connect_timeout=connect_timeout,
pool_timeout=pool_timeout,
api_kwargs=api_kwargs,
entities=entities,
)
async def edit_message_caption(
self,
caption: Optional[str] = None,
reply_markup: Optional["InlineKeyboardMarkup"] = None,
parse_mode: ODVInput[str] = DEFAULT_NONE,
caption_entities: Optional[Sequence["MessageEntity"]] = None,
show_caption_above_media: Optional[bool] = None,
*,
read_timeout: ODVInput[float] = DEFAULT_NONE,
write_timeout: ODVInput[float] = DEFAULT_NONE,
connect_timeout: ODVInput[float] = DEFAULT_NONE,
pool_timeout: ODVInput[float] = DEFAULT_NONE,
api_kwargs: Optional[JSONDict] = None,
) -> Union[Message, bool]:
"""Shortcut for either::
await update.callback_query.message.edit_caption(*args, **kwargs)
or::
await bot.edit_message_caption(
inline_message_id=update.callback_query.inline_message_id, *args, **kwargs,
)
For the documentation of the arguments, please see
:meth:`telegram.Bot.edit_message_caption` and :meth:`telegram.Message.edit_caption`.
.. versionchanged:: 20.8
Raises :exc:`TypeError` if :attr:`message` is not accessible.
Returns:
:class:`telegram.Message`: On success, if edited message is sent by the bot, the
edited Message is returned, otherwise :obj:`True` is returned.
Raises:
:exc:`TypeError` if :attr:`message` is not accessible.
"""
if self.inline_message_id:
return await self.get_bot().edit_message_caption(
caption=caption,
inline_message_id=self.inline_message_id,
reply_markup=reply_markup,
read_timeout=read_timeout,
write_timeout=write_timeout,
connect_timeout=connect_timeout,
pool_timeout=pool_timeout,
parse_mode=parse_mode,
api_kwargs=api_kwargs,
caption_entities=caption_entities,
chat_id=None,
message_id=None,
show_caption_above_media=show_caption_above_media,
# inline messages can not be sent on behalf of a bcid
business_connection_id=None,
)
return await self._get_message().edit_caption(
caption=caption,
reply_markup=reply_markup,
read_timeout=read_timeout,
write_timeout=write_timeout,
connect_timeout=connect_timeout,
pool_timeout=pool_timeout,
parse_mode=parse_mode,
api_kwargs=api_kwargs,
caption_entities=caption_entities,
show_caption_above_media=show_caption_above_media,
)
async def edit_message_checklist(
self,
checklist: InputChecklist,
reply_markup: Optional["InlineKeyboardMarkup"] = None,
*,
read_timeout: ODVInput[float] = DEFAULT_NONE,
write_timeout: ODVInput[float] = DEFAULT_NONE,
connect_timeout: ODVInput[float] = DEFAULT_NONE,
pool_timeout: ODVInput[float] = DEFAULT_NONE,
api_kwargs: Optional[JSONDict] = None,
) -> Union[Message, bool]:
"""Shortcut for::
await update.callback_query.message.edit_checklist(*args, **kwargs)
For the documentation of the arguments, please see
:meth:`telegram.Message.edit_checklist`.
.. versionadded:: 22.3
Returns:
:class:`telegram.Message`: On success, the edited Message is returned.
Raises:
:exc:`TypeError` if :attr:`message` is not accessible.
"""
return await self._get_message().edit_checklist(
checklist=checklist,
reply_markup=reply_markup,
read_timeout=read_timeout,
write_timeout=write_timeout,
connect_timeout=connect_timeout,
pool_timeout=pool_timeout,
api_kwargs=api_kwargs,
)
async def edit_message_reply_markup(
self,
reply_markup: Optional["InlineKeyboardMarkup"] = None,
*,
read_timeout: ODVInput[float] = DEFAULT_NONE,
write_timeout: ODVInput[float] = DEFAULT_NONE,
connect_timeout: ODVInput[float] = DEFAULT_NONE,
pool_timeout: ODVInput[float] = DEFAULT_NONE,
api_kwargs: Optional[JSONDict] = None,
) -> Union[Message, bool]:
"""Shortcut for either::
await update.callback_query.message.edit_reply_markup(*args, **kwargs)
or::
await bot.edit_message_reply_markup(
inline_message_id=update.callback_query.inline_message_id, *args, **kwargs
)
For the documentation of the arguments, please see
:meth:`telegram.Bot.edit_message_reply_markup` and
:meth:`telegram.Message.edit_reply_markup`.
.. versionchanged:: 20.8
Raises :exc:`TypeError` if :attr:`message` is not accessible.
Returns:
:class:`telegram.Message`: On success, if edited message is sent by the bot, the
edited Message is returned, otherwise :obj:`True` is returned.
Raises:
:exc:`TypeError` if :attr:`message` is not accessible.
"""
if self.inline_message_id:
return await self.get_bot().edit_message_reply_markup(
reply_markup=reply_markup,
inline_message_id=self.inline_message_id,
read_timeout=read_timeout,
write_timeout=write_timeout,
connect_timeout=connect_timeout,
pool_timeout=pool_timeout,
api_kwargs=api_kwargs,
chat_id=None,
message_id=None,
# inline messages can not be sent on behalf of a bcid
business_connection_id=None,
)
return await self._get_message().edit_reply_markup(
reply_markup=reply_markup,
read_timeout=read_timeout,
write_timeout=write_timeout,
connect_timeout=connect_timeout,
pool_timeout=pool_timeout,
api_kwargs=api_kwargs,
)
async def edit_message_media(
self,
media: "InputMedia",
reply_markup: Optional["InlineKeyboardMarkup"] = None,
*,
read_timeout: ODVInput[float] = DEFAULT_NONE,
write_timeout: ODVInput[float] = DEFAULT_NONE,
connect_timeout: ODVInput[float] = DEFAULT_NONE,
pool_timeout: ODVInput[float] = DEFAULT_NONE,
api_kwargs: Optional[JSONDict] = None,
) -> Union[Message, bool]:
"""Shortcut for either::
await update.callback_query.message.edit_media(*args, **kwargs)
or::
await bot.edit_message_media(
inline_message_id=update.callback_query.inline_message_id, *args, **kwargs
)
For the documentation of the arguments, please see
:meth:`telegram.Bot.edit_message_media` and :meth:`telegram.Message.edit_media`.
.. versionchanged:: 20.8
Raises :exc:`TypeError` if :attr:`message` is not accessible.
Returns:
:class:`telegram.Message`: On success, if edited message is not an inline message, the
edited Message is returned, otherwise :obj:`True` is returned.
Raises:
:exc:`TypeError` if :attr:`message` is not accessible.
"""
if self.inline_message_id:
return await self.get_bot().edit_message_media(
inline_message_id=self.inline_message_id,
media=media,
reply_markup=reply_markup,
read_timeout=read_timeout,
write_timeout=write_timeout,
connect_timeout=connect_timeout,
pool_timeout=pool_timeout,
api_kwargs=api_kwargs,
chat_id=None,
message_id=None,
# inline messages can not be sent on behalf of a bcid
business_connection_id=None,
)
return await self._get_message().edit_media(
media=media,
reply_markup=reply_markup,
read_timeout=read_timeout,
write_timeout=write_timeout,
connect_timeout=connect_timeout,
pool_timeout=pool_timeout,
api_kwargs=api_kwargs,
)
async def edit_message_live_location(
self,
latitude: Optional[float] = None,
longitude: Optional[float] = None,
reply_markup: Optional["InlineKeyboardMarkup"] = None,
horizontal_accuracy: Optional[float] = None,
heading: Optional[int] = None,
proximity_alert_radius: Optional[int] = None,
live_period: Optional[TimePeriod] = None,
*,
location: Optional[Location] = None,
read_timeout: ODVInput[float] = DEFAULT_NONE,
write_timeout: ODVInput[float] = DEFAULT_NONE,
connect_timeout: ODVInput[float] = DEFAULT_NONE,
pool_timeout: ODVInput[float] = DEFAULT_NONE,
api_kwargs: Optional[JSONDict] = None,
) -> Union[Message, bool]:
"""Shortcut for either::
await update.callback_query.message.edit_live_location(*args, **kwargs)
or::
await bot.edit_message_live_location(
inline_message_id=update.callback_query.inline_message_id, *args, **kwargs
)
For the documentation of the arguments, please see
:meth:`telegram.Bot.edit_message_live_location` and
:meth:`telegram.Message.edit_live_location`.
.. versionchanged:: 20.8
Raises :exc:`TypeError` if :attr:`message` is not accessible.
Returns:
:class:`telegram.Message`: On success, if edited message is sent by the bot, the
edited Message is returned, otherwise :obj:`True` is returned.
Raises:
:exc:`TypeError` if :attr:`message` is not accessible.
"""
if self.inline_message_id:
return await self.get_bot().edit_message_live_location(
inline_message_id=self.inline_message_id,
latitude=latitude,
longitude=longitude,
location=location,
reply_markup=reply_markup,
read_timeout=read_timeout,
write_timeout=write_timeout,
connect_timeout=connect_timeout,
pool_timeout=pool_timeout,
api_kwargs=api_kwargs,
horizontal_accuracy=horizontal_accuracy,
heading=heading,
proximity_alert_radius=proximity_alert_radius,
live_period=live_period,
chat_id=None,
message_id=None,
# inline messages can not be sent on behalf of a bcid
business_connection_id=None,
)
return await self._get_message().edit_live_location(
latitude=latitude,
longitude=longitude,
location=location,
reply_markup=reply_markup,
read_timeout=read_timeout,
write_timeout=write_timeout,
connect_timeout=connect_timeout,
pool_timeout=pool_timeout,
api_kwargs=api_kwargs,
horizontal_accuracy=horizontal_accuracy,
heading=heading,
proximity_alert_radius=proximity_alert_radius,
live_period=live_period,
)
async def stop_message_live_location(
self,
reply_markup: Optional["InlineKeyboardMarkup"] = None,
*,
read_timeout: ODVInput[float] = DEFAULT_NONE,
write_timeout: ODVInput[float] = DEFAULT_NONE,
connect_timeout: ODVInput[float] = DEFAULT_NONE,
pool_timeout: ODVInput[float] = DEFAULT_NONE,
api_kwargs: Optional[JSONDict] = None,
) -> Union[Message, bool]:
"""Shortcut for either::
await update.callback_query.message.stop_live_location(*args, **kwargs)
or::
await bot.stop_message_live_location(
inline_message_id=update.callback_query.inline_message_id, *args, **kwargs
)
For the documentation of the arguments, please see
:meth:`telegram.Bot.stop_message_live_location` and
:meth:`telegram.Message.stop_live_location`.
.. versionchanged:: 20.8
Raises :exc:`TypeError` if :attr:`message` is not accessible.
Returns:
:class:`telegram.Message`: On success, if edited message is sent by the bot, the
edited Message is returned, otherwise :obj:`True` is returned.
Raises:
:exc:`TypeError` if :attr:`message` is not accessible.
"""
if self.inline_message_id:
return await self.get_bot().stop_message_live_location(
inline_message_id=self.inline_message_id,
reply_markup=reply_markup,
read_timeout=read_timeout,
write_timeout=write_timeout,
connect_timeout=connect_timeout,
pool_timeout=pool_timeout,
api_kwargs=api_kwargs,
chat_id=None,
message_id=None,
# inline messages can not be sent on behalf of a bcid
business_connection_id=None,
)
return await self._get_message().stop_live_location(
reply_markup=reply_markup,
read_timeout=read_timeout,
write_timeout=write_timeout,
connect_timeout=connect_timeout,
pool_timeout=pool_timeout,
api_kwargs=api_kwargs,
)
async def set_game_score(
self,
user_id: int,
score: int,
force: Optional[bool] = None,
disable_edit_message: Optional[bool] = None,
*,
read_timeout: ODVInput[float] = DEFAULT_NONE,
write_timeout: ODVInput[float] = DEFAULT_NONE,
connect_timeout: ODVInput[float] = DEFAULT_NONE,
pool_timeout: ODVInput[float] = DEFAULT_NONE,
api_kwargs: Optional[JSONDict] = None,
) -> Union[Message, bool]:
"""Shortcut for either::
await update.callback_query.message.set_game_score(*args, **kwargs)
or::
await bot.set_game_score(
inline_message_id=update.callback_query.inline_message_id, *args, **kwargs
)
For the documentation of the arguments, please see
:meth:`telegram.Bot.set_game_score` and :meth:`telegram.Message.set_game_score`.
.. versionchanged:: 20.8
Raises :exc:`TypeError` if :attr:`message` is not accessible.
Returns:
:class:`telegram.Message`: On success, if edited message is sent by the bot, the
edited Message is returned, otherwise :obj:`True` is returned.
Raises:
:exc:`TypeError` if :attr:`message` is not accessible.
"""
if self.inline_message_id:
return await self.get_bot().set_game_score(
inline_message_id=self.inline_message_id,
user_id=user_id,
score=score,
force=force,
disable_edit_message=disable_edit_message,
read_timeout=read_timeout,
write_timeout=write_timeout,
connect_timeout=connect_timeout,
pool_timeout=pool_timeout,
api_kwargs=api_kwargs,
chat_id=None,
message_id=None,
)
return await self._get_message().set_game_score(
user_id=user_id,
score=score,
force=force,
disable_edit_message=disable_edit_message,
read_timeout=read_timeout,
write_timeout=write_timeout,
connect_timeout=connect_timeout,
pool_timeout=pool_timeout,
api_kwargs=api_kwargs,
)
async def get_game_high_scores(
self,
user_id: int,
*,
read_timeout: ODVInput[float] = DEFAULT_NONE,
write_timeout: ODVInput[float] = DEFAULT_NONE,
connect_timeout: ODVInput[float] = DEFAULT_NONE,
pool_timeout: ODVInput[float] = DEFAULT_NONE,
api_kwargs: Optional[JSONDict] = None,
) -> tuple["GameHighScore", ...]:
"""Shortcut for either::
await update.callback_query.message.get_game_high_score(*args, **kwargs)
or::
await bot.get_game_high_scores(
inline_message_id=update.callback_query.inline_message_id, *args, **kwargs
)
For the documentation of the arguments, please see
:meth:`telegram.Bot.get_game_high_scores` and
:meth:`telegram.Message.get_game_high_scores`.
.. versionchanged:: 20.8
Raises :exc:`TypeError` if :attr:`message` is not accessible.
Returns:
tuple[:class:`telegram.GameHighScore`]
Raises:
:exc:`TypeError` if :attr:`message` is not accessible.
"""
if self.inline_message_id:
return await self.get_bot().get_game_high_scores(
inline_message_id=self.inline_message_id,
user_id=user_id,
read_timeout=read_timeout,
write_timeout=write_timeout,
connect_timeout=connect_timeout,
pool_timeout=pool_timeout,
api_kwargs=api_kwargs,
chat_id=None,
message_id=None,
)
return await self._get_message().get_game_high_scores(
user_id=user_id,
read_timeout=read_timeout,
write_timeout=write_timeout,
connect_timeout=connect_timeout,
pool_timeout=pool_timeout,
api_kwargs=api_kwargs,
)
async def delete_message(
self,
*,
read_timeout: ODVInput[float] = DEFAULT_NONE,
write_timeout: ODVInput[float] = DEFAULT_NONE,
connect_timeout: ODVInput[float] = DEFAULT_NONE,
pool_timeout: ODVInput[float] = DEFAULT_NONE,
api_kwargs: Optional[JSONDict] = None,
) -> bool:
"""Shortcut for::
await update.callback_query.message.delete(*args, **kwargs)
For the documentation of the arguments, please see :meth:`telegram.Message.delete`.
.. versionchanged:: 20.8
Raises :exc:`TypeError` if :attr:`message` is not accessible.
Returns:
:obj:`bool`: On success, :obj:`True` is returned.
Raises:
:exc:`TypeError` if :attr:`message` is not accessible.
"""
return await self._get_message(action="delete").delete(
read_timeout=read_timeout,
write_timeout=write_timeout,
connect_timeout=connect_timeout,
pool_timeout=pool_timeout,
api_kwargs=api_kwargs,
)
async def pin_message(
self,
disable_notification: ODVInput[bool] = DEFAULT_NONE,
*,
read_timeout: ODVInput[float] = DEFAULT_NONE,
write_timeout: ODVInput[float] = DEFAULT_NONE,
connect_timeout: ODVInput[float] = DEFAULT_NONE,
pool_timeout: ODVInput[float] = DEFAULT_NONE,
api_kwargs: Optional[JSONDict] = None,
) -> bool:
"""Shortcut for::
await update.callback_query.message.pin(*args, **kwargs)
For the documentation of the arguments, please see :meth:`telegram.Message.pin`.
.. versionchanged:: 20.8
Raises :exc:`TypeError` if :attr:`message` is not accessible.
Returns:
:obj:`bool`: On success, :obj:`True` is returned.
Raises:
:exc:`TypeError` if :attr:`message` is not accessible.
"""
return await self._get_message(action="pin").pin(
disable_notification=disable_notification,
read_timeout=read_timeout,
write_timeout=write_timeout,
connect_timeout=connect_timeout,
pool_timeout=pool_timeout,
api_kwargs=api_kwargs,
)
async def unpin_message(
self,
*,
read_timeout: ODVInput[float] = DEFAULT_NONE,
write_timeout: ODVInput[float] = DEFAULT_NONE,
connect_timeout: ODVInput[float] = DEFAULT_NONE,
pool_timeout: ODVInput[float] = DEFAULT_NONE,
api_kwargs: Optional[JSONDict] = None,
) -> bool:
"""Shortcut for::
await update.callback_query.message.unpin(*args, **kwargs)
For the documentation of the arguments, please see :meth:`telegram.Message.unpin`.
.. versionchanged:: 20.8
Raises :exc:`TypeError` if :attr:`message` is not accessible.
Returns:
:obj:`bool`: On success, :obj:`True` is returned.
Raises:
:exc:`TypeError` if :attr:`message` is not accessible.
"""
return await self._get_message(action="unpin").unpin(
read_timeout=read_timeout,
write_timeout=write_timeout,
connect_timeout=connect_timeout,
pool_timeout=pool_timeout,
api_kwargs=api_kwargs,
)
async def copy_message(
self,
chat_id: Union[int, str],
caption: Optional[str] = None,
parse_mode: ODVInput[str] = DEFAULT_NONE,
caption_entities: Optional[Sequence["MessageEntity"]] = None,
disable_notification: ODVInput[bool] = DEFAULT_NONE,
reply_markup: Optional[ReplyMarkup] = None,
protect_content: ODVInput[bool] = DEFAULT_NONE,
message_thread_id: Optional[int] = None,
reply_parameters: Optional["ReplyParameters"] = None,
show_caption_above_media: Optional[bool] = None,
allow_paid_broadcast: Optional[bool] = None,
video_start_timestamp: Optional[int] = None,
*,
allow_sending_without_reply: ODVInput[bool] = DEFAULT_NONE,
reply_to_message_id: Optional[int] = None,
read_timeout: ODVInput[float] = DEFAULT_NONE,
write_timeout: ODVInput[float] = DEFAULT_NONE,
connect_timeout: ODVInput[float] = DEFAULT_NONE,
pool_timeout: ODVInput[float] = DEFAULT_NONE,
api_kwargs: Optional[JSONDict] = None,
) -> "MessageId":
"""Shortcut for::
await update.callback_query.message.copy(
from_chat_id=update.message.chat_id,
message_id=update.message.message_id,
*args,
**kwargs
)
For the documentation of the arguments, please see :meth:`telegram.Message.copy`.
.. versionchanged:: 20.8
Raises :exc:`TypeError` if :attr:`message` is not accessible.
Returns:
:class:`telegram.MessageId`: On success, returns the MessageId of the sent message.
Raises:
:exc:`TypeError` if :attr:`message` is not accessible.
"""
return await self._get_message(action="copy").copy(
chat_id=chat_id,
caption=caption,
parse_mode=parse_mode,
video_start_timestamp=video_start_timestamp,
caption_entities=caption_entities,
disable_notification=disable_notification,
reply_to_message_id=reply_to_message_id,
allow_sending_without_reply=allow_sending_without_reply,
reply_markup=reply_markup,
read_timeout=read_timeout,
write_timeout=write_timeout,
connect_timeout=connect_timeout,
pool_timeout=pool_timeout,
api_kwargs=api_kwargs,
protect_content=protect_content,
message_thread_id=message_thread_id,
reply_parameters=reply_parameters,
show_caption_above_media=show_caption_above_media,
allow_paid_broadcast=allow_paid_broadcast,
)
MAX_ANSWER_TEXT_LENGTH: Final[int] = (
constants.CallbackQueryLimit.ANSWER_CALLBACK_QUERY_TEXT_LENGTH
)
"""
:const:`telegram.constants.CallbackQueryLimit.ANSWER_CALLBACK_QUERY_TEXT_LENGTH`
.. versionadded:: 13.2
"""

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,247 @@
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2025
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser Public License for more details.
#
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains the class which represents a Telegram ChatAdministratorRights."""
from typing import Optional
from telegram._telegramobject import TelegramObject
from telegram._utils.types import JSONDict
class ChatAdministratorRights(TelegramObject):
"""Represents the rights of an administrator in a chat.
Objects of this class are comparable in terms of equality. Two objects of this class are
considered equal, if their :attr:`is_anonymous`, :attr:`can_manage_chat`,
:attr:`can_delete_messages`, :attr:`can_manage_video_chats`, :attr:`can_restrict_members`,
:attr:`can_promote_members`, :attr:`can_change_info`, :attr:`can_invite_users`,
:attr:`can_post_messages`, :attr:`can_edit_messages`, :attr:`can_pin_messages`,
:attr:`can_manage_topics`, :attr:`can_post_stories`, :attr:`can_delete_stories`, and
:attr:`can_edit_stories` are equal.
.. versionadded:: 20.0
.. versionchanged:: 20.0
:attr:`can_manage_topics` is considered as well when comparing objects of
this type in terms of equality.
.. versionchanged:: 20.6
:attr:`can_post_stories`, :attr:`can_edit_stories`, and :attr:`can_delete_stories` are
considered as well when comparing objects of this type in terms of equality.
.. versionchanged:: 21.1
As of this version, :attr:`can_post_stories`, :attr:`can_edit_stories`,
and :attr:`can_delete_stories` is now required. Thus, the order of arguments had to be
changed.
Args:
is_anonymous (:obj:`bool`): :obj:`True`, if the user's presence in the chat is hidden.
can_manage_chat (:obj:`bool`): :obj:`True`, if the administrator can access the chat event
log, get boost list, see hidden supergroup and channel members, report spam messages
and ignore slow mode. Implied by any other administrator privilege.
can_delete_messages (:obj:`bool`): :obj:`True`, if the administrator can delete messages of
other users.
can_manage_video_chats (:obj:`bool`): :obj:`True`, if the administrator can manage video
chats.
can_restrict_members (:obj:`bool`): :obj:`True`, if the administrator can restrict, ban or
unban chat members, or access supergroup statistics.
can_promote_members (:obj:`bool`): :obj:`True`, if the administrator can add new
administrators with a subset of their own privileges or demote administrators
that they have promoted, directly or indirectly (promoted by administrators that
were appointed by the user).
can_change_info (:obj:`bool`): :obj:`True`, if the user is allowed to change the chat title
, photo and other settings.
can_invite_users (:obj:`bool`): :obj:`True`, if the user is allowed to invite new users to
the chat.
can_post_messages (:obj:`bool`, optional): :obj:`True`, if the administrator can post
messages in the channel, or access channel statistics; for channels only.
can_edit_messages (:obj:`bool`, optional): :obj:`True`, if the administrator can edit
messages of other users and can pin messages; for channels only.
can_pin_messages (:obj:`bool`, optional): :obj:`True`, if the user is allowed to pin
messages; for groups and supergroups only.
can_post_stories (:obj:`bool`): :obj:`True`, if the administrator can post
stories to the chat.
.. versionadded:: 20.6
.. versionchanged:: 21.0
|non_optional_story_argument|
can_edit_stories (:obj:`bool`): :obj:`True`, if the administrator can edit stories posted
by other users, post stories to the chat page, pin chat stories, and access the chat's
story archive
.. versionadded:: 20.6
.. versionchanged:: 21.0
|non_optional_story_argument|
can_delete_stories (:obj:`bool`): :obj:`True`, if the administrator can delete
stories posted by other users.
.. versionadded:: 20.6
.. versionchanged:: 21.0
|non_optional_story_argument|
can_manage_topics (:obj:`bool`, optional): :obj:`True`, if the user is allowed
to create, rename, close, and reopen forum topics; for supergroups only.
.. versionadded:: 20.0
Attributes:
is_anonymous (:obj:`bool`): :obj:`True`, if the user's presence in the chat is hidden.
can_manage_chat (:obj:`bool`): :obj:`True`, if the administrator can access the chat event
log, get boost list, see hidden supergroup and channel members, report spam messages
and ignore slow mode. Implied by any other administrator privilege.
can_delete_messages (:obj:`bool`): :obj:`True`, if the administrator can delete messages of
other users.
can_manage_video_chats (:obj:`bool`): :obj:`True`, if the administrator can manage video
chats.
can_restrict_members (:obj:`bool`): :obj:`True`, if the administrator can restrict, ban or
unban chat members, or access supergroup statistics.
can_promote_members (:obj:`bool`): :obj:`True`, if the administrator can add new
administrators with a subset of their own privileges or demote administrators that he
has promoted, directly or indirectly (promoted by administrators that were appointed by
the user.)
can_change_info (:obj:`bool`): :obj:`True`, if the user is allowed to change the chat title
,photo and other settings.
can_invite_users (:obj:`bool`): :obj:`True`, if the user is allowed to invite new users to
the chat.
can_post_messages (:obj:`bool`): Optional. :obj:`True`, if the administrator can post
messages in the channel, or access channel statistics; for channels only.
can_edit_messages (:obj:`bool`): Optional. :obj:`True`, if the administrator can edit
messages of other users and can pin messages; for channels only.
can_pin_messages (:obj:`bool`): Optional. :obj:`True`, if the user is allowed to pin
messages; for groups and supergroups only.
can_post_stories (:obj:`bool`): :obj:`True`, if the administrator can post
stories to the chat.
.. versionadded:: 20.6
.. versionchanged:: 21.0
|non_optional_story_argument|
can_edit_stories (:obj:`bool`): :obj:`True`, if the administrator can edit stories posted
by other users, post stories to the chat page, pin chat stories, and access the chat's
story archive
.. versionadded:: 20.6
.. versionchanged:: 21.0
|non_optional_story_argument|
can_delete_stories (:obj:`bool`): :obj:`True`, if the administrator can delete
stories posted by other users.
.. versionadded:: 20.6
.. versionchanged:: 21.0
|non_optional_story_argument|
can_manage_topics (:obj:`bool`): Optional. :obj:`True`, if the user is allowed
to create, rename, close, and reopen forum topics; for supergroups only.
.. versionadded:: 20.0
"""
__slots__ = (
"can_change_info",
"can_delete_messages",
"can_delete_stories",
"can_edit_messages",
"can_edit_stories",
"can_invite_users",
"can_manage_chat",
"can_manage_topics",
"can_manage_video_chats",
"can_pin_messages",
"can_post_messages",
"can_post_stories",
"can_promote_members",
"can_restrict_members",
"is_anonymous",
)
def __init__(
self,
is_anonymous: bool,
can_manage_chat: bool,
can_delete_messages: bool,
can_manage_video_chats: bool,
can_restrict_members: bool,
can_promote_members: bool,
can_change_info: bool,
can_invite_users: bool,
can_post_stories: bool,
can_edit_stories: bool,
can_delete_stories: bool,
can_post_messages: Optional[bool] = None,
can_edit_messages: Optional[bool] = None,
can_pin_messages: Optional[bool] = None,
can_manage_topics: Optional[bool] = None,
*,
api_kwargs: Optional[JSONDict] = None,
) -> None:
super().__init__(api_kwargs=api_kwargs)
# Required
self.is_anonymous: bool = is_anonymous
self.can_manage_chat: bool = can_manage_chat
self.can_delete_messages: bool = can_delete_messages
self.can_manage_video_chats: bool = can_manage_video_chats
self.can_restrict_members: bool = can_restrict_members
self.can_promote_members: bool = can_promote_members
self.can_change_info: bool = can_change_info
self.can_invite_users: bool = can_invite_users
self.can_post_stories: bool = can_post_stories
self.can_edit_stories: bool = can_edit_stories
self.can_delete_stories: bool = can_delete_stories
# Optionals
self.can_post_messages: Optional[bool] = can_post_messages
self.can_edit_messages: Optional[bool] = can_edit_messages
self.can_pin_messages: Optional[bool] = can_pin_messages
self.can_manage_topics: Optional[bool] = can_manage_topics
self._id_attrs = (
self.is_anonymous,
self.can_manage_chat,
self.can_delete_messages,
self.can_manage_video_chats,
self.can_restrict_members,
self.can_promote_members,
self.can_change_info,
self.can_invite_users,
self.can_post_messages,
self.can_edit_messages,
self.can_pin_messages,
self.can_manage_topics,
self.can_post_stories,
self.can_edit_stories,
self.can_delete_stories,
)
self._freeze()
@classmethod
def all_rights(cls) -> "ChatAdministratorRights":
"""
This method returns the :class:`ChatAdministratorRights` object with all attributes set to
:obj:`True`. This is e.g. useful when changing the bot's default administrator rights with
:meth:`telegram.Bot.set_my_default_administrator_rights`.
.. versionadded:: 20.0
"""
return cls(*(True,) * len(cls.__slots__))
@classmethod
def no_rights(cls) -> "ChatAdministratorRights":
"""
This method returns the :class:`ChatAdministratorRights` object with all attributes set to
:obj:`False`.
.. versionadded:: 20.0
"""
return cls(*(False,) * len(cls.__slots__))

View File

@@ -0,0 +1,532 @@
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2025
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser Public License for more details.
#
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains objects related to chat backgrounds."""
from collections.abc import Sequence
from typing import TYPE_CHECKING, Final, Optional
from telegram import constants
from telegram._files.document import Document
from telegram._telegramobject import TelegramObject
from telegram._utils import enum
from telegram._utils.argumentparsing import de_json_optional, parse_sequence_arg
from telegram._utils.types import JSONDict
if TYPE_CHECKING:
from telegram import Bot
class BackgroundFill(TelegramObject):
"""Base class for Telegram BackgroundFill Objects. It can be one of:
* :class:`telegram.BackgroundFillSolid`
* :class:`telegram.BackgroundFillGradient`
* :class:`telegram.BackgroundFillFreeformGradient`
Objects of this class are comparable in terms of equality. Two objects of this class are
considered equal, if their :attr:`type` is equal.
.. versionadded:: 21.2
Args:
type (:obj:`str`): Type of the background fill. Can be one of:
:attr:`~telegram.BackgroundFill.SOLID`, :attr:`~telegram.BackgroundFill.GRADIENT`
or :attr:`~telegram.BackgroundFill.FREEFORM_GRADIENT`.
Attributes:
type (:obj:`str`): Type of the background fill. Can be one of:
:attr:`~telegram.BackgroundFill.SOLID`, :attr:`~telegram.BackgroundFill.GRADIENT`
or :attr:`~telegram.BackgroundFill.FREEFORM_GRADIENT`.
"""
__slots__ = ("type",)
SOLID: Final[constants.BackgroundFillType] = constants.BackgroundFillType.SOLID
""":const:`telegram.constants.BackgroundFillType.SOLID`"""
GRADIENT: Final[constants.BackgroundFillType] = constants.BackgroundFillType.GRADIENT
""":const:`telegram.constants.BackgroundFillType.GRADIENT`"""
FREEFORM_GRADIENT: Final[constants.BackgroundFillType] = (
constants.BackgroundFillType.FREEFORM_GRADIENT
)
""":const:`telegram.constants.BackgroundFillType.FREEFORM_GRADIENT`"""
def __init__(
self,
type: str, # pylint: disable=redefined-builtin
*,
api_kwargs: Optional[JSONDict] = None,
):
super().__init__(api_kwargs=api_kwargs)
# Required by all subclasses
self.type: str = enum.get_member(constants.BackgroundFillType, type, type)
self._id_attrs = (self.type,)
self._freeze()
@classmethod
def de_json(cls, data: JSONDict, bot: Optional["Bot"] = None) -> "BackgroundFill":
"""See :meth:`telegram.TelegramObject.de_json`."""
data = cls._parse_data(data)
_class_mapping: dict[str, type[BackgroundFill]] = {
cls.SOLID: BackgroundFillSolid,
cls.GRADIENT: BackgroundFillGradient,
cls.FREEFORM_GRADIENT: BackgroundFillFreeformGradient,
}
if cls is BackgroundFill and data.get("type") in _class_mapping:
return _class_mapping[data.pop("type")].de_json(data=data, bot=bot)
return super().de_json(data=data, bot=bot)
class BackgroundFillSolid(BackgroundFill):
"""
The background is filled using the selected color.
Objects of this class are comparable in terms of equality. Two objects of this class are
considered equal, if their :attr:`color` is equal.
.. versionadded:: 21.2
Args:
color (:obj:`int`): The color of the background fill in the `RGB24` format.
Attributes:
type (:obj:`str`): Type of the background fill. Always
:attr:`~telegram.BackgroundFill.SOLID`.
color (:obj:`int`): The color of the background fill in the `RGB24` format.
"""
__slots__ = ("color",)
def __init__(
self,
color: int,
*,
api_kwargs: Optional[JSONDict] = None,
):
super().__init__(type=self.SOLID, api_kwargs=api_kwargs)
with self._unfrozen():
self.color: int = color
self._id_attrs = (self.color,)
class BackgroundFillGradient(BackgroundFill):
"""
The background is a gradient fill.
Objects of this class are comparable in terms of equality. Two objects of this class are
considered equal, if their :attr:`top_color`, :attr:`bottom_color`
and :attr:`rotation_angle` are equal.
.. versionadded:: 21.2
Args:
top_color (:obj:`int`): Top color of the gradient in the `RGB24` format.
bottom_color (:obj:`int`): Bottom color of the gradient in the `RGB24` format.
rotation_angle (:obj:`int`): Clockwise rotation angle of the background
fill in degrees;
0-:tg-const:`telegram.constants.BackgroundFillLimit.MAX_ROTATION_ANGLE`.
Attributes:
type (:obj:`str`): Type of the background fill. Always
:attr:`~telegram.BackgroundFill.GRADIENT`.
top_color (:obj:`int`): Top color of the gradient in the `RGB24` format.
bottom_color (:obj:`int`): Bottom color of the gradient in the `RGB24` format.
rotation_angle (:obj:`int`): Clockwise rotation angle of the background
fill in degrees;
0-:tg-const:`telegram.constants.BackgroundFillLimit.MAX_ROTATION_ANGLE`.
"""
__slots__ = ("bottom_color", "rotation_angle", "top_color")
def __init__(
self,
top_color: int,
bottom_color: int,
rotation_angle: int,
*,
api_kwargs: Optional[JSONDict] = None,
):
super().__init__(type=self.GRADIENT, api_kwargs=api_kwargs)
with self._unfrozen():
self.top_color: int = top_color
self.bottom_color: int = bottom_color
self.rotation_angle: int = rotation_angle
self._id_attrs = (self.top_color, self.bottom_color, self.rotation_angle)
class BackgroundFillFreeformGradient(BackgroundFill):
"""
The background is a freeform gradient that rotates after every message in the chat.
Objects of this class are comparable in terms of equality. Two objects of this class are
considered equal, if their :attr:`colors` is equal.
.. versionadded:: 21.2
Args:
colors (Sequence[:obj:`int`]): A list of the 3 or 4 base colors that are used to
generate the freeform gradient in the `RGB24` format
Attributes:
type (:obj:`str`): Type of the background fill. Always
:attr:`~telegram.BackgroundFill.FREEFORM_GRADIENT`.
colors (Sequence[:obj:`int`]): A list of the 3 or 4 base colors that are used to
generate the freeform gradient in the `RGB24` format
"""
__slots__ = ("colors",)
def __init__(
self,
colors: Sequence[int],
*,
api_kwargs: Optional[JSONDict] = None,
):
super().__init__(type=self.FREEFORM_GRADIENT, api_kwargs=api_kwargs)
with self._unfrozen():
self.colors: tuple[int, ...] = parse_sequence_arg(colors)
self._id_attrs = (self.colors,)
class BackgroundType(TelegramObject):
"""Base class for Telegram BackgroundType Objects. It can be one of:
* :class:`telegram.BackgroundTypeFill`
* :class:`telegram.BackgroundTypeWallpaper`
* :class:`telegram.BackgroundTypePattern`
* :class:`telegram.BackgroundTypeChatTheme`.
Objects of this class are comparable in terms of equality. Two objects of this class are
considered equal, if their :attr:`type` is equal.
.. versionadded:: 21.2
Args:
type (:obj:`str`): Type of the background. Can be one of:
:attr:`~telegram.BackgroundType.FILL`, :attr:`~telegram.BackgroundType.WALLPAPER`
:attr:`~telegram.BackgroundType.PATTERN` or
:attr:`~telegram.BackgroundType.CHAT_THEME`.
Attributes:
type (:obj:`str`): Type of the background. Can be one of:
:attr:`~telegram.BackgroundType.FILL`, :attr:`~telegram.BackgroundType.WALLPAPER`
:attr:`~telegram.BackgroundType.PATTERN` or
:attr:`~telegram.BackgroundType.CHAT_THEME`.
"""
__slots__ = ("type",)
FILL: Final[constants.BackgroundTypeType] = constants.BackgroundTypeType.FILL
""":const:`telegram.constants.BackgroundTypeType.FILL`"""
WALLPAPER: Final[constants.BackgroundTypeType] = constants.BackgroundTypeType.WALLPAPER
""":const:`telegram.constants.BackgroundTypeType.WALLPAPER`"""
PATTERN: Final[constants.BackgroundTypeType] = constants.BackgroundTypeType.PATTERN
""":const:`telegram.constants.BackgroundTypeType.PATTERN`"""
CHAT_THEME: Final[constants.BackgroundTypeType] = constants.BackgroundTypeType.CHAT_THEME
""":const:`telegram.constants.BackgroundTypeType.CHAT_THEME`"""
def __init__(
self,
type: str, # pylint: disable=redefined-builtin
*,
api_kwargs: Optional[JSONDict] = None,
):
super().__init__(api_kwargs=api_kwargs)
# Required by all subclasses
self.type: str = enum.get_member(constants.BackgroundTypeType, type, type)
self._id_attrs = (self.type,)
self._freeze()
@classmethod
def de_json(cls, data: JSONDict, bot: Optional["Bot"] = None) -> "BackgroundType":
"""See :meth:`telegram.TelegramObject.de_json`."""
data = cls._parse_data(data)
_class_mapping: dict[str, type[BackgroundType]] = {
cls.FILL: BackgroundTypeFill,
cls.WALLPAPER: BackgroundTypeWallpaper,
cls.PATTERN: BackgroundTypePattern,
cls.CHAT_THEME: BackgroundTypeChatTheme,
}
if cls is BackgroundType and data.get("type") in _class_mapping:
return _class_mapping[data.pop("type")].de_json(data=data, bot=bot)
if "fill" in data:
data["fill"] = de_json_optional(data.get("fill"), BackgroundFill, bot)
if "document" in data:
data["document"] = de_json_optional(data.get("document"), Document, bot)
return super().de_json(data=data, bot=bot)
class BackgroundTypeFill(BackgroundType):
"""
The background is automatically filled based on the selected colors.
Objects of this class are comparable in terms of equality. Two objects of this class are
considered equal, if their :attr:`fill` and :attr:`dark_theme_dimming` are equal.
.. versionadded:: 21.2
Args:
fill (:class:`telegram.BackgroundFill`): The background fill.
dark_theme_dimming (:obj:`int`): Dimming of the background in dark themes, as a
percentage;
0-:tg-const:`telegram.constants.BackgroundTypeLimit.MAX_DIMMING`.
Attributes:
type (:obj:`str`): Type of the background. Always
:attr:`~telegram.BackgroundType.FILL`.
fill (:class:`telegram.BackgroundFill`): The background fill.
dark_theme_dimming (:obj:`int`): Dimming of the background in dark themes, as a
percentage;
0-:tg-const:`telegram.constants.BackgroundTypeLimit.MAX_DIMMING`.
"""
__slots__ = ("dark_theme_dimming", "fill")
def __init__(
self,
fill: BackgroundFill,
dark_theme_dimming: int,
*,
api_kwargs: Optional[JSONDict] = None,
):
super().__init__(type=self.FILL, api_kwargs=api_kwargs)
with self._unfrozen():
self.fill: BackgroundFill = fill
self.dark_theme_dimming: int = dark_theme_dimming
self._id_attrs = (self.fill, self.dark_theme_dimming)
class BackgroundTypeWallpaper(BackgroundType):
"""
The background is a wallpaper in the `JPEG` format.
Objects of this class are comparable in terms of equality. Two objects of this class are
considered equal, if their :attr:`document` and :attr:`dark_theme_dimming` are equal.
.. versionadded:: 21.2
Args:
document (:class:`telegram.Document`): Document with the wallpaper
dark_theme_dimming (:obj:`int`): Dimming of the background in dark themes, as a
percentage;
0-:tg-const:`telegram.constants.BackgroundTypeLimit.MAX_DIMMING`.
is_blurred (:obj:`bool`, optional): :obj:`True`, if the wallpaper is downscaled to fit
in a 450x450 square and then box-blurred with radius 12
is_moving (:obj:`bool`, optional): :obj:`True`, if the background moves slightly
when the device is tilted
Attributes:
type (:obj:`str`): Type of the background. Always
:attr:`~telegram.BackgroundType.WALLPAPER`.
document (:class:`telegram.Document`): Document with the wallpaper
dark_theme_dimming (:obj:`int`): Dimming of the background in dark themes, as a
percentage;
0-:tg-const:`telegram.constants.BackgroundTypeLimit.MAX_DIMMING`.
is_blurred (:obj:`bool`): Optional. :obj:`True`, if the wallpaper is downscaled to fit
in a 450x450 square and then box-blurred with radius 12
is_moving (:obj:`bool`): Optional. :obj:`True`, if the background moves slightly
when the device is tilted
"""
__slots__ = ("dark_theme_dimming", "document", "is_blurred", "is_moving")
def __init__(
self,
document: Document,
dark_theme_dimming: int,
is_blurred: Optional[bool] = None,
is_moving: Optional[bool] = None,
*,
api_kwargs: Optional[JSONDict] = None,
):
super().__init__(type=self.WALLPAPER, api_kwargs=api_kwargs)
with self._unfrozen():
# Required
self.document: Document = document
self.dark_theme_dimming: int = dark_theme_dimming
# Optionals
self.is_blurred: Optional[bool] = is_blurred
self.is_moving: Optional[bool] = is_moving
self._id_attrs = (self.document, self.dark_theme_dimming)
class BackgroundTypePattern(BackgroundType):
"""
The background is a ``.PNG`` or ``.TGV`` (gzipped subset of ``SVG`` with ``MIME`` type
``"application/x-tgwallpattern"``) pattern to be combined with the background fill
chosen by the user.
Objects of this class are comparable in terms of equality. Two objects of this class are
considered equal, if their :attr:`document` and :attr:`fill` and :attr:`intensity` are equal.
.. versionadded:: 21.2
Args:
document (:class:`telegram.Document`): Document with the pattern.
fill (:class:`telegram.BackgroundFill`): The background fill that is combined with
the pattern.
intensity (:obj:`int`): Intensity of the pattern when it is shown above the filled
background;
0-:tg-const:`telegram.constants.BackgroundTypeLimit.MAX_INTENSITY`.
is_inverted (:obj:`int`, optional): :obj:`True`, if the background fill must be applied
only to the pattern itself. All other pixels are black in this case. For dark
themes only.
is_moving (:obj:`bool`, optional): :obj:`True`, if the background moves slightly
when the device is tilted.
Attributes:
type (:obj:`str`): Type of the background. Always
:attr:`~telegram.BackgroundType.PATTERN`.
document (:class:`telegram.Document`): Document with the pattern.
fill (:class:`telegram.BackgroundFill`): The background fill that is combined with
the pattern.
intensity (:obj:`int`): Intensity of the pattern when it is shown above the filled
background;
0-:tg-const:`telegram.constants.BackgroundTypeLimit.MAX_INTENSITY`.
is_inverted (:obj:`int`): Optional. :obj:`True`, if the background fill must be applied
only to the pattern itself. All other pixels are black in this case. For dark
themes only.
is_moving (:obj:`bool`): Optional. :obj:`True`, if the background moves slightly
when the device is tilted.
"""
__slots__ = (
"document",
"fill",
"intensity",
"is_inverted",
"is_moving",
)
def __init__(
self,
document: Document,
fill: BackgroundFill,
intensity: int,
is_inverted: Optional[bool] = None,
is_moving: Optional[bool] = None,
*,
api_kwargs: Optional[JSONDict] = None,
):
super().__init__(type=self.PATTERN, api_kwargs=api_kwargs)
with self._unfrozen():
# Required
self.document: Document = document
self.fill: BackgroundFill = fill
self.intensity: int = intensity
# Optionals
self.is_inverted: Optional[bool] = is_inverted
self.is_moving: Optional[bool] = is_moving
self._id_attrs = (self.document, self.fill, self.intensity)
class BackgroundTypeChatTheme(BackgroundType):
"""
The background is taken directly from a built-in chat theme.
Objects of this class are comparable in terms of equality. Two objects of this class are
considered equal, if their :attr:`theme_name` is equal.
.. versionadded:: 21.2
Args:
theme_name (:obj:`str`): Name of the chat theme, which is usually an emoji.
Attributes:
type (:obj:`str`): Type of the background. Always
:attr:`~telegram.BackgroundType.CHAT_THEME`.
theme_name (:obj:`str`): Name of the chat theme, which is usually an emoji.
"""
__slots__ = ("theme_name",)
def __init__(
self,
theme_name: str,
*,
api_kwargs: Optional[JSONDict] = None,
):
super().__init__(type=self.CHAT_THEME, api_kwargs=api_kwargs)
with self._unfrozen():
self.theme_name: str = theme_name
self._id_attrs = (self.theme_name,)
class ChatBackground(TelegramObject):
"""
This object represents a chat background.
Objects of this class are comparable in terms of equality. Two objects of this class are
considered equal, if their :attr:`type` is equal.
.. versionadded:: 21.2
Args:
type (:class:`telegram.BackgroundType`): Type of the background.
Attributes:
type (:class:`telegram.BackgroundType`): Type of the background.
"""
__slots__ = ("type",)
def __init__(
self,
type: BackgroundType, # pylint: disable=redefined-builtin
*,
api_kwargs: Optional[JSONDict] = None,
):
super().__init__(api_kwargs=api_kwargs)
self.type: BackgroundType = type
self._id_attrs = (self.type,)
self._freeze()
@classmethod
def de_json(cls, data: JSONDict, bot: Optional["Bot"] = None) -> "ChatBackground":
"""See :meth:`telegram.TelegramObject.de_json`."""
data = cls._parse_data(data)
data["type"] = de_json_optional(data.get("type"), BackgroundType, bot)
return super().de_json(data=data, bot=bot)

View File

@@ -0,0 +1,439 @@
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2025
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser Public License for more details.
#
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains the classes that represent Telegram ChatBoosts."""
import datetime as dtm
from collections.abc import Sequence
from typing import TYPE_CHECKING, Final, Optional
from telegram import constants
from telegram._chat import Chat
from telegram._telegramobject import TelegramObject
from telegram._user import User
from telegram._utils import enum
from telegram._utils.argumentparsing import de_json_optional, de_list_optional, parse_sequence_arg
from telegram._utils.datetime import extract_tzinfo_from_defaults, from_timestamp
from telegram._utils.types import JSONDict
if TYPE_CHECKING:
from telegram import Bot
class ChatBoostAdded(TelegramObject):
"""
This object represents a service message about a user boosting a chat.
Objects of this class are comparable in terms of equality.
Two objects of this class are considered equal, if their
:attr:`boost_count` are equal.
.. versionadded:: 21.0
Args:
boost_count (:obj:`int`): Number of boosts added by the user.
Attributes:
boost_count (:obj:`int`): Number of boosts added by the user.
"""
__slots__ = ("boost_count",)
def __init__(
self,
boost_count: int,
*,
api_kwargs: Optional[JSONDict] = None,
) -> None:
super().__init__(api_kwargs=api_kwargs)
self.boost_count: int = boost_count
self._id_attrs = (self.boost_count,)
self._freeze()
class ChatBoostSource(TelegramObject):
"""
Base class for Telegram ChatBoostSource objects. It can be one of:
* :class:`telegram.ChatBoostSourcePremium`
* :class:`telegram.ChatBoostSourceGiftCode`
* :class:`telegram.ChatBoostSourceGiveaway`
Objects of this class are comparable in terms of equality. Two objects of this class are
considered equal, if their :attr:`source` is equal.
.. versionadded:: 20.8
Args:
source (:obj:`str`): The source of the chat boost. Can be one of:
:attr:`~telegram.ChatBoostSource.PREMIUM`, :attr:`~telegram.ChatBoostSource.GIFT_CODE`,
or :attr:`~telegram.ChatBoostSource.GIVEAWAY`.
Attributes:
source (:obj:`str`): The source of the chat boost. Can be one of:
:attr:`~telegram.ChatBoostSource.PREMIUM`, :attr:`~telegram.ChatBoostSource.GIFT_CODE`,
or :attr:`~telegram.ChatBoostSource.GIVEAWAY`.
"""
__slots__ = ("source",)
PREMIUM: Final[str] = constants.ChatBoostSources.PREMIUM
""":const:`telegram.constants.ChatBoostSources.PREMIUM`"""
GIFT_CODE: Final[str] = constants.ChatBoostSources.GIFT_CODE
""":const:`telegram.constants.ChatBoostSources.GIFT_CODE`"""
GIVEAWAY: Final[str] = constants.ChatBoostSources.GIVEAWAY
""":const:`telegram.constants.ChatBoostSources.GIVEAWAY`"""
def __init__(self, source: str, *, api_kwargs: Optional[JSONDict] = None):
super().__init__(api_kwargs=api_kwargs)
# Required by all subclasses:
self.source: str = enum.get_member(constants.ChatBoostSources, source, source)
self._id_attrs = (self.source,)
self._freeze()
@classmethod
def de_json(cls, data: JSONDict, bot: Optional["Bot"] = None) -> "ChatBoostSource":
"""See :meth:`telegram.TelegramObject.de_json`."""
data = cls._parse_data(data)
_class_mapping: dict[str, type[ChatBoostSource]] = {
cls.PREMIUM: ChatBoostSourcePremium,
cls.GIFT_CODE: ChatBoostSourceGiftCode,
cls.GIVEAWAY: ChatBoostSourceGiveaway,
}
if cls is ChatBoostSource and data.get("source") in _class_mapping:
return _class_mapping[data.pop("source")].de_json(data=data, bot=bot)
if "user" in data:
data["user"] = de_json_optional(data.get("user"), User, bot)
return super().de_json(data=data, bot=bot)
class ChatBoostSourcePremium(ChatBoostSource):
"""
The boost was obtained by subscribing to Telegram Premium or by gifting a Telegram Premium
subscription to another user.
.. versionadded:: 20.8
Args:
user (:class:`telegram.User`): User that boosted the chat.
Attributes:
source (:obj:`str`): The source of the chat boost. Always
:attr:`~telegram.ChatBoostSource.PREMIUM`.
user (:class:`telegram.User`): User that boosted the chat.
"""
__slots__ = ("user",)
def __init__(self, user: User, *, api_kwargs: Optional[JSONDict] = None):
super().__init__(source=self.PREMIUM, api_kwargs=api_kwargs)
with self._unfrozen():
self.user: User = user
class ChatBoostSourceGiftCode(ChatBoostSource):
"""
The boost was obtained by the creation of Telegram Premium gift codes to boost a chat. Each
such code boosts the chat 4 times for the duration of the corresponding Telegram Premium
subscription.
.. versionadded:: 20.8
Args:
user (:class:`telegram.User`): User for which the gift code was created.
Attributes:
source (:obj:`str`): The source of the chat boost. Always
:attr:`~telegram.ChatBoostSource.GIFT_CODE`.
user (:class:`telegram.User`): User for which the gift code was created.
"""
__slots__ = ("user",)
def __init__(self, user: User, *, api_kwargs: Optional[JSONDict] = None):
super().__init__(source=self.GIFT_CODE, api_kwargs=api_kwargs)
with self._unfrozen():
self.user: User = user
class ChatBoostSourceGiveaway(ChatBoostSource):
"""
The boost was obtained by the creation of a Telegram Premium giveaway or a Telegram Star.
This boosts the chat 4 times for the duration of the corresponding Telegram Premium
subscription for Telegram Premium giveaways and :attr:`prize_star_count` / 500 times for
one year for Telegram Star giveaways.
.. versionadded:: 20.8
Args:
giveaway_message_id (:obj:`int`): Identifier of a message in the chat with the giveaway;
the message could have been deleted already. May be 0 if the message isn't sent yet.
user (:class:`telegram.User`, optional): User that won the prize in the giveaway if any;
for Telegram Premium giveaways only.
prize_star_count (:obj:`int`, optional): The number of Telegram Stars to be split between
giveaway winners; for Telegram Star giveaways only.
.. versionadded:: 21.6
is_unclaimed (:obj:`bool`, optional): :obj:`True`, if the giveaway was completed, but
there was no user to win the prize.
Attributes:
source (:obj:`str`): Source of the boost. Always
:attr:`~telegram.ChatBoostSource.GIVEAWAY`.
giveaway_message_id (:obj:`int`): Identifier of a message in the chat with the giveaway;
the message could have been deleted already. May be 0 if the message isn't sent yet.
user (:class:`telegram.User`): Optional. User that won the prize in the giveaway if any.
prize_star_count (:obj:`int`): Optional. The number of Telegram Stars to be split between
giveaway winners; for Telegram Star giveaways only.
.. versionadded:: 21.6
is_unclaimed (:obj:`bool`): Optional. :obj:`True`, if the giveaway was completed, but
there was no user to win the prize.
"""
__slots__ = ("giveaway_message_id", "is_unclaimed", "prize_star_count", "user")
def __init__(
self,
giveaway_message_id: int,
user: Optional[User] = None,
is_unclaimed: Optional[bool] = None,
prize_star_count: Optional[int] = None,
*,
api_kwargs: Optional[JSONDict] = None,
):
super().__init__(source=self.GIVEAWAY, api_kwargs=api_kwargs)
with self._unfrozen():
self.giveaway_message_id: int = giveaway_message_id
self.user: Optional[User] = user
self.prize_star_count: Optional[int] = prize_star_count
self.is_unclaimed: Optional[bool] = is_unclaimed
class ChatBoost(TelegramObject):
"""
This object contains information about a chat boost.
Objects of this class are comparable in terms of equality. Two objects of this class are
considered equal, if their :attr:`boost_id`, :attr:`add_date`, :attr:`expiration_date`,
and :attr:`source` are equal.
.. versionadded:: 20.8
Args:
boost_id (:obj:`str`): Unique identifier of the boost.
add_date (:obj:`datetime.datetime`): Point in time when the chat was boosted.
expiration_date (:obj:`datetime.datetime`): Point in time when the boost
will automatically expire, unless the booster's Telegram Premium subscription is
prolonged.
source (:class:`telegram.ChatBoostSource`): Source of the added boost.
Attributes:
boost_id (:obj:`str`): Unique identifier of the boost.
add_date (:obj:`datetime.datetime`): Point in time when the chat was boosted.
|datetime_localization|
expiration_date (:obj:`datetime.datetime`): Point in time when the boost
will automatically expire, unless the booster's Telegram Premium subscription is
prolonged. |datetime_localization|
source (:class:`telegram.ChatBoostSource`): Source of the added boost.
"""
__slots__ = ("add_date", "boost_id", "expiration_date", "source")
def __init__(
self,
boost_id: str,
add_date: dtm.datetime,
expiration_date: dtm.datetime,
source: ChatBoostSource,
*,
api_kwargs: Optional[JSONDict] = None,
):
super().__init__(api_kwargs=api_kwargs)
self.boost_id: str = boost_id
self.add_date: dtm.datetime = add_date
self.expiration_date: dtm.datetime = expiration_date
self.source: ChatBoostSource = source
self._id_attrs = (self.boost_id, self.add_date, self.expiration_date, self.source)
self._freeze()
@classmethod
def de_json(cls, data: JSONDict, bot: Optional["Bot"] = None) -> "ChatBoost":
"""See :meth:`telegram.TelegramObject.de_json`."""
data = cls._parse_data(data)
data["source"] = de_json_optional(data.get("source"), ChatBoostSource, bot)
loc_tzinfo = extract_tzinfo_from_defaults(bot)
data["add_date"] = from_timestamp(data.get("add_date"), tzinfo=loc_tzinfo)
data["expiration_date"] = from_timestamp(data.get("expiration_date"), tzinfo=loc_tzinfo)
return super().de_json(data=data, bot=bot)
class ChatBoostUpdated(TelegramObject):
"""This object represents a boost added to a chat or changed.
Objects of this class are comparable in terms of equality. Two objects of this class are
considered equal, if their :attr:`chat`, and :attr:`boost` are equal.
.. versionadded:: 20.8
Args:
chat (:class:`telegram.Chat`): Chat which was boosted.
boost (:class:`telegram.ChatBoost`): Information about the chat boost.
Attributes:
chat (:class:`telegram.Chat`): Chat which was boosted.
boost (:class:`telegram.ChatBoost`): Information about the chat boost.
"""
__slots__ = ("boost", "chat")
def __init__(
self,
chat: Chat,
boost: ChatBoost,
*,
api_kwargs: Optional[JSONDict] = None,
):
super().__init__(api_kwargs=api_kwargs)
self.chat: Chat = chat
self.boost: ChatBoost = boost
self._id_attrs = (self.chat.id, self.boost)
self._freeze()
@classmethod
def de_json(cls, data: JSONDict, bot: Optional["Bot"] = None) -> "ChatBoostUpdated":
"""See :meth:`telegram.TelegramObject.de_json`."""
data = cls._parse_data(data)
data["chat"] = de_json_optional(data.get("chat"), Chat, bot)
data["boost"] = de_json_optional(data.get("boost"), ChatBoost, bot)
return super().de_json(data=data, bot=bot)
class ChatBoostRemoved(TelegramObject):
"""
This object represents a boost removed from a chat.
Objects of this class are comparable in terms of equality. Two objects of this class are
considered equal, if their :attr:`chat`, :attr:`boost_id`, :attr:`remove_date`, and
:attr:`source` are equal.
Args:
chat (:class:`telegram.Chat`): Chat which was boosted.
boost_id (:obj:`str`): Unique identifier of the boost.
remove_date (:obj:`datetime.datetime`): Point in time when the boost was removed.
source (:class:`telegram.ChatBoostSource`): Source of the removed boost.
Attributes:
chat (:class:`telegram.Chat`): Chat which was boosted.
boost_id (:obj:`str`): Unique identifier of the boost.
remove_date (:obj:`datetime.datetime`): Point in time when the boost was removed.
|datetime_localization|
source (:class:`telegram.ChatBoostSource`): Source of the removed boost.
"""
__slots__ = ("boost_id", "chat", "remove_date", "source")
def __init__(
self,
chat: Chat,
boost_id: str,
remove_date: dtm.datetime,
source: ChatBoostSource,
*,
api_kwargs: Optional[JSONDict] = None,
):
super().__init__(api_kwargs=api_kwargs)
self.chat: Chat = chat
self.boost_id: str = boost_id
self.remove_date: dtm.datetime = remove_date
self.source: ChatBoostSource = source
self._id_attrs = (self.chat, self.boost_id, self.remove_date, self.source)
self._freeze()
@classmethod
def de_json(cls, data: JSONDict, bot: Optional["Bot"] = None) -> "ChatBoostRemoved":
"""See :meth:`telegram.TelegramObject.de_json`."""
data = cls._parse_data(data)
data["chat"] = de_json_optional(data.get("chat"), Chat, bot)
data["source"] = de_json_optional(data.get("source"), ChatBoostSource, bot)
loc_tzinfo = extract_tzinfo_from_defaults(bot)
data["remove_date"] = from_timestamp(data.get("remove_date"), tzinfo=loc_tzinfo)
return super().de_json(data=data, bot=bot)
class UserChatBoosts(TelegramObject):
"""This object represents a list of boosts added to a chat by a user.
Objects of this class are comparable in terms of equality. Two objects of this class are
considered equal, if their :attr:`boosts` are equal.
.. versionadded:: 20.8
Args:
boosts (Sequence[:class:`telegram.ChatBoost`]): List of boosts added to the chat by the
user.
Attributes:
boosts (tuple[:class:`telegram.ChatBoost`]): List of boosts added to the chat by the user.
"""
__slots__ = ("boosts",)
def __init__(
self,
boosts: Sequence[ChatBoost],
*,
api_kwargs: Optional[JSONDict] = None,
):
super().__init__(api_kwargs=api_kwargs)
self.boosts: tuple[ChatBoost, ...] = parse_sequence_arg(boosts)
self._id_attrs = (self.boosts,)
self._freeze()
@classmethod
def de_json(cls, data: JSONDict, bot: Optional["Bot"] = None) -> "UserChatBoosts":
"""See :meth:`telegram.TelegramObject.de_json`."""
data = cls._parse_data(data)
data["boosts"] = de_list_optional(data.get("boosts"), ChatBoost, bot)
return super().de_json(data=data, bot=bot)

View File

@@ -0,0 +1,599 @@
#!/usr/bin/env python
# pylint: disable=redefined-builtin
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2025
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser Public License for more details.
#
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents a Telegram ChatFullInfo."""
import datetime as dtm
from collections.abc import Sequence
from typing import TYPE_CHECKING, Optional, Union
from telegram._birthdate import Birthdate
from telegram._chat import Chat, _ChatBase
from telegram._chatlocation import ChatLocation
from telegram._chatpermissions import ChatPermissions
from telegram._files.chatphoto import ChatPhoto
from telegram._gifts import AcceptedGiftTypes
from telegram._reaction import ReactionType
from telegram._utils.argumentparsing import (
de_json_optional,
de_list_optional,
parse_sequence_arg,
to_timedelta,
)
from telegram._utils.datetime import (
extract_tzinfo_from_defaults,
from_timestamp,
get_timedelta_value,
)
from telegram._utils.types import JSONDict, TimePeriod
if TYPE_CHECKING:
from telegram import Bot, BusinessIntro, BusinessLocation, BusinessOpeningHours, Message
class ChatFullInfo(_ChatBase):
"""
This object contains full information about a chat.
Objects of this class are comparable in terms of equality. Two objects of this class are
considered equal, if their :attr:`~telegram.Chat.id` is equal.
.. versionadded:: 21.2
.. versionchanged:: 21.3
Explicit support for all shortcut methods known from :class:`telegram.Chat` on this
object. Previously those were only available because this class inherited from
:class:`telegram.Chat`.
.. versionremoved:: 22.3
Removed argument and attribute ``can_send_gift`` deprecated by API 9.0.
Args:
id (:obj:`int`): Unique identifier for this chat.
type (:obj:`str`): Type of chat, can be either :attr:`PRIVATE`, :attr:`GROUP`,
:attr:`SUPERGROUP` or :attr:`CHANNEL`.
accent_color_id (:obj:`int`, optional): Identifier of the
:class:`accent color <telegram.constants.AccentColor>` for the chat name and
backgrounds of the chat photo, reply header, and link preview. See `accent colors`_
for more details.
.. versionadded:: 20.8
max_reaction_count (:obj:`int`): The maximum number of reactions that can be set on a
message in the chat.
.. versionadded:: 21.2
accepted_gift_types (:class:`telegram.AcceptedGiftTypes`): Information about types of
gifts that are accepted by the chat or by the corresponding user for private chats.
.. versionadded:: 22.1
title (:obj:`str`, optional): Title, for supergroups, channels and group chats.
username (:obj:`str`, optional): Username, for private chats, supergroups and channels if
available.
first_name (:obj:`str`, optional): First name of the other party in a private chat.
last_name (:obj:`str`, optional): Last name of the other party in a private chat.
is_forum (:obj:`bool`, optional): :obj:`True`, if the supergroup chat is a forum
(has topics_ enabled).
.. versionadded:: 20.0
photo (:class:`telegram.ChatPhoto`, optional): Chat photo.
active_usernames (Sequence[:obj:`str`], optional): If set, the list of all `active chat
usernames <https://telegram.org/blog/topics-in-groups-collectible-usernames\
#collectible-usernames>`_; for private chats, supergroups and channels.
.. versionadded:: 20.0
birthdate (:class:`telegram.Birthdate`, optional): For private chats,
the date of birth of the user.
.. versionadded:: 21.1
business_intro (:class:`telegram.BusinessIntro`, optional): For private chats with
business accounts, the intro of the business.
.. versionadded:: 21.1
business_location (:class:`telegram.BusinessLocation`, optional): For private chats with
business accounts, the location of the business.
.. versionadded:: 21.1
business_opening_hours (:class:`telegram.BusinessOpeningHours`, optional): For private
chats with business accounts, the opening hours of the business.
.. versionadded:: 21.1
personal_chat (:class:`telegram.Chat`, optional): For private chats, the personal channel
of the user.
.. versionadded:: 21.1
available_reactions (Sequence[:class:`telegram.ReactionType`], optional): List of available
reactions allowed in the chat. If omitted, then all of
:const:`telegram.constants.ReactionEmoji` are allowed.
.. versionadded:: 20.8
background_custom_emoji_id (:obj:`str`, optional): Custom emoji identifier of emoji chosen
by the chat for the reply header and link preview background.
.. versionadded:: 20.8
profile_accent_color_id (:obj:`int`, optional): Identifier of the
:class:`accent color <telegram.constants.ProfileAccentColor>` for the chat's profile
background. See profile `accent colors`_ for more details.
.. versionadded:: 20.8
profile_background_custom_emoji_id (:obj:`str`, optional): Custom emoji identifier of
the emoji chosen by the chat for its profile background.
.. versionadded:: 20.8
emoji_status_custom_emoji_id (:obj:`str`, optional): Custom emoji identifier of emoji
status of the chat or the other party in a private chat.
.. versionadded:: 20.0
emoji_status_expiration_date (:class:`datetime.datetime`, optional): Expiration date of
emoji status of the chat or the other party in a private chat, as a datetime object,
if any.
|datetime_localization|
.. versionadded:: 20.5
bio (:obj:`str`, optional): Bio of the other party in a private chat.
has_private_forwards (:obj:`bool`, optional): :obj:`True`, if privacy settings of the other
party in the private chat allows to use ``tg://user?id=<user_id>`` links only in chats
with the user.
.. versionadded:: 13.9
has_restricted_voice_and_video_messages (:obj:`bool`, optional): :obj:`True`, if the
privacy settings of the other party restrict sending voice and video note messages
in the private chat.
.. versionadded:: 20.0
join_to_send_messages (:obj:`bool`, optional): :obj:`True`, if users need to join the
supergroup before they can send messages.
.. versionadded:: 20.0
join_by_request (:obj:`bool`, optional): :obj:`True`, if all users directly joining the
supergroup without using an invite link need to be approved by supergroup
administrators.
.. versionadded:: 20.0
description (:obj:`str`, optional): Description, for groups, supergroups and channel chats.
invite_link (:obj:`str`, optional): Primary invite link, for groups, supergroups and
channel.
pinned_message (:class:`telegram.Message`, optional): The most recent pinned message
(by sending date).
permissions (:class:`telegram.ChatPermissions`): Optional. Default chat member permissions,
for groups and supergroups.
slow_mode_delay (:obj:`int` | :class:`datetime.timedelta`, optional): For supergroups,
the minimum allowed delay between consecutive messages sent by each unprivileged user.
.. versionchanged:: v22.2
|time-period-input|
unrestrict_boost_count (:obj:`int`, optional): For supergroups, the minimum number of
boosts that a non-administrator user needs to add in order to ignore slow mode and chat
permissions.
.. versionadded:: 21.0
message_auto_delete_time (:obj:`int` | :class:`datetime.timedelta`, optional): The time
after which all messages sent to the chat will be automatically deleted; in seconds.
.. versionadded:: 13.4
.. versionchanged:: v22.2
|time-period-input|
has_aggressive_anti_spam_enabled (:obj:`bool`, optional): :obj:`True`, if aggressive
anti-spam checks are enabled in the supergroup. The field is only available to chat
administrators.
.. versionadded:: 20.0
has_hidden_members (:obj:`bool`, optional): :obj:`True`, if non-administrators can only
get the list of bots and administrators in the chat.
.. versionadded:: 20.0
has_protected_content (:obj:`bool`, optional): :obj:`True`, if messages from the chat can't
be forwarded to other chats.
.. versionadded:: 13.9
has_visible_history (:obj:`bool`, optional): :obj:`True`, if new chat members will have
access to old messages; available only to chat administrators.
.. versionadded:: 20.8
sticker_set_name (:obj:`str`, optional): For supergroups, name of group sticker set.
can_set_sticker_set (:obj:`bool`, optional): :obj:`True`, if the bot can change group the
sticker set.
custom_emoji_sticker_set_name (:obj:`str`, optional): For supergroups, the name of the
group's custom emoji sticker set. Custom emoji from this set can be used by all users
and bots in the group.
.. versionadded:: 21.0
linked_chat_id (:obj:`int`, optional): Unique identifier for the linked chat, i.e. the
discussion group identifier for a channel and vice versa; for supergroups and channel
chats.
location (:class:`telegram.ChatLocation`, optional): For supergroups, the location to which
the supergroup is connected.
can_send_paid_media (:obj:`bool`, optional): :obj:`True`, if paid media messages can be
sent or forwarded to the channel chat. The field is available only for channel chats.
.. versionadded:: 21.4
Attributes:
id (:obj:`int`): Unique identifier for this chat.
type (:obj:`str`): Type of chat, can be either :attr:`PRIVATE`, :attr:`GROUP`,
:attr:`SUPERGROUP` or :attr:`CHANNEL`.
accent_color_id (:obj:`int`): Optional. Identifier of the
:class:`accent color <telegram.constants.AccentColor>` for the chat name and
backgrounds of the chat photo, reply header, and link preview. See `accent colors`_
for more details.
.. versionadded:: 20.8
max_reaction_count (:obj:`int`): The maximum number of reactions that can be set on a
message in the chat.
.. versionadded:: 21.2
accepted_gift_types (:class:`telegram.AcceptedGiftTypes`): Information about types of
gifts that are accepted by the chat or by the corresponding user for private chats.
.. versionadded:: 22.1
title (:obj:`str`, optional): Title, for supergroups, channels and group chats.
username (:obj:`str`, optional): Username, for private chats, supergroups and channels if
available.
first_name (:obj:`str`, optional): First name of the other party in a private chat.
last_name (:obj:`str`, optional): Last name of the other party in a private chat.
is_forum (:obj:`bool`, optional): :obj:`True`, if the supergroup chat is a forum
(has topics_ enabled).
.. versionadded:: 20.0
photo (:class:`telegram.ChatPhoto`): Optional. Chat photo.
active_usernames (tuple[:obj:`str`]): Optional. If set, the list of all `active chat
usernames <https://telegram.org/blog/topics-in-groups-collectible-usernames\
#collectible-usernames>`_; for private chats, supergroups and channels.
This list is empty if the chat has no active usernames or this chat instance was not
obtained via :meth:`~telegram.Bot.get_chat`.
.. versionadded:: 20.0
birthdate (:class:`telegram.Birthdate`): Optional. For private chats,
the date of birth of the user.
.. versionadded:: 21.1
business_intro (:class:`telegram.BusinessIntro`): Optional. For private chats with
business accounts, the intro of the business.
.. versionadded:: 21.1
business_location (:class:`telegram.BusinessLocation`): Optional. For private chats with
business accounts, the location of the business.
.. versionadded:: 21.1
business_opening_hours (:class:`telegram.BusinessOpeningHours`): Optional. For private
chats with business accounts, the opening hours of the business.
.. versionadded:: 21.1
personal_chat (:class:`telegram.Chat`): Optional. For private chats, the personal channel
of the user.
.. versionadded:: 21.1
available_reactions (tuple[:class:`telegram.ReactionType`]): Optional. List of available
reactions allowed in the chat. If omitted, then all of
:const:`telegram.constants.ReactionEmoji` are allowed.
.. versionadded:: 20.8
background_custom_emoji_id (:obj:`str`): Optional. Custom emoji identifier of emoji chosen
by the chat for the reply header and link preview background.
.. versionadded:: 20.8
profile_accent_color_id (:obj:`int`): Optional. Identifier of the
:class:`accent color <telegram.constants.ProfileAccentColor>` for the chat's profile
background. See profile `accent colors`_ for more details.
.. versionadded:: 20.8
profile_background_custom_emoji_id (:obj:`str`): Optional. Custom emoji identifier of
the emoji chosen by the chat for its profile background.
.. versionadded:: 20.8
emoji_status_custom_emoji_id (:obj:`str`): Optional. Custom emoji identifier of emoji
status of the chat or the other party in a private chat.
.. versionadded:: 20.0
emoji_status_expiration_date (:class:`datetime.datetime`): Optional. Expiration date of
emoji status of the chat or the other party in a private chat, as a datetime object,
if any.
|datetime_localization|
.. versionadded:: 20.5
bio (:obj:`str`): Optional. Bio of the other party in a private chat.
has_private_forwards (:obj:`bool`): Optional. :obj:`True`, if privacy settings of the other
party in the private chat allows to use ``tg://user?id=<user_id>`` links only in chats
with the user.
.. versionadded:: 13.9
has_restricted_voice_and_video_messages (:obj:`bool`): Optional. :obj:`True`, if the
privacy settings of the other party restrict sending voice and video note messages
in the private chat.
.. versionadded:: 20.0
join_to_send_messages (:obj:`bool`): Optional. :obj:`True`, if users need to join
the supergroup before they can send messages.
.. versionadded:: 20.0
join_by_request (:obj:`bool`): Optional. :obj:`True`, if all users directly joining the
supergroup without using an invite link need to be approved by supergroup
administrators.
.. versionadded:: 20.0
description (:obj:`str`): Optional. Description, for groups, supergroups and channel chats.
invite_link (:obj:`str`): Optional. Primary invite link, for groups, supergroups and
channel.
pinned_message (:class:`telegram.Message`): Optional. The most recent pinned message
(by sending date).
permissions (:class:`telegram.ChatPermissions`): Optional. Default chat member permissions,
for groups and supergroups.
slow_mode_delay (:obj:`int` | :class:`datetime.timedelta`): Optional. For supergroups,
the minimum allowed delay between consecutive messages sent by each unprivileged user.
.. deprecated:: v22.2
|time-period-int-deprecated|
unrestrict_boost_count (:obj:`int`): Optional. For supergroups, the minimum number of
boosts that a non-administrator user needs to add in order to ignore slow mode and chat
permissions.
.. versionadded:: 21.0
message_auto_delete_time (:obj:`int` | :class:`datetime.timedelta`): Optional. The time
after which all messages sent to the chat will be automatically deleted; in seconds.
.. versionadded:: 13.4
.. deprecated:: v22.2
|time-period-int-deprecated|
has_aggressive_anti_spam_enabled (:obj:`bool`): Optional. :obj:`True`, if aggressive
anti-spam checks are enabled in the supergroup. The field is only available to chat
administrators.
.. versionadded:: 20.0
has_hidden_members (:obj:`bool`): Optional. :obj:`True`, if non-administrators can only
get the list of bots and administrators in the chat.
.. versionadded:: 20.0
has_protected_content (:obj:`bool`): Optional. :obj:`True`, if messages from the chat can't
be forwarded to other chats.
.. versionadded:: 13.9
has_visible_history (:obj:`bool`): Optional. :obj:`True`, if new chat members will have
access to old messages; available only to chat administrators.
.. versionadded:: 20.8
sticker_set_name (:obj:`str`): Optional. For supergroups, name of Group sticker set.
can_set_sticker_set (:obj:`bool`): Optional. :obj:`True`, if the bot can change group the
sticker set.
custom_emoji_sticker_set_name (:obj:`str`): Optional. For supergroups, the name of the
group's custom emoji sticker set. Custom emoji from this set can be used by all users
and bots in the group.
.. versionadded:: 21.0
linked_chat_id (:obj:`int`): Optional. Unique identifier for the linked chat, i.e. the
discussion group identifier for a channel and vice versa; for supergroups and channel
chats.
location (:class:`telegram.ChatLocation`): Optional. For supergroups, the location to which
the supergroup is connected.
can_send_paid_media (:obj:`bool`): Optional. :obj:`True`, if paid media messages can be
sent or forwarded to the channel chat. The field is available only for channel chats.
.. versionadded:: 21.4
.. _accent colors: https://core.telegram.org/bots/api#accent-colors
.. _topics: https://telegram.org/blog/topics-in-groups-collectible-usernames#topics-in-groups
"""
__slots__ = (
"_message_auto_delete_time",
"_slow_mode_delay",
"accent_color_id",
"accepted_gift_types",
"active_usernames",
"available_reactions",
"background_custom_emoji_id",
"bio",
"birthdate",
"business_intro",
"business_location",
"business_opening_hours",
"can_send_paid_media",
"can_set_sticker_set",
"custom_emoji_sticker_set_name",
"description",
"emoji_status_custom_emoji_id",
"emoji_status_expiration_date",
"has_aggressive_anti_spam_enabled",
"has_hidden_members",
"has_private_forwards",
"has_protected_content",
"has_restricted_voice_and_video_messages",
"has_visible_history",
"invite_link",
"join_by_request",
"join_to_send_messages",
"linked_chat_id",
"location",
"max_reaction_count",
"permissions",
"personal_chat",
"photo",
"pinned_message",
"profile_accent_color_id",
"profile_background_custom_emoji_id",
"sticker_set_name",
"unrestrict_boost_count",
)
def __init__(
self,
id: int,
type: str,
accent_color_id: int,
max_reaction_count: int,
accepted_gift_types: AcceptedGiftTypes,
title: Optional[str] = None,
username: Optional[str] = None,
first_name: Optional[str] = None,
last_name: Optional[str] = None,
is_forum: Optional[bool] = None,
photo: Optional[ChatPhoto] = None,
active_usernames: Optional[Sequence[str]] = None,
birthdate: Optional[Birthdate] = None,
business_intro: Optional["BusinessIntro"] = None,
business_location: Optional["BusinessLocation"] = None,
business_opening_hours: Optional["BusinessOpeningHours"] = None,
personal_chat: Optional["Chat"] = None,
available_reactions: Optional[Sequence[ReactionType]] = None,
background_custom_emoji_id: Optional[str] = None,
profile_accent_color_id: Optional[int] = None,
profile_background_custom_emoji_id: Optional[str] = None,
emoji_status_custom_emoji_id: Optional[str] = None,
emoji_status_expiration_date: Optional[dtm.datetime] = None,
bio: Optional[str] = None,
has_private_forwards: Optional[bool] = None,
has_restricted_voice_and_video_messages: Optional[bool] = None,
join_to_send_messages: Optional[bool] = None,
join_by_request: Optional[bool] = None,
description: Optional[str] = None,
invite_link: Optional[str] = None,
pinned_message: Optional["Message"] = None,
permissions: Optional[ChatPermissions] = None,
slow_mode_delay: Optional[TimePeriod] = None,
unrestrict_boost_count: Optional[int] = None,
message_auto_delete_time: Optional[TimePeriod] = None,
has_aggressive_anti_spam_enabled: Optional[bool] = None,
has_hidden_members: Optional[bool] = None,
has_protected_content: Optional[bool] = None,
has_visible_history: Optional[bool] = None,
sticker_set_name: Optional[str] = None,
can_set_sticker_set: Optional[bool] = None,
custom_emoji_sticker_set_name: Optional[str] = None,
linked_chat_id: Optional[int] = None,
location: Optional[ChatLocation] = None,
can_send_paid_media: Optional[bool] = None,
*,
api_kwargs: Optional[JSONDict] = None,
):
super().__init__(
id=id,
type=type,
title=title,
username=username,
first_name=first_name,
last_name=last_name,
is_forum=is_forum,
api_kwargs=api_kwargs,
)
# Required and unique to this class-
with self._unfrozen():
self.max_reaction_count: int = max_reaction_count
self.photo: Optional[ChatPhoto] = photo
self.bio: Optional[str] = bio
self.has_private_forwards: Optional[bool] = has_private_forwards
self.description: Optional[str] = description
self.invite_link: Optional[str] = invite_link
self.pinned_message: Optional[Message] = pinned_message
self.permissions: Optional[ChatPermissions] = permissions
self._slow_mode_delay: Optional[dtm.timedelta] = to_timedelta(slow_mode_delay)
self._message_auto_delete_time: Optional[dtm.timedelta] = to_timedelta(
message_auto_delete_time
)
self.has_protected_content: Optional[bool] = has_protected_content
self.has_visible_history: Optional[bool] = has_visible_history
self.sticker_set_name: Optional[str] = sticker_set_name
self.can_set_sticker_set: Optional[bool] = can_set_sticker_set
self.linked_chat_id: Optional[int] = linked_chat_id
self.location: Optional[ChatLocation] = location
self.join_to_send_messages: Optional[bool] = join_to_send_messages
self.join_by_request: Optional[bool] = join_by_request
self.has_restricted_voice_and_video_messages: Optional[bool] = (
has_restricted_voice_and_video_messages
)
self.active_usernames: tuple[str, ...] = parse_sequence_arg(active_usernames)
self.emoji_status_custom_emoji_id: Optional[str] = emoji_status_custom_emoji_id
self.emoji_status_expiration_date: Optional[dtm.datetime] = (
emoji_status_expiration_date
)
self.has_aggressive_anti_spam_enabled: Optional[bool] = (
has_aggressive_anti_spam_enabled
)
self.has_hidden_members: Optional[bool] = has_hidden_members
self.available_reactions: Optional[tuple[ReactionType, ...]] = parse_sequence_arg(
available_reactions
)
self.accent_color_id: Optional[int] = accent_color_id
self.background_custom_emoji_id: Optional[str] = background_custom_emoji_id
self.profile_accent_color_id: Optional[int] = profile_accent_color_id
self.profile_background_custom_emoji_id: Optional[str] = (
profile_background_custom_emoji_id
)
self.unrestrict_boost_count: Optional[int] = unrestrict_boost_count
self.custom_emoji_sticker_set_name: Optional[str] = custom_emoji_sticker_set_name
self.birthdate: Optional[Birthdate] = birthdate
self.personal_chat: Optional[Chat] = personal_chat
self.business_intro: Optional[BusinessIntro] = business_intro
self.business_location: Optional[BusinessLocation] = business_location
self.business_opening_hours: Optional[BusinessOpeningHours] = business_opening_hours
self.can_send_paid_media: Optional[bool] = can_send_paid_media
self.accepted_gift_types: AcceptedGiftTypes = accepted_gift_types
@property
def slow_mode_delay(self) -> Optional[Union[int, dtm.timedelta]]:
return get_timedelta_value(self._slow_mode_delay, attribute="slow_mode_delay")
@property
def message_auto_delete_time(self) -> Optional[Union[int, dtm.timedelta]]:
return get_timedelta_value(
self._message_auto_delete_time, attribute="message_auto_delete_time"
)
@classmethod
def de_json(cls, data: JSONDict, bot: Optional["Bot"] = None) -> "ChatFullInfo":
"""See :meth:`telegram.TelegramObject.de_json`."""
data = cls._parse_data(data)
# Get the local timezone from the bot if it has defaults
loc_tzinfo = extract_tzinfo_from_defaults(bot)
data["emoji_status_expiration_date"] = from_timestamp(
data.get("emoji_status_expiration_date"), tzinfo=loc_tzinfo
)
data["photo"] = de_json_optional(data.get("photo"), ChatPhoto, bot)
data["accepted_gift_types"] = de_json_optional(
data.get("accepted_gift_types"), AcceptedGiftTypes, bot
)
from telegram import ( # pylint: disable=import-outside-toplevel # noqa: PLC0415
BusinessIntro,
BusinessLocation,
BusinessOpeningHours,
Message,
)
data["pinned_message"] = de_json_optional(data.get("pinned_message"), Message, bot)
data["permissions"] = de_json_optional(data.get("permissions"), ChatPermissions, bot)
data["location"] = de_json_optional(data.get("location"), ChatLocation, bot)
data["available_reactions"] = de_list_optional(
data.get("available_reactions"), ReactionType, bot
)
data["birthdate"] = de_json_optional(data.get("birthdate"), Birthdate, bot)
data["personal_chat"] = de_json_optional(data.get("personal_chat"), Chat, bot)
data["business_intro"] = de_json_optional(data.get("business_intro"), BusinessIntro, bot)
data["business_location"] = de_json_optional(
data.get("business_location"), BusinessLocation, bot
)
data["business_opening_hours"] = de_json_optional(
data.get("business_opening_hours"), BusinessOpeningHours, bot
)
return super().de_json(data=data, bot=bot)

View File

@@ -0,0 +1,205 @@
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2025
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser Public License for more details.
#
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents an invite link for a chat."""
import datetime as dtm
from typing import TYPE_CHECKING, Optional, Union
from telegram._telegramobject import TelegramObject
from telegram._user import User
from telegram._utils.argumentparsing import de_json_optional, to_timedelta
from telegram._utils.datetime import (
extract_tzinfo_from_defaults,
from_timestamp,
get_timedelta_value,
)
from telegram._utils.types import JSONDict, TimePeriod
if TYPE_CHECKING:
from telegram import Bot
class ChatInviteLink(TelegramObject):
"""This object represents an invite link for a chat.
Objects of this class are comparable in terms of equality. Two objects of this class are
considered equal, if their :attr:`invite_link`, :attr:`creator`, :attr:`creates_join_request`,
:attr:`is_primary` and :attr:`is_revoked` are equal.
.. versionadded:: 13.4
.. versionchanged:: 20.0
* The argument & attribute :attr:`creates_join_request` is now required to comply with the
Bot API.
* Comparing objects of this class now also takes :attr:`creates_join_request` into account.
Args:
invite_link (:obj:`str`): The invite link.
creator (:class:`telegram.User`): Creator of the link.
creates_join_request (:obj:`bool`): :obj:`True`, if users joining the chat via
the link need to be approved by chat administrators.
.. versionadded:: 13.8
is_primary (:obj:`bool`): :obj:`True`, if the link is primary.
is_revoked (:obj:`bool`): :obj:`True`, if the link is revoked.
expire_date (:class:`datetime.datetime`, optional): Date when the link will expire or
has been expired.
.. versionchanged:: 20.3
|datetime_localization|
member_limit (:obj:`int`, optional): Maximum number of users that can be members of the
chat simultaneously after joining the chat via this invite link;
:tg-const:`telegram.constants.ChatInviteLinkLimit.MIN_MEMBER_LIMIT`-
:tg-const:`telegram.constants.ChatInviteLinkLimit.MAX_MEMBER_LIMIT`.
name (:obj:`str`, optional): Invite link name.
0-:tg-const:`telegram.constants.ChatInviteLinkLimit.NAME_LENGTH` characters.
.. versionadded:: 13.8
pending_join_request_count (:obj:`int`, optional): Number of pending join requests
created using this link.
.. versionadded:: 13.8
subscription_period (:obj:`int` | :class:`datetime.timedelta`, optional): The number of
seconds the subscription will be active for before the next payment.
.. versionadded:: 21.5
.. versionchanged:: v22.2
|time-period-input|
subscription_price (:obj:`int`, optional): The amount of Telegram Stars a user must pay
initially and after each subsequent subscription period to be a member of the chat
using the link.
.. versionadded:: 21.5
Attributes:
invite_link (:obj:`str`): The invite link. If the link was created by another chat
administrator, then the second part of the link will be replaced with ``''``.
creator (:class:`telegram.User`): Creator of the link.
creates_join_request (:obj:`bool`): :obj:`True`, if users joining the chat via
the link need to be approved by chat administrators.
.. versionadded:: 13.8
is_primary (:obj:`bool`): :obj:`True`, if the link is primary.
is_revoked (:obj:`bool`): :obj:`True`, if the link is revoked.
expire_date (:class:`datetime.datetime`): Optional. Date when the link will expire or
has been expired.
.. versionchanged:: 20.3
|datetime_localization|
member_limit (:obj:`int`): Optional. Maximum number of users that can be members
of the chat simultaneously after joining the chat via this invite link;
:tg-const:`telegram.constants.ChatInviteLinkLimit.MIN_MEMBER_LIMIT`-
:tg-const:`telegram.constants.ChatInviteLinkLimit.MAX_MEMBER_LIMIT`.
name (:obj:`str`): Optional. Invite link name.
0-:tg-const:`telegram.constants.ChatInviteLinkLimit.NAME_LENGTH` characters.
.. versionadded:: 13.8
pending_join_request_count (:obj:`int`): Optional. Number of pending join requests
created using this link.
.. versionadded:: 13.8
subscription_period (:obj:`int` | :class:`datetime.timedelta`): Optional. The number of
seconds the subscription will be active for before the next payment.
.. versionadded:: 21.5
.. deprecated:: v22.2
|time-period-int-deprecated|
subscription_price (:obj:`int`): Optional. The amount of Telegram Stars a user must pay
initially and after each subsequent subscription period to be a member of the chat
using the link.
.. versionadded:: 21.5
"""
__slots__ = (
"_subscription_period",
"creates_join_request",
"creator",
"expire_date",
"invite_link",
"is_primary",
"is_revoked",
"member_limit",
"name",
"pending_join_request_count",
"subscription_price",
)
def __init__(
self,
invite_link: str,
creator: User,
creates_join_request: bool,
is_primary: bool,
is_revoked: bool,
expire_date: Optional[dtm.datetime] = None,
member_limit: Optional[int] = None,
name: Optional[str] = None,
pending_join_request_count: Optional[int] = None,
subscription_period: Optional[TimePeriod] = None,
subscription_price: Optional[int] = None,
*,
api_kwargs: Optional[JSONDict] = None,
):
super().__init__(api_kwargs=api_kwargs)
# Required
self.invite_link: str = invite_link
self.creator: User = creator
self.creates_join_request: bool = creates_join_request
self.is_primary: bool = is_primary
self.is_revoked: bool = is_revoked
# Optionals
self.expire_date: Optional[dtm.datetime] = expire_date
self.member_limit: Optional[int] = member_limit
self.name: Optional[str] = name
self.pending_join_request_count: Optional[int] = (
int(pending_join_request_count) if pending_join_request_count is not None else None
)
self._subscription_period: Optional[dtm.timedelta] = to_timedelta(subscription_period)
self.subscription_price: Optional[int] = subscription_price
self._id_attrs = (
self.invite_link,
self.creates_join_request,
self.creator,
self.is_primary,
self.is_revoked,
)
self._freeze()
@property
def subscription_period(self) -> Optional[Union[int, dtm.timedelta]]:
return get_timedelta_value(self._subscription_period, attribute="subscription_period")
@classmethod
def de_json(cls, data: JSONDict, bot: Optional["Bot"] = None) -> "ChatInviteLink":
"""See :meth:`telegram.TelegramObject.de_json`."""
data = cls._parse_data(data)
# Get the local timezone from the bot if it has defaults
loc_tzinfo = extract_tzinfo_from_defaults(bot)
data["creator"] = de_json_optional(data.get("creator"), User, bot)
data["expire_date"] = from_timestamp(data.get("expire_date", None), tzinfo=loc_tzinfo)
return super().de_json(data=data, bot=bot)

View File

@@ -0,0 +1,209 @@
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2025
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser Public License for more details.
#
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents a Telegram ChatJoinRequest."""
import datetime as dtm
from typing import TYPE_CHECKING, Optional
from telegram._chat import Chat
from telegram._chatinvitelink import ChatInviteLink
from telegram._telegramobject import TelegramObject
from telegram._user import User
from telegram._utils.argumentparsing import de_json_optional
from telegram._utils.datetime import extract_tzinfo_from_defaults, from_timestamp
from telegram._utils.defaultvalue import DEFAULT_NONE
from telegram._utils.types import JSONDict, ODVInput
if TYPE_CHECKING:
from telegram import Bot
class ChatJoinRequest(TelegramObject):
"""This object represents a join request sent to a chat.
Objects of this class are comparable in terms of equality. Two objects of this class are
considered equal, if their :attr:`chat`, :attr:`from_user` and :attr:`date` are equal.
Note:
* Since Bot API 5.5, bots are allowed to contact users who sent a join request to a chat
where the bot is an administrator with the
:attr:`~telegram.ChatMemberAdministrator.can_invite_users` administrator right - even
if the user never interacted with the bot before.
* Telegram does not guarantee that :attr:`from_user.id <from_user>` coincides with the
``chat_id`` of the user. Please use :attr:`user_chat_id` to contact the user in
response to their join request.
.. versionadded:: 13.8
.. versionchanged:: 20.1
In Bot API 6.5 the argument :paramref:`user_chat_id` was added, which changes the position
of the optional arguments :paramref:`bio` and :paramref:`invite_link`.
Args:
chat (:class:`telegram.Chat`): Chat to which the request was sent.
from_user (:class:`telegram.User`): User that sent the join request.
date (:class:`datetime.datetime`): Date the request was sent.
.. versionchanged:: 20.3
|datetime_localization|
user_chat_id (:obj:`int`): Identifier of a private chat with the user who sent the join
request. This number may have more than 32 significant bits and some programming
languages may have difficulty/silent defects in interpreting it. But it has at most 52
significant bits, so a 64-bit integer or double-precision float type are safe for
storing this identifier. The bot can use this identifier for 5 minutes to send messages
until the join request is processed, assuming no other administrator contacted the
user.
.. versionadded:: 20.1
bio (:obj:`str`, optional): Bio of the user.
invite_link (:class:`telegram.ChatInviteLink`, optional): Chat invite link that was used
by the user to send the join request.
Attributes:
chat (:class:`telegram.Chat`): Chat to which the request was sent.
from_user (:class:`telegram.User`): User that sent the join request.
date (:class:`datetime.datetime`): Date the request was sent.
.. versionchanged:: 20.3
|datetime_localization|
user_chat_id (:obj:`int`): Identifier of a private chat with the user who sent the join
request. This number may have more than 32 significant bits and some programming
languages may have difficulty/silent defects in interpreting it. But it has at most 52
significant bits, so a 64-bit integer or double-precision float type are safe for
storing this identifier. The bot can use this identifier for 24 hours to send messages
until the join request is processed, assuming no other administrator contacted the
user.
.. versionadded:: 20.1
bio (:obj:`str`): Optional. Bio of the user.
invite_link (:class:`telegram.ChatInviteLink`): Optional. Chat invite link that was used
by the user to send the join request.
Note:
When a user joins a *public* group via an invite link, this attribute may not
be present. However, this behavior is undocument and may be subject to change.
See `this GitHub thread <https://github.com/tdlib/telegram-bot-api/issues/428>`_
for some discussion.
"""
__slots__ = ("bio", "chat", "date", "from_user", "invite_link", "user_chat_id")
def __init__(
self,
chat: Chat,
from_user: User,
date: dtm.datetime,
user_chat_id: int,
bio: Optional[str] = None,
invite_link: Optional[ChatInviteLink] = None,
*,
api_kwargs: Optional[JSONDict] = None,
):
super().__init__(api_kwargs=api_kwargs)
# Required
self.chat: Chat = chat
self.from_user: User = from_user
self.date: dtm.datetime = date
self.user_chat_id: int = user_chat_id
# Optionals
self.bio: Optional[str] = bio
self.invite_link: Optional[ChatInviteLink] = invite_link
self._id_attrs = (self.chat, self.from_user, self.date)
self._freeze()
@classmethod
def de_json(cls, data: JSONDict, bot: Optional["Bot"] = None) -> "ChatJoinRequest":
"""See :meth:`telegram.TelegramObject.de_json`."""
data = cls._parse_data(data)
# Get the local timezone from the bot if it has defaults
loc_tzinfo = extract_tzinfo_from_defaults(bot)
data["chat"] = de_json_optional(data.get("chat"), Chat, bot)
data["from_user"] = de_json_optional(data.pop("from", None), User, bot)
data["date"] = from_timestamp(data.get("date", None), tzinfo=loc_tzinfo)
data["invite_link"] = de_json_optional(data.get("invite_link"), ChatInviteLink, bot)
return super().de_json(data=data, bot=bot)
async def approve(
self,
*,
read_timeout: ODVInput[float] = DEFAULT_NONE,
write_timeout: ODVInput[float] = DEFAULT_NONE,
connect_timeout: ODVInput[float] = DEFAULT_NONE,
pool_timeout: ODVInput[float] = DEFAULT_NONE,
api_kwargs: Optional[JSONDict] = None,
) -> bool:
"""Shortcut for::
await bot.approve_chat_join_request(
chat_id=update.effective_chat.id, user_id=update.effective_user.id, *args, **kwargs
)
For the documentation of the arguments, please see
:meth:`telegram.Bot.approve_chat_join_request`.
Returns:
:obj:`bool`: On success, :obj:`True` is returned.
"""
return await self.get_bot().approve_chat_join_request(
chat_id=self.chat.id,
user_id=self.from_user.id,
read_timeout=read_timeout,
write_timeout=write_timeout,
connect_timeout=connect_timeout,
pool_timeout=pool_timeout,
api_kwargs=api_kwargs,
)
async def decline(
self,
*,
read_timeout: ODVInput[float] = DEFAULT_NONE,
write_timeout: ODVInput[float] = DEFAULT_NONE,
connect_timeout: ODVInput[float] = DEFAULT_NONE,
pool_timeout: ODVInput[float] = DEFAULT_NONE,
api_kwargs: Optional[JSONDict] = None,
) -> bool:
"""Shortcut for::
await bot.decline_chat_join_request(
chat_id=update.effective_chat.id, user_id=update.effective_user.id, *args, **kwargs
)
For the documentation of the arguments, please see
:meth:`telegram.Bot.decline_chat_join_request`.
Returns:
:obj:`bool`: On success, :obj:`True` is returned.
"""
return await self.get_bot().decline_chat_join_request(
chat_id=self.chat.id,
user_id=self.from_user.id,
read_timeout=read_timeout,
write_timeout=write_timeout,
connect_timeout=connect_timeout,
pool_timeout=pool_timeout,
api_kwargs=api_kwargs,
)

View File

@@ -0,0 +1,89 @@
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2025
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser Public License for more details.
#
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents a location to which a chat is connected."""
from typing import TYPE_CHECKING, Final, Optional
from telegram import constants
from telegram._files.location import Location
from telegram._telegramobject import TelegramObject
from telegram._utils.argumentparsing import de_json_optional
from telegram._utils.types import JSONDict
if TYPE_CHECKING:
from telegram import Bot
class ChatLocation(TelegramObject):
"""This object represents a location to which a chat is connected.
Objects of this class are comparable in terms of equality. Two objects of this class are
considered equal, if their :attr:`location` is equal.
Args:
location (:class:`telegram.Location`): The location to which the supergroup is connected.
Can't be a live location.
address (:obj:`str`): Location address;
:tg-const:`telegram.ChatLocation.MIN_ADDRESS`-
:tg-const:`telegram.ChatLocation.MAX_ADDRESS` characters, as defined by the chat owner.
Attributes:
location (:class:`telegram.Location`): The location to which the supergroup is connected.
Can't be a live location.
address (:obj:`str`): Location address;
:tg-const:`telegram.ChatLocation.MIN_ADDRESS`-
:tg-const:`telegram.ChatLocation.MAX_ADDRESS` characters, as defined by the chat owner.
"""
__slots__ = ("address", "location")
def __init__(
self,
location: Location,
address: str,
*,
api_kwargs: Optional[JSONDict] = None,
):
super().__init__(api_kwargs=api_kwargs)
self.location: Location = location
self.address: str = address
self._id_attrs = (self.location,)
self._freeze()
@classmethod
def de_json(cls, data: JSONDict, bot: Optional["Bot"] = None) -> "ChatLocation":
"""See :meth:`telegram.TelegramObject.de_json`."""
data = cls._parse_data(data)
data["location"] = de_json_optional(data.get("location"), Location, bot)
return super().de_json(data=data, bot=bot)
MIN_ADDRESS: Final[int] = constants.LocationLimit.MIN_CHAT_LOCATION_ADDRESS
""":const:`telegram.constants.LocationLimit.MIN_CHAT_LOCATION_ADDRESS`
.. versionadded:: 20.0
"""
MAX_ADDRESS: Final[int] = constants.LocationLimit.MAX_CHAT_LOCATION_ADDRESS
""":const:`telegram.constants.LocationLimit.MAX_CHAT_LOCATION_ADDRESS`
.. versionadded:: 20.0
"""

View File

@@ -0,0 +1,662 @@
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2025
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser Public License for more details.
#
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents a Telegram ChatMember."""
import datetime as dtm
from typing import TYPE_CHECKING, Final, Optional
from telegram import constants
from telegram._telegramobject import TelegramObject
from telegram._user import User
from telegram._utils import enum
from telegram._utils.argumentparsing import de_json_optional
from telegram._utils.datetime import extract_tzinfo_from_defaults, from_timestamp
from telegram._utils.types import JSONDict
if TYPE_CHECKING:
from telegram import Bot
class ChatMember(TelegramObject):
"""Base class for Telegram ChatMember Objects.
Currently, the following 6 types of chat members are supported:
* :class:`telegram.ChatMemberOwner`
* :class:`telegram.ChatMemberAdministrator`
* :class:`telegram.ChatMemberMember`
* :class:`telegram.ChatMemberRestricted`
* :class:`telegram.ChatMemberLeft`
* :class:`telegram.ChatMemberBanned`
Objects of this class are comparable in terms of equality. Two objects of this class are
considered equal, if their :attr:`user` and :attr:`status` are equal.
Examples:
:any:`Chat Member Bot <examples.chatmemberbot>`
.. versionchanged:: 20.0
* As of Bot API 5.3, :class:`ChatMember` is nothing but the base class for the subclasses
listed above and is no longer returned directly by :meth:`~telegram.Bot.get_chat`.
Therefore, most of the arguments and attributes were removed and you should no longer
use :class:`ChatMember` directly.
* The constant ``ChatMember.CREATOR`` was replaced by :attr:`~telegram.ChatMember.OWNER`
* The constant ``ChatMember.KICKED`` was replaced by :attr:`~telegram.ChatMember.BANNED`
Args:
user (:class:`telegram.User`): Information about the user.
status (:obj:`str`): The member's status in the chat. Can be
:attr:`~telegram.ChatMember.ADMINISTRATOR`, :attr:`~telegram.ChatMember.OWNER`,
:attr:`~telegram.ChatMember.BANNED`, :attr:`~telegram.ChatMember.LEFT`,
:attr:`~telegram.ChatMember.MEMBER` or :attr:`~telegram.ChatMember.RESTRICTED`.
Attributes:
user (:class:`telegram.User`): Information about the user.
status (:obj:`str`): The member's status in the chat. Can be
:attr:`~telegram.ChatMember.ADMINISTRATOR`, :attr:`~telegram.ChatMember.OWNER`,
:attr:`~telegram.ChatMember.BANNED`, :attr:`~telegram.ChatMember.LEFT`,
:attr:`~telegram.ChatMember.MEMBER` or :attr:`~telegram.ChatMember.RESTRICTED`.
"""
__slots__ = ("status", "user")
ADMINISTRATOR: Final[str] = constants.ChatMemberStatus.ADMINISTRATOR
""":const:`telegram.constants.ChatMemberStatus.ADMINISTRATOR`"""
OWNER: Final[str] = constants.ChatMemberStatus.OWNER
""":const:`telegram.constants.ChatMemberStatus.OWNER`"""
BANNED: Final[str] = constants.ChatMemberStatus.BANNED
""":const:`telegram.constants.ChatMemberStatus.BANNED`"""
LEFT: Final[str] = constants.ChatMemberStatus.LEFT
""":const:`telegram.constants.ChatMemberStatus.LEFT`"""
MEMBER: Final[str] = constants.ChatMemberStatus.MEMBER
""":const:`telegram.constants.ChatMemberStatus.MEMBER`"""
RESTRICTED: Final[str] = constants.ChatMemberStatus.RESTRICTED
""":const:`telegram.constants.ChatMemberStatus.RESTRICTED`"""
def __init__(
self,
user: User,
status: str,
*,
api_kwargs: Optional[JSONDict] = None,
):
super().__init__(api_kwargs=api_kwargs)
# Required by all subclasses
self.user: User = user
self.status: str = enum.get_member(constants.ChatMemberStatus, status, status)
self._id_attrs = (self.user, self.status)
self._freeze()
@classmethod
def de_json(cls, data: JSONDict, bot: Optional["Bot"] = None) -> "ChatMember":
"""See :meth:`telegram.TelegramObject.de_json`."""
data = cls._parse_data(data)
_class_mapping: dict[str, type[ChatMember]] = {
cls.OWNER: ChatMemberOwner,
cls.ADMINISTRATOR: ChatMemberAdministrator,
cls.MEMBER: ChatMemberMember,
cls.RESTRICTED: ChatMemberRestricted,
cls.LEFT: ChatMemberLeft,
cls.BANNED: ChatMemberBanned,
}
if cls is ChatMember and data.get("status") in _class_mapping:
return _class_mapping[data.pop("status")].de_json(data=data, bot=bot)
data["user"] = de_json_optional(data.get("user"), User, bot)
if "until_date" in data:
# Get the local timezone from the bot if it has defaults
loc_tzinfo = extract_tzinfo_from_defaults(bot)
data["until_date"] = from_timestamp(data.get("until_date"), tzinfo=loc_tzinfo)
# This is a deprecated field that TG still returns for backwards compatibility
# Let's filter it out to speed up the de-json process
if cls is ChatMemberRestricted and data.get("can_send_media_messages") is not None:
api_kwargs = {"can_send_media_messages": data.pop("can_send_media_messages")}
return super()._de_json(data=data, bot=bot, api_kwargs=api_kwargs)
return super().de_json(data=data, bot=bot)
class ChatMemberOwner(ChatMember):
"""
Represents a chat member that owns the chat
and has all administrator privileges.
.. versionadded:: 13.7
Args:
user (:class:`telegram.User`): Information about the user.
is_anonymous (:obj:`bool`): :obj:`True`, if the
user's presence in the chat is hidden.
custom_title (:obj:`str`, optional): Custom title for this user.
Attributes:
status (:obj:`str`): The member's status in the chat,
always :tg-const:`telegram.ChatMember.OWNER`.
user (:class:`telegram.User`): Information about the user.
is_anonymous (:obj:`bool`): :obj:`True`, if the user's
presence in the chat is hidden.
custom_title (:obj:`str`): Optional. Custom title for
this user.
"""
__slots__ = ("custom_title", "is_anonymous")
def __init__(
self,
user: User,
is_anonymous: bool,
custom_title: Optional[str] = None,
*,
api_kwargs: Optional[JSONDict] = None,
):
super().__init__(status=ChatMember.OWNER, user=user, api_kwargs=api_kwargs)
with self._unfrozen():
self.is_anonymous: bool = is_anonymous
self.custom_title: Optional[str] = custom_title
class ChatMemberAdministrator(ChatMember):
"""
Represents a chat member that has some additional privileges.
.. versionadded:: 13.7
.. versionchanged:: 20.0
* Argument and attribute ``can_manage_voice_chats`` were renamed to
:paramref:`can_manage_video_chats` and :attr:`can_manage_video_chats` in accordance to
Bot API 6.0.
* The argument :paramref:`can_manage_topics` was added, which changes the position of the
optional argument :paramref:`custom_title`.
.. versionchanged:: 21.1
As of this version, :attr:`can_post_stories`, :attr:`can_edit_stories`,
and :attr:`can_delete_stories` is now required. Thus, the order of arguments had to be
changed.
Args:
user (:class:`telegram.User`): Information about the user.
can_be_edited (:obj:`bool`): :obj:`True`, if the bot
is allowed to edit administrator privileges of that user.
is_anonymous (:obj:`bool`): :obj:`True`, if the user's
presence in the chat is hidden.
can_manage_chat (:obj:`bool`): :obj:`True`, if the administrator can access the chat event
log, get boost list, see hidden supergroup and channel members, report spam messages
and ignore slow mode. Implied by any other administrator privilege.
can_delete_messages (:obj:`bool`): :obj:`True`, if the
administrator can delete messages of other users.
can_manage_video_chats (:obj:`bool`): :obj:`True`, if the
administrator can manage video chats.
.. versionadded:: 20.0
can_restrict_members (:obj:`bool`): :obj:`True`, if the
administrator can restrict, ban or unban chat members.
can_promote_members (:obj:`bool`): :obj:`True`, if the administrator
can add new administrators with a subset of his own privileges or demote
administrators that he has promoted, directly or indirectly (promoted by
administrators that were appointed by the user).
can_change_info (:obj:`bool`): :obj:`True`, if the user can change
the chat title, photo and other settings.
can_invite_users (:obj:`bool`): :obj:`True`, if the user can invite
new users to the chat.
can_post_messages (:obj:`bool`, optional): :obj:`True`, if the
administrator can post messages in the channel, or access channel statistics;
for channels only.
can_edit_messages (:obj:`bool`, optional): :obj:`True`, if the
administrator can edit messages of other users and can pin
messages; for channels only.
can_pin_messages (:obj:`bool`, optional): :obj:`True`, if the user is allowed
to pin messages; for groups and supergroups only.
can_post_stories (:obj:`bool`): :obj:`True`, if the administrator can post
stories to the chat.
.. versionadded:: 20.6
.. versionchanged:: 21.0
|non_optional_story_argument|
can_edit_stories (:obj:`bool`): :obj:`True`, if the administrator can edit stories posted
by other users, post stories to the chat page, pin chat stories, and access the chat's
story archive
.. versionadded:: 20.6
.. versionchanged:: 21.0
|non_optional_story_argument|
can_delete_stories (:obj:`bool`): :obj:`True`, if the administrator can delete
stories posted by other users.
.. versionadded:: 20.6
.. versionchanged:: 21.0
|non_optional_story_argument|
can_manage_topics (:obj:`bool`, optional): :obj:`True`, if the user is allowed
to create, rename, close, and reopen forum topics; for supergroups only.
.. versionadded:: 20.0
custom_title (:obj:`str`, optional): Custom title for this user.
Attributes:
status (:obj:`str`): The member's status in the chat,
always :tg-const:`telegram.ChatMember.ADMINISTRATOR`.
user (:class:`telegram.User`): Information about the user.
can_be_edited (:obj:`bool`): :obj:`True`, if the bot
is allowed to edit administrator privileges of that user.
is_anonymous (:obj:`bool`): :obj:`True`, if the user's
presence in the chat is hidden.
can_manage_chat (:obj:`bool`): :obj:`True`, if the administrator can access the chat event
log, get boost list, see hidden supergroup and channel members, report spam messages
and ignore slow mode. Implied by any other administrator privilege.
can_delete_messages (:obj:`bool`): :obj:`True`, if the
administrator can delete messages of other users.
can_manage_video_chats (:obj:`bool`): :obj:`True`, if the
administrator can manage video chats.
.. versionadded:: 20.0
can_restrict_members (:obj:`bool`): :obj:`True`, if the
administrator can restrict, ban or unban chat members, or access supergroup statistics.
can_promote_members (:obj:`bool`): :obj:`True`, if the administrator can add new
administrators with a subset of their own privileges or demote administrators
that they have promoted, directly or indirectly (promoted by administrators that
were appointed by the user).
can_change_info (:obj:`bool`): :obj:`True`, if the user can change
the chat title, photo and other settings.
can_invite_users (:obj:`bool`): :obj:`True`, if the user can invite
new users to the chat.
can_post_messages (:obj:`bool`): Optional. :obj:`True`, if the
administrator can post messages in the channel or access channel statistics;
for channels only.
can_edit_messages (:obj:`bool`): Optional. :obj:`True`, if the
administrator can edit messages of other users and can pin
messages; for channels only.
can_pin_messages (:obj:`bool`): Optional. :obj:`True`, if the user is allowed
to pin messages; for groups and supergroups only.
can_post_stories (:obj:`bool`): :obj:`True`, if the administrator can post
stories to the chat.
.. versionadded:: 20.6
.. versionchanged:: 21.0
|non_optional_story_argument|
can_edit_stories (:obj:`bool`): :obj:`True`, if the administrator can edit stories posted
by other users, post stories to the chat page, pin chat stories, and access the chat's
story archive
.. versionadded:: 20.6
.. versionchanged:: 21.0
|non_optional_story_argument|
can_delete_stories (:obj:`bool`): :obj:`True`, if the administrator can delete
stories posted by other users.
.. versionadded:: 20.6
.. versionchanged:: 21.0
|non_optional_story_argument|
can_manage_topics (:obj:`bool`): Optional. :obj:`True`, if the user is allowed
to create, rename, close, and reopen forum topics; for supergroups only
.. versionadded:: 20.0
custom_title (:obj:`str`): Optional. Custom title for this user.
"""
__slots__ = (
"can_be_edited",
"can_change_info",
"can_delete_messages",
"can_delete_stories",
"can_edit_messages",
"can_edit_stories",
"can_invite_users",
"can_manage_chat",
"can_manage_topics",
"can_manage_video_chats",
"can_pin_messages",
"can_post_messages",
"can_post_stories",
"can_promote_members",
"can_restrict_members",
"custom_title",
"is_anonymous",
)
def __init__(
self,
user: User,
can_be_edited: bool,
is_anonymous: bool,
can_manage_chat: bool,
can_delete_messages: bool,
can_manage_video_chats: bool,
can_restrict_members: bool,
can_promote_members: bool,
can_change_info: bool,
can_invite_users: bool,
can_post_stories: bool,
can_edit_stories: bool,
can_delete_stories: bool,
can_post_messages: Optional[bool] = None,
can_edit_messages: Optional[bool] = None,
can_pin_messages: Optional[bool] = None,
can_manage_topics: Optional[bool] = None,
custom_title: Optional[str] = None,
*,
api_kwargs: Optional[JSONDict] = None,
):
super().__init__(status=ChatMember.ADMINISTRATOR, user=user, api_kwargs=api_kwargs)
with self._unfrozen():
self.can_be_edited: bool = can_be_edited
self.is_anonymous: bool = is_anonymous
self.can_manage_chat: bool = can_manage_chat
self.can_delete_messages: bool = can_delete_messages
self.can_manage_video_chats: bool = can_manage_video_chats
self.can_restrict_members: bool = can_restrict_members
self.can_promote_members: bool = can_promote_members
self.can_change_info: bool = can_change_info
self.can_invite_users: bool = can_invite_users
self.can_post_stories: bool = can_post_stories
self.can_edit_stories: bool = can_edit_stories
self.can_delete_stories: bool = can_delete_stories
# Optionals
self.can_post_messages: Optional[bool] = can_post_messages
self.can_edit_messages: Optional[bool] = can_edit_messages
self.can_pin_messages: Optional[bool] = can_pin_messages
self.can_manage_topics: Optional[bool] = can_manage_topics
self.custom_title: Optional[str] = custom_title
class ChatMemberMember(ChatMember):
"""
Represents a chat member that has no additional
privileges or restrictions.
.. versionadded:: 13.7
Args:
user (:class:`telegram.User`): Information about the user.
until_date (:class:`datetime.datetime`, optional): Date when the user's subscription will
expire.
.. versionadded:: 21.5
Attributes:
status (:obj:`str`): The member's status in the chat,
always :tg-const:`telegram.ChatMember.MEMBER`.
user (:class:`telegram.User`): Information about the user.
until_date (:class:`datetime.datetime`): Optional. Date when the user's subscription will
expire.
.. versionadded:: 21.5
"""
__slots__ = ("until_date",)
def __init__(
self,
user: User,
until_date: Optional[dtm.datetime] = None,
*,
api_kwargs: Optional[JSONDict] = None,
):
super().__init__(status=ChatMember.MEMBER, user=user, api_kwargs=api_kwargs)
with self._unfrozen():
self.until_date: Optional[dtm.datetime] = until_date
class ChatMemberRestricted(ChatMember):
"""
Represents a chat member that is under certain restrictions
in the chat. Supergroups only.
.. versionadded:: 13.7
.. versionchanged:: 20.0
All arguments were made positional and their order was changed.
The argument can_manage_topics was added.
.. versionchanged:: 20.5
Removed deprecated argument and attribute ``can_send_media_messages``.
Args:
user (:class:`telegram.User`): Information about the user.
is_member (:obj:`bool`): :obj:`True`, if the user is a
member of the chat at the moment of the request.
can_change_info (:obj:`bool`): :obj:`True`, if the user can change
the chat title, photo and other settings.
can_invite_users (:obj:`bool`): :obj:`True`, if the user can invite
new users to the chat.
can_pin_messages (:obj:`bool`): :obj:`True`, if the user is allowed
to pin messages; groups and supergroups only.
can_send_messages (:obj:`bool`): :obj:`True`, if the user is allowed
to send text messages, contacts, invoices, locations and venues.
can_send_polls (:obj:`bool`): :obj:`True`, if the user is allowed
to send polls.
can_send_other_messages (:obj:`bool`): :obj:`True`, if the user is allowed
to send animations, games, stickers and use inline bots.
can_add_web_page_previews (:obj:`bool`): :obj:`True`, if the user is
allowed to add web page previews to their messages.
can_manage_topics (:obj:`bool`): :obj:`True`, if the user is allowed to create
forum topics.
.. versionadded:: 20.0
until_date (:class:`datetime.datetime`): Date when restrictions
will be lifted for this user.
.. versionchanged:: 20.3
|datetime_localization|
can_send_audios (:obj:`bool`): :obj:`True`, if the user is allowed to send audios.
.. versionadded:: 20.1
can_send_documents (:obj:`bool`): :obj:`True`, if the user is allowed to send documents.
.. versionadded:: 20.1
can_send_photos (:obj:`bool`): :obj:`True`, if the user is allowed to send photos.
.. versionadded:: 20.1
can_send_videos (:obj:`bool`): :obj:`True`, if the user is allowed to send videos.
.. versionadded:: 20.1
can_send_video_notes (:obj:`bool`): :obj:`True`, if the user is allowed to send video
notes.
.. versionadded:: 20.1
can_send_voice_notes (:obj:`bool`): :obj:`True`, if the user is allowed to send voice
notes.
.. versionadded:: 20.1
Attributes:
status (:obj:`str`): The member's status in the chat,
always :tg-const:`telegram.ChatMember.RESTRICTED`.
user (:class:`telegram.User`): Information about the user.
is_member (:obj:`bool`): :obj:`True`, if the user is a
member of the chat at the moment of the request.
can_change_info (:obj:`bool`): :obj:`True`, if the user can change
the chat title, photo and other settings.
can_invite_users (:obj:`bool`): :obj:`True`, if the user can invite
new users to the chat.
can_pin_messages (:obj:`bool`): :obj:`True`, if the user is allowed
to pin messages; groups and supergroups only.
can_send_messages (:obj:`bool`): :obj:`True`, if the user is allowed
to send text messages, contacts, locations and venues.
can_send_polls (:obj:`bool`): :obj:`True`, if the user is allowed
to send polls.
can_send_other_messages (:obj:`bool`): :obj:`True`, if the user is allowed
to send animations, games, stickers and use inline bots.
can_add_web_page_previews (:obj:`bool`): :obj:`True`, if the user is
allowed to add web page previews to their messages.
can_manage_topics (:obj:`bool`): :obj:`True`, if the user is allowed to create
forum topics.
.. versionadded:: 20.0
until_date (:class:`datetime.datetime`): Date when restrictions
will be lifted for this user.
.. versionchanged:: 20.3
|datetime_localization|
can_send_audios (:obj:`bool`): :obj:`True`, if the user is allowed to send audios.
.. versionadded:: 20.1
can_send_documents (:obj:`bool`): :obj:`True`, if the user is allowed to send documents.
.. versionadded:: 20.1
can_send_photos (:obj:`bool`): :obj:`True`, if the user is allowed to send photos.
.. versionadded:: 20.1
can_send_videos (:obj:`bool`): :obj:`True`, if the user is allowed to send videos.
.. versionadded:: 20.1
can_send_video_notes (:obj:`bool`): :obj:`True`, if the user is allowed to send video
notes.
.. versionadded:: 20.1
can_send_voice_notes (:obj:`bool`): :obj:`True`, if the user is allowed to send voice
notes.
.. versionadded:: 20.1
"""
__slots__ = (
"can_add_web_page_previews",
"can_change_info",
"can_invite_users",
"can_manage_topics",
"can_pin_messages",
"can_send_audios",
"can_send_documents",
"can_send_messages",
"can_send_other_messages",
"can_send_photos",
"can_send_polls",
"can_send_video_notes",
"can_send_videos",
"can_send_voice_notes",
"is_member",
"until_date",
)
def __init__(
self,
user: User,
is_member: bool,
can_change_info: bool,
can_invite_users: bool,
can_pin_messages: bool,
can_send_messages: bool,
can_send_polls: bool,
can_send_other_messages: bool,
can_add_web_page_previews: bool,
can_manage_topics: bool,
until_date: dtm.datetime,
can_send_audios: bool,
can_send_documents: bool,
can_send_photos: bool,
can_send_videos: bool,
can_send_video_notes: bool,
can_send_voice_notes: bool,
*,
api_kwargs: Optional[JSONDict] = None,
):
super().__init__(status=ChatMember.RESTRICTED, user=user, api_kwargs=api_kwargs)
with self._unfrozen():
self.is_member: bool = is_member
self.can_change_info: bool = can_change_info
self.can_invite_users: bool = can_invite_users
self.can_pin_messages: bool = can_pin_messages
self.can_send_messages: bool = can_send_messages
self.can_send_polls: bool = can_send_polls
self.can_send_other_messages: bool = can_send_other_messages
self.can_add_web_page_previews: bool = can_add_web_page_previews
self.can_manage_topics: bool = can_manage_topics
self.until_date: dtm.datetime = until_date
self.can_send_audios: bool = can_send_audios
self.can_send_documents: bool = can_send_documents
self.can_send_photos: bool = can_send_photos
self.can_send_videos: bool = can_send_videos
self.can_send_video_notes: bool = can_send_video_notes
self.can_send_voice_notes: bool = can_send_voice_notes
class ChatMemberLeft(ChatMember):
"""
Represents a chat member that isn't currently a member of the chat,
but may join it themselves.
.. versionadded:: 13.7
Args:
user (:class:`telegram.User`): Information about the user.
Attributes:
status (:obj:`str`): The member's status in the chat,
always :tg-const:`telegram.ChatMember.LEFT`.
user (:class:`telegram.User`): Information about the user.
"""
__slots__ = ()
def __init__(
self,
user: User,
*,
api_kwargs: Optional[JSONDict] = None,
):
super().__init__(status=ChatMember.LEFT, user=user, api_kwargs=api_kwargs)
self._freeze()
class ChatMemberBanned(ChatMember):
"""
Represents a chat member that was banned in the chat and
can't return to the chat or view chat messages.
.. versionadded:: 13.7
Args:
user (:class:`telegram.User`): Information about the user.
until_date (:class:`datetime.datetime`): Date when restrictions
will be lifted for this user.
.. versionchanged:: 20.3
|datetime_localization|
Attributes:
status (:obj:`str`): The member's status in the chat,
always :tg-const:`telegram.ChatMember.BANNED`.
user (:class:`telegram.User`): Information about the user.
until_date (:class:`datetime.datetime`): Date when restrictions
will be lifted for this user.
.. versionchanged:: 20.3
|datetime_localization|
"""
__slots__ = ("until_date",)
def __init__(
self,
user: User,
until_date: dtm.datetime,
*,
api_kwargs: Optional[JSONDict] = None,
):
super().__init__(status=ChatMember.BANNED, user=user, api_kwargs=api_kwargs)
with self._unfrozen():
self.until_date: dtm.datetime = until_date

View File

@@ -0,0 +1,213 @@
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2025
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser Public License for more details.
#
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents a Telegram ChatMemberUpdated."""
import datetime as dtm
from typing import TYPE_CHECKING, Optional, Union
from telegram._chat import Chat
from telegram._chatinvitelink import ChatInviteLink
from telegram._chatmember import ChatMember
from telegram._telegramobject import TelegramObject
from telegram._user import User
from telegram._utils.argumentparsing import de_json_optional
from telegram._utils.datetime import extract_tzinfo_from_defaults, from_timestamp
from telegram._utils.types import JSONDict
if TYPE_CHECKING:
from telegram import Bot
class ChatMemberUpdated(TelegramObject):
"""This object represents changes in the status of a chat member.
Objects of this class are comparable in terms of equality. Two objects of this class are
considered equal, if their :attr:`chat`, :attr:`from_user`, :attr:`date`,
:attr:`old_chat_member` and :attr:`new_chat_member` are equal.
.. versionadded:: 13.4
Note:
In Python :keyword:`from` is a reserved word. Use :paramref:`from_user` instead.
Examples:
:any:`Chat Member Bot <examples.chatmemberbot>`
Args:
chat (:class:`telegram.Chat`): Chat the user belongs to.
from_user (:class:`telegram.User`): Performer of the action, which resulted in the change.
date (:class:`datetime.datetime`): Date the change was done in Unix time. Converted to
:class:`datetime.datetime`.
.. versionchanged:: 20.3
|datetime_localization|
old_chat_member (:class:`telegram.ChatMember`): Previous information about the chat member.
new_chat_member (:class:`telegram.ChatMember`): New information about the chat member.
invite_link (:class:`telegram.ChatInviteLink`, optional): Chat invite link, which was used
by the user to join the chat. For joining by invite link events only.
via_chat_folder_invite_link (:obj:`bool`, optional): :obj:`True`, if the user joined the
chat via a chat folder invite link
.. versionadded:: 20.3
via_join_request (:obj:`bool`, optional): :obj:`True`, if the user joined the chat after
sending a direct join request without using an invite link and being approved by
an administrator
.. versionadded:: 21.2
Attributes:
chat (:class:`telegram.Chat`): Chat the user belongs to.
from_user (:class:`telegram.User`): Performer of the action, which resulted in the change.
date (:class:`datetime.datetime`): Date the change was done in Unix time. Converted to
:class:`datetime.datetime`.
.. versionchanged:: 20.3
|datetime_localization|
old_chat_member (:class:`telegram.ChatMember`): Previous information about the chat member.
new_chat_member (:class:`telegram.ChatMember`): New information about the chat member.
invite_link (:class:`telegram.ChatInviteLink`): Optional. Chat invite link, which was used
by the user to join the chat. For joining by invite link events only.
via_chat_folder_invite_link (:obj:`bool`): Optional. :obj:`True`, if the user joined the
chat via a chat folder invite link
.. versionadded:: 20.3
via_join_request (:obj:`bool`): Optional. :obj:`True`, if the user joined the chat after
sending a direct join request without using an invite link and being approved
by an administrator
.. versionadded:: 21.2
"""
__slots__ = (
"chat",
"date",
"from_user",
"invite_link",
"new_chat_member",
"old_chat_member",
"via_chat_folder_invite_link",
"via_join_request",
)
def __init__(
self,
chat: Chat,
from_user: User,
date: dtm.datetime,
old_chat_member: ChatMember,
new_chat_member: ChatMember,
invite_link: Optional[ChatInviteLink] = None,
via_chat_folder_invite_link: Optional[bool] = None,
via_join_request: Optional[bool] = None,
*,
api_kwargs: Optional[JSONDict] = None,
):
super().__init__(api_kwargs=api_kwargs)
# Required
self.chat: Chat = chat
self.from_user: User = from_user
self.date: dtm.datetime = date
self.old_chat_member: ChatMember = old_chat_member
self.new_chat_member: ChatMember = new_chat_member
self.via_chat_folder_invite_link: Optional[bool] = via_chat_folder_invite_link
# Optionals
self.invite_link: Optional[ChatInviteLink] = invite_link
self.via_join_request: Optional[bool] = via_join_request
self._id_attrs = (
self.chat,
self.from_user,
self.date,
self.old_chat_member,
self.new_chat_member,
)
self._freeze()
@classmethod
def de_json(cls, data: JSONDict, bot: Optional["Bot"] = None) -> "ChatMemberUpdated":
"""See :meth:`telegram.TelegramObject.de_json`."""
data = cls._parse_data(data)
# Get the local timezone from the bot if it has defaults
loc_tzinfo = extract_tzinfo_from_defaults(bot)
data["chat"] = de_json_optional(data.get("chat"), Chat, bot)
data["from_user"] = de_json_optional(data.pop("from", None), User, bot)
data["date"] = from_timestamp(data.get("date"), tzinfo=loc_tzinfo)
data["old_chat_member"] = de_json_optional(data.get("old_chat_member"), ChatMember, bot)
data["new_chat_member"] = de_json_optional(data.get("new_chat_member"), ChatMember, bot)
data["invite_link"] = de_json_optional(data.get("invite_link"), ChatInviteLink, bot)
return super().de_json(data=data, bot=bot)
def _get_attribute_difference(self, attribute: str) -> tuple[object, object]:
try:
old = self.old_chat_member[attribute]
except KeyError:
old = None
try:
new = self.new_chat_member[attribute]
except KeyError:
new = None
return old, new
def difference(
self,
) -> dict[
str,
tuple[Union[str, bool, dtm.datetime, User], Union[str, bool, dtm.datetime, User]],
]:
"""Computes the difference between :attr:`old_chat_member` and :attr:`new_chat_member`.
Example:
.. code:: pycon
>>> chat_member_updated.difference()
{'custom_title': ('old title', 'new title')}
Note:
To determine, if the :attr:`telegram.ChatMember.user` attribute has changed, *every*
attribute of the user will be checked.
.. versionadded:: 13.5
Returns:
dict[:obj:`str`, tuple[:class:`object`, :class:`object`]]: A dictionary mapping
attribute names to tuples of the form ``(old_value, new_value)``
"""
# we first get the names of the attributes that have changed
# user.to_dict() is unhashable, so that needs some special casing further down
old_dict = self.old_chat_member.to_dict()
old_user_dict = old_dict.pop("user")
new_dict = self.new_chat_member.to_dict()
new_user_dict = new_dict.pop("user")
# Generator for speed: we only need to iterate over it once
# we can't directly use the values from old_dict ^ new_dict b/c that set is unordered
attributes = (entry[0] for entry in set(old_dict.items()) ^ set(new_dict.items()))
result = {attribute: self._get_attribute_difference(attribute) for attribute in attributes}
if old_user_dict != new_user_dict:
result["user"] = (self.old_chat_member.user, self.new_chat_member.user)
return result # type: ignore[return-value]

View File

@@ -0,0 +1,244 @@
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2025
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser Public License for more details.
#
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents a Telegram ChatPermission."""
from typing import TYPE_CHECKING, Optional
from telegram._telegramobject import TelegramObject
from telegram._utils.types import JSONDict
if TYPE_CHECKING:
from telegram import Bot
class ChatPermissions(TelegramObject):
"""Describes actions that a non-administrator user is allowed to take in a chat.
Objects of this class are comparable in terms of equality. Two objects of this class are
considered equal, if their :attr:`can_send_messages`,
:attr:`can_send_polls`, :attr:`can_send_other_messages`, :attr:`can_add_web_page_previews`,
:attr:`can_change_info`, :attr:`can_invite_users`, :attr:`can_pin_messages`,
:attr:`can_send_audios`, :attr:`can_send_documents`, :attr:`can_send_photos`,
:attr:`can_send_videos`, :attr:`can_send_video_notes`, :attr:`can_send_voice_notes`, and
:attr:`can_manage_topics` are equal.
.. versionchanged:: 20.0
:attr:`can_manage_topics` is considered as well when comparing objects of
this type in terms of equality.
.. versionchanged:: 20.5
* :attr:`can_send_audios`, :attr:`can_send_documents`, :attr:`can_send_photos`,
:attr:`can_send_videos`, :attr:`can_send_video_notes` and :attr:`can_send_voice_notes`
are considered as well when comparing objects of this type in terms of equality.
* Removed deprecated argument and attribute ``can_send_media_messages``.
Note:
Though not stated explicitly in the official docs, Telegram changes not only the
permissions that are set, but also sets all the others to :obj:`False`. However, since not
documented, this behavior may change unbeknown to PTB.
Args:
can_send_messages (:obj:`bool`, optional): :obj:`True`, if the user is allowed to send text
messages, contacts, locations and venues.
can_send_polls (:obj:`bool`, optional): :obj:`True`, if the user is allowed to send polls.
can_send_other_messages (:obj:`bool`, optional): :obj:`True`, if the user is allowed to
send animations, games, stickers and use inline bots.
can_add_web_page_previews (:obj:`bool`, optional): :obj:`True`, if the user is allowed to
add web page previews to their messages.
can_change_info (:obj:`bool`, optional): :obj:`True`, if the user is allowed to change the
chat title, photo and other settings. Ignored in public supergroups.
can_invite_users (:obj:`bool`, optional): :obj:`True`, if the user is allowed to invite new
users to the chat.
can_pin_messages (:obj:`bool`, optional): :obj:`True`, if the user is allowed to pin
messages. Ignored in public supergroups.
can_manage_topics (:obj:`bool`, optional): :obj:`True`, if the user is allowed
to create forum topics. If omitted defaults to the value of
:attr:`can_pin_messages`.
.. versionadded:: 20.0
can_send_audios (:obj:`bool`): :obj:`True`, if the user is allowed to send audios.
.. versionadded:: 20.1
can_send_documents (:obj:`bool`): :obj:`True`, if the user is allowed to send documents.
.. versionadded:: 20.1
can_send_photos (:obj:`bool`): :obj:`True`, if the user is allowed to send photos.
.. versionadded:: 20.1
can_send_videos (:obj:`bool`): :obj:`True`, if the user is allowed to send videos.
.. versionadded:: 20.1
can_send_video_notes (:obj:`bool`): :obj:`True`, if the user is allowed to send video
notes.
.. versionadded:: 20.1
can_send_voice_notes (:obj:`bool`): :obj:`True`, if the user is allowed to send voice
notes.
.. versionadded:: 20.1
Attributes:
can_send_messages (:obj:`bool`): Optional. :obj:`True`, if the user is allowed to send text
messages, contacts, locations and venues.
can_send_polls (:obj:`bool`): Optional. :obj:`True`, if the user is allowed to send polls,
implies :attr:`can_send_messages`.
can_send_other_messages (:obj:`bool`): Optional. :obj:`True`, if the user is allowed to
send animations, games, stickers and use inline bots.
can_add_web_page_previews (:obj:`bool`): Optional. :obj:`True`, if the user is allowed to
add web page previews to their messages.
can_change_info (:obj:`bool`): Optional. :obj:`True`, if the user is allowed to change the
chat title, photo and other settings. Ignored in public supergroups.
can_invite_users (:obj:`bool`): Optional. :obj:`True`, if the user is allowed to invite
new users to the chat.
can_pin_messages (:obj:`bool`): Optional. :obj:`True`, if the user is allowed to pin
messages. Ignored in public supergroups.
can_manage_topics (:obj:`bool`): Optional. :obj:`True`, if the user is allowed
to create forum topics. If omitted defaults to the value of
:attr:`can_pin_messages`.
.. versionadded:: 20.0
can_send_audios (:obj:`bool`): :obj:`True`, if the user is allowed to send audios.
.. versionadded:: 20.1
can_send_documents (:obj:`bool`): :obj:`True`, if the user is allowed to send documents.
.. versionadded:: 20.1
can_send_photos (:obj:`bool`): :obj:`True`, if the user is allowed to send photos.
.. versionadded:: 20.1
can_send_videos (:obj:`bool`): :obj:`True`, if the user is allowed to send videos.
.. versionadded:: 20.1
can_send_video_notes (:obj:`bool`): :obj:`True`, if the user is allowed to send video
notes.
.. versionadded:: 20.1
can_send_voice_notes (:obj:`bool`): :obj:`True`, if the user is allowed to send voice
notes.
.. versionadded:: 20.1
"""
__slots__ = (
"can_add_web_page_previews",
"can_change_info",
"can_invite_users",
"can_manage_topics",
"can_pin_messages",
"can_send_audios",
"can_send_documents",
"can_send_messages",
"can_send_other_messages",
"can_send_photos",
"can_send_polls",
"can_send_video_notes",
"can_send_videos",
"can_send_voice_notes",
)
def __init__(
self,
can_send_messages: Optional[bool] = None,
can_send_polls: Optional[bool] = None,
can_send_other_messages: Optional[bool] = None,
can_add_web_page_previews: Optional[bool] = None,
can_change_info: Optional[bool] = None,
can_invite_users: Optional[bool] = None,
can_pin_messages: Optional[bool] = None,
can_manage_topics: Optional[bool] = None,
can_send_audios: Optional[bool] = None,
can_send_documents: Optional[bool] = None,
can_send_photos: Optional[bool] = None,
can_send_videos: Optional[bool] = None,
can_send_video_notes: Optional[bool] = None,
can_send_voice_notes: Optional[bool] = None,
*,
api_kwargs: Optional[JSONDict] = None,
):
super().__init__(api_kwargs=api_kwargs)
# Required
self.can_send_messages: Optional[bool] = can_send_messages
self.can_send_polls: Optional[bool] = can_send_polls
self.can_send_other_messages: Optional[bool] = can_send_other_messages
self.can_add_web_page_previews: Optional[bool] = can_add_web_page_previews
self.can_change_info: Optional[bool] = can_change_info
self.can_invite_users: Optional[bool] = can_invite_users
self.can_pin_messages: Optional[bool] = can_pin_messages
self.can_manage_topics: Optional[bool] = can_manage_topics
self.can_send_audios: Optional[bool] = can_send_audios
self.can_send_documents: Optional[bool] = can_send_documents
self.can_send_photos: Optional[bool] = can_send_photos
self.can_send_videos: Optional[bool] = can_send_videos
self.can_send_video_notes: Optional[bool] = can_send_video_notes
self.can_send_voice_notes: Optional[bool] = can_send_voice_notes
self._id_attrs = (
self.can_send_messages,
self.can_send_polls,
self.can_send_other_messages,
self.can_add_web_page_previews,
self.can_change_info,
self.can_invite_users,
self.can_pin_messages,
self.can_manage_topics,
self.can_send_audios,
self.can_send_documents,
self.can_send_photos,
self.can_send_videos,
self.can_send_video_notes,
self.can_send_voice_notes,
)
self._freeze()
@classmethod
def all_permissions(cls) -> "ChatPermissions":
"""
This method returns an :class:`ChatPermissions` instance with all attributes
set to :obj:`True`. This is e.g. useful when unrestricting a chat member with
:meth:`telegram.Bot.restrict_chat_member`.
.. versionadded:: 20.0
"""
return cls(*(14 * (True,)))
@classmethod
def no_permissions(cls) -> "ChatPermissions":
"""
This method returns an :class:`ChatPermissions` instance
with all attributes set to :obj:`False`.
.. versionadded:: 20.0
"""
return cls(*(14 * (False,)))
@classmethod
def de_json(cls, data: JSONDict, bot: Optional["Bot"] = None) -> "ChatPermissions":
"""See :meth:`telegram.TelegramObject.de_json`."""
data = cls._parse_data(data)
api_kwargs = {}
# This is a deprecated field that TG still returns for backwards compatibility
# Let's filter it out to speed up the de-json process
if data.get("can_send_media_messages") is not None:
api_kwargs["can_send_media_messages"] = data.pop("can_send_media_messages")
return super()._de_json(data=data, bot=bot, api_kwargs=api_kwargs)

View File

@@ -0,0 +1,392 @@
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2025
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser Public License for more details.
#
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an objects related to Telegram checklists."""
import datetime as dtm
from collections.abc import Sequence
from typing import TYPE_CHECKING, Optional
from telegram._messageentity import MessageEntity
from telegram._telegramobject import TelegramObject
from telegram._user import User
from telegram._utils.argumentparsing import de_json_optional, de_list_optional, parse_sequence_arg
from telegram._utils.datetime import extract_tzinfo_from_defaults, from_timestamp
from telegram._utils.entities import parse_message_entities, parse_message_entity
from telegram._utils.types import JSONDict
from telegram.constants import ZERO_DATE
if TYPE_CHECKING:
from telegram import Bot, Message
class ChecklistTask(TelegramObject):
"""
Describes a task in a checklist.
Objects of this class are comparable in terms of equality.
Two objects of this class are considered equal, if all their :attr:`id` is equal.
.. versionadded:: 22.3
Args:
id (:obj:`int`): Unique identifier of the task.
text (:obj:`str`): Text of the task.
text_entities (Sequence[:class:`telegram.MessageEntity`], optional): Special
entities that appear in the task text.
completed_by_user (:class:`telegram.User`, optional): User that completed the task; omitted
if the task wasn't completed
completion_date (:class:`datetime.datetime`, optional): Point in time when
the task was completed; :attr:`~telegram.constants.ZERO_DATE` if the task wasn't
completed
|datetime_localization|
Attributes:
id (:obj:`int`): Unique identifier of the task.
text (:obj:`str`): Text of the task.
text_entities (Tuple[:class:`telegram.MessageEntity`]): Optional. Special
entities that appear in the task text.
completed_by_user (:class:`telegram.User`): Optional. User that completed the task; omitted
if the task wasn't completed
completion_date (:class:`datetime.datetime`): Optional. Point in time when
the task was completed; :attr:`~telegram.constants.ZERO_DATE` if the task wasn't
completed
|datetime_localization|
"""
__slots__ = (
"completed_by_user",
"completion_date",
"id",
"text",
"text_entities",
)
def __init__(
self,
id: int, # pylint: disable=redefined-builtin
text: str,
text_entities: Optional[Sequence[MessageEntity]] = None,
completed_by_user: Optional[User] = None,
completion_date: Optional[dtm.datetime] = None,
*,
api_kwargs: Optional[JSONDict] = None,
):
super().__init__(api_kwargs=api_kwargs)
self.id: int = id
self.text: str = text
self.text_entities: tuple[MessageEntity, ...] = parse_sequence_arg(text_entities)
self.completed_by_user: Optional[User] = completed_by_user
self.completion_date: Optional[dtm.datetime] = completion_date
self._id_attrs = (self.id,)
self._freeze()
@classmethod
def de_json(cls, data: JSONDict, bot: Optional["Bot"] = None) -> "ChecklistTask":
"""See :meth:`telegram.TelegramObject.de_json`."""
data = cls._parse_data(data)
# Get the local timezone from the bot if it has defaults
loc_tzinfo = extract_tzinfo_from_defaults(bot)
if (date := data.get("completion_date")) == 0:
data["completion_date"] = ZERO_DATE
else:
data["completion_date"] = from_timestamp(date, tzinfo=loc_tzinfo)
data["completed_by_user"] = de_json_optional(data.get("completed_by_user"), User, bot)
data["text_entities"] = de_list_optional(data.get("text_entities"), MessageEntity, bot)
return super().de_json(data=data, bot=bot)
def parse_entity(self, entity: MessageEntity) -> str:
"""Returns the text in :attr:`text`
from a given :class:`telegram.MessageEntity` of :attr:`text_entities`.
Note:
This method is present because Telegram calculates the offset and length in
UTF-16 codepoint pairs, which some versions of Python don't handle automatically.
(That is, you can't just slice ``ChecklistTask.text`` with the offset and length.)
Args:
entity (:class:`telegram.MessageEntity`): The entity to extract the text from. It must
be an entity that belongs to :attr:`text_entities`.
Returns:
:obj:`str`: The text of the given entity.
"""
return parse_message_entity(self.text, entity)
def parse_entities(self, types: Optional[list[str]] = None) -> dict[MessageEntity, str]:
"""
Returns a :obj:`dict` that maps :class:`telegram.MessageEntity` to :obj:`str`.
It contains entities from this checklist task filtered by their ``type`` attribute as
the key, and the text that each entity belongs to as the value of the :obj:`dict`.
Note:
This method should always be used instead of the :attr:`text_entities`
attribute, since it calculates the correct substring from the message text based on
UTF-16 codepoints. See :attr:`parse_entity` for more info.
Args:
types (list[:obj:`str`], optional): List of ``MessageEntity`` types as strings. If the
``type`` attribute of an entity is contained in this list, it will be returned.
Defaults to :attr:`telegram.MessageEntity.ALL_TYPES`.
Returns:
dict[:class:`telegram.MessageEntity`, :obj:`str`]: A dictionary of entities mapped to
the text that belongs to them, calculated based on UTF-16 codepoints.
"""
return parse_message_entities(self.text, self.text_entities, types)
class Checklist(TelegramObject):
"""
Describes a checklist.
Objects of this class are comparable in terms of equality.
Two objects of this class are considered equal, if all their :attr:`tasks` are equal.
.. versionadded:: 22.3
Args:
title (:obj:`str`): Title of the checklist.
title_entities (Sequence[:class:`telegram.MessageEntity`], optional): Special
entities that appear in the checklist title.
tasks (Sequence[:class:`telegram.ChecklistTask`]): List of tasks in the checklist.
others_can_add_tasks (:obj:`bool`, optional): :obj:`True` if users other than the creator
of the list can add tasks to the list
others_can_mark_tasks_as_done (:obj:`bool`, optional): :obj:`True` if users other than the
creator of the list can mark tasks as done or not done
Attributes:
title (:obj:`str`): Title of the checklist.
title_entities (Tuple[:class:`telegram.MessageEntity`]): Optional. Special
entities that appear in the checklist title.
tasks (Tuple[:class:`telegram.ChecklistTask`]): List of tasks in the checklist.
others_can_add_tasks (:obj:`bool`): Optional. :obj:`True` if users other than the creator
of the list can add tasks to the list
others_can_mark_tasks_as_done (:obj:`bool`): Optional. :obj:`True` if users other than the
creator of the list can mark tasks as done or not done
"""
__slots__ = (
"others_can_add_tasks",
"others_can_mark_tasks_as_done",
"tasks",
"title",
"title_entities",
)
def __init__(
self,
title: str,
tasks: Sequence[ChecklistTask],
title_entities: Optional[Sequence[MessageEntity]] = None,
others_can_add_tasks: Optional[bool] = None,
others_can_mark_tasks_as_done: Optional[bool] = None,
*,
api_kwargs: Optional[JSONDict] = None,
):
super().__init__(api_kwargs=api_kwargs)
self.title: str = title
self.title_entities: tuple[MessageEntity, ...] = parse_sequence_arg(title_entities)
self.tasks: tuple[ChecklistTask, ...] = parse_sequence_arg(tasks)
self.others_can_add_tasks: Optional[bool] = others_can_add_tasks
self.others_can_mark_tasks_as_done: Optional[bool] = others_can_mark_tasks_as_done
self._id_attrs = (self.tasks,)
self._freeze()
@classmethod
def de_json(cls, data: JSONDict, bot: Optional["Bot"] = None) -> "Checklist":
"""See :meth:`telegram.TelegramObject.de_json`."""
data = cls._parse_data(data)
data["title_entities"] = de_list_optional(data.get("title_entities"), MessageEntity, bot)
data["tasks"] = de_list_optional(data.get("tasks"), ChecklistTask, bot)
return super().de_json(data=data, bot=bot)
def parse_entity(self, entity: MessageEntity) -> str:
"""Returns the text in :attr:`title`
from a given :class:`telegram.MessageEntity` of :attr:`title_entities`.
Note:
This method is present because Telegram calculates the offset and length in
UTF-16 codepoint pairs, which some versions of Python don't handle automatically.
(That is, you can't just slice :attr:`title` with the offset and length.)
Args:
entity (:class:`telegram.MessageEntity`): The entity to extract the text from. It must
be an entity that belongs to :attr:`title_entities`.
Returns:
:obj:`str`: The text of the given entity.
"""
return parse_message_entity(self.title, entity)
def parse_entities(self, types: Optional[list[str]] = None) -> dict[MessageEntity, str]:
"""
Returns a :obj:`dict` that maps :class:`telegram.MessageEntity` to :obj:`str`.
It contains entities from this checklist's title filtered by their ``type`` attribute as
the key, and the text that each entity belongs to as the value of the :obj:`dict`.
Note:
This method should always be used instead of the :attr:`title_entities`
attribute, since it calculates the correct substring from the message text based on
UTF-16 codepoints. See :attr:`parse_entity` for more info.
Args:
types (list[:obj:`str`], optional): List of ``MessageEntity`` types as strings. If the
``type`` attribute of an entity is contained in this list, it will be returned.
Defaults to :attr:`telegram.MessageEntity.ALL_TYPES`.
Returns:
dict[:class:`telegram.MessageEntity`, :obj:`str`]: A dictionary of entities mapped to
the text that belongs to them, calculated based on UTF-16 codepoints.
"""
return parse_message_entities(self.title, self.title_entities, types)
class ChecklistTasksDone(TelegramObject):
"""
Describes a service message about checklist tasks marked as done or not done.
Objects of this class are comparable in terms of equality.
Two objects of this class are considered equal, if their :attr:`marked_as_done_task_ids` and
:attr:`marked_as_not_done_task_ids` are equal.
.. versionadded:: 22.3
Args:
checklist_message (:class:`telegram.Message`, optional): Message containing the checklist
whose tasks were marked as done or not done. Note that the ~:class:`telegram.Message`
object in this field will not contain the :attr:`~telegram.Message.reply_to_message`
field even if it itself is a reply.
marked_as_done_task_ids (Sequence[:obj:`int`], optional): Identifiers of the tasks that
were marked as done
marked_as_not_done_task_ids (Sequence[:obj:`int`], optional): Identifiers of the tasks that
were marked as not done
Attributes:
checklist_message (:class:`telegram.Message`): Optional. Message containing the checklist
whose tasks were marked as done or not done. Note that the ~:class:`telegram.Message`
object in this field will not contain the :attr:`~telegram.Message.reply_to_message`
field even if it itself is a reply.
marked_as_done_task_ids (Tuple[:obj:`int`]): Optional. Identifiers of the tasks that were
marked as done
marked_as_not_done_task_ids (Tuple[:obj:`int`]): Optional. Identifiers of the tasks that
were marked as not done
"""
__slots__ = (
"checklist_message",
"marked_as_done_task_ids",
"marked_as_not_done_task_ids",
)
def __init__(
self,
checklist_message: Optional["Message"] = None,
marked_as_done_task_ids: Optional[Sequence[int]] = None,
marked_as_not_done_task_ids: Optional[Sequence[int]] = None,
*,
api_kwargs: Optional[JSONDict] = None,
):
super().__init__(api_kwargs=api_kwargs)
self.checklist_message: Optional[Message] = checklist_message
self.marked_as_done_task_ids: tuple[int, ...] = parse_sequence_arg(marked_as_done_task_ids)
self.marked_as_not_done_task_ids: tuple[int, ...] = parse_sequence_arg(
marked_as_not_done_task_ids
)
self._id_attrs = (self.marked_as_done_task_ids, self.marked_as_not_done_task_ids)
self._freeze()
@classmethod
def de_json(cls, data: JSONDict, bot: Optional["Bot"] = None) -> "ChecklistTasksDone":
"""See :meth:`telegram.TelegramObject.de_json`."""
data = cls._parse_data(data)
# needs to be imported here to avoid circular import issues
from telegram import Message # pylint: disable=import-outside-toplevel # noqa: PLC0415
data["checklist_message"] = de_json_optional(data.get("checklist_message"), Message, bot)
return super().de_json(data=data, bot=bot)
class ChecklistTasksAdded(TelegramObject):
"""
Describes a service message about tasks added to a checklist.
Objects of this class are comparable in terms of equality.
Two objects of this class are considered equal, if their :attr:`tasks` are equal.
.. versionadded:: 22.3
Args:
checklist_message (:class:`telegram.Message`, optional): Message containing the checklist
to which tasks were added. Note that the ~:class:`telegram.Message`
object in this field will not contain the :attr:`~telegram.Message.reply_to_message`
field even if it itself is a reply.
tasks (Sequence[:class:`telegram.ChecklistTask`]): List of tasks added to the checklist
Attributes:
checklist_message (:class:`telegram.Message`): Optional. Message containing the checklist
to which tasks were added. Note that the ~:class:`telegram.Message`
object in this field will not contain the :attr:`~telegram.Message.reply_to_message`
field even if it itself is a reply.
tasks (Tuple[:class:`telegram.ChecklistTask`]): List of tasks added to the checklist
"""
__slots__ = ("checklist_message", "tasks")
def __init__(
self,
tasks: Sequence[ChecklistTask],
checklist_message: Optional["Message"] = None,
*,
api_kwargs: Optional[JSONDict] = None,
):
super().__init__(api_kwargs=api_kwargs)
self.checklist_message: Optional[Message] = checklist_message
self.tasks: tuple[ChecklistTask, ...] = parse_sequence_arg(tasks)
self._id_attrs = (self.tasks,)
self._freeze()
@classmethod
def de_json(cls, data: JSONDict, bot: Optional["Bot"] = None) -> "ChecklistTasksAdded":
"""See :meth:`telegram.TelegramObject.de_json`."""
data = cls._parse_data(data)
# needs to be imported here to avoid circular import issues
from telegram import Message # pylint: disable=import-outside-toplevel # noqa: PLC0415
data["checklist_message"] = de_json_optional(data.get("checklist_message"), Message, bot)
data["tasks"] = ChecklistTask.de_list(data.get("tasks", []), bot)
return super().de_json(data=data, bot=bot)

View File

@@ -0,0 +1,105 @@
#!/usr/bin/env python
# pylint: disable=too-many-arguments
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2025
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser Public License for more details.
#
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents a Telegram ChosenInlineResult."""
from typing import TYPE_CHECKING, Optional
from telegram._files.location import Location
from telegram._telegramobject import TelegramObject
from telegram._user import User
from telegram._utils.argumentparsing import de_json_optional
from telegram._utils.types import JSONDict
if TYPE_CHECKING:
from telegram import Bot
class ChosenInlineResult(TelegramObject):
"""
Represents a result of an inline query that was chosen by the user and sent to their chat
partner.
Objects of this class are comparable in terms of equality. Two objects of this class are
considered equal, if their :attr:`result_id` is equal.
Note:
* In Python :keyword:`from` is a reserved word. Use :paramref:`from_user` instead.
* It is necessary to enable inline feedback via `@Botfather <https://t.me/BotFather>`_ in
order to receive these objects in updates.
Args:
result_id (:obj:`str`): The unique identifier for the result that was chosen.
from_user (:class:`telegram.User`): The user that chose the result.
location (:class:`telegram.Location`, optional): Sender location, only for bots that
require user location.
inline_message_id (:obj:`str`, optional): 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 (:obj:`str`): The query that was used to obtain the result.
Attributes:
result_id (:obj:`str`): The unique identifier for the result that was chosen.
from_user (:class:`telegram.User`): The user that chose the result.
location (:class:`telegram.Location`): Optional. Sender location, only for bots that
require user location.
inline_message_id (:obj:`str`): Optional. 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 (:obj:`str`): The query that was used to obtain the result.
"""
__slots__ = ("from_user", "inline_message_id", "location", "query", "result_id")
def __init__(
self,
result_id: str,
from_user: User,
query: str,
location: Optional[Location] = None,
inline_message_id: Optional[str] = None,
*,
api_kwargs: Optional[JSONDict] = None,
):
super().__init__(api_kwargs=api_kwargs)
# Required
self.result_id: str = result_id
self.from_user: User = from_user
self.query: str = query
# Optionals
self.location: Optional[Location] = location
self.inline_message_id: Optional[str] = inline_message_id
self._id_attrs = (self.result_id,)
self._freeze()
@classmethod
def de_json(cls, data: JSONDict, bot: Optional["Bot"] = None) -> "ChosenInlineResult":
"""See :meth:`telegram.TelegramObject.de_json`."""
data = cls._parse_data(data)
# Required
data["from_user"] = de_json_optional(data.pop("from", None), User, bot)
# Optionals
data["location"] = de_json_optional(data.get("location"), Location, bot)
return super().de_json(data=data, bot=bot)

View File

@@ -0,0 +1,55 @@
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2025
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser Public License for more details.
#
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents a Telegram CopyTextButton."""
from typing import Optional
from telegram._telegramobject import TelegramObject
from telegram._utils.types import JSONDict
class CopyTextButton(TelegramObject):
"""
This object represents an inline keyboard button that copies specified text to the clipboard.
Objects of this class are comparable in terms of equality. Two objects of this class are
considered equal, if their :attr:`text` is equal.
.. versionadded:: 21.7
Args:
text (:obj:`str`): The text to be copied to the clipboard;
:tg-const:`telegram.constants.InlineKeyboardButtonLimit.MIN_COPY_TEXT`-
:tg-const:`telegram.constants.InlineKeyboardButtonLimit.MAX_COPY_TEXT` characters
Attributes:
text (:obj:`str`): The text to be copied to the clipboard;
:tg-const:`telegram.constants.InlineKeyboardButtonLimit.MIN_COPY_TEXT`-
:tg-const:`telegram.constants.InlineKeyboardButtonLimit.MAX_COPY_TEXT` characters
"""
__slots__ = ("text",)
def __init__(self, text: str, *, api_kwargs: Optional[JSONDict] = None):
super().__init__(api_kwargs=api_kwargs)
self.text: str = text
self._id_attrs = (self.text,)
self._freeze()

View File

@@ -0,0 +1,160 @@
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2025
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser Public License for more details.
#
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents a Telegram Dice."""
from typing import Final, Optional
from telegram import constants
from telegram._telegramobject import TelegramObject
from telegram._utils.types import JSONDict
class Dice(TelegramObject):
"""
This object represents an animated emoji with a random value for currently supported base
emoji. (The singular form of "dice" is "die". However, PTB mimics the Telegram API, which uses
the term "dice".)
Objects of this class are comparable in terms of equality. Two objects of this class are
considered equal, if their :attr:`value` and :attr:`emoji` are equal.
Note:
If :attr:`emoji` is :tg-const:`telegram.Dice.DARTS`, a value of 6 currently
represents a bullseye, while a value of 1 indicates that the dartboard was missed.
However, this behaviour is undocumented and might be changed by Telegram.
If :attr:`emoji` is :tg-const:`telegram.Dice.BASKETBALL`, a value of 4 or 5
currently score a basket, while a value of 1 to 3 indicates that the basket was missed.
However, this behaviour is undocumented and might be changed by Telegram.
If :attr:`emoji` is :tg-const:`telegram.Dice.FOOTBALL`, a value of 4 to 5
currently scores a goal, while a value of 1 to 3 indicates that the goal was missed.
However, this behaviour is undocumented and might be changed by Telegram.
If :attr:`emoji` is :tg-const:`telegram.Dice.BOWLING`, a value of 6 knocks
all the pins, while a value of 1 means all the pins were missed.
However, this behaviour is undocumented and might be changed by Telegram.
If :attr:`emoji` is :tg-const:`telegram.Dice.SLOT_MACHINE`, each value
corresponds to a unique combination of symbols, which
can be found in our
:wiki:`wiki <Code-snippets#map-a-slot-machine-dice-value-to-the-corresponding-symbols>`.
However, this behaviour is undocumented and might be changed by Telegram.
..
In args, some links for limits of `value` intentionally point to constants for only
one emoji of a group to avoid duplication. For example, maximum value for Dice, Darts and
Bowling is linked to a constant for Bowling.
Args:
value (:obj:`int`): Value of the dice.
:tg-const:`telegram.Dice.MIN_VALUE`-:tg-const:`telegram.Dice.MAX_VALUE_BOWLING`
for :tg-const:`telegram.Dice.DICE`, :tg-const:`telegram.Dice.DARTS` and
:tg-const:`telegram.Dice.BOWLING` base emoji,
:tg-const:`telegram.Dice.MIN_VALUE`-:tg-const:`telegram.Dice.MAX_VALUE_BASKETBALL`
for :tg-const:`telegram.Dice.BASKETBALL` and :tg-const:`telegram.Dice.FOOTBALL`
base emoji,
:tg-const:`telegram.Dice.MIN_VALUE`-:tg-const:`telegram.Dice.MAX_VALUE_SLOT_MACHINE`
for :tg-const:`telegram.Dice.SLOT_MACHINE` base emoji.
emoji (:obj:`str`): Emoji on which the dice throw animation is based.
Attributes:
value (:obj:`int`): Value of the dice.
:tg-const:`telegram.Dice.MIN_VALUE`-:tg-const:`telegram.Dice.MAX_VALUE_BOWLING`
for :tg-const:`telegram.Dice.DICE`, :tg-const:`telegram.Dice.DARTS` and
:tg-const:`telegram.Dice.BOWLING` base emoji,
:tg-const:`telegram.Dice.MIN_VALUE`-:tg-const:`telegram.Dice.MAX_VALUE_BASKETBALL`
for :tg-const:`telegram.Dice.BASKETBALL` and :tg-const:`telegram.Dice.FOOTBALL`
base emoji,
:tg-const:`telegram.Dice.MIN_VALUE`-:tg-const:`telegram.Dice.MAX_VALUE_SLOT_MACHINE`
for :tg-const:`telegram.Dice.SLOT_MACHINE` base emoji.
emoji (:obj:`str`): Emoji on which the dice throw animation is based.
"""
__slots__ = ("emoji", "value")
def __init__(self, value: int, emoji: str, *, api_kwargs: Optional[JSONDict] = None):
super().__init__(api_kwargs=api_kwargs)
self.value: int = value
self.emoji: str = emoji
self._id_attrs = (self.value, self.emoji)
self._freeze()
DICE: Final[str] = constants.DiceEmoji.DICE
""":const:`telegram.constants.DiceEmoji.DICE`"""
DARTS: Final[str] = constants.DiceEmoji.DARTS
""":const:`telegram.constants.DiceEmoji.DARTS`"""
BASKETBALL: Final[str] = constants.DiceEmoji.BASKETBALL
""":const:`telegram.constants.DiceEmoji.BASKETBALL`"""
FOOTBALL: Final[str] = constants.DiceEmoji.FOOTBALL
""":const:`telegram.constants.DiceEmoji.FOOTBALL`"""
SLOT_MACHINE: Final[str] = constants.DiceEmoji.SLOT_MACHINE
""":const:`telegram.constants.DiceEmoji.SLOT_MACHINE`"""
BOWLING: Final[str] = constants.DiceEmoji.BOWLING
"""
:const:`telegram.constants.DiceEmoji.BOWLING`
.. versionadded:: 13.4
"""
ALL_EMOJI: Final[list[str]] = list(constants.DiceEmoji)
"""list[:obj:`str`]: A list of all available dice emoji."""
MIN_VALUE: Final[int] = constants.DiceLimit.MIN_VALUE
""":const:`telegram.constants.DiceLimit.MIN_VALUE`
.. versionadded:: 20.0
"""
MAX_VALUE_BOWLING: Final[int] = constants.DiceLimit.MAX_VALUE_BOWLING
""":const:`telegram.constants.DiceLimit.MAX_VALUE_BOWLING`
.. versionadded:: 20.0
"""
MAX_VALUE_DARTS: Final[int] = constants.DiceLimit.MAX_VALUE_DARTS
""":const:`telegram.constants.DiceLimit.MAX_VALUE_DARTS`
.. versionadded:: 20.0
"""
MAX_VALUE_DICE: Final[int] = constants.DiceLimit.MAX_VALUE_DICE
""":const:`telegram.constants.DiceLimit.MAX_VALUE_DICE`
.. versionadded:: 20.0
"""
MAX_VALUE_BASKETBALL: Final[int] = constants.DiceLimit.MAX_VALUE_BASKETBALL
""":const:`telegram.constants.DiceLimit.MAX_VALUE_BASKETBALL`
.. versionadded:: 20.0
"""
MAX_VALUE_FOOTBALL: Final[int] = constants.DiceLimit.MAX_VALUE_FOOTBALL
""":const:`telegram.constants.DiceLimit.MAX_VALUE_FOOTBALL`
.. versionadded:: 20.0
"""
MAX_VALUE_SLOT_MACHINE: Final[int] = constants.DiceLimit.MAX_VALUE_SLOT_MACHINE
""":const:`telegram.constants.DiceLimit.MAX_VALUE_SLOT_MACHINE`
.. versionadded:: 20.0
"""

View File

@@ -0,0 +1,73 @@
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2025
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser Public License for more details.
#
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents a Direct Message Price."""
from typing import Optional
from telegram._telegramobject import TelegramObject
from telegram._utils.types import JSONDict
class DirectMessagePriceChanged(TelegramObject):
"""
Describes a service message about a change in the price of direct messages sent to a channel
chat.
.. versionadded:: 22.3
Objects of this class are comparable in terms of equality. Two objects of this class are
considered equal, if their :attr:`are_direct_messages_enabled`, and
:attr:`direct_message_star_count` are equal.
Args:
are_direct_messages_enabled (:obj:`bool`):
:obj:`True`, if direct messages are enabled for the channel chat; :obj:`False`
otherwise.
direct_message_star_count (:obj:`int`, optional):
The new number of Telegram Stars that must be paid by users for each direct message
sent to the channel. Does not apply to users who have been exempted by administrators.
Defaults to ``0``.
Attributes:
are_direct_messages_enabled (:obj:`bool`):
:obj:`True`, if direct messages are enabled for the channel chat; :obj:`False`
otherwise.
direct_message_star_count (:obj:`int`):
Optional. The new number of Telegram Stars that must be paid by users for each direct
message sent to the channel. Does not apply to users who have been exempted by
administrators. Defaults to ``0``.
"""
__slots__ = ("are_direct_messages_enabled", "direct_message_star_count")
def __init__(
self,
are_direct_messages_enabled: bool,
direct_message_star_count: Optional[int] = None,
*,
api_kwargs: Optional[JSONDict] = None,
):
super().__init__(api_kwargs=api_kwargs)
self.are_direct_messages_enabled: bool = are_direct_messages_enabled
self.direct_message_star_count: Optional[int] = direct_message_star_count
self._id_attrs = (self.are_direct_messages_enabled, self.direct_message_star_count)
self._freeze()

View File

@@ -0,0 +1,100 @@
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2025
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser Public License for more details.
#
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""Common base class for media objects"""
from typing import TYPE_CHECKING, Optional
from telegram._telegramobject import TelegramObject
from telegram._utils.defaultvalue import DEFAULT_NONE
from telegram._utils.types import JSONDict, ODVInput
if TYPE_CHECKING:
from telegram import File
class _BaseMedium(TelegramObject):
"""Base class for objects representing the various media file types.
Objects of this class are comparable in terms of equality. Two objects of this class are
considered equal, if their :attr:`file_unique_id` is equal.
Args:
file_id (:obj:`str`): Identifier for this file, which can be used to download
or reuse the file.
file_unique_id (:obj:`str`): Unique identifier for this file, which
is supposed to be the same over time and for different bots.
Can't be used to download or reuse the file.
file_size (:obj:`int`, optional): File size.
Attributes:
file_id (:obj:`str`): File identifier.
file_unique_id (:obj:`str`): Unique identifier for this file, which
is supposed to be the same over time and for different bots.
Can't be used to download or reuse the file.
file_size (:obj:`int`): Optional. File size.
"""
__slots__ = ("file_id", "file_size", "file_unique_id")
def __init__(
self,
file_id: str,
file_unique_id: str,
file_size: Optional[int] = None,
*,
api_kwargs: Optional[JSONDict] = None,
):
super().__init__(api_kwargs=api_kwargs)
# Required
self.file_id: str = str(file_id)
self.file_unique_id: str = str(file_unique_id)
# Optionals
self.file_size: Optional[int] = file_size
self._id_attrs = (self.file_unique_id,)
async def get_file(
self,
*,
read_timeout: ODVInput[float] = DEFAULT_NONE,
write_timeout: ODVInput[float] = DEFAULT_NONE,
connect_timeout: ODVInput[float] = DEFAULT_NONE,
pool_timeout: ODVInput[float] = DEFAULT_NONE,
api_kwargs: Optional[JSONDict] = None,
) -> "File":
"""Convenience wrapper over :meth:`telegram.Bot.get_file`
For the documentation of the arguments, please see :meth:`telegram.Bot.get_file`.
Returns:
:class:`telegram.File`
Raises:
:class:`telegram.error.TelegramError`
"""
return await self.get_bot().get_file(
file_id=self.file_id,
read_timeout=read_timeout,
write_timeout=write_timeout,
connect_timeout=connect_timeout,
pool_timeout=pool_timeout,
api_kwargs=api_kwargs,
)

View File

@@ -0,0 +1,101 @@
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2025
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser Public License for more details.
#
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""Common base class for media objects with thumbnails"""
from typing import TYPE_CHECKING, Optional, TypeVar
from telegram._files._basemedium import _BaseMedium
from telegram._files.photosize import PhotoSize
from telegram._utils.argumentparsing import de_json_optional
from telegram._utils.types import JSONDict
if TYPE_CHECKING:
from telegram import Bot
# pylint: disable=invalid-name
ThumbedMT_co = TypeVar("ThumbedMT_co", bound="_BaseThumbedMedium", covariant=True)
class _BaseThumbedMedium(_BaseMedium):
"""
Base class for objects representing the various media file types that may include a thumbnail.
Objects of this class are comparable in terms of equality. Two objects of this class are
considered equal, if their :attr:`file_unique_id` is equal.
Args:
file_id (:obj:`str`): Identifier for this file, which can be used to download
or reuse the file.
file_unique_id (:obj:`str`): Unique identifier for this file, which
is supposed to be the same over time and for different bots.
Can't be used to download or reuse the file.
file_size (:obj:`int`, optional): File size.
thumbnail (:class:`telegram.PhotoSize`, optional): Thumbnail as defined by the sender.
.. versionadded:: 20.2
Attributes:
file_id (:obj:`str`): File identifier.
file_unique_id (:obj:`str`): Unique identifier for this file, which
is supposed to be the same over time and for different bots.
Can't be used to download or reuse the file.
file_size (:obj:`int`): Optional. File size.
thumbnail (:class:`telegram.PhotoSize`): Optional. Thumbnail as defined by the sender.
.. versionadded:: 20.2
"""
__slots__ = ("thumbnail",)
def __init__(
self,
file_id: str,
file_unique_id: str,
file_size: Optional[int] = None,
thumbnail: Optional[PhotoSize] = None,
*,
api_kwargs: Optional[JSONDict] = None,
):
super().__init__(
file_id=file_id,
file_unique_id=file_unique_id,
file_size=file_size,
api_kwargs=api_kwargs,
)
self.thumbnail: Optional[PhotoSize] = thumbnail
@classmethod
def de_json(
cls: type[ThumbedMT_co], data: JSONDict, bot: Optional["Bot"] = None
) -> ThumbedMT_co:
"""See :meth:`telegram.TelegramObject.de_json`."""
data = cls._parse_data(data)
# In case this wasn't already done by the subclass
if not isinstance(data.get("thumbnail"), PhotoSize):
data["thumbnail"] = de_json_optional(data.get("thumbnail"), PhotoSize, bot)
api_kwargs = {}
# This is a deprecated field that TG still returns for backwards compatibility
# Let's filter it out to speed up the de-json process
if data.get("thumb") is not None:
api_kwargs["thumb"] = data.pop("thumb")
return super()._de_json(data=data, bot=bot, api_kwargs=api_kwargs)

View File

@@ -0,0 +1,166 @@
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2025
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser Public License for more details.
#
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains objects that represent paid media in Telegram."""
import datetime as dtm
from typing import Final, Optional, Union
from telegram import constants
from telegram._files.inputfile import InputFile
from telegram._telegramobject import TelegramObject
from telegram._utils import enum
from telegram._utils.argumentparsing import to_timedelta
from telegram._utils.files import parse_file_input
from telegram._utils.types import FileInput, JSONDict
class InputStoryContent(TelegramObject):
"""This object describes the content of a story to post. Currently, it can be one of:
* :class:`telegram.InputStoryContentPhoto`
* :class:`telegram.InputStoryContentVideo`
.. versionadded:: 22.1
Args:
type (:obj:`str`): Type of the content.
Attributes:
type (:obj:`str`): Type of the content.
"""
__slots__ = ("type",)
PHOTO: Final[str] = constants.InputStoryContentType.PHOTO
""":const:`telegram.constants.InputStoryContentType.PHOTO`"""
VIDEO: Final[str] = constants.InputStoryContentType.VIDEO
""":const:`telegram.constants.InputStoryContentType.VIDEO`"""
def __init__(
self,
type: str, # pylint: disable=redefined-builtin
*,
api_kwargs: Optional[JSONDict] = None,
) -> None:
super().__init__(api_kwargs=api_kwargs)
self.type: str = enum.get_member(constants.InputStoryContentType, type, type)
self._freeze()
@staticmethod
def _parse_file_input(file_input: FileInput) -> Union[str, InputFile]:
# We use local_mode=True because we don't have access to the actual setting and want
# things to work in local mode.
return parse_file_input(file_input, attach=True, local_mode=True)
class InputStoryContentPhoto(InputStoryContent):
"""Describes a photo to post as a story.
.. versionadded:: 22.1
Args:
photo (:term:`file object` | :obj:`bytes` | :class:`pathlib.Path` | :obj:`str`, \
optional): The photo to post as a story. The photo must be of the
size :tg-const:`telegram.constants.InputStoryContentLimit.PHOTO_WIDTH`
x :tg-const:`telegram.constants.InputStoryContentLimit.PHOTO_HEIGHT` and must not
exceed :tg-const:`telegram.constants.InputStoryContentLimit.PHOTOSIZE_UPLOAD` MB.
|uploadinputnopath|.
Attributes:
type (:obj:`str`): Type of the content, must be :attr:`~telegram.InputStoryContent.PHOTO`.
photo (:class:`telegram.InputFile`): The photo to post as a story. The photo must be of the
size :tg-const:`telegram.constants.InputStoryContentLimit.PHOTO_WIDTH`
x :tg-const:`telegram.constants.InputStoryContentLimit.PHOTO_HEIGHT` and must not
exceed :tg-const:`telegram.constants.InputStoryContentLimit.PHOTOSIZE_UPLOAD` MB.
"""
__slots__ = ("photo",)
def __init__(
self,
photo: FileInput,
*,
api_kwargs: Optional[JSONDict] = None,
) -> None:
super().__init__(type=InputStoryContent.PHOTO, api_kwargs=api_kwargs)
with self._unfrozen():
self.photo: Union[str, InputFile] = self._parse_file_input(photo)
class InputStoryContentVideo(InputStoryContent):
"""
Describes a video to post as a story.
.. versionadded:: 22.1
Args:
video (:term:`file object` | :obj:`bytes` | :class:`pathlib.Path` | :obj:`str`, \
optional): The video to post as a story. The video must be of
the size :tg-const:`telegram.constants.InputStoryContentLimit.VIDEO_WIDTH`
x :tg-const:`telegram.constants.InputStoryContentLimit.VIDEO_HEIGHT`,
streamable, encoded with ``H.265`` codec, with key frames added
each second in the ``MPEG4`` format, and must not exceed
:tg-const:`telegram.constants.InputStoryContentLimit.VIDEOSIZE_UPLOAD` MB.
|uploadinputnopath|.
duration (:class:`datetime.timedelta` | :obj:`int` | :obj:`float`, optional): Precise
duration of the video in seconds;
0-:tg-const:`telegram.constants.InputStoryContentLimit.MAX_VIDEO_DURATION`
cover_frame_timestamp (:class:`datetime.timedelta` | :obj:`int` | :obj:`float`, optional):
Timestamp in seconds of the frame that will be used as the static cover for the story.
Defaults to ``0.0``.
is_animation (:obj:`bool`, optional): Pass :obj:`True` if the video has no sound
Attributes:
type (:obj:`str`): Type of the content, must be :attr:`~telegram.InputStoryContent.VIDEO`.
video (:class:`telegram.InputFile`): The video to post as a story. The video must be of
the size :tg-const:`telegram.constants.InputStoryContentLimit.VIDEO_WIDTH`
x :tg-const:`telegram.constants.InputStoryContentLimit.VIDEO_HEIGHT`,
streamable, encoded with ``H.265`` codec, with key frames added
each second in the ``MPEG4`` format, and must not exceed
:tg-const:`telegram.constants.InputStoryContentLimit.VIDEOSIZE_UPLOAD` MB.
duration (:class:`datetime.timedelta`): Optional. Precise duration of the video in seconds;
0-:tg-const:`telegram.constants.InputStoryContentLimit.MAX_VIDEO_DURATION`
cover_frame_timestamp (:class:`datetime.timedelta`): Optional. Timestamp in seconds of the
frame that will be used as the static cover for the story. Defaults to ``0.0``.
is_animation (:obj:`bool`): Optional. Pass :obj:`True` if the video has no sound
"""
__slots__ = ("cover_frame_timestamp", "duration", "is_animation", "video")
def __init__(
self,
video: FileInput,
duration: Optional[Union[float, dtm.timedelta]] = None,
cover_frame_timestamp: Optional[Union[float, dtm.timedelta]] = None,
is_animation: Optional[bool] = None,
*,
api_kwargs: Optional[JSONDict] = None,
) -> None:
super().__init__(type=InputStoryContent.VIDEO, api_kwargs=api_kwargs)
with self._unfrozen():
self.video: Union[str, InputFile] = self._parse_file_input(video)
self.duration: Optional[dtm.timedelta] = to_timedelta(duration)
self.cover_frame_timestamp: Optional[dtm.timedelta] = to_timedelta(
cover_frame_timestamp
)
self.is_animation: Optional[bool] = is_animation

View File

@@ -0,0 +1,119 @@
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2025
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser Public License for more details.
#
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents a Telegram Animation."""
import datetime as dtm
from typing import Optional, Union
from telegram._files._basethumbedmedium import _BaseThumbedMedium
from telegram._files.photosize import PhotoSize
from telegram._utils.argumentparsing import to_timedelta
from telegram._utils.datetime import get_timedelta_value
from telegram._utils.types import JSONDict, TimePeriod
class Animation(_BaseThumbedMedium):
"""This object represents an animation file (GIF or H.264/MPEG-4 AVC video without sound).
Objects of this class are comparable in terms of equality. Two objects of this class are
considered equal, if their :attr:`file_unique_id` is equal.
.. versionchanged:: 20.5
|removed_thumb_note|
Args:
file_id (:obj:`str`): Identifier for this file, which can be used to download
or reuse the file.
file_unique_id (:obj:`str`): Unique identifier for this file, which
is supposed to be the same over time and for different bots.
Can't be used to download or reuse the file.
width (:obj:`int`): Video width as defined by the sender.
height (:obj:`int`): Video height as defined by the sender.
duration (:obj:`int` | :class:`datetime.timedelta`, optional): Duration of the video
in seconds as defined by the sender.
.. versionchanged:: v22.2
|time-period-input|
file_name (:obj:`str`, optional): Original animation filename as defined by the sender.
mime_type (:obj:`str`, optional): MIME type of the file as defined by the sender.
file_size (:obj:`int`, optional): File size in bytes.
thumbnail (:class:`telegram.PhotoSize`, optional): Animation thumbnail as defined by
sender.
.. versionadded:: 20.2
Attributes:
file_id (:obj:`str`): Identifier for this file, which can be used to download
or reuse the file.
file_unique_id (:obj:`str`): Unique identifier for this file, which
is supposed to be the same over time and for different bots.
Can't be used to download or reuse the file.
width (:obj:`int`): Video width as defined by the sender.
height (:obj:`int`): Video height as defined by the sender.
duration (:obj:`int` | :class:`datetime.timedelta`): Duration of the video in seconds
as defined by the sender.
.. deprecated:: v22.2
|time-period-int-deprecated|
file_name (:obj:`str`): Optional. Original animation filename as defined by the sender.
mime_type (:obj:`str`): Optional. MIME type of the file as defined by the sender.
file_size (:obj:`int`): Optional. File size in bytes.
thumbnail (:class:`telegram.PhotoSize`): Optional. Animation thumbnail as defined by
sender.
.. versionadded:: 20.2
"""
__slots__ = ("_duration", "file_name", "height", "mime_type", "width")
def __init__(
self,
file_id: str,
file_unique_id: str,
width: int,
height: int,
duration: TimePeriod,
file_name: Optional[str] = None,
mime_type: Optional[str] = None,
file_size: Optional[int] = None,
thumbnail: Optional[PhotoSize] = None,
*,
api_kwargs: Optional[JSONDict] = None,
):
super().__init__(
file_id=file_id,
file_unique_id=file_unique_id,
file_size=file_size,
api_kwargs=api_kwargs,
thumbnail=thumbnail,
)
with self._unfrozen():
# Required
self.width: int = width
self.height: int = height
self._duration: dtm.timedelta = to_timedelta(duration)
# Optional
self.mime_type: Optional[str] = mime_type
self.file_name: Optional[str] = file_name
@property
def duration(self) -> Union[int, dtm.timedelta]:
return get_timedelta_value( # type: ignore[return-value]
self._duration, attribute="duration"
)

View File

@@ -0,0 +1,121 @@
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2025
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser Public License for more details.
#
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents a Telegram Audio."""
import datetime as dtm
from typing import Optional, Union
from telegram._files._basethumbedmedium import _BaseThumbedMedium
from telegram._files.photosize import PhotoSize
from telegram._utils.argumentparsing import to_timedelta
from telegram._utils.datetime import get_timedelta_value
from telegram._utils.types import JSONDict, TimePeriod
class Audio(_BaseThumbedMedium):
"""This object represents an audio file to be treated as music by the Telegram clients.
Objects of this class are comparable in terms of equality. Two objects of this class are
considered equal, if their :attr:`file_unique_id` is equal.
.. versionchanged:: 20.5
|removed_thumb_note|
Args:
file_id (:obj:`str`): Identifier for this file, which can be used to download
or reuse the file.
file_unique_id (:obj:`str`): Unique identifier for this file, which is supposed to be
the same over time and for different bots. Can't be used to download or reuse the file.
duration (:obj:`int` | :class:`datetime.timedelta`): Duration of the audio in
seconds as defined by the sender.
.. versionchanged:: v22.2
|time-period-input|
performer (:obj:`str`, optional): Performer of the audio as defined by the sender or by
audio tags.
title (:obj:`str`, optional): Title of the audio as defined by the sender or by audio tags.
file_name (:obj:`str`, optional): Original filename as defined by the sender.
mime_type (:obj:`str`, optional): MIME type of the file as defined by the sender.
file_size (:obj:`int`, optional): File size in bytes.
thumbnail (:class:`telegram.PhotoSize`, optional): Thumbnail of the album cover to
which the music file belongs.
.. versionadded:: 20.2
Attributes:
file_id (:obj:`str`): Identifier for this file, which can be used to download
or reuse the file.
file_unique_id (:obj:`str`): Unique identifier for this file, which is supposed to be
the same over time and for different bots. Can't be used to download or reuse the file.
duration (:obj:`int` | :class:`datetime.timedelta`): Duration of the audio in seconds as
defined by the sender.
.. deprecated:: v22.2
|time-period-int-deprecated|
performer (:obj:`str`): Optional. Performer of the audio as defined by the sender or by
audio tags.
title (:obj:`str`): Optional. Title of the audio as defined by the sender or by audio tags.
file_name (:obj:`str`): Optional. Original filename as defined by the sender.
mime_type (:obj:`str`): Optional. MIME type of the file as defined by the sender.
file_size (:obj:`int`): Optional. File size in bytes.
thumbnail (:class:`telegram.PhotoSize`): Optional. Thumbnail of the album cover to
which the music file belongs.
.. versionadded:: 20.2
"""
__slots__ = ("_duration", "file_name", "mime_type", "performer", "title")
def __init__(
self,
file_id: str,
file_unique_id: str,
duration: TimePeriod,
performer: Optional[str] = None,
title: Optional[str] = None,
mime_type: Optional[str] = None,
file_size: Optional[int] = None,
file_name: Optional[str] = None,
thumbnail: Optional[PhotoSize] = None,
*,
api_kwargs: Optional[JSONDict] = None,
):
super().__init__(
file_id=file_id,
file_unique_id=file_unique_id,
file_size=file_size,
thumbnail=thumbnail,
api_kwargs=api_kwargs,
)
with self._unfrozen():
# Required
self._duration: dtm.timedelta = to_timedelta(duration)
# Optional
self.performer: Optional[str] = performer
self.title: Optional[str] = title
self.mime_type: Optional[str] = mime_type
self.file_name: Optional[str] = file_name
@property
def duration(self) -> Union[int, dtm.timedelta]:
return get_timedelta_value( # type: ignore[return-value]
self._duration, attribute="duration"
)

View File

@@ -0,0 +1,176 @@
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2025
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser Public License for more details.
#
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents a Telegram ChatPhoto."""
from typing import TYPE_CHECKING, Final, Optional
from telegram import constants
from telegram._telegramobject import TelegramObject
from telegram._utils.defaultvalue import DEFAULT_NONE
from telegram._utils.types import JSONDict, ODVInput
if TYPE_CHECKING:
from telegram import File
class ChatPhoto(TelegramObject):
"""This object represents a chat photo.
Objects of this class are comparable in terms of equality. Two objects of this class are
considered equal, if their :attr:`small_file_unique_id` and :attr:`big_file_unique_id` are
equal.
Args:
small_file_id (:obj:`str`): File identifier of small
(:tg-const:`telegram.ChatPhoto.SIZE_SMALL` x :tg-const:`telegram.ChatPhoto.SIZE_SMALL`)
chat photo. This file_id can be used only for photo download and only for as long
as the photo is not changed.
small_file_unique_id (:obj:`str`): Unique file identifier of small
(:tg-const:`telegram.ChatPhoto.SIZE_SMALL` x :tg-const:`telegram.ChatPhoto.SIZE_SMALL`)
chat photo, which is supposed to be the same over time and for different bots.
Can't be used to download or reuse the file.
big_file_id (:obj:`str`): File identifier of big
(:tg-const:`telegram.ChatPhoto.SIZE_BIG` x :tg-const:`telegram.ChatPhoto.SIZE_BIG`)
chat photo. This file_id can be used only for photo download and only for as long as
the photo is not changed.
big_file_unique_id (:obj:`str`): Unique file identifier of big
(:tg-const:`telegram.ChatPhoto.SIZE_BIG` x :tg-const:`telegram.ChatPhoto.SIZE_BIG`)
chat photo, which is supposed to be the same over time and for different bots.
Can't be used to download or reuse the file.
Attributes:
small_file_id (:obj:`str`): File identifier of small
(:tg-const:`telegram.ChatPhoto.SIZE_SMALL` x :tg-const:`telegram.ChatPhoto.SIZE_SMALL`)
chat photo. This file_id can be used only for photo download and only for as long
as the photo is not changed.
small_file_unique_id (:obj:`str`): Unique file identifier of small
(:tg-const:`telegram.ChatPhoto.SIZE_SMALL` x :tg-const:`telegram.ChatPhoto.SIZE_SMALL`)
chat photo, which is supposed to be the same over time and for different bots.
Can't be used to download or reuse the file.
big_file_id (:obj:`str`): File identifier of big
(:tg-const:`telegram.ChatPhoto.SIZE_BIG` x :tg-const:`telegram.ChatPhoto.SIZE_BIG`)
chat photo. This file_id can be used only for photo download and only for as long as
the photo is not changed.
big_file_unique_id (:obj:`str`): Unique file identifier of big
(:tg-const:`telegram.ChatPhoto.SIZE_BIG` x :tg-const:`telegram.ChatPhoto.SIZE_BIG`)
chat photo, which is supposed to be the same over time and for different bots.
Can't be used to download or reuse the file.
"""
__slots__ = (
"big_file_id",
"big_file_unique_id",
"small_file_id",
"small_file_unique_id",
)
def __init__(
self,
small_file_id: str,
small_file_unique_id: str,
big_file_id: str,
big_file_unique_id: str,
*,
api_kwargs: Optional[JSONDict] = None,
):
super().__init__(api_kwargs=api_kwargs)
self.small_file_id: str = small_file_id
self.small_file_unique_id: str = small_file_unique_id
self.big_file_id: str = big_file_id
self.big_file_unique_id: str = big_file_unique_id
self._id_attrs = (
self.small_file_unique_id,
self.big_file_unique_id,
)
self._freeze()
async def get_small_file(
self,
*,
read_timeout: ODVInput[float] = DEFAULT_NONE,
write_timeout: ODVInput[float] = DEFAULT_NONE,
connect_timeout: ODVInput[float] = DEFAULT_NONE,
pool_timeout: ODVInput[float] = DEFAULT_NONE,
api_kwargs: Optional[JSONDict] = None,
) -> "File":
"""Convenience wrapper over :meth:`telegram.Bot.get_file` for getting the small
(:tg-const:`telegram.ChatPhoto.SIZE_SMALL` x :tg-const:`telegram.ChatPhoto.SIZE_SMALL`)
chat photo
For the documentation of the arguments, please see :meth:`telegram.Bot.get_file`.
Returns:
:class:`telegram.File`
Raises:
:class:`telegram.error.TelegramError`
"""
return await self.get_bot().get_file(
file_id=self.small_file_id,
read_timeout=read_timeout,
write_timeout=write_timeout,
connect_timeout=connect_timeout,
pool_timeout=pool_timeout,
api_kwargs=api_kwargs,
)
async def get_big_file(
self,
*,
read_timeout: ODVInput[float] = DEFAULT_NONE,
write_timeout: ODVInput[float] = DEFAULT_NONE,
connect_timeout: ODVInput[float] = DEFAULT_NONE,
pool_timeout: ODVInput[float] = DEFAULT_NONE,
api_kwargs: Optional[JSONDict] = None,
) -> "File":
"""Convenience wrapper over :meth:`telegram.Bot.get_file` for getting the
big (:tg-const:`telegram.ChatPhoto.SIZE_BIG` x :tg-const:`telegram.ChatPhoto.SIZE_BIG`)
chat photo
For the documentation of the arguments, please see :meth:`telegram.Bot.get_file`.
Returns:
:class:`telegram.File`
Raises:
:class:`telegram.error.TelegramError`
"""
return await self.get_bot().get_file(
file_id=self.big_file_id,
read_timeout=read_timeout,
write_timeout=write_timeout,
connect_timeout=connect_timeout,
pool_timeout=pool_timeout,
api_kwargs=api_kwargs,
)
SIZE_SMALL: Final[int] = constants.ChatPhotoSize.SMALL
""":const:`telegram.constants.ChatPhotoSize.SMALL`
.. versionadded:: 20.0
"""
SIZE_BIG: Final[int] = constants.ChatPhotoSize.BIG
""":const:`telegram.constants.ChatPhotoSize.BIG`
.. versionadded:: 20.0
"""

View File

@@ -0,0 +1,71 @@
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2025
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser Public License for more details.
#
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents a Telegram Contact."""
from typing import Optional
from telegram._telegramobject import TelegramObject
from telegram._utils.types import JSONDict
class Contact(TelegramObject):
"""This object represents a phone contact.
Objects of this class are comparable in terms of equality. Two objects of this class are
considered equal, if their :attr:`phone_number` is equal.
Args:
phone_number (:obj:`str`): Contact's phone number.
first_name (:obj:`str`): Contact's first name.
last_name (:obj:`str`, optional): Contact's last name.
user_id (:obj:`int`, optional): Contact's user identifier in Telegram.
vcard (:obj:`str`, optional): Additional data about the contact in the form of a vCard.
Attributes:
phone_number (:obj:`str`): Contact's phone number.
first_name (:obj:`str`): Contact's first name.
last_name (:obj:`str`): Optional. Contact's last name.
user_id (:obj:`int`): Optional. Contact's user identifier in Telegram.
vcard (:obj:`str`): Optional. Additional data about the contact in the form of a vCard.
"""
__slots__ = ("first_name", "last_name", "phone_number", "user_id", "vcard")
def __init__(
self,
phone_number: str,
first_name: str,
last_name: Optional[str] = None,
user_id: Optional[int] = None,
vcard: Optional[str] = None,
*,
api_kwargs: Optional[JSONDict] = None,
):
super().__init__(api_kwargs=api_kwargs)
# Required
self.phone_number: str = str(phone_number)
self.first_name: str = first_name
# Optionals
self.last_name: Optional[str] = last_name
self.user_id: Optional[int] = user_id
self.vcard: Optional[str] = vcard
self._id_attrs = (self.phone_number,)
self._freeze()

View File

@@ -0,0 +1,88 @@
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2025
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser Public License for more details.
#
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents a Telegram Document."""
from typing import Optional
from telegram._files._basethumbedmedium import _BaseThumbedMedium
from telegram._files.photosize import PhotoSize
from telegram._utils.types import JSONDict
class Document(_BaseThumbedMedium):
"""This object represents a general file
(as opposed to photos, voice messages and audio files).
Objects of this class are comparable in terms of equality. Two objects of this class are
considered equal, if their :attr:`file_unique_id` is equal.
.. versionchanged:: 20.5
|removed_thumb_note|
Args:
file_id (:obj:`str`): Identifier for this file, which can be used to download
or reuse the file.
file_unique_id (:obj:`str`): Unique identifier for this file, which is supposed to be
the same over time and for different bots. Can't be used to download or reuse the file.
file_name (:obj:`str`, optional): Original filename as defined by the sender.
mime_type (:obj:`str`, optional): MIME type of the file as defined by the sender.
file_size (:obj:`int`, optional): File size in bytes.
thumbnail (:class:`telegram.PhotoSize`, optional): Document thumbnail as defined by the
sender.
.. versionadded:: 20.2
Attributes:
file_id (:obj:`str`): Identifier for this file, which can be used to download
or reuse the file.
file_unique_id (:obj:`str`): Unique identifier for this file, which is supposed to be
the same over time and for different bots. Can't be used to download or reuse the file.
file_name (:obj:`str`): Optional. Original filename as defined by the sender.
mime_type (:obj:`str`): Optional. MIME type of the file as defined by the sender.
file_size (:obj:`int`): Optional. File size in bytes.
thumbnail (:class:`telegram.PhotoSize`): Optional. Document thumbnail as defined by the
sender.
.. versionadded:: 20.2
"""
__slots__ = ("file_name", "mime_type")
def __init__(
self,
file_id: str,
file_unique_id: str,
file_name: Optional[str] = None,
mime_type: Optional[str] = None,
file_size: Optional[int] = None,
thumbnail: Optional[PhotoSize] = None,
*,
api_kwargs: Optional[JSONDict] = None,
):
super().__init__(
file_id=file_id,
file_unique_id=file_unique_id,
file_size=file_size,
thumbnail=thumbnail,
api_kwargs=api_kwargs,
)
with self._unfrozen():
# Optional
self.mime_type: Optional[str] = mime_type
self.file_name: Optional[str] = file_name

View File

@@ -0,0 +1,371 @@
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2025
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser Public License for more details.
#
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents a Telegram File."""
import shutil
import urllib.parse as urllib_parse
from base64 import b64decode
from pathlib import Path
from typing import TYPE_CHECKING, BinaryIO, Optional
from telegram._passport.credentials import decrypt
from telegram._telegramobject import TelegramObject
from telegram._utils.defaultvalue import DEFAULT_NONE
from telegram._utils.files import is_local_file
from telegram._utils.types import FilePathInput, JSONDict, ODVInput
if TYPE_CHECKING:
from telegram import FileCredentials
class File(TelegramObject):
"""
This object represents a file ready to be downloaded. The file can be e.g. downloaded with
:attr:`download_to_drive`. 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 :meth:`telegram.Bot.get_file`.
Objects of this class are comparable in terms of equality. Two objects of this class are
considered equal, if their :attr:`file_unique_id` is equal.
.. versionchanged:: 20.0
``download`` was split into :meth:`download_to_drive` and :meth:`download_to_memory`.
Note:
* Maximum file size to download is
:tg-const:`telegram.constants.FileSizeLimit.FILESIZE_DOWNLOAD`.
* If you obtain an instance of this class from :attr:`telegram.PassportFile.get_file`,
then it will automatically be decrypted as it downloads when you call e.g.
:meth:`download_to_drive`.
Args:
file_id (:obj:`str`): Identifier for this file, which can be used to download
or reuse the file.
file_unique_id (:obj:`str`): Unique identifier for this file, which
is supposed to be the same over time and for different bots.
Can't be used to download or reuse the file.
file_size (:obj:`int`, optional): File size in bytes, if known.
file_path (:obj:`str`, optional): File path. Use e.g. :meth:`download_to_drive` to get the
file.
Attributes:
file_id (:obj:`str`): Identifier for this file, which can be used to download
or reuse the file.
file_unique_id (:obj:`str`): Unique identifier for this file, which
is supposed to be the same over time and for different bots.
Can't be used to download or reuse the file.
file_size (:obj:`int`): Optional. File size in bytes, if known.
file_path (:obj:`str`): Optional. File path. Use e.g. :meth:`download_to_drive` to get the
file.
"""
__slots__ = (
"_credentials",
"file_id",
"file_path",
"file_size",
"file_unique_id",
)
def __init__(
self,
file_id: str,
file_unique_id: str,
file_size: Optional[int] = None,
file_path: Optional[str] = None,
*,
api_kwargs: Optional[JSONDict] = None,
):
super().__init__(api_kwargs=api_kwargs)
# Required
self.file_id: str = str(file_id)
self.file_unique_id: str = str(file_unique_id)
# Optionals
self.file_size: Optional[int] = file_size
self.file_path: Optional[str] = file_path
self._credentials: Optional[FileCredentials] = None
self._id_attrs = (self.file_unique_id,)
self._freeze()
def _get_encoded_url(self) -> str:
"""Convert any UTF-8 char in :obj:`File.file_path` into a url encoded ASCII string."""
sres = urllib_parse.urlsplit(str(self.file_path))
return urllib_parse.urlunsplit(
urllib_parse.SplitResult(
sres.scheme, sres.netloc, urllib_parse.quote(sres.path), sres.query, sres.fragment
)
)
def _prepare_decrypt(self, buf: bytes) -> bytes:
return decrypt(b64decode(self._credentials.secret), b64decode(self._credentials.hash), buf)
async def download_to_drive(
self,
custom_path: Optional[FilePathInput] = None,
*,
read_timeout: ODVInput[float] = DEFAULT_NONE,
write_timeout: ODVInput[float] = DEFAULT_NONE,
connect_timeout: ODVInput[float] = DEFAULT_NONE,
pool_timeout: ODVInput[float] = DEFAULT_NONE,
) -> Path:
"""
Download this file. By default, the file is saved in the current working directory with
:attr:`file_path` as file name. If :paramref:`custom_path` is supplied as a :obj:`str` or
:obj:`pathlib.Path`, it will be saved to that path.
Note:
If :paramref:`custom_path` isn't provided and :attr:`file_path` is the path of a
local file (which is the case when a Bot API Server is running in local mode), this
method will just return the path.
The only exception to this are encrypted files (e.g. a passport file). For these, a
file with the prefix `decrypted_` will be created in the same directory as the
original file in order to decrypt the file without changing the existing one
in-place.
.. seealso:: :wiki:`Working with Files and Media <Working-with-Files-and-Media>`
.. versionchanged:: 20.0
* :paramref:`custom_path` parameter now also accepts :class:`pathlib.Path` as argument.
* Returns :class:`pathlib.Path` object in cases where previously a :obj:`str` was
returned.
* This method was previously called ``download``. It was split into
:meth:`download_to_drive` and :meth:`download_to_memory`.
.. versionchanged:: 21.7
Raises :exc:`RuntimeError` if :attr:`file_path` is not set. Note that files without
a :attr:`file_path` could never be downloaded, as this attribute is mandatory for that
operation.
Args:
custom_path (:class:`pathlib.Path` | :obj:`str` , optional): The path where the file
will be saved to. If not specified, will be saved in the current working directory
with :attr:`file_path` as file name or the :attr:`file_id` if :attr:`file_path`
is not set.
Keyword Args:
read_timeout (:obj:`float` | :obj:`None`, optional): Value to pass to
:paramref:`telegram.request.BaseRequest.post.read_timeout`. Defaults to
:attr:`~telegram.request.BaseRequest.DEFAULT_NONE`.
write_timeout (:obj:`float` | :obj:`None`, optional): Value to pass to
:paramref:`telegram.request.BaseRequest.post.write_timeout`. Defaults to
:attr:`~telegram.request.BaseRequest.DEFAULT_NONE`.
connect_timeout (:obj:`float` | :obj:`None`, optional): Value to pass to
:paramref:`telegram.request.BaseRequest.post.connect_timeout`. Defaults to
:attr:`~telegram.request.BaseRequest.DEFAULT_NONE`.
pool_timeout (:obj:`float` | :obj:`None`, optional): Value to pass to
:paramref:`telegram.request.BaseRequest.post.pool_timeout`. Defaults to
:attr:`~telegram.request.BaseRequest.DEFAULT_NONE`.
Returns:
:class:`pathlib.Path`: Returns the Path object the file was downloaded to.
Raises:
RuntimeError: If :attr:`file_path` is not set.
"""
if not self.file_path:
raise RuntimeError("No `file_path` available for this file. Can not download.")
local_file = is_local_file(self.file_path)
url = None if local_file else self._get_encoded_url()
# if _credentials exists we want to decrypt the file
if local_file and self._credentials:
file_to_decrypt = Path(self.file_path)
buf = self._prepare_decrypt(file_to_decrypt.read_bytes())
if custom_path is not None:
path = Path(custom_path)
else:
path = Path(str(file_to_decrypt.parent) + "/decrypted_" + file_to_decrypt.name)
path.write_bytes(buf)
return path
if custom_path is not None and local_file:
shutil.copyfile(self.file_path, str(custom_path))
return Path(custom_path)
if custom_path:
filename = Path(custom_path)
elif local_file:
return Path(self.file_path)
else:
filename = Path(Path(self.file_path).name)
buf = await self.get_bot().request.retrieve(
url,
read_timeout=read_timeout,
write_timeout=write_timeout,
connect_timeout=connect_timeout,
pool_timeout=pool_timeout,
)
if self._credentials:
buf = self._prepare_decrypt(buf)
filename.write_bytes(buf)
return filename
async def download_to_memory(
self,
out: BinaryIO,
*,
read_timeout: ODVInput[float] = DEFAULT_NONE,
write_timeout: ODVInput[float] = DEFAULT_NONE,
connect_timeout: ODVInput[float] = DEFAULT_NONE,
pool_timeout: ODVInput[float] = DEFAULT_NONE,
) -> None:
"""
Download this file into memory. :paramref:`out` needs to be supplied with a
:obj:`io.BufferedIOBase`, the file contents will be saved to that object using the
:obj:`out.write<io.BufferedIOBase.write>` method.
.. seealso:: :wiki:`Working with Files and Media <Working-with-Files-and-Media>`
Hint:
If you want to immediately read the data from ``out`` after calling this method, you
should call ``out.seek(0)`` first. See also :meth:`io.IOBase.seek`.
.. versionadded:: 20.0
.. versionchanged:: 21.7
Raises :exc:`RuntimeError` if :attr:`file_path` is not set. Note that files without
a :attr:`file_path` could never be downloaded, as this attribute is mandatory for that
operation.
Args:
out (:obj:`io.BufferedIOBase`): A file-like object. Must be opened for writing in
binary mode.
Keyword Args:
read_timeout (:obj:`float` | :obj:`None`, optional): Value to pass to
:paramref:`telegram.request.BaseRequest.post.read_timeout`. Defaults to
:attr:`~telegram.request.BaseRequest.DEFAULT_NONE`.
write_timeout (:obj:`float` | :obj:`None`, optional): Value to pass to
:paramref:`telegram.request.BaseRequest.post.write_timeout`. Defaults to
:attr:`~telegram.request.BaseRequest.DEFAULT_NONE`.
connect_timeout (:obj:`float` | :obj:`None`, optional): Value to pass to
:paramref:`telegram.request.BaseRequest.post.connect_timeout`. Defaults to
:attr:`~telegram.request.BaseRequest.DEFAULT_NONE`.
pool_timeout (:obj:`float` | :obj:`None`, optional): Value to pass to
:paramref:`telegram.request.BaseRequest.post.pool_timeout`. Defaults to
:attr:`~telegram.request.BaseRequest.DEFAULT_NONE`.
Raises:
RuntimeError: If :attr:`file_path` is not set.
"""
if not self.file_path:
raise RuntimeError("No `file_path` available for this file. Can not download.")
local_file = is_local_file(self.file_path)
url = None if local_file else self._get_encoded_url()
path = Path(self.file_path) if local_file else None
if local_file:
buf = path.read_bytes()
else:
buf = await self.get_bot().request.retrieve(
url,
read_timeout=read_timeout,
write_timeout=write_timeout,
connect_timeout=connect_timeout,
pool_timeout=pool_timeout,
)
if self._credentials:
buf = self._prepare_decrypt(buf)
out.write(buf)
async def download_as_bytearray(
self,
buf: Optional[bytearray] = None,
*,
read_timeout: ODVInput[float] = DEFAULT_NONE,
write_timeout: ODVInput[float] = DEFAULT_NONE,
connect_timeout: ODVInput[float] = DEFAULT_NONE,
pool_timeout: ODVInput[float] = DEFAULT_NONE,
) -> bytearray:
"""Download this file and return it as a bytearray.
.. versionchanged:: 21.7
Raises :exc:`RuntimeError` if :attr:`file_path` is not set. Note that files without
a :attr:`file_path` could never be downloaded, as this attribute is mandatory for that
operation.
Args:
buf (:obj:`bytearray`, optional): Extend the given bytearray with the downloaded data.
Keyword Args:
read_timeout (:obj:`float` | :obj:`None`, optional): Value to pass to
:paramref:`telegram.request.BaseRequest.post.read_timeout`. Defaults to
:attr:`~telegram.request.BaseRequest.DEFAULT_NONE`.
.. versionadded:: 20.0
write_timeout (:obj:`float` | :obj:`None`, optional): Value to pass to
:paramref:`telegram.request.BaseRequest.post.write_timeout`. Defaults to
:attr:`~telegram.request.BaseRequest.DEFAULT_NONE`.
.. versionadded:: 20.0
connect_timeout (:obj:`float` | :obj:`None`, optional): Value to pass to
:paramref:`telegram.request.BaseRequest.post.connect_timeout`. Defaults to
:attr:`~telegram.request.BaseRequest.DEFAULT_NONE`.
.. versionadded:: 20.0
pool_timeout (:obj:`float` | :obj:`None`, optional): Value to pass to
:paramref:`telegram.request.BaseRequest.post.pool_timeout`. Defaults to
:attr:`~telegram.request.BaseRequest.DEFAULT_NONE`.
.. versionadded:: 20.0
Returns:
:obj:`bytearray`: The same object as :paramref:`buf` if it was specified. Otherwise a
newly allocated :obj:`bytearray`.
Raises:
RuntimeError: If :attr:`file_path` is not set.
"""
if not self.file_path:
raise RuntimeError("No `file_path` available for this file. Can not download.")
if buf is None:
buf = bytearray()
if is_local_file(self.file_path):
bytes_data = Path(self.file_path).read_bytes()
else:
bytes_data = await self.get_bot().request.retrieve(
self._get_encoded_url(),
read_timeout=read_timeout,
write_timeout=write_timeout,
connect_timeout=connect_timeout,
pool_timeout=pool_timeout,
)
if self._credentials:
buf.extend(self._prepare_decrypt(bytes_data))
else:
buf.extend(bytes_data)
return buf
def set_credentials(self, credentials: "FileCredentials") -> None:
"""Sets the passport credentials for the file.
Args:
credentials (:class:`telegram.FileCredentials`): The credentials.
"""
self._credentials = credentials

View File

@@ -0,0 +1,142 @@
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2025
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser Public License for more details.
#
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents a Telegram InputFile."""
import mimetypes
from typing import IO, Optional, Union
from uuid import uuid4
from telegram._utils.files import guess_file_name, load_file
from telegram._utils.strings import TextEncoding
from telegram._utils.types import FieldTuple
_DEFAULT_MIME_TYPE = "application/octet-stream"
class InputFile:
"""This object represents a Telegram InputFile.
.. versionchanged:: 20.0
* The former attribute ``attach`` was renamed to :attr:`attach_name`.
* Method ``is_image`` was removed. If you pass :obj:`bytes` to :paramref:`obj` and would
like to have the mime type automatically guessed, please pass :paramref:`filename`
in addition.
Args:
obj (:term:`file object` | :obj:`bytes` | :obj:`str`): An open file descriptor or the files
content as bytes or string.
Note:
If :paramref:`obj` is a string, it will be encoded as bytes via
:external:obj:`obj.encode('utf-8') <str.encode>`.
.. versionchanged:: 20.0
Accept string input.
filename (:obj:`str`, optional): Filename for this InputFile.
attach (:obj:`bool`, optional): Pass :obj:`True` if the parameter this file belongs to in
the request to Telegram should point to the multipart data via an ``attach://`` URI.
Defaults to `False`.
read_file_handle (:obj:`bool`, optional): If :obj:`True` and :paramref:`obj` is a file
handle, the data will be read from the file handle on initialization of this object.
If :obj:`False`, the file handle will be passed on to the
:attr:`networking backend <telegram.request.BaseRequest.do_request>` which will have
to handle the reading. Defaults to :obj:`True`.
Tip:
If you upload extremely large files, you may want to set this to :obj:`False` to
avoid reading the complete file into memory. Additionally, this may be supported
better by the networking backend (in particular it is handled better by
the default :class:`~telegram.request.HTTPXRequest`).
Important:
If you set this to :obj:`False`, you have to ensure that the file handle is still
open when the request is made. In particular, the following snippet can *not* work
as expected.
.. code-block:: python
with open('file.txt', 'rb') as file:
input_file = InputFile(file, read_file_handle=False)
# here the file handle is already closed and the upload will fail
await bot.send_document(chat_id, input_file)
.. versionadded:: 21.5
Attributes:
input_file_content (:obj:`bytes` | :class:`IO`): The binary content of the file to send.
attach_name (:obj:`str`): Optional. If present, the parameter this file belongs to in
the request to Telegram should point to the multipart data via a an URI of the form
``attach://<attach_name>`` URI.
filename (:obj:`str`): Filename for the file to be sent.
mimetype (:obj:`str`): The mimetype inferred from the file to be sent.
"""
__slots__ = ("attach_name", "filename", "input_file_content", "mimetype")
def __init__(
self,
obj: Union[IO[bytes], bytes, str],
filename: Optional[str] = None,
attach: bool = False,
read_file_handle: bool = True,
):
if isinstance(obj, bytes):
self.input_file_content: Union[bytes, IO[bytes]] = obj
elif isinstance(obj, str):
self.input_file_content = obj.encode(TextEncoding.UTF_8)
elif read_file_handle:
reported_filename, self.input_file_content = load_file(obj)
filename = filename or reported_filename
else:
self.input_file_content = obj
filename = filename or guess_file_name(obj)
self.attach_name: Optional[str] = "attached" + uuid4().hex if attach else None
if filename:
self.mimetype: str = (
mimetypes.guess_type(filename, strict=False)[0] or _DEFAULT_MIME_TYPE
)
else:
self.mimetype = _DEFAULT_MIME_TYPE
self.filename: str = filename or self.mimetype.replace("/", ".")
@property
def field_tuple(self) -> FieldTuple:
"""Field tuple representing the contents of the file for upload to the Telegram servers.
.. versionchanged:: 21.5
Content may now be a file handle.
Returns:
tuple[:obj:`str`, :obj:`bytes` | :class:`IO`, :obj:`str`]:
"""
return self.filename, self.input_file_content, self.mimetype
@property
def attach_uri(self) -> Optional[str]:
"""URI to insert into the JSON data for uploading the file. Returns :obj:`None`, if
:attr:`attach_name` is :obj:`None`.
"""
return f"attach://{self.attach_name}" if self.attach_name else None

View File

@@ -0,0 +1,915 @@
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2025
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser Public License for more details.
#
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""Base class for Telegram InputMedia Objects."""
import datetime as dtm
from collections.abc import Sequence
from typing import Final, Optional, Union
from telegram import constants
from telegram._files.animation import Animation
from telegram._files.audio import Audio
from telegram._files.document import Document
from telegram._files.inputfile import InputFile
from telegram._files.photosize import PhotoSize
from telegram._files.video import Video
from telegram._messageentity import MessageEntity
from telegram._telegramobject import TelegramObject
from telegram._utils import enum
from telegram._utils.argumentparsing import parse_sequence_arg, to_timedelta
from telegram._utils.datetime import get_timedelta_value
from telegram._utils.defaultvalue import DEFAULT_NONE
from telegram._utils.files import parse_file_input
from telegram._utils.types import FileInput, JSONDict, ODVInput, TimePeriod
from telegram.constants import InputMediaType
MediaType = Union[Animation, Audio, Document, PhotoSize, Video]
class InputMedia(TelegramObject):
"""
Base class for Telegram InputMedia Objects.
.. versionchanged:: 20.0
Added arguments and attributes :attr:`type`, :attr:`media`, :attr:`caption`,
:attr:`caption_entities`, :paramref:`parse_mode`.
.. seealso:: :wiki:`Working with Files and Media <Working-with-Files-and-Media>`
Args:
media_type (:obj:`str`): Type of media that the instance represents.
media (:obj:`str` | :class:`~telegram.InputFile`): File to send.
|fileinputnopath|
caption (:obj:`str`, optional): Caption of the media to be sent,
0-:tg-const:`telegram.constants.MessageLimit.CAPTION_LENGTH` characters after entities
parsing.
caption_entities (Sequence[:class:`telegram.MessageEntity`], optional): |caption_entities|
.. versionchanged:: 20.0
|sequenceclassargs|
parse_mode (:obj:`str`, optional): |parse_mode|
Attributes:
type (:obj:`str`): Type of the input media.
media (:obj:`str` | :class:`telegram.InputFile`): Media to send.
caption (:obj:`str`): Optional. Caption of the media to be sent,
0-:tg-const:`telegram.constants.MessageLimit.CAPTION_LENGTH` characters after entities
parsing.
parse_mode (:obj:`str`): Optional. |parse_mode|
caption_entities (tuple[:class:`telegram.MessageEntity`]): Optional. |captionentitiesattr|
.. versionchanged:: 20.0
* |tupleclassattrs|
* |alwaystuple|
"""
__slots__ = ("caption", "caption_entities", "media", "parse_mode", "type")
def __init__(
self,
media_type: str,
media: Union[str, InputFile],
caption: Optional[str] = None,
caption_entities: Optional[Sequence[MessageEntity]] = None,
parse_mode: ODVInput[str] = DEFAULT_NONE,
*,
api_kwargs: Optional[JSONDict] = None,
):
super().__init__(api_kwargs=api_kwargs)
self.type: str = enum.get_member(constants.InputMediaType, media_type, media_type)
self.media: Union[str, InputFile] = media
self.caption: Optional[str] = caption
self.caption_entities: tuple[MessageEntity, ...] = parse_sequence_arg(caption_entities)
self.parse_mode: ODVInput[str] = parse_mode
self._freeze()
@staticmethod
def _parse_thumbnail_input(thumbnail: Optional[FileInput]) -> Optional[Union[str, InputFile]]:
# We use local_mode=True because we don't have access to the actual setting and want
# things to work in local mode.
return (
parse_file_input(thumbnail, attach=True, local_mode=True)
if thumbnail is not None
else thumbnail
)
class InputPaidMedia(TelegramObject):
"""
Base class for Telegram InputPaidMedia Objects. Currently, it can be one of:
* :class:`telegram.InputPaidMediaPhoto`
* :class:`telegram.InputPaidMediaVideo`
.. seealso:: :wiki:`Working with Files and Media <Working-with-Files-and-Media>`
.. versionadded:: 21.4
Args:
type (:obj:`str`): Type of media that the instance represents.
media (:obj:`str` | :class:`~telegram.InputFile`): File
to send. |fileinputnopath|
Attributes:
type (:obj:`str`): Type of the input media.
media (:obj:`str` | :class:`telegram.InputFile`): Media to send.
"""
PHOTO: Final[str] = constants.InputPaidMediaType.PHOTO
""":const:`telegram.constants.InputPaidMediaType.PHOTO`"""
VIDEO: Final[str] = constants.InputPaidMediaType.VIDEO
""":const:`telegram.constants.InputPaidMediaType.VIDEO`"""
__slots__ = ("media", "type")
def __init__(
self,
type: str, # pylint: disable=redefined-builtin
media: Union[str, InputFile],
*,
api_kwargs: Optional[JSONDict] = None,
):
super().__init__(api_kwargs=api_kwargs)
self.type: str = enum.get_member(constants.InputPaidMediaType, type, type)
self.media: Union[str, InputFile] = media
self._freeze()
class InputPaidMediaPhoto(InputPaidMedia):
"""The paid media to send is a photo.
.. seealso:: :wiki:`Working with Files and Media <Working-with-Files-and-Media>`
.. versionadded:: 21.4
Args:
media (:obj:`str` | :term:`file object` | :class:`~telegram.InputFile` | :obj:`bytes` | \
:class:`pathlib.Path` | :class:`telegram.PhotoSize`): File to send. |fileinputnopath|
Lastly you can pass an existing :class:`telegram.PhotoSize` object to send.
Attributes:
type (:obj:`str`): Type of the media, always
:tg-const:`telegram.constants.InputPaidMediaType.PHOTO`.
media (:obj:`str` | :class:`telegram.InputFile`): Photo to send.
"""
__slots__ = ()
def __init__(
self,
media: Union[FileInput, PhotoSize],
*,
api_kwargs: Optional[JSONDict] = None,
):
media = parse_file_input(media, PhotoSize, attach=True, local_mode=True)
super().__init__(type=InputPaidMedia.PHOTO, media=media, api_kwargs=api_kwargs)
self._freeze()
class InputPaidMediaVideo(InputPaidMedia):
"""
The paid media to send is a video.
.. seealso:: :wiki:`Working with Files and Media <Working-with-Files-and-Media>`
.. versionadded:: 21.4
Note:
* When using a :class:`telegram.Video` for the :attr:`media` attribute, it will take the
width, height and duration from that video, unless otherwise specified with the optional
arguments.
* :paramref:`thumbnail` will be ignored for small video files, for which Telegram can
easily generate thumbnails. However, this behaviour is undocumented and might be
changed by Telegram.
Args:
media (:obj:`str` | :term:`file object` | :class:`~telegram.InputFile` | :obj:`bytes` | \
:class:`pathlib.Path` | :class:`telegram.Video`): File to send. |fileinputnopath|
Lastly you can pass an existing :class:`telegram.Video` object to send.
thumbnail (:term:`file object` | :obj:`bytes` | :class:`pathlib.Path` | :obj:`str`, \
optional): |thumbdocstringnopath|
cover (:term:`file object` | :obj:`bytes` | :class:`pathlib.Path` | :obj:`str`, \
optional): Cover for the video in the message. |fileinputnopath|
.. versionchanged:: 21.11
start_timestamp (:obj:`int`, optional): Start timestamp for the video in the message
.. versionchanged:: 21.11
width (:obj:`int`, optional): Video width.
height (:obj:`int`, optional): Video height.
duration (:obj:`int` | :class:`datetime.timedelta`, optional): Video duration in seconds.
.. versionchanged:: v22.2
|time-period-input|
supports_streaming (:obj:`bool`, optional): Pass :obj:`True`, if the uploaded video is
suitable for streaming.
Attributes:
type (:obj:`str`): Type of the media, always
:tg-const:`telegram.constants.InputPaidMediaType.VIDEO`.
media (:obj:`str` | :class:`telegram.InputFile`): Video to send.
thumbnail (:class:`telegram.InputFile`): Optional. |thumbdocstringbase|
cover (:class:`telegram.InputFile`): Optional. Cover for the video in the message.
|fileinputnopath|
.. versionchanged:: 21.11
start_timestamp (:obj:`int`): Optional. Start timestamp for the video in the message
.. versionchanged:: 21.11
width (:obj:`int`): Optional. Video width.
height (:obj:`int`): Optional. Video height.
duration (:obj:`int` | :class:`datetime.timedelta`): Optional. Video duration in seconds.
.. deprecated:: v22.2
|time-period-int-deprecated|
supports_streaming (:obj:`bool`): Optional. :obj:`True`, if the uploaded video is
suitable for streaming.
"""
__slots__ = (
"_duration",
"cover",
"height",
"start_timestamp",
"supports_streaming",
"thumbnail",
"width",
)
def __init__(
self,
media: Union[FileInput, Video],
thumbnail: Optional[FileInput] = None,
width: Optional[int] = None,
height: Optional[int] = None,
duration: Optional[TimePeriod] = None,
supports_streaming: Optional[bool] = None,
cover: Optional[FileInput] = None,
start_timestamp: Optional[int] = None,
*,
api_kwargs: Optional[JSONDict] = None,
):
if isinstance(media, Video):
width = width if width is not None else media.width
height = height if height is not None else media.height
duration = duration if duration is not None else media._duration
media = media.file_id
else:
# We use local_mode=True because we don't have access to the actual setting and want
# things to work in local mode.
media = parse_file_input(media, attach=True, local_mode=True)
super().__init__(type=InputPaidMedia.VIDEO, media=media, api_kwargs=api_kwargs)
with self._unfrozen():
self.thumbnail: Optional[Union[str, InputFile]] = InputMedia._parse_thumbnail_input(
thumbnail
)
self.width: Optional[int] = width
self.height: Optional[int] = height
self._duration: Optional[dtm.timedelta] = to_timedelta(duration)
self.supports_streaming: Optional[bool] = supports_streaming
self.cover: Optional[Union[InputFile, str]] = (
parse_file_input(cover, attach=True, local_mode=True) if cover else None
)
self.start_timestamp: Optional[int] = start_timestamp
@property
def duration(self) -> Optional[Union[int, dtm.timedelta]]:
return get_timedelta_value(self._duration, attribute="duration")
class InputMediaAnimation(InputMedia):
"""Represents an animation file (GIF or H.264/MPEG-4 AVC video without sound) to be sent.
Note:
When using a :class:`telegram.Animation` for the :attr:`media` attribute, it will take the
width, height and duration from that animation, unless otherwise specified with the
optional arguments.
.. seealso:: :wiki:`Working with Files and Media <Working-with-Files-and-Media>`
.. versionchanged:: 20.5
|removed_thumb_note|
Args:
media (:obj:`str` | :term:`file object` | :class:`~telegram.InputFile` | :obj:`bytes` | \
:class:`pathlib.Path` | :class:`telegram.Animation`): File to send. |fileinputnopath|
Lastly you can pass an existing :class:`telegram.Animation` object to send.
.. versionchanged:: 13.2
Accept :obj:`bytes` as input.
filename (:obj:`str`, optional): Custom file name for the animation, when uploading a
new file. Convenience parameter, useful e.g. when sending files generated by the
:obj:`tempfile` module.
.. versionadded:: 13.1
caption (:obj:`str`, optional): Caption of the animation to be sent,
0-:tg-const:`telegram.constants.MessageLimit.CAPTION_LENGTH` characters
after entities parsing.
parse_mode (:obj:`str`, optional): |parse_mode|
caption_entities (Sequence[:class:`telegram.MessageEntity`], optional): |caption_entities|
.. versionchanged:: 20.0
|sequenceclassargs|
width (:obj:`int`, optional): Animation width.
height (:obj:`int`, optional): Animation height.
duration (:obj:`int` | :class:`datetime.timedelta`, optional): Animation duration
in seconds.
.. versionchanged:: v22.2
|time-period-input|
has_spoiler (:obj:`bool`, optional): Pass :obj:`True`, if the animation needs to be covered
with a spoiler animation.
.. versionadded:: 20.0
thumbnail (:term:`file object` | :obj:`bytes` | :class:`pathlib.Path` | :obj:`str`, \
optional): |thumbdocstringnopath|
.. versionadded:: 20.2
show_caption_above_media (:obj:`bool`, optional): Pass |show_cap_above_med|
.. versionadded:: 21.3
Attributes:
type (:obj:`str`): :tg-const:`telegram.constants.InputMediaType.ANIMATION`.
media (:obj:`str` | :class:`telegram.InputFile`): Animation to send.
caption (:obj:`str`): Optional. Caption of the animation to be sent,
0-:tg-const:`telegram.constants.MessageLimit.CAPTION_LENGTH` characters
after entities parsing.
parse_mode (:obj:`str`): Optional. The parse mode to use for text formatting.
caption_entities (tuple[:class:`telegram.MessageEntity`]): Optional. |captionentitiesattr|
.. versionchanged:: 20.0
* |tupleclassattrs|
* |alwaystuple|
width (:obj:`int`): Optional. Animation width.
height (:obj:`int`): Optional. Animation height.
duration (:obj:`int` | :class:`datetime.timedelta`): Optional. Animation duration
in seconds.
.. deprecated:: v22.2
|time-period-int-deprecated|
has_spoiler (:obj:`bool`): Optional. :obj:`True`, if the animation is covered with a
spoiler animation.
.. versionadded:: 20.0
thumbnail (:class:`telegram.InputFile`): Optional. |thumbdocstringbase|
.. versionadded:: 20.2
show_caption_above_media (:obj:`bool`): Optional. |show_cap_above_med|
.. versionadded:: 21.3
"""
__slots__ = (
"_duration",
"has_spoiler",
"height",
"show_caption_above_media",
"thumbnail",
"width",
)
def __init__(
self,
media: Union[FileInput, Animation],
caption: Optional[str] = None,
parse_mode: ODVInput[str] = DEFAULT_NONE,
width: Optional[int] = None,
height: Optional[int] = None,
duration: Optional[TimePeriod] = None,
caption_entities: Optional[Sequence[MessageEntity]] = None,
filename: Optional[str] = None,
has_spoiler: Optional[bool] = None,
thumbnail: Optional[FileInput] = None,
show_caption_above_media: Optional[bool] = None,
*,
api_kwargs: Optional[JSONDict] = None,
):
if isinstance(media, Animation):
width = media.width if width is None else width
height = media.height if height is None else height
duration = duration if duration is not None else media._duration
media = media.file_id
else:
# We use local_mode=True because we don't have access to the actual setting and want
# things to work in local mode.
media = parse_file_input(media, filename=filename, attach=True, local_mode=True)
super().__init__(
InputMediaType.ANIMATION,
media,
caption,
caption_entities,
parse_mode,
api_kwargs=api_kwargs,
)
with self._unfrozen():
self.thumbnail: Optional[Union[str, InputFile]] = self._parse_thumbnail_input(
thumbnail
)
self.width: Optional[int] = width
self.height: Optional[int] = height
self._duration: Optional[dtm.timedelta] = to_timedelta(duration)
self.has_spoiler: Optional[bool] = has_spoiler
self.show_caption_above_media: Optional[bool] = show_caption_above_media
@property
def duration(self) -> Optional[Union[int, dtm.timedelta]]:
return get_timedelta_value(self._duration, attribute="duration")
class InputMediaPhoto(InputMedia):
"""Represents a photo to be sent.
.. seealso:: :wiki:`Working with Files and Media <Working-with-Files-and-Media>`
Args:
media (:obj:`str` | :term:`file object` | :class:`~telegram.InputFile` | :obj:`bytes` | \
:class:`pathlib.Path` | :class:`telegram.PhotoSize`): File to send. |fileinputnopath|
Lastly you can pass an existing :class:`telegram.PhotoSize` object to send.
.. versionchanged:: 13.2
Accept :obj:`bytes` as input.
filename (:obj:`str`, optional): Custom file name for the photo, when uploading a
new file. Convenience parameter, useful e.g. when sending files generated by the
:obj:`tempfile` module.
.. versionadded:: 13.1
caption (:obj:`str`, optional ): Caption of the photo to be sent,
0-:tg-const:`telegram.constants.MessageLimit.CAPTION_LENGTH` characters after
entities parsing.
parse_mode (:obj:`str`, optional): |parse_mode|
caption_entities (Sequence[:class:`telegram.MessageEntity`], optional): |caption_entities|
.. versionchanged:: 20.0
|sequenceclassargs|
has_spoiler (:obj:`bool`, optional): Pass :obj:`True`, if the photo needs to be covered
with a spoiler animation.
.. versionadded:: 20.0
show_caption_above_media (:obj:`bool`, optional): Pass |show_cap_above_med|
.. versionadded:: 21.3
Attributes:
type (:obj:`str`): :tg-const:`telegram.constants.InputMediaType.PHOTO`.
media (:obj:`str` | :class:`telegram.InputFile`): Photo to send.
caption (:obj:`str`): Optional. Caption of the photo to be sent,
0-:tg-const:`telegram.constants.MessageLimit.CAPTION_LENGTH` characters
after entities parsing.
parse_mode (:obj:`str`): Optional. |parse_mode|
caption_entities (tuple[:class:`telegram.MessageEntity`]): Optional. |captionentitiesattr|
.. versionchanged:: 20.0
* |tupleclassattrs|
* |alwaystuple|
has_spoiler (:obj:`bool`): Optional. :obj:`True`, if the photo is covered with a
spoiler animation.
.. versionadded:: 20.0
show_caption_above_media (:obj:`bool`): Optional. |show_cap_above_med|
.. versionadded:: 21.3
"""
__slots__ = (
"has_spoiler",
"show_caption_above_media",
)
def __init__(
self,
media: Union[FileInput, PhotoSize],
caption: Optional[str] = None,
parse_mode: ODVInput[str] = DEFAULT_NONE,
caption_entities: Optional[Sequence[MessageEntity]] = None,
filename: Optional[str] = None,
has_spoiler: Optional[bool] = None,
show_caption_above_media: Optional[bool] = None,
*,
api_kwargs: Optional[JSONDict] = None,
):
# We use local_mode=True because we don't have access to the actual setting and want
# things to work in local mode.
media = parse_file_input(media, PhotoSize, filename=filename, attach=True, local_mode=True)
super().__init__(
InputMediaType.PHOTO,
media,
caption,
caption_entities,
parse_mode,
api_kwargs=api_kwargs,
)
with self._unfrozen():
self.has_spoiler: Optional[bool] = has_spoiler
self.show_caption_above_media: Optional[bool] = show_caption_above_media
class InputMediaVideo(InputMedia):
"""Represents a video to be sent.
.. seealso:: :wiki:`Working with Files and Media <Working-with-Files-and-Media>`
Note:
* When using a :class:`telegram.Video` for the :attr:`media` attribute, it will take the
width, height and duration from that video, unless otherwise specified with the optional
arguments.
* :paramref:`thumbnail` will be ignored for small video files, for which Telegram can
easily generate thumbnails. However, this behaviour is undocumented and might be
changed by Telegram.
.. versionchanged:: 20.5
|removed_thumb_note|
Args:
media (:obj:`str` | :term:`file object` | :class:`~telegram.InputFile` | :obj:`bytes` | \
:class:`pathlib.Path` | :class:`telegram.Video`): File to send. |fileinputnopath|
Lastly you can pass an existing :class:`telegram.Video` object to send.
.. versionchanged:: 13.2
Accept :obj:`bytes` as input.
filename (:obj:`str`, optional): Custom file name for the video, when uploading a
new file. Convenience parameter, useful e.g. when sending files generated by the
:obj:`tempfile` module.
.. versionadded:: 13.1
caption (:obj:`str`, optional): Caption of the video to be sent,
0-:tg-const:`telegram.constants.MessageLimit.CAPTION_LENGTH` characters after
entities parsing.
parse_mode (:obj:`str`, optional): |parse_mode|
caption_entities (Sequence[:class:`telegram.MessageEntity`], optional): |caption_entities|
.. versionchanged:: 20.0
|sequenceclassargs|
width (:obj:`int`, optional): Video width.
height (:obj:`int`, optional): Video height.
duration (:obj:`int` | :class:`datetime.timedelta`, optional): Video duration in seconds.
.. versionchanged:: v22.2
|time-period-input|
supports_streaming (:obj:`bool`, optional): Pass :obj:`True`, if the uploaded video is
suitable for streaming.
has_spoiler (:obj:`bool`, optional): Pass :obj:`True`, if the video needs to be covered
with a spoiler animation.
.. versionadded:: 20.0
thumbnail (:term:`file object` | :obj:`bytes` | :class:`pathlib.Path` | :obj:`str`, \
optional): |thumbdocstringnopath|
.. versionadded:: 20.2
cover (:term:`file object` | :obj:`bytes` | :class:`pathlib.Path` | :obj:`str`, \
optional): Cover for the video in the message. |fileinputnopath|
.. versionchanged:: 21.11
start_timestamp (:obj:`int`, optional): Start timestamp for the video in the message
.. versionchanged:: 21.11
show_caption_above_media (:obj:`bool`, optional): Pass |show_cap_above_med|
.. versionadded:: 21.3
Attributes:
type (:obj:`str`): :tg-const:`telegram.constants.InputMediaType.VIDEO`.
media (:obj:`str` | :class:`telegram.InputFile`): Video file to send.
caption (:obj:`str`): Optional. Caption of the video to be sent,
0-:tg-const:`telegram.constants.MessageLimit.CAPTION_LENGTH` characters
after entities parsing.
parse_mode (:obj:`str`): Optional. |parse_mode|
caption_entities (tuple[:class:`telegram.MessageEntity`]): Optional. |captionentitiesattr|
.. versionchanged:: 20.0
* |tupleclassattrs|
* |alwaystuple|
width (:obj:`int`): Optional. Video width.
height (:obj:`int`): Optional. Video height.
duration (:obj:`int` | :class:`datetime.timedelta`): Optional. Video duration in seconds.
.. deprecated:: v22.2
|time-period-int-deprecated|
supports_streaming (:obj:`bool`): Optional. :obj:`True`, if the uploaded video is
suitable for streaming.
has_spoiler (:obj:`bool`): Optional. :obj:`True`, if the video is covered with a
spoiler animation.
.. versionadded:: 20.0
thumbnail (:class:`telegram.InputFile`): Optional. |thumbdocstringbase|
.. versionadded:: 20.2
show_caption_above_media (:obj:`bool`): Optional. |show_cap_above_med|
.. versionadded:: 21.3
cover (:class:`telegram.InputFile`): Optional. Cover for the video in the message.
|fileinputnopath|
.. versionchanged:: 21.11
start_timestamp (:obj:`int`): Optional. Start timestamp for the video in the message
.. versionchanged:: 21.11
"""
__slots__ = (
"_duration",
"cover",
"has_spoiler",
"height",
"show_caption_above_media",
"start_timestamp",
"supports_streaming",
"thumbnail",
"width",
)
def __init__(
self,
media: Union[FileInput, Video],
caption: Optional[str] = None,
width: Optional[int] = None,
height: Optional[int] = None,
duration: Optional[TimePeriod] = None,
supports_streaming: Optional[bool] = None,
parse_mode: ODVInput[str] = DEFAULT_NONE,
caption_entities: Optional[Sequence[MessageEntity]] = None,
filename: Optional[str] = None,
has_spoiler: Optional[bool] = None,
thumbnail: Optional[FileInput] = None,
show_caption_above_media: Optional[bool] = None,
cover: Optional[FileInput] = None,
start_timestamp: Optional[int] = None,
*,
api_kwargs: Optional[JSONDict] = None,
):
if isinstance(media, Video):
width = width if width is not None else media.width
height = height if height is not None else media.height
duration = duration if duration is not None else media._duration
media = media.file_id
else:
# We use local_mode=True because we don't have access to the actual setting and want
# things to work in local mode.
media = parse_file_input(media, filename=filename, attach=True, local_mode=True)
super().__init__(
InputMediaType.VIDEO,
media,
caption,
caption_entities,
parse_mode,
api_kwargs=api_kwargs,
)
with self._unfrozen():
self.width: Optional[int] = width
self.height: Optional[int] = height
self._duration: Optional[dtm.timedelta] = to_timedelta(duration)
self.thumbnail: Optional[Union[str, InputFile]] = self._parse_thumbnail_input(
thumbnail
)
self.supports_streaming: Optional[bool] = supports_streaming
self.has_spoiler: Optional[bool] = has_spoiler
self.show_caption_above_media: Optional[bool] = show_caption_above_media
self.cover: Optional[Union[InputFile, str]] = (
parse_file_input(cover, attach=True, local_mode=True) if cover else None
)
self.start_timestamp: Optional[int] = start_timestamp
@property
def duration(self) -> Optional[Union[int, dtm.timedelta]]:
return get_timedelta_value(self._duration, attribute="duration")
class InputMediaAudio(InputMedia):
"""Represents an audio file to be treated as music to be sent.
.. seealso:: :wiki:`Working with Files and Media <Working-with-Files-and-Media>`
Note:
When using a :class:`telegram.Audio` for the :attr:`media` attribute, it will take the
duration, performer and title from that video, unless otherwise specified with the
optional arguments.
.. versionchanged:: 20.5
|removed_thumb_note|
Args:
media (:obj:`str` | :term:`file object` | :class:`~telegram.InputFile` | :obj:`bytes` | \
:class:`pathlib.Path` | :class:`telegram.Audio`): File to send. |fileinputnopath|
Lastly you can pass an existing :class:`telegram.Audio` object to send.
.. versionchanged:: 13.2
Accept :obj:`bytes` as input.
filename (:obj:`str`, optional): Custom file name for the audio, when uploading a
new file. Convenience parameter, useful e.g. when sending files generated by the
:obj:`tempfile` module.
.. versionadded:: 13.1
caption (:obj:`str`, optional): Caption of the audio to be sent,
0-:tg-const:`telegram.constants.MessageLimit.CAPTION_LENGTH` characters after
entities parsing.
parse_mode (:obj:`str`, optional): |parse_mode|
caption_entities (Sequence[:class:`telegram.MessageEntity`], optional): |caption_entities|
.. versionchanged:: 20.0
|sequenceclassargs|
duration (:obj:`int` | :class:`datetime.timedelta`, optional): Duration of the audio
in seconds as defined by the sender.
.. versionchanged:: v22.2
|time-period-input|
performer (:obj:`str`, optional): Performer of the audio as defined by the sender or by
audio tags.
title (:obj:`str`, optional): Title of the audio as defined by the sender or by audio tags.
thumbnail (:term:`file object` | :obj:`bytes` | :class:`pathlib.Path` | :obj:`str`, \
optional): |thumbdocstringnopath|
.. versionadded:: 20.2
Attributes:
type (:obj:`str`): :tg-const:`telegram.constants.InputMediaType.AUDIO`.
media (:obj:`str` | :class:`telegram.InputFile`): Audio file to send.
caption (:obj:`str`): Optional. Caption of the audio to be sent,
0-:tg-const:`telegram.constants.MessageLimit.CAPTION_LENGTH` characters
after entities parsing.
parse_mode (:obj:`str`): Optional. |parse_mode|
caption_entities (tuple[:class:`telegram.MessageEntity`]): Optional. |captionentitiesattr|
.. versionchanged:: 20.0
* |tupleclassattrs|
* |alwaystuple|
duration (:obj:`int` | :class:`datetime.timedelta`): Optional. Duration of the audio
in seconds.
.. deprecated:: v22.2
|time-period-int-deprecated|
performer (:obj:`str`): Optional. Performer of the audio as defined by the sender or by
audio tags.
title (:obj:`str`): Optional. Title of the audio as defined by the sender or by audio tags.
thumbnail (:class:`telegram.InputFile`): Optional. |thumbdocstringbase|
.. versionadded:: 20.2
"""
__slots__ = ("_duration", "performer", "thumbnail", "title")
def __init__(
self,
media: Union[FileInput, Audio],
caption: Optional[str] = None,
parse_mode: ODVInput[str] = DEFAULT_NONE,
duration: Optional[TimePeriod] = None,
performer: Optional[str] = None,
title: Optional[str] = None,
caption_entities: Optional[Sequence[MessageEntity]] = None,
filename: Optional[str] = None,
thumbnail: Optional[FileInput] = None,
*,
api_kwargs: Optional[JSONDict] = None,
):
if isinstance(media, Audio):
duration = duration if duration is not None else media._duration
performer = media.performer if performer is None else performer
title = media.title if title is None else title
media = media.file_id
else:
# We use local_mode=True because we don't have access to the actual setting and want
# things to work in local mode.
media = parse_file_input(media, filename=filename, attach=True, local_mode=True)
super().__init__(
InputMediaType.AUDIO,
media,
caption,
caption_entities,
parse_mode,
api_kwargs=api_kwargs,
)
with self._unfrozen():
self.thumbnail: Optional[Union[str, InputFile]] = self._parse_thumbnail_input(
thumbnail
)
self._duration: Optional[dtm.timedelta] = to_timedelta(duration)
self.title: Optional[str] = title
self.performer: Optional[str] = performer
@property
def duration(self) -> Optional[Union[int, dtm.timedelta]]:
return get_timedelta_value(self._duration, attribute="duration")
class InputMediaDocument(InputMedia):
"""Represents a general file to be sent.
.. seealso:: :wiki:`Working with Files and Media <Working-with-Files-and-Media>`
.. versionchanged:: 20.5
|removed_thumb_note|
Args:
media (:obj:`str` | :term:`file object` | :class:`~telegram.InputFile` | :obj:`bytes` \
| :class:`pathlib.Path` | :class:`telegram.Document`): File to send. |fileinputnopath|
Lastly you can pass an existing :class:`telegram.Document` object to send.
.. versionchanged:: 13.2
Accept :obj:`bytes` as input.
filename (:obj:`str`, optional): Custom file name for the document, when uploading a
new file. Convenience parameter, useful e.g. when sending files generated by the
:obj:`tempfile` module.
.. versionadded:: 13.1
caption (:obj:`str`, optional): Caption of the document to be sent,
0-:tg-const:`telegram.constants.MessageLimit.CAPTION_LENGTH` characters after
entities parsing.
parse_mode (:obj:`str`, optional): |parse_mode|
caption_entities (Sequence[:class:`telegram.MessageEntity`], optional): |caption_entities|
.. versionchanged:: 20.0
|sequenceclassargs|
disable_content_type_detection (:obj:`bool`, optional): Disables automatic server-side
content type detection for files uploaded using multipart/form-data. Always
:obj:`True`, if the document is sent as part of an album.
thumbnail (:term:`file object` | :obj:`bytes` | :class:`pathlib.Path` | :obj:`str`, \
optional): |thumbdocstringnopath|
.. versionadded:: 20.2
Attributes:
type (:obj:`str`): :tg-const:`telegram.constants.InputMediaType.DOCUMENT`.
media (:obj:`str` | :class:`telegram.InputFile`): File to send.
caption (:obj:`str`): Optional. Caption of the document to be sent,
0-:tg-const:`telegram.constants.MessageLimit.CAPTION_LENGTH` characters
after entities parsing.
parse_mode (:obj:`str`): Optional. |parse_mode|
caption_entities (tuple[:class:`telegram.MessageEntity`]): Optional. |captionentitiesattr|
.. versionchanged:: 20.0
* |tupleclassattrs|
* |alwaystuple|
disable_content_type_detection (:obj:`bool`): Optional. Disables automatic server-side
content type detection for files uploaded using multipart/form-data. Always
:obj:`True`, if the document is sent as part of an album.
thumbnail (:class:`telegram.InputFile`): Optional. |thumbdocstringbase|
.. versionadded:: 20.2
"""
__slots__ = ("disable_content_type_detection", "thumbnail")
def __init__(
self,
media: Union[FileInput, Document],
caption: Optional[str] = None,
parse_mode: ODVInput[str] = DEFAULT_NONE,
disable_content_type_detection: Optional[bool] = None,
caption_entities: Optional[Sequence[MessageEntity]] = None,
filename: Optional[str] = None,
thumbnail: Optional[FileInput] = None,
*,
api_kwargs: Optional[JSONDict] = None,
):
# We use local_mode=True because we don't have access to the actual setting and want
# things to work in local mode.
media = parse_file_input(media, Document, filename=filename, attach=True, local_mode=True)
super().__init__(
InputMediaType.DOCUMENT,
media,
caption,
caption_entities,
parse_mode,
api_kwargs=api_kwargs,
)
with self._unfrozen():
self.thumbnail: Optional[Union[str, InputFile]] = self._parse_thumbnail_input(
thumbnail
)
self.disable_content_type_detection: Optional[bool] = disable_content_type_detection

View File

@@ -0,0 +1,138 @@
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2025
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser Public License for more details.
#
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an objects that represents a InputProfilePhoto and subclasses."""
import datetime as dtm
from typing import TYPE_CHECKING, Optional, Union
from telegram import constants
from telegram._telegramobject import TelegramObject
from telegram._utils import enum
from telegram._utils.argumentparsing import to_timedelta
from telegram._utils.files import parse_file_input
from telegram._utils.types import FileInput, JSONDict
if TYPE_CHECKING:
from telegram import InputFile
class InputProfilePhoto(TelegramObject):
"""This object describes a profile photo to set. Currently, it can be one of
* :class:`InputProfilePhotoStatic`
* :class:`InputProfilePhotoAnimated`
.. versionadded:: 22.1
Args:
type (:obj:`str`): Type of the profile photo.
Attributes:
type (:obj:`str`): Type of the profile photo.
"""
STATIC = constants.InputProfilePhotoType.STATIC
""":obj:`str`: :tg-const:`telegram.constants.InputProfilePhotoType.STATIC`."""
ANIMATED = constants.InputProfilePhotoType.ANIMATED
""":obj:`str`: :tg-const:`telegram.constants.InputProfilePhotoType.ANIMATED`."""
__slots__ = ("type",)
def __init__(
self,
type: str, # pylint: disable=redefined-builtin
*,
api_kwargs: Optional[JSONDict] = None,
):
super().__init__(api_kwargs=api_kwargs)
self.type: str = enum.get_member(constants.InputProfilePhotoType, type, type)
self._freeze()
class InputProfilePhotoStatic(InputProfilePhoto):
"""A static profile photo in the .JPG format.
.. versionadded:: 22.1
Args:
photo (:term:`file object` | :class:`~telegram.InputFile` | :obj:`bytes` | \
:class:`pathlib.Path`): The static profile photo. |uploadinputnopath|
Attributes:
type (:obj:`str`): :tg-const:`telegram.constants.InputProfilePhotoType.STATIC`.
photo (:class:`telegram.InputFile` | :obj:`str`): The static profile photo.
"""
__slots__ = ("photo",)
def __init__(
self,
photo: FileInput,
*,
api_kwargs: Optional[JSONDict] = None,
):
super().__init__(type=constants.InputProfilePhotoType.STATIC, api_kwargs=api_kwargs)
with self._unfrozen():
# We use local_mode=True because we don't have access to the actual setting and want
# things to work in local mode.
self.photo: Union[str, InputFile] = parse_file_input(
photo, attach=True, local_mode=True
)
class InputProfilePhotoAnimated(InputProfilePhoto):
"""An animated profile photo in the MPEG4 format.
.. versionadded:: 22.1
Args:
animation (:term:`file object` | :class:`~telegram.InputFile` | :obj:`bytes` | \
:class:`pathlib.Path`): The animated profile photo. |uploadinputnopath|
main_frame_timestamp (:class:`datetime.timedelta` | :obj:`int` | :obj:`float`, optional):
Timestamp in seconds of the frame that will be used as the static profile photo.
Defaults to ``0.0``.
Attributes:
type (:obj:`str`): :tg-const:`telegram.constants.InputProfilePhotoType.ANIMATED`.
animation (:class:`telegram.InputFile` | :obj:`str`): The animated profile photo.
main_frame_timestamp (:class:`datetime.timedelta`): Optional. Timestamp in seconds of the
frame that will be used as the static profile photo. Defaults to ``0.0``.
"""
__slots__ = ("animation", "main_frame_timestamp")
def __init__(
self,
animation: FileInput,
main_frame_timestamp: Union[float, dtm.timedelta, None] = None,
*,
api_kwargs: Optional[JSONDict] = None,
):
super().__init__(type=constants.InputProfilePhotoType.ANIMATED, api_kwargs=api_kwargs)
with self._unfrozen():
# We use local_mode=True because we don't have access to the actual setting and want
# things to work in local mode.
self.animation: Union[str, InputFile] = parse_file_input(
animation, attach=True, local_mode=True
)
self.main_frame_timestamp: Optional[dtm.timedelta] = to_timedelta(main_frame_timestamp)

View File

@@ -0,0 +1,119 @@
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2025
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser Public License for more details.
#
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents a Telegram InputSticker."""
from collections.abc import Sequence
from typing import TYPE_CHECKING, Optional, Union
from telegram._files.sticker import MaskPosition
from telegram._telegramobject import TelegramObject
from telegram._utils.argumentparsing import parse_sequence_arg
from telegram._utils.files import parse_file_input
from telegram._utils.types import FileInput, JSONDict
if TYPE_CHECKING:
from telegram._files.inputfile import InputFile
class InputSticker(TelegramObject):
"""
This object describes a sticker to be added to a sticker set.
.. versionadded:: 20.2
.. versionchanged:: 21.1
As of Bot API 7.2, the new argument :paramref:`format` is a required argument, and thus the
order of the arguments has changed.
Args:
sticker (:obj:`str` | :term:`file object` | :class:`~telegram.InputFile` | :obj:`bytes` \
| :class:`pathlib.Path`): The
added sticker. |uploadinputnopath| Animated and video stickers can't be uploaded via
HTTP URL.
emoji_list (Sequence[:obj:`str`]): Sequence of
:tg-const:`telegram.constants.StickerLimit.MIN_STICKER_EMOJI` -
:tg-const:`telegram.constants.StickerLimit.MAX_STICKER_EMOJI` emoji associated with the
sticker.
mask_position (:class:`telegram.MaskPosition`, optional): Position where the mask should be
placed on faces. For ":tg-const:`telegram.constants.StickerType.MASK`" stickers only.
keywords (Sequence[:obj:`str`], optional): Sequence of
0-:tg-const:`telegram.constants.StickerLimit.MAX_SEARCH_KEYWORDS` search keywords
for the sticker with the total length of up to
:tg-const:`telegram.constants.StickerLimit.MAX_KEYWORD_LENGTH` characters. For
":tg-const:`telegram.constants.StickerType.REGULAR`" and
":tg-const:`telegram.constants.StickerType.CUSTOM_EMOJI`" stickers only.
format (:obj:`str`): Format of the added sticker, must be one of
:tg-const:`telegram.constants.StickerFormat.STATIC` for a
``.WEBP`` or ``.PNG`` image, :tg-const:`telegram.constants.StickerFormat.ANIMATED`
for a ``.TGS`` animation, :tg-const:`telegram.constants.StickerFormat.VIDEO` for a
``.WEBM`` video.
.. versionadded:: 21.1
Attributes:
sticker (:obj:`str` | :class:`telegram.InputFile`): The added sticker.
emoji_list (tuple[:obj:`str`]): Tuple of
:tg-const:`telegram.constants.StickerLimit.MIN_STICKER_EMOJI` -
:tg-const:`telegram.constants.StickerLimit.MAX_STICKER_EMOJI` emoji associated with the
sticker.
mask_position (:class:`telegram.MaskPosition`): Optional. Position where the mask should be
placed on faces. For ":tg-const:`telegram.constants.StickerType.MASK`" stickers only.
keywords (tuple[:obj:`str`]): Optional. Tuple of
0-:tg-const:`telegram.constants.StickerLimit.MAX_SEARCH_KEYWORDS` search keywords
for the sticker with the total length of up to
:tg-const:`telegram.constants.StickerLimit.MAX_KEYWORD_LENGTH` characters. For
":tg-const:`telegram.constants.StickerType.REGULAR`" and
":tg-const:`telegram.constants.StickerType.CUSTOM_EMOJI`" stickers only.
":tg-const:`telegram.constants.StickerType.CUSTOM_EMOJI`" stickers only.
format (:obj:`str`): Format of the added sticker, must be one of
:tg-const:`telegram.constants.StickerFormat.STATIC` for a
``.WEBP`` or ``.PNG`` image, :tg-const:`telegram.constants.StickerFormat.ANIMATED`
for a ``.TGS`` animation, :tg-const:`telegram.constants.StickerFormat.VIDEO` for a
``.WEBM`` video.
.. versionadded:: 21.1
"""
__slots__ = ("emoji_list", "format", "keywords", "mask_position", "sticker")
def __init__(
self,
sticker: FileInput,
emoji_list: Sequence[str],
format: str, # pylint: disable=redefined-builtin
mask_position: Optional[MaskPosition] = None,
keywords: Optional[Sequence[str]] = None,
*,
api_kwargs: Optional[JSONDict] = None,
):
super().__init__(api_kwargs=api_kwargs)
# We use local_mode=True because we don't have access to the actual setting and want
# things to work in local mode.
self.sticker: Union[str, InputFile] = parse_file_input(
sticker,
local_mode=True,
attach=True,
)
self.emoji_list: tuple[str, ...] = parse_sequence_arg(emoji_list)
self.format: str = format
self.mask_position: Optional[MaskPosition] = mask_position
self.keywords: tuple[str, ...] = parse_sequence_arg(keywords)
self._freeze()

View File

@@ -0,0 +1,128 @@
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2025
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser Public License for more details.
#
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents a Telegram Location."""
import datetime as dtm
from typing import Final, Optional, Union
from telegram import constants
from telegram._telegramobject import TelegramObject
from telegram._utils.argumentparsing import to_timedelta
from telegram._utils.datetime import get_timedelta_value
from telegram._utils.types import JSONDict, TimePeriod
class Location(TelegramObject):
"""This object represents a point on the map.
Objects of this class are comparable in terms of equality. Two objects of this class are
considered equal, if their :attr:`longitude` and :attr:`latitude` are equal.
Args:
longitude (:obj:`float`): Longitude as defined by the sender.
latitude (:obj:`float`): Latitude as defined by the sender.
horizontal_accuracy (:obj:`float`, optional): The radius of uncertainty for the location,
measured in meters; 0-:tg-const:`telegram.Location.HORIZONTAL_ACCURACY`.
live_period (:obj:`int` | :class:`datetime.timedelta`, optional): Time relative to the
message sending date, during which the location can be updated, in seconds. For active
live locations only.
.. versionchanged:: v22.2
|time-period-input|
heading (:obj:`int`, optional): The direction in which user is moving, in degrees;
:tg-const:`telegram.Location.MIN_HEADING`-:tg-const:`telegram.Location.MAX_HEADING`.
For active live locations only.
proximity_alert_radius (:obj:`int`, optional): Maximum distance for proximity alerts about
approaching another chat member, in meters. For sent live locations only.
Attributes:
longitude (:obj:`float`): Longitude as defined by the sender.
latitude (:obj:`float`): Latitude as defined by the sender.
horizontal_accuracy (:obj:`float`): Optional. The radius of uncertainty for the location,
measured in meters; 0-:tg-const:`telegram.Location.HORIZONTAL_ACCURACY`.
live_period (:obj:`int` | :class:`datetime.timedelta`): Optional. Time relative to the
message sending date, during which the location can be updated, in seconds. For active
live locations only.
.. deprecated:: v22.2
|time-period-int-deprecated|
heading (:obj:`int`): Optional. The direction in which user is moving, in degrees;
:tg-const:`telegram.Location.MIN_HEADING`-:tg-const:`telegram.Location.MAX_HEADING`.
For active live locations only.
proximity_alert_radius (:obj:`int`): Optional. Maximum distance for proximity alerts about
approaching another chat member, in meters. For sent live locations only.
"""
__slots__ = (
"_live_period",
"heading",
"horizontal_accuracy",
"latitude",
"longitude",
"proximity_alert_radius",
)
def __init__(
self,
longitude: float,
latitude: float,
horizontal_accuracy: Optional[float] = None,
live_period: Optional[TimePeriod] = None,
heading: Optional[int] = None,
proximity_alert_radius: Optional[int] = None,
*,
api_kwargs: Optional[JSONDict] = None,
):
super().__init__(api_kwargs=api_kwargs)
# Required
self.longitude: float = longitude
self.latitude: float = latitude
# Optionals
self.horizontal_accuracy: Optional[float] = horizontal_accuracy
self._live_period: Optional[dtm.timedelta] = to_timedelta(live_period)
self.heading: Optional[int] = heading
self.proximity_alert_radius: Optional[int] = (
int(proximity_alert_radius) if proximity_alert_radius else None
)
self._id_attrs = (self.longitude, self.latitude)
self._freeze()
@property
def live_period(self) -> Optional[Union[int, dtm.timedelta]]:
return get_timedelta_value(self._live_period, attribute="live_period")
HORIZONTAL_ACCURACY: Final[int] = constants.LocationLimit.HORIZONTAL_ACCURACY
""":const:`telegram.constants.LocationLimit.HORIZONTAL_ACCURACY`
.. versionadded:: 20.0
"""
MIN_HEADING: Final[int] = constants.LocationLimit.MIN_HEADING
""":const:`telegram.constants.LocationLimit.MIN_HEADING`
.. versionadded:: 20.0
"""
MAX_HEADING: Final[int] = constants.LocationLimit.MAX_HEADING
""":const:`telegram.constants.LocationLimit.MAX_HEADING`
.. versionadded:: 20.0
"""

View File

@@ -0,0 +1,77 @@
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2025
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser Public License for more details.
#
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents a Telegram PhotoSize."""
from typing import Optional
from telegram._files._basemedium import _BaseMedium
from telegram._utils.types import JSONDict
class PhotoSize(_BaseMedium):
"""This object represents one size of a photo or a file/sticker thumbnail.
Objects of this class are comparable in terms of equality. Two objects of this class are
considered equal, if their :attr:`file_unique_id` is equal.
Args:
file_id (:obj:`str`): Identifier for this file, which can be used to download
or reuse the file.
file_unique_id (:obj:`str`): Unique identifier for this file, which
is supposed to be the same over time and for different bots.
Can't be used to download or reuse the file.
width (:obj:`int`): Photo width.
height (:obj:`int`): Photo height.
file_size (:obj:`int`, optional): File size in bytes.
Attributes:
file_id (:obj:`str`): Identifier for this file, which can be used to download
or reuse the file.
file_unique_id (:obj:`str`): Unique identifier for this file, which
is supposed to be the same over time and for different bots.
Can't be used to download or reuse the file.
width (:obj:`int`): Photo width.
height (:obj:`int`): Photo height.
file_size (:obj:`int`): Optional. File size in bytes.
"""
__slots__ = ("height", "width")
def __init__(
self,
file_id: str,
file_unique_id: str,
width: int,
height: int,
file_size: Optional[int] = None,
*,
api_kwargs: Optional[JSONDict] = None,
):
super().__init__(
file_id=file_id,
file_unique_id=file_unique_id,
file_size=file_size,
api_kwargs=api_kwargs,
)
with self._unfrozen():
# Required
self.width: int = width
self.height: int = height

View File

@@ -0,0 +1,382 @@
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2025
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser Public License for more details.
#
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains objects that represent stickers."""
from collections.abc import Sequence
from typing import TYPE_CHECKING, Final, Optional
from telegram import constants
from telegram._files._basethumbedmedium import _BaseThumbedMedium
from telegram._files.file import File
from telegram._files.photosize import PhotoSize
from telegram._telegramobject import TelegramObject
from telegram._utils import enum
from telegram._utils.argumentparsing import de_json_optional, de_list_optional, parse_sequence_arg
from telegram._utils.types import JSONDict
if TYPE_CHECKING:
from telegram import Bot
class Sticker(_BaseThumbedMedium):
"""This object represents a sticker.
Objects of this class are comparable in terms of equality. Two objects of this class are
considered equal, if their :attr:`file_unique_id` is equal.
Note:
As of v13.11 :paramref:`is_video` is a required argument and therefore the order of the
arguments had to be changed. Use keyword arguments to make sure that the arguments are
passed correctly.
.. versionchanged:: 20.5
|removed_thumb_note|
Args:
file_id (:obj:`str`): Identifier for this file, which can be used to download
or reuse the file.
file_unique_id (:obj:`str`): Unique identifier for this file, which
is supposed to be the same over time and for different bots.
Can't be used to download or reuse the file.
width (:obj:`int`): Sticker width.
height (:obj:`int`): Sticker height.
is_animated (:obj:`bool`): :obj:`True`, if the sticker is animated.
is_video (:obj:`bool`): :obj:`True`, if the sticker is a video sticker.
.. versionadded:: 13.11
type (:obj:`str`): Type of the sticker. Currently one of :attr:`REGULAR`,
:attr:`MASK`, :attr:`CUSTOM_EMOJI`. The type of the sticker is independent from its
format, which is determined by the fields :attr:`is_animated` and :attr:`is_video`.
.. versionadded:: 20.0
emoji (:obj:`str`, optional): Emoji associated with the sticker
set_name (:obj:`str`, optional): Name of the sticker set to which the sticker belongs.
mask_position (:class:`telegram.MaskPosition`, optional): For mask stickers, the position
where the mask should be placed.
file_size (:obj:`int`, optional): File size in bytes.
premium_animation (:class:`telegram.File`, optional): For premium regular stickers,
premium animation for the sticker.
.. versionadded:: 20.0
custom_emoji_id (:obj:`str`, optional): For custom emoji stickers, unique identifier of the
custom emoji.
.. versionadded:: 20.0
thumbnail (:class:`telegram.PhotoSize`, optional): Sticker thumbnail in the ``.WEBP`` or
``.JPG`` format.
.. versionadded:: 20.2
needs_repainting (:obj:`bool`, optional): :obj:`True`, if the sticker must be repainted to
a text color in messages, the color of the Telegram Premium badge in emoji status,
white color on chat photos, or another appropriate color in other places.
.. versionadded:: 20.2
Attributes:
file_id (:obj:`str`): Identifier for this file, which can be used to download
or reuse the file.
file_unique_id (:obj:`str`): Unique identifier for this file, which
is supposed to be the same over time and for different bots.
Can't be used to download or reuse the file.
width (:obj:`int`): Sticker width.
height (:obj:`int`): Sticker height.
is_animated (:obj:`bool`): :obj:`True`, if the sticker is animated.
is_video (:obj:`bool`): :obj:`True`, if the sticker is a video sticker.
.. versionadded:: 13.11
type (:obj:`str`): Type of the sticker. Currently one of :attr:`REGULAR`,
:attr:`MASK`, :attr:`CUSTOM_EMOJI`. The type of the sticker is independent from its
format, which is determined by the fields :attr:`is_animated` and :attr:`is_video`.
.. versionadded:: 20.0
emoji (:obj:`str`): Optional. Emoji associated with the sticker.
set_name (:obj:`str`): Optional. Name of the sticker set to which the sticker belongs.
mask_position (:class:`telegram.MaskPosition`): Optional. For mask stickers, the position
where the mask should be placed.
file_size (:obj:`int`): Optional. File size in bytes.
premium_animation (:class:`telegram.File`): Optional. For premium regular stickers,
premium animation for the sticker.
.. versionadded:: 20.0
custom_emoji_id (:obj:`str`): Optional. For custom emoji stickers, unique identifier of the
custom emoji.
.. versionadded:: 20.0
thumbnail (:class:`telegram.PhotoSize`): Optional. Sticker thumbnail in the ``.WEBP`` or
``.JPG`` format.
.. versionadded:: 20.2
needs_repainting (:obj:`bool`): Optional. :obj:`True`, if the sticker must be repainted to
a text color in messages, the color of the Telegram Premium badge in emoji status,
white color on chat photos, or another appropriate color in other places.
.. versionadded:: 20.2
"""
__slots__ = (
"custom_emoji_id",
"emoji",
"height",
"is_animated",
"is_video",
"mask_position",
"needs_repainting",
"premium_animation",
"set_name",
"type",
"width",
)
def __init__(
self,
file_id: str,
file_unique_id: str,
width: int,
height: int,
is_animated: bool,
is_video: bool,
type: str, # pylint: disable=redefined-builtin
emoji: Optional[str] = None,
file_size: Optional[int] = None,
set_name: Optional[str] = None,
mask_position: Optional["MaskPosition"] = None,
premium_animation: Optional["File"] = None,
custom_emoji_id: Optional[str] = None,
thumbnail: Optional[PhotoSize] = None,
needs_repainting: Optional[bool] = None,
*,
api_kwargs: Optional[JSONDict] = None,
):
super().__init__(
file_id=file_id,
file_unique_id=file_unique_id,
file_size=file_size,
thumbnail=thumbnail,
api_kwargs=api_kwargs,
)
with self._unfrozen():
# Required
self.width: int = width
self.height: int = height
self.is_animated: bool = is_animated
self.is_video: bool = is_video
self.type: str = enum.get_member(constants.StickerType, type, type)
# Optional
self.emoji: Optional[str] = emoji
self.set_name: Optional[str] = set_name
self.mask_position: Optional[MaskPosition] = mask_position
self.premium_animation: Optional[File] = premium_animation
self.custom_emoji_id: Optional[str] = custom_emoji_id
self.needs_repainting: Optional[bool] = needs_repainting
REGULAR: Final[str] = constants.StickerType.REGULAR
""":const:`telegram.constants.StickerType.REGULAR`"""
MASK: Final[str] = constants.StickerType.MASK
""":const:`telegram.constants.StickerType.MASK`"""
CUSTOM_EMOJI: Final[str] = constants.StickerType.CUSTOM_EMOJI
""":const:`telegram.constants.StickerType.CUSTOM_EMOJI`"""
@classmethod
def de_json(cls, data: JSONDict, bot: Optional["Bot"] = None) -> "Sticker":
"""See :meth:`telegram.TelegramObject.de_json`."""
data = cls._parse_data(data)
data["thumbnail"] = de_json_optional(data.get("thumbnail"), PhotoSize, bot)
data["mask_position"] = de_json_optional(data.get("mask_position"), MaskPosition, bot)
data["premium_animation"] = de_json_optional(data.get("premium_animation"), File, bot)
api_kwargs = {}
# This is a deprecated field that TG still returns for backwards compatibility
# Let's filter it out to speed up the de-json process
if data.get("thumb") is not None:
api_kwargs["thumb"] = data.pop("thumb")
return super()._de_json(data=data, bot=bot, api_kwargs=api_kwargs)
class StickerSet(TelegramObject):
"""This object represents a sticker set.
Objects of this class are comparable in terms of equality. Two objects of this class are
considered equal, if their :attr:`name` is equal.
Note:
As of v13.11 :paramref:`is_video` is a required argument and therefore the order of the
arguments had to be changed. Use keyword arguments to make sure that the arguments are
passed correctly.
.. versionchanged:: 20.0
The parameter ``contains_masks`` has been removed. Use :paramref:`sticker_type` instead.
.. versionchanged:: 21.1
The parameters ``is_video`` and ``is_animated`` are deprecated and now made optional. Thus,
the order of the arguments had to be changed.
.. versionchanged:: 20.5
|removed_thumb_note|
.. versionremoved:: 21.2
Removed the deprecated arguments and attributes ``is_animated`` and ``is_video``.
Args:
name (:obj:`str`): Sticker set name.
title (:obj:`str`): Sticker set title.
stickers (Sequence[:class:`telegram.Sticker`]): List of all set stickers.
.. versionchanged:: 20.0
|sequenceclassargs|
sticker_type (:obj:`str`): Type of stickers in the set, currently one of
:attr:`telegram.Sticker.REGULAR`, :attr:`telegram.Sticker.MASK`,
:attr:`telegram.Sticker.CUSTOM_EMOJI`.
.. versionadded:: 20.0
thumbnail (:class:`telegram.PhotoSize`, optional): Sticker set thumbnail in the ``.WEBP``,
``.TGS``, or ``.WEBM`` format.
.. versionadded:: 20.2
Attributes:
name (:obj:`str`): Sticker set name.
title (:obj:`str`): Sticker set title.
stickers (tuple[:class:`telegram.Sticker`]): List of all set stickers.
.. versionchanged:: 20.0
|tupleclassattrs|
sticker_type (:obj:`str`): Type of stickers in the set, currently one of
:attr:`telegram.Sticker.REGULAR`, :attr:`telegram.Sticker.MASK`,
:attr:`telegram.Sticker.CUSTOM_EMOJI`.
.. versionadded:: 20.0
thumbnail (:class:`telegram.PhotoSize`): Optional. Sticker set thumbnail in the ``.WEBP``,
``.TGS``, or ``.WEBM`` format.
.. versionadded:: 20.2
"""
__slots__ = (
"name",
"sticker_type",
"stickers",
"thumbnail",
"title",
)
def __init__(
self,
name: str,
title: str,
stickers: Sequence[Sticker],
sticker_type: str,
thumbnail: Optional[PhotoSize] = None,
*,
api_kwargs: Optional[JSONDict] = None,
):
super().__init__(api_kwargs=api_kwargs)
self.name: str = name
self.title: str = title
self.stickers: tuple[Sticker, ...] = parse_sequence_arg(stickers)
self.sticker_type: str = sticker_type
# Optional
self.thumbnail: Optional[PhotoSize] = thumbnail
self._id_attrs = (self.name,)
self._freeze()
@classmethod
def de_json(cls, data: JSONDict, bot: Optional["Bot"] = None) -> "StickerSet":
"""See :meth:`telegram.TelegramObject.de_json`."""
data = cls._parse_data(data)
data["thumbnail"] = de_json_optional(data.get("thumbnail"), PhotoSize, bot)
data["stickers"] = de_list_optional(data.get("stickers"), Sticker, bot)
api_kwargs = {}
# These are deprecated fields that TG still returns for backwards compatibility
# Let's filter them out to speed up the de-json process
for deprecated_field in ("contains_masks", "thumb", "is_animated", "is_video"):
if deprecated_field in data:
api_kwargs[deprecated_field] = data.pop(deprecated_field)
return super()._de_json(data=data, bot=bot, api_kwargs=api_kwargs)
class MaskPosition(TelegramObject):
"""This object describes the position on faces where a mask should be placed by default.
Objects of this class are comparable in terms of equality. Two objects of this class are
considered equal, if their :attr:`point`, :attr:`x_shift`, :attr:`y_shift` and, :attr:`scale`
are equal.
Args:
point (:obj:`str`): The part of the face relative to which the mask should be placed.
One of :attr:`FOREHEAD`, :attr:`EYES`, :attr:`MOUTH`, or :attr:`CHIN`.
x_shift (:obj:`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 (:obj:`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 (:obj:`float`): Mask scaling coefficient. For example, ``2.0`` means double size.
Attributes:
point (:obj:`str`): The part of the face relative to which the mask should be placed.
One of :attr:`FOREHEAD`, :attr:`EYES`, :attr:`MOUTH`, or :attr:`CHIN`.
x_shift (:obj:`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 (:obj:`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 (:obj:`float`): Mask scaling coefficient. For example, ``2.0`` means double size.
"""
__slots__ = ("point", "scale", "x_shift", "y_shift")
FOREHEAD: Final[str] = constants.MaskPosition.FOREHEAD
""":const:`telegram.constants.MaskPosition.FOREHEAD`"""
EYES: Final[str] = constants.MaskPosition.EYES
""":const:`telegram.constants.MaskPosition.EYES`"""
MOUTH: Final[str] = constants.MaskPosition.MOUTH
""":const:`telegram.constants.MaskPosition.MOUTH`"""
CHIN: Final[str] = constants.MaskPosition.CHIN
""":const:`telegram.constants.MaskPosition.CHIN`"""
def __init__(
self,
point: str,
x_shift: float,
y_shift: float,
scale: float,
*,
api_kwargs: Optional[JSONDict] = None,
):
super().__init__(api_kwargs=api_kwargs)
self.point: str = point
self.x_shift: float = x_shift
self.y_shift: float = y_shift
self.scale: float = scale
self._id_attrs = (self.point, self.x_shift, self.y_shift, self.scale)
self._freeze()

View File

@@ -0,0 +1,113 @@
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2025
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser Public License for more details.
#
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents a Telegram Venue."""
from typing import TYPE_CHECKING, Optional
from telegram._files.location import Location
from telegram._telegramobject import TelegramObject
from telegram._utils.argumentparsing import de_json_optional
from telegram._utils.types import JSONDict
if TYPE_CHECKING:
from telegram import Bot
class Venue(TelegramObject):
"""This object represents a venue.
Objects of this class are comparable in terms of equality. Two objects of this class are
considered equal, if their :attr:`location` and :attr:`title` are equal.
Note:
Foursquare details and Google Place details are mutually exclusive. However, this
behaviour is undocumented and might be changed by Telegram.
Args:
location (:class:`telegram.Location`): Venue location.
title (:obj:`str`): Name of the venue.
address (:obj:`str`): Address of the venue.
foursquare_id (:obj:`str`, optional): Foursquare identifier of the venue.
foursquare_type (:obj:`str`, optional): Foursquare type of the venue. (For example,
"arts_entertainment/default", "arts_entertainment/aquarium" or "food/icecream".)
google_place_id (:obj:`str`, optional): Google Places identifier of the venue.
google_place_type (:obj:`str`, optional): Google Places type of the venue. (See
`supported types <https://developers.google.com/maps/documentation/places/web-service\
/supported_types>`_.)
Attributes:
location (:class:`telegram.Location`): Venue location.
title (:obj:`str`): Name of the venue.
address (:obj:`str`): Address of the venue.
foursquare_id (:obj:`str`): Optional. Foursquare identifier of the venue.
foursquare_type (:obj:`str`): Optional. Foursquare type of the venue. (For example,
"arts_entertainment/default", "arts_entertainment/aquarium" or "food/icecream".)
google_place_id (:obj:`str`): Optional. Google Places identifier of the venue.
google_place_type (:obj:`str`): Optional. Google Places type of the venue. (See
`supported types <https://developers.google.com/maps/documentation/places/web-service\
/supported_types>`_.)
"""
__slots__ = (
"address",
"foursquare_id",
"foursquare_type",
"google_place_id",
"google_place_type",
"location",
"title",
)
def __init__(
self,
location: Location,
title: str,
address: str,
foursquare_id: Optional[str] = None,
foursquare_type: Optional[str] = None,
google_place_id: Optional[str] = None,
google_place_type: Optional[str] = None,
*,
api_kwargs: Optional[JSONDict] = None,
):
super().__init__(api_kwargs=api_kwargs)
# Required
self.location: Location = location
self.title: str = title
self.address: str = address
# Optionals
self.foursquare_id: Optional[str] = foursquare_id
self.foursquare_type: Optional[str] = foursquare_type
self.google_place_id: Optional[str] = google_place_id
self.google_place_type: Optional[str] = google_place_type
self._id_attrs = (self.location, self.title)
self._freeze()
@classmethod
def de_json(cls, data: JSONDict, bot: Optional["Bot"] = None) -> "Venue":
"""See :meth:`telegram.TelegramObject.de_json`."""
data = cls._parse_data(data)
data["location"] = de_json_optional(data.get("location"), Location, bot)
return super().de_json(data=data, bot=bot)

View File

@@ -0,0 +1,165 @@
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2025
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser Public License for more details.
#
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents a Telegram Video."""
import datetime as dtm
from collections.abc import Sequence
from typing import TYPE_CHECKING, Optional, Union
from telegram._files._basethumbedmedium import _BaseThumbedMedium
from telegram._files.photosize import PhotoSize
from telegram._utils.argumentparsing import de_list_optional, parse_sequence_arg, to_timedelta
from telegram._utils.datetime import get_timedelta_value
from telegram._utils.types import JSONDict, TimePeriod
if TYPE_CHECKING:
from telegram import Bot
class Video(_BaseThumbedMedium):
"""This object represents a video file.
Objects of this class are comparable in terms of equality. Two objects of this class are
considered equal, if their :attr:`file_unique_id` is equal.
.. versionchanged:: 20.5
|removed_thumb_note|
Args:
file_id (:obj:`str`): Identifier for this file, which can be used to download
or reuse the file.
file_unique_id (:obj:`str`): Unique identifier for this file, which
is supposed to be the same over time and for different bots.
Can't be used to download or reuse the file.
width (:obj:`int`): Video width as defined by the sender.
height (:obj:`int`): Video height as defined by the sender.
duration (:obj:`int` | :class:`datetime.timedelta`): Duration of the video
in seconds as defined by the sender.
.. versionchanged:: v22.2
|time-period-input|
file_name (:obj:`str`, optional): Original filename as defined by the sender.
mime_type (:obj:`str`, optional): MIME type of a file as defined by the sender.
file_size (:obj:`int`, optional): File size in bytes.
thumbnail (:class:`telegram.PhotoSize`, optional): Video thumbnail.
.. versionadded:: 20.2
cover (Sequence[:class:`telegram.PhotoSize`], optional): Available sizes of the cover of
the video in the message.
.. versionadded:: 21.11
start_timestamp (:obj:`int` | :class:`datetime.timedelta`, optional): Timestamp in seconds
from which the video will play in the message
.. versionadded:: 21.11
.. versionchanged:: v22.2
|time-period-input|
Attributes:
file_id (:obj:`str`): Identifier for this file, which can be used to download
or reuse the file.
file_unique_id (:obj:`str`): Unique identifier for this file, which
is supposed to be the same over time and for different bots.
Can't be used to download or reuse the file.
width (:obj:`int`): Video width as defined by the sender.
height (:obj:`int`): Video height as defined by the sender.
duration (:obj:`int` | :class:`datetime.timedelta`): Duration of the video in seconds
as defined by the sender.
.. deprecated:: v22.2
|time-period-int-deprecated|
file_name (:obj:`str`): Optional. Original filename as defined by the sender.
mime_type (:obj:`str`): Optional. MIME type of a file as defined by the sender.
file_size (:obj:`int`): Optional. File size in bytes.
thumbnail (:class:`telegram.PhotoSize`): Optional. Video thumbnail.
.. versionadded:: 20.2
cover (tuple[:class:`telegram.PhotoSize`]): Optional, Available sizes of the cover of
the video in the message.
.. versionadded:: 21.11
start_timestamp (:obj:`int` | :class:`datetime.timedelta`): Optional. Timestamp in seconds
from which the video will play in the message
.. versionadded:: 21.11
.. deprecated:: v22.2
|time-period-int-deprecated|
"""
__slots__ = (
"_duration",
"_start_timestamp",
"cover",
"file_name",
"height",
"mime_type",
"width",
)
def __init__(
self,
file_id: str,
file_unique_id: str,
width: int,
height: int,
duration: TimePeriod,
mime_type: Optional[str] = None,
file_size: Optional[int] = None,
file_name: Optional[str] = None,
thumbnail: Optional[PhotoSize] = None,
cover: Optional[Sequence[PhotoSize]] = None,
start_timestamp: Optional[TimePeriod] = None,
*,
api_kwargs: Optional[JSONDict] = None,
):
super().__init__(
file_id=file_id,
file_unique_id=file_unique_id,
file_size=file_size,
thumbnail=thumbnail,
api_kwargs=api_kwargs,
)
with self._unfrozen():
# Required
self.width: int = width
self.height: int = height
self._duration: dtm.timedelta = to_timedelta(duration)
# Optional
self.mime_type: Optional[str] = mime_type
self.file_name: Optional[str] = file_name
self.cover: Optional[Sequence[PhotoSize]] = parse_sequence_arg(cover)
self._start_timestamp: Optional[dtm.timedelta] = to_timedelta(start_timestamp)
@property
def duration(self) -> Union[int, dtm.timedelta]:
return get_timedelta_value( # type: ignore[return-value]
self._duration, attribute="duration"
)
@property
def start_timestamp(self) -> Optional[Union[int, dtm.timedelta]]:
return get_timedelta_value(self._start_timestamp, attribute="start_timestamp")
@classmethod
def de_json(cls, data: JSONDict, bot: Optional["Bot"] = None) -> "Video":
"""See :meth:`telegram.TelegramObject.de_json`."""
data = cls._parse_data(data)
data["cover"] = de_list_optional(data.get("cover"), PhotoSize, bot)
return super().de_json(data=data, bot=bot)

View File

@@ -0,0 +1,107 @@
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2025
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser Public License for more details.
#
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents a Telegram VideoNote."""
import datetime as dtm
from typing import Optional, Union
from telegram._files._basethumbedmedium import _BaseThumbedMedium
from telegram._files.photosize import PhotoSize
from telegram._utils.argumentparsing import to_timedelta
from telegram._utils.datetime import get_timedelta_value
from telegram._utils.types import JSONDict, TimePeriod
class VideoNote(_BaseThumbedMedium):
"""This object represents a video message (available in Telegram apps as of v.4.0).
Objects of this class are comparable in terms of equality. Two objects of this class are
considered equal, if their :attr:`file_unique_id` is equal.
.. versionchanged:: 20.5
|removed_thumb_note|
Args:
file_id (:obj:`str`): Identifier for this file, which can be used to download
or reuse the file.
file_unique_id (:obj:`str`): Unique identifier for this file, which
is supposed to be the same over time and for different bots.
Can't be used to download or reuse the file.
length (:obj:`int`): Video width and height (diameter of the video message) as defined
by sender.
duration (:obj:`int` | :class:`datetime.timedelta`): Duration of the video in
seconds as defined by the sender.
.. versionchanged:: v22.2
|time-period-input|
file_size (:obj:`int`, optional): File size in bytes.
thumbnail (:class:`telegram.PhotoSize`, optional): Video thumbnail.
.. versionadded:: 20.2
Attributes:
file_id (:obj:`str`): Identifier for this file, which can be used to download
or reuse the file.
file_unique_id (:obj:`str`): Unique identifier for this file, which
is supposed to be the same over time and for different bots.
Can't be used to download or reuse the file.
length (:obj:`int`): Video width and height (diameter of the video message) as defined
by sender.
duration (:obj:`int` | :class:`datetime.timedelta`): Duration of the video in seconds as
defined by the sender.
.. deprecated:: v22.2
|time-period-int-deprecated|
file_size (:obj:`int`): Optional. File size in bytes.
thumbnail (:class:`telegram.PhotoSize`): Optional. Video thumbnail.
.. versionadded:: 20.2
"""
__slots__ = ("_duration", "length")
def __init__(
self,
file_id: str,
file_unique_id: str,
length: int,
duration: TimePeriod,
file_size: Optional[int] = None,
thumbnail: Optional[PhotoSize] = None,
*,
api_kwargs: Optional[JSONDict] = None,
):
super().__init__(
file_id=file_id,
file_unique_id=file_unique_id,
file_size=file_size,
thumbnail=thumbnail,
api_kwargs=api_kwargs,
)
with self._unfrozen():
# Required
self.length: int = length
self._duration: dtm.timedelta = to_timedelta(duration)
@property
def duration(self) -> Union[int, dtm.timedelta]:
return get_timedelta_value( # type: ignore[return-value]
self._duration, attribute="duration"
)

View File

@@ -0,0 +1,93 @@
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2025
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser Public License for more details.
#
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents a Telegram Voice."""
import datetime as dtm
from typing import Optional, Union
from telegram._files._basemedium import _BaseMedium
from telegram._utils.argumentparsing import to_timedelta
from telegram._utils.datetime import get_timedelta_value
from telegram._utils.types import JSONDict, TimePeriod
class Voice(_BaseMedium):
"""This object represents a voice note.
Objects of this class are comparable in terms of equality. Two objects of this class are
considered equal, if their :attr:`file_unique_id` is equal.
Args:
file_id (:obj:`str`): Identifier for this file, which can be used to download
or reuse the file.
file_unique_id (:obj:`str`): Unique identifier for this file, which
is supposed to be the same over time and for different bots.
Can't be used to download or reuse the file.
duration (:obj:`int` | :class:`datetime.timedelta`): Duration of the audio in
seconds as defined by the sender.
.. versionchanged:: v22.2
|time-period-input|
mime_type (:obj:`str`, optional): MIME type of the file as defined by the sender.
file_size (:obj:`int`, optional): File size in bytes.
Attributes:
file_id (:obj:`str`): Identifier for this file, which can be used to download
or reuse the file.
file_unique_id (:obj:`str`): Unique identifier for this file, which
is supposed to be the same over time and for different bots.
Can't be used to download or reuse the file.
duration (:obj:`int` | :class:`datetime.timedelta`): Duration of the audio in seconds as
defined by the sender.
.. deprecated:: v22.2
|time-period-int-deprecated|
mime_type (:obj:`str`): Optional. MIME type of the file as defined by the sender.
file_size (:obj:`int`): Optional. File size in bytes.
"""
__slots__ = ("_duration", "mime_type")
def __init__(
self,
file_id: str,
file_unique_id: str,
duration: TimePeriod,
mime_type: Optional[str] = None,
file_size: Optional[int] = None,
*,
api_kwargs: Optional[JSONDict] = None,
):
super().__init__(
file_id=file_id,
file_unique_id=file_unique_id,
file_size=file_size,
api_kwargs=api_kwargs,
)
with self._unfrozen():
# Required
self._duration: dtm.timedelta = to_timedelta(duration)
# Optional
self.mime_type: Optional[str] = mime_type
@property
def duration(self) -> Union[int, dtm.timedelta]:
return get_timedelta_value( # type: ignore[return-value]
self._duration, attribute="duration"
)

View File

@@ -0,0 +1,106 @@
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2025
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser Public License for more details.
#
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents a Telegram ForceReply."""
from typing import Final, Optional
from telegram import constants
from telegram._telegramobject import TelegramObject
from telegram._utils.types import JSONDict
class ForceReply(TelegramObject):
"""
Upon receiving a message with this object, Telegram clients will display a reply interface to
the user (act as if the user has selected the 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 <https://core.telegram.org/bots/features#privacy-mode>`_. Not
supported in channels and for messages sent on behalf of a Telegram Business account.
Objects of this class are comparable in terms of equality. Two objects of this class are
considered equal, if their :attr:`selective` is equal.
.. versionchanged:: 20.0
The (undocumented) argument ``force_reply`` was removed and instead :attr:`force_reply`
is now always set to :obj:`True` as expected by the Bot API.
Args:
selective (:obj:`bool`, optional): Use this parameter if you want to force reply from
specific users only. Targets:
1) Users that are @mentioned in the :attr:`~telegram.Message.text` of the
:class:`telegram.Message` object.
2) If the bot's message is a reply to a message in the same chat and forum topic,
sender of the original message.
input_field_placeholder (:obj:`str`, optional): The placeholder to be shown in the input
field when the reply is active;
:tg-const:`telegram.ForceReply.MIN_INPUT_FIELD_PLACEHOLDER`-
:tg-const:`telegram.ForceReply.MAX_INPUT_FIELD_PLACEHOLDER`
characters.
.. versionadded:: 13.7
Attributes:
force_reply (:obj:`True`): Shows reply interface to the user, as if they manually selected
the bots message and tapped 'Reply'.
selective (:obj:`bool`): Optional. Force reply from specific users only. Targets:
1) Users that are @mentioned in the :attr:`~telegram.Message.text` of the
:class:`telegram.Message` object.
2) If the bot's message is a reply to a message in the same chat and forum topic,
sender of the original message.
input_field_placeholder (:obj:`str`): Optional. The placeholder to be shown in the input
field when the reply is active;
:tg-const:`telegram.ForceReply.MIN_INPUT_FIELD_PLACEHOLDER`-
:tg-const:`telegram.ForceReply.MAX_INPUT_FIELD_PLACEHOLDER`
characters.
.. versionadded:: 13.7
"""
__slots__ = ("force_reply", "input_field_placeholder", "selective")
def __init__(
self,
selective: Optional[bool] = None,
input_field_placeholder: Optional[str] = None,
*,
api_kwargs: Optional[JSONDict] = None,
):
super().__init__(api_kwargs=api_kwargs)
self.force_reply: bool = True
self.selective: Optional[bool] = selective
self.input_field_placeholder: Optional[str] = input_field_placeholder
self._id_attrs = (self.selective,)
self._freeze()
MIN_INPUT_FIELD_PLACEHOLDER: Final[int] = constants.ReplyLimit.MIN_INPUT_FIELD_PLACEHOLDER
""":const:`telegram.constants.ReplyLimit.MIN_INPUT_FIELD_PLACEHOLDER`
.. versionadded:: 20.0
"""
MAX_INPUT_FIELD_PLACEHOLDER: Final[int] = constants.ReplyLimit.MAX_INPUT_FIELD_PLACEHOLDER
""":const:`telegram.constants.ReplyLimit.MAX_INPUT_FIELD_PLACEHOLDER`
.. versionadded:: 20.0
"""

View File

@@ -0,0 +1,215 @@
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2025
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser Public License for more details.
#
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains objects related to Telegram forum topics."""
from typing import Optional
from telegram._telegramobject import TelegramObject
from telegram._utils.types import JSONDict
class ForumTopic(TelegramObject):
"""
This object represents a forum topic.
Objects of this class are comparable in terms of equality. Two objects of this class are
considered equal, if their :attr:`message_thread_id`, :attr:`name` and :attr:`icon_color`
are equal.
.. versionadded:: 20.0
Args:
message_thread_id (:obj:`int`): Unique identifier of the forum topic
name (:obj:`str`): Name of the topic
icon_color (:obj:`int`): Color of the topic icon in RGB format
icon_custom_emoji_id (:obj:`str`, optional): Unique identifier of the custom emoji shown
as the topic icon.
Attributes:
message_thread_id (:obj:`int`): Unique identifier of the forum topic
name (:obj:`str`): Name of the topic
icon_color (:obj:`int`): Color of the topic icon in RGB format
icon_custom_emoji_id (:obj:`str`): Optional. Unique identifier of the custom emoji shown
as the topic icon.
"""
__slots__ = ("icon_color", "icon_custom_emoji_id", "message_thread_id", "name")
def __init__(
self,
message_thread_id: int,
name: str,
icon_color: int,
icon_custom_emoji_id: Optional[str] = None,
*,
api_kwargs: Optional[JSONDict] = None,
):
super().__init__(api_kwargs=api_kwargs)
self.message_thread_id: int = message_thread_id
self.name: str = name
self.icon_color: int = icon_color
self.icon_custom_emoji_id: Optional[str] = icon_custom_emoji_id
self._id_attrs = (self.message_thread_id, self.name, self.icon_color)
self._freeze()
class ForumTopicCreated(TelegramObject):
"""
This object represents the content of a service message about a new forum topic created in
the chat.
Objects of this class are comparable in terms of equality. Two objects of this class are
considered equal, if their :attr:`name` and :attr:`icon_color` are equal.
.. versionadded:: 20.0
Args:
name (:obj:`str`): Name of the topic
icon_color (:obj:`int`): Color of the topic icon in RGB format
icon_custom_emoji_id (:obj:`str`, optional): Unique identifier of the custom emoji shown
as the topic icon.
Attributes:
name (:obj:`str`): Name of the topic
icon_color (:obj:`int`): Color of the topic icon in RGB format
icon_custom_emoji_id (:obj:`str`): Optional. Unique identifier of the custom emoji shown
as the topic icon.
"""
__slots__ = ("icon_color", "icon_custom_emoji_id", "name")
def __init__(
self,
name: str,
icon_color: int,
icon_custom_emoji_id: Optional[str] = None,
*,
api_kwargs: Optional[JSONDict] = None,
):
super().__init__(api_kwargs=api_kwargs)
self.name: str = name
self.icon_color: int = icon_color
self.icon_custom_emoji_id: Optional[str] = icon_custom_emoji_id
self._id_attrs = (self.name, self.icon_color)
self._freeze()
class ForumTopicClosed(TelegramObject):
"""
This object represents a service message about a forum topic closed in the chat.
Currently holds no information.
.. versionadded:: 20.0
"""
__slots__ = ()
def __init__(self, *, api_kwargs: Optional[JSONDict] = None) -> None:
super().__init__(api_kwargs=api_kwargs)
self._freeze()
class ForumTopicReopened(TelegramObject):
"""
This object represents a service message about a forum topic reopened in the chat.
Currently holds no information.
.. versionadded:: 20.0
"""
__slots__ = ()
def __init__(self, *, api_kwargs: Optional[JSONDict] = None) -> None:
super().__init__(api_kwargs=api_kwargs)
self._freeze()
class ForumTopicEdited(TelegramObject):
"""
This object represents a service message about an edited forum topic.
Objects of this class are comparable in terms of equality. Two objects of this class are
considered equal, if their :attr:`name` and :attr:`icon_custom_emoji_id` are equal.
.. versionadded:: 20.0
Args:
name (:obj:`str`, optional): New name of the topic, if it was edited.
icon_custom_emoji_id (:obj:`str`, optional): New identifier of the custom emoji shown as
the topic icon, if it was edited; an empty string if the icon was removed.
Attributes:
name (:obj:`str`): Optional. New name of the topic, if it was edited.
icon_custom_emoji_id (:obj:`str`): Optional. New identifier of the custom emoji shown as
the topic icon, if it was edited; an empty string if the icon was removed.
"""
__slots__ = ("icon_custom_emoji_id", "name")
def __init__(
self,
name: Optional[str] = None,
icon_custom_emoji_id: Optional[str] = None,
*,
api_kwargs: Optional[JSONDict] = None,
):
super().__init__(api_kwargs=api_kwargs)
self.name: Optional[str] = name
self.icon_custom_emoji_id: Optional[str] = icon_custom_emoji_id
self._id_attrs = (self.name, self.icon_custom_emoji_id)
self._freeze()
class GeneralForumTopicHidden(TelegramObject):
"""
This object represents a service message about General forum topic hidden in the chat.
Currently holds no information.
.. versionadded:: 20.0
"""
__slots__ = ()
def __init__(self, *, api_kwargs: Optional[JSONDict] = None):
super().__init__(api_kwargs=api_kwargs)
self._freeze()
class GeneralForumTopicUnhidden(TelegramObject):
"""
This object represents a service message about General forum topic unhidden in the chat.
Currently holds no information.
.. versionadded:: 20.0
"""
__slots__ = ()
def __init__(self, *, api_kwargs: Optional[JSONDict] = None):
super().__init__(api_kwargs=api_kwargs)
self._freeze()

View File

@@ -0,0 +1,35 @@
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2025
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser Public License for more details.
#
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents a Telegram CallbackGame."""
from typing import Optional
from telegram._telegramobject import TelegramObject
from telegram._utils.types import JSONDict
class CallbackGame(TelegramObject):
"""A placeholder, currently holds no information. Use BotFather to set up your game."""
__slots__ = ()
def __init__(self, *, api_kwargs: Optional[JSONDict] = None) -> None:
super().__init__(api_kwargs=api_kwargs)
self._freeze()

View File

@@ -0,0 +1,194 @@
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2025
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser Public License for more details.
#
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents a Telegram Game."""
from collections.abc import Sequence
from typing import TYPE_CHECKING, Optional
from telegram._files.animation import Animation
from telegram._files.photosize import PhotoSize
from telegram._messageentity import MessageEntity
from telegram._telegramobject import TelegramObject
from telegram._utils.argumentparsing import de_json_optional, de_list_optional, parse_sequence_arg
from telegram._utils.strings import TextEncoding
from telegram._utils.types import JSONDict
if TYPE_CHECKING:
from telegram import Bot
class Game(TelegramObject):
"""
This object represents a game. Use `BotFather <https://t.me/BotFather>`_ to create and edit
games, their short names will act as unique identifiers.
Objects of this class are comparable in terms of equality. Two objects of this class are
considered equal, if their :attr:`title`, :attr:`description` and :attr:`photo` are equal.
Args:
title (:obj:`str`): Title of the game.
description (:obj:`str`): Description of the game.
photo (Sequence[:class:`telegram.PhotoSize`]): Photo that will be displayed in the game
message in chats.
.. versionchanged:: 20.0
|sequenceclassargs|
text (:obj:`str`, optional): 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 :meth:`telegram.Bot.set_game_score`, or manually edited
using :meth:`telegram.Bot.edit_message_text`.
0-:tg-const:`telegram.constants.MessageLimit.MAX_TEXT_LENGTH` characters.
text_entities (Sequence[:class:`telegram.MessageEntity`], optional): Special entities that
appear in text, such as usernames, URLs, bot commands, etc.
.. versionchanged:: 20.0
|sequenceclassargs|
animation (:class:`telegram.Animation`, optional): Animation that will be displayed in the
game message in chats. Upload via `BotFather <https://t.me/BotFather>`_.
Attributes:
title (:obj:`str`): Title of the game.
description (:obj:`str`): Description of the game.
photo (tuple[:class:`telegram.PhotoSize`]): Photo that will be displayed in the game
message in chats.
.. versionchanged:: 20.0
|tupleclassattrs|
text (:obj:`str`): Optional. 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 :meth:`telegram.Bot.set_game_score`, or manually edited
using :meth:`telegram.Bot.edit_message_text`.
0-:tg-const:`telegram.constants.MessageLimit.MAX_TEXT_LENGTH` characters.
text_entities (tuple[:class:`telegram.MessageEntity`]): Optional. Special entities that
appear in text, such as usernames, URLs, bot commands, etc.
This tuple is empty if the message does not contain text entities.
.. versionchanged:: 20.0
|tupleclassattrs|
animation (:class:`telegram.Animation`): Optional. Animation that will be displayed in the
game message in chats. Upload via `BotFather <https://t.me/BotFather>`_.
"""
__slots__ = (
"animation",
"description",
"photo",
"text",
"text_entities",
"title",
)
def __init__(
self,
title: str,
description: str,
photo: Sequence[PhotoSize],
text: Optional[str] = None,
text_entities: Optional[Sequence[MessageEntity]] = None,
animation: Optional[Animation] = None,
*,
api_kwargs: Optional[JSONDict] = None,
):
super().__init__(api_kwargs=api_kwargs)
# Required
self.title: str = title
self.description: str = description
self.photo: tuple[PhotoSize, ...] = parse_sequence_arg(photo)
# Optionals
self.text: Optional[str] = text
self.text_entities: tuple[MessageEntity, ...] = parse_sequence_arg(text_entities)
self.animation: Optional[Animation] = animation
self._id_attrs = (self.title, self.description, self.photo)
self._freeze()
@classmethod
def de_json(cls, data: JSONDict, bot: Optional["Bot"] = None) -> "Game":
"""See :meth:`telegram.TelegramObject.de_json`."""
data = cls._parse_data(data)
data["photo"] = de_list_optional(data.get("photo"), PhotoSize, bot)
data["text_entities"] = de_list_optional(data.get("text_entities"), MessageEntity, bot)
data["animation"] = de_json_optional(data.get("animation"), Animation, bot)
return super().de_json(data=data, bot=bot)
def parse_text_entity(self, entity: MessageEntity) -> str:
"""Returns the text from a given :class:`telegram.MessageEntity`.
Note:
This method is present because Telegram calculates the offset and length in
UTF-16 codepoint pairs, which some versions of Python don't handle automatically.
(That is, you can't just slice ``Message.text`` with the offset and length.)
Args:
entity (:class:`telegram.MessageEntity`): The entity to extract the text from. It must
be an entity that belongs to this message.
Returns:
:obj:`str`: The text of the given entity.
Raises:
RuntimeError: If this game has no text.
"""
if not self.text:
raise RuntimeError("This Game has no 'text'.")
entity_text = self.text.encode(TextEncoding.UTF_16_LE)
entity_text = entity_text[entity.offset * 2 : (entity.offset + entity.length) * 2]
return entity_text.decode(TextEncoding.UTF_16_LE)
def parse_text_entities(self, types: Optional[list[str]] = None) -> dict[MessageEntity, str]:
"""
Returns a :obj:`dict` that maps :class:`telegram.MessageEntity` to :obj:`str`.
It contains entities from this message filtered by their
:attr:`~telegram.MessageEntity.type` attribute as the key, and the text that each entity
belongs to as the value of the :obj:`dict`.
Note:
This method should always be used instead of the :attr:`text_entities` attribute, since
it calculates the correct substring from the message text based on UTF-16 codepoints.
See :attr:`parse_text_entity` for more info.
Args:
types (list[:obj:`str`], optional): List of :class:`telegram.MessageEntity` types as
strings. If the :attr:`~telegram.MessageEntity.type` attribute of an entity is
contained in this list, it will be returned. Defaults to
:attr:`telegram.MessageEntity.ALL_TYPES`.
Returns:
dict[:class:`telegram.MessageEntity`, :obj:`str`]: A dictionary of entities mapped to
the text that belongs to them, calculated based on UTF-16 codepoints.
"""
if types is None:
types = MessageEntity.ALL_TYPES
return {
entity: self.parse_text_entity(entity)
for entity in self.text_entities
if entity.type in types
}

View File

@@ -0,0 +1,71 @@
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2025
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser Public License for more details.
#
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents a Telegram GameHighScore."""
from typing import TYPE_CHECKING, Optional
from telegram._telegramobject import TelegramObject
from telegram._user import User
from telegram._utils.argumentparsing import de_json_optional
from telegram._utils.types import JSONDict
if TYPE_CHECKING:
from telegram import Bot
class GameHighScore(TelegramObject):
"""This object represents one row of the high scores table for a game.
Objects of this class are comparable in terms of equality. Two objects of this class are
considered equal, if their :attr:`position`, :attr:`user` and :attr:`score` are equal.
Args:
position (:obj:`int`): Position in high score table for the game.
user (:class:`telegram.User`): User.
score (:obj:`int`): Score.
Attributes:
position (:obj:`int`): Position in high score table for the game.
user (:class:`telegram.User`): User.
score (:obj:`int`): Score.
"""
__slots__ = ("position", "score", "user")
def __init__(
self, position: int, user: User, score: int, *, api_kwargs: Optional[JSONDict] = None
):
super().__init__(api_kwargs=api_kwargs)
self.position: int = position
self.user: User = user
self.score: int = score
self._id_attrs = (self.position, self.user, self.score)
self._freeze()
@classmethod
def de_json(cls, data: JSONDict, bot: Optional["Bot"] = None) -> "GameHighScore":
"""See :meth:`telegram.TelegramObject.de_json`."""
data = cls._parse_data(data)
data["user"] = de_json_optional(data.get("user"), User, bot)
return super().de_json(data=data, bot=bot)

View File

@@ -0,0 +1,357 @@
#!/usr/bin/env python
# pylint: disable=redefined-builtin
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2025
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser Public License for more details.
#
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]
"""This module contains classes related to gifs sent by bots."""
from collections.abc import Sequence
from typing import TYPE_CHECKING, Optional
from telegram._files.sticker import Sticker
from telegram._messageentity import MessageEntity
from telegram._telegramobject import TelegramObject
from telegram._utils.argumentparsing import de_json_optional, de_list_optional, parse_sequence_arg
from telegram._utils.entities import parse_message_entities, parse_message_entity
from telegram._utils.types import JSONDict
if TYPE_CHECKING:
from telegram import Bot
class Gift(TelegramObject):
"""This object represents a gift that can be sent by the bot.
Objects of this class are comparable in terms of equality. Two objects of this class are
considered equal if their :attr:`id` is equal.
.. versionadded:: 21.8
Args:
id (:obj:`str`): Unique identifier of the gift
sticker (:class:`~telegram.Sticker`): The sticker that represents the gift
star_count (:obj:`int`): The number of Telegram Stars that must be paid to send the sticker
total_count (:obj:`int`, optional): The total number of the gifts of this type that can be
sent; for limited gifts only
remaining_count (:obj:`int`, optional): The number of remaining gifts of this type that can
be sent; for limited gifts only
upgrade_star_count (:obj:`int`, optional): The number of Telegram Stars that must be paid
to upgrade the gift to a unique one
.. versionadded:: 21.10
Attributes:
id (:obj:`str`): Unique identifier of the gift
sticker (:class:`~telegram.Sticker`): The sticker that represents the gift
star_count (:obj:`int`): The number of Telegram Stars that must be paid to send the sticker
total_count (:obj:`int`): Optional. The total number of the gifts of this type that can be
sent; for limited gifts only
remaining_count (:obj:`int`): Optional. The number of remaining gifts of this type that can
be sent; for limited gifts only
upgrade_star_count (:obj:`int`): Optional. The number of Telegram Stars that must be paid
to upgrade the gift to a unique one
.. versionadded:: 21.10
"""
__slots__ = (
"id",
"remaining_count",
"star_count",
"sticker",
"total_count",
"upgrade_star_count",
)
def __init__(
self,
id: str,
sticker: Sticker,
star_count: int,
total_count: Optional[int] = None,
remaining_count: Optional[int] = None,
upgrade_star_count: Optional[int] = None,
*,
api_kwargs: Optional[JSONDict] = None,
):
super().__init__(api_kwargs=api_kwargs)
self.id: str = id
self.sticker: Sticker = sticker
self.star_count: int = star_count
self.total_count: Optional[int] = total_count
self.remaining_count: Optional[int] = remaining_count
self.upgrade_star_count: Optional[int] = upgrade_star_count
self._id_attrs = (self.id,)
self._freeze()
@classmethod
def de_json(cls, data: JSONDict, bot: Optional["Bot"] = None) -> "Gift":
"""See :meth:`telegram.TelegramObject.de_json`."""
data = cls._parse_data(data)
data["sticker"] = de_json_optional(data.get("sticker"), Sticker, bot)
return super().de_json(data=data, bot=bot)
class Gifts(TelegramObject):
"""This object represent a list of gifts.
Objects of this class are comparable in terms of equality. Two objects of this class are
considered equal if their :attr:`gifts` are equal.
.. versionadded:: 21.8
Args:
gifts (Sequence[:class:`Gift`]): The sequence of gifts
Attributes:
gifts (tuple[:class:`Gift`]): The sequence of gifts
"""
__slots__ = ("gifts",)
def __init__(
self,
gifts: Sequence[Gift],
*,
api_kwargs: Optional[JSONDict] = None,
):
super().__init__(api_kwargs=api_kwargs)
self.gifts: tuple[Gift, ...] = parse_sequence_arg(gifts)
self._id_attrs = (self.gifts,)
self._freeze()
@classmethod
def de_json(cls, data: JSONDict, bot: Optional["Bot"] = None) -> "Gifts":
"""See :meth:`telegram.TelegramObject.de_json`."""
data = cls._parse_data(data)
data["gifts"] = de_list_optional(data.get("gifts"), Gift, bot)
return super().de_json(data=data, bot=bot)
class GiftInfo(TelegramObject):
"""Describes a service message about a regular gift that was sent or received.
Objects of this class are comparable in terms of equality. Two objects of this class are
considered equal if their :attr:`gift` is equal.
.. versionadded:: 22.1
Args:
gift (:class:`Gift`): Information about the gift.
owned_gift_id (:obj:`str`, optional): Unique identifier of the received gift for the bot;
only present for gifts received on behalf of business accounts
convert_star_count (:obj:`int`, optional) Number of Telegram Stars that can be claimed by
the receiver by converting the gift; omitted if conversion to Telegram Stars
is impossible
prepaid_upgrade_star_count (:obj:`int`, optional): Number of Telegram Stars that were
prepaid by the sender for the ability to upgrade the gift
can_be_upgraded (:obj:`bool`, optional): :obj:`True`, if the gift can be upgraded
to a unique gift.
text (:obj:`str`, optional): Text of the message that was added to the gift.
entities (Sequence[:class:`telegram.MessageEntity`], optional): Special entities that
appear in the text.
is_private (:obj:`bool`, optional): :obj:`True`, if the sender and gift text are
shown only to the gift receiver; otherwise, everyone will be able to see them.
Attributes:
gift (:class:`Gift`): Information about the gift.
owned_gift_id (:obj:`str`): Optional. Unique identifier of the received gift for the bot;
only present for gifts received on behalf of business accounts
convert_star_count (:obj:`int`): Optional. Number of Telegram Stars that can be claimed by
the receiver by converting the gift; omitted if conversion to Telegram Stars
is impossible
prepaid_upgrade_star_count (:obj:`int`): Optional. Number of Telegram Stars that were
prepaid by the sender for the ability to upgrade the gift
can_be_upgraded (:obj:`bool`): Optional. :obj:`True`, if the gift can be upgraded
to a unique gift.
text (:obj:`str`): Optional. Text of the message that was added to the gift.
entities (Sequence[:class:`telegram.MessageEntity`]): Optional. Special entities that
appear in the text.
is_private (:obj:`bool`): Optional. :obj:`True`, if the sender and gift text are
shown only to the gift receiver; otherwise, everyone will be able to see them.
"""
__slots__ = (
"can_be_upgraded",
"convert_star_count",
"entities",
"gift",
"is_private",
"owned_gift_id",
"prepaid_upgrade_star_count",
"text",
)
def __init__(
self,
gift: Gift,
owned_gift_id: Optional[str] = None,
convert_star_count: Optional[int] = None,
prepaid_upgrade_star_count: Optional[int] = None,
can_be_upgraded: Optional[bool] = None,
text: Optional[str] = None,
entities: Optional[Sequence[MessageEntity]] = None,
is_private: Optional[bool] = None,
*,
api_kwargs: Optional[JSONDict] = None,
):
super().__init__(api_kwargs=api_kwargs)
# Required
self.gift: Gift = gift
# Optional
self.owned_gift_id: Optional[str] = owned_gift_id
self.convert_star_count: Optional[int] = convert_star_count
self.prepaid_upgrade_star_count: Optional[int] = prepaid_upgrade_star_count
self.can_be_upgraded: Optional[bool] = can_be_upgraded
self.text: Optional[str] = text
self.entities: tuple[MessageEntity, ...] = parse_sequence_arg(entities)
self.is_private: Optional[bool] = is_private
self._id_attrs = (self.gift,)
self._freeze()
@classmethod
def de_json(cls, data: JSONDict, bot: Optional["Bot"] = None) -> "GiftInfo":
"""See :meth:`telegram.TelegramObject.de_json`."""
data = cls._parse_data(data)
data["gift"] = de_json_optional(data.get("gift"), Gift, bot)
data["entities"] = de_list_optional(data.get("entities"), MessageEntity, bot)
return super().de_json(data=data, bot=bot)
def parse_entity(self, entity: MessageEntity) -> str:
"""Returns the text in :attr:`text`
from a given :class:`telegram.MessageEntity` of :attr:`entities`.
Note:
This method is present because Telegram calculates the offset and length in
UTF-16 codepoint pairs, which some versions of Python don't handle automatically.
(That is, you can't just slice ``Message.text`` with the offset and length.)
Args:
entity (:class:`telegram.MessageEntity`): The entity to extract the text from. It must
be an entity that belongs to :attr:`entities`.
Returns:
:obj:`str`: The text of the given entity.
Raises:
RuntimeError: If the gift info has no text.
"""
if not self.text:
raise RuntimeError("This GiftInfo has no 'text'.")
return parse_message_entity(self.text, entity)
def parse_entities(self, types: Optional[list[str]] = None) -> dict[MessageEntity, str]:
"""
Returns a :obj:`dict` that maps :class:`telegram.MessageEntity` to :obj:`str`.
It contains entities from this gift info's text filtered by their ``type`` attribute as
the key, and the text that each entity belongs to as the value of the :obj:`dict`.
Note:
This method should always be used instead of the :attr:`entities`
attribute, since it calculates the correct substring from the message text based on
UTF-16 codepoints. See :attr:`parse_entity` for more info.
Args:
types (list[:obj:`str`], optional): List of ``MessageEntity`` types as strings. If the
``type`` attribute of an entity is contained in this list, it will be returned.
Defaults to :attr:`telegram.MessageEntity.ALL_TYPES`.
Returns:
dict[:class:`telegram.MessageEntity`, :obj:`str`]: A dictionary of entities mapped to
the text that belongs to them, calculated based on UTF-16 codepoints.
Raises:
RuntimeError: If the gift info has no text.
"""
if not self.text:
raise RuntimeError("This GiftInfo has no 'text'.")
return parse_message_entities(self.text, self.entities, types)
class AcceptedGiftTypes(TelegramObject):
"""This object describes the types of gifts that can be gifted to a user or a chat.
Objects of this class are comparable in terms of equality. Two objects of this class are
considered equal if their :attr:`unlimited_gifts`, :attr:`limited_gifts`,
:attr:`unique_gifts` and :attr:`premium_subscription` are equal.
.. versionadded:: 22.1
Args:
unlimited_gifts (:class:`bool`): :obj:`True`, if unlimited regular gifts are accepted.
limited_gifts (:class:`bool`): :obj:`True`, if limited regular gifts are accepted.
unique_gifts (:class:`bool`): :obj:`True`, if unique gifts or gifts that can be upgraded
to unique for free are accepted.
premium_subscription (:class:`bool`): :obj:`True`, if a Telegram Premium subscription
is accepted.
Attributes:
unlimited_gifts (:class:`bool`): :obj:`True`, if unlimited regular gifts are accepted.
limited_gifts (:class:`bool`): :obj:`True`, if limited regular gifts are accepted.
unique_gifts (:class:`bool`): :obj:`True`, if unique gifts or gifts that can be upgraded
to unique for free are accepted.
premium_subscription (:class:`bool`): :obj:`True`, if a Telegram Premium subscription
is accepted.
"""
__slots__ = (
"limited_gifts",
"premium_subscription",
"unique_gifts",
"unlimited_gifts",
)
def __init__(
self,
unlimited_gifts: bool,
limited_gifts: bool,
unique_gifts: bool,
premium_subscription: bool,
*,
api_kwargs: Optional[JSONDict] = None,
):
super().__init__(api_kwargs=api_kwargs)
self.unlimited_gifts: bool = unlimited_gifts
self.limited_gifts: bool = limited_gifts
self.unique_gifts: bool = unique_gifts
self.premium_subscription: bool = premium_subscription
self._id_attrs = (
self.unlimited_gifts,
self.limited_gifts,
self.unique_gifts,
self.premium_subscription,
)
self._freeze()

View File

@@ -0,0 +1,380 @@
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2025
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser Public License for more details.
#
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an objects that are related to Telegram giveaways."""
import datetime as dtm
from collections.abc import Sequence
from typing import TYPE_CHECKING, Optional
from telegram._chat import Chat
from telegram._telegramobject import TelegramObject
from telegram._user import User
from telegram._utils.argumentparsing import de_json_optional, de_list_optional, parse_sequence_arg
from telegram._utils.datetime import extract_tzinfo_from_defaults, from_timestamp
from telegram._utils.types import JSONDict
if TYPE_CHECKING:
from telegram import Bot, Message
class Giveaway(TelegramObject):
"""This object represents a message about a scheduled giveaway.
Objects of this class are comparable in terms of equality. Two objects of this class are
considered equal, if their :attr:`chats`, :attr:`winners_selection_date` and
:attr:`winner_count` are equal.
.. versionadded:: 20.8
Args:
chats (tuple[:class:`telegram.Chat`]): The list of chats which the user must join to
participate in the giveaway.
winners_selection_date (:class:`datetime.datetime`): The date when the giveaway winner will
be selected. |datetime_localization|
winner_count (:obj:`int`): The number of users which are supposed to be selected as winners
of the giveaway.
only_new_members (:obj:`True`, optional): If :obj:`True`, only users who join the chats
after the giveaway started should be eligible to win.
has_public_winners (:obj:`True`, optional): :obj:`True`, if the list of giveaway winners
will be visible to everyone
prize_description (:obj:`str`, optional): Description of additional giveaway prize
country_codes (Sequence[:obj:`str`]): A list of two-letter ISO 3166-1 alpha-2
country codes indicating the countries from which eligible users for the giveaway must
come. If empty, then all users can participate in the giveaway. Users with a phone
number that was bought on Fragment can always participate in giveaways.
prize_star_count (:obj:`int`, optional): The number of Telegram Stars to be split between
giveaway winners; for Telegram Star giveaways only.
.. versionadded:: 21.6
premium_subscription_month_count (:obj:`int`, optional): The number of months the Telegram
Premium subscription won from the giveaway will be active for; for Telegram Premium
giveaways only.
Attributes:
chats (Sequence[:class:`telegram.Chat`]): The list of chats which the user must join to
participate in the giveaway.
winners_selection_date (:class:`datetime.datetime`): The date when the giveaway winner will
be selected. |datetime_localization|
winner_count (:obj:`int`): The number of users which are supposed to be selected as winners
of the giveaway.
only_new_members (:obj:`True`): Optional. If :obj:`True`, only users who join the chats
after the giveaway started should be eligible to win.
has_public_winners (:obj:`True`): Optional. :obj:`True`, if the list of giveaway winners
will be visible to everyone
prize_description (:obj:`str`): Optional. Description of additional giveaway prize
country_codes (tuple[:obj:`str`]): Optional. A tuple of two-letter ISO 3166-1 alpha-2
country codes indicating the countries from which eligible users for the giveaway must
come. If empty, then all users can participate in the giveaway. Users with a phone
number that was bought on Fragment can always participate in giveaways.
prize_star_count (:obj:`int`): Optional. The number of Telegram Stars to be split between
giveaway winners; for Telegram Star giveaways only.
.. versionadded:: 21.6
premium_subscription_month_count (:obj:`int`): Optional. The number of months the Telegram
Premium subscription won from the giveaway will be active for; for Telegram Premium
giveaways only.
"""
__slots__ = (
"chats",
"country_codes",
"has_public_winners",
"only_new_members",
"premium_subscription_month_count",
"prize_description",
"prize_star_count",
"winner_count",
"winners_selection_date",
)
def __init__(
self,
chats: Sequence[Chat],
winners_selection_date: dtm.datetime,
winner_count: int,
only_new_members: Optional[bool] = None,
has_public_winners: Optional[bool] = None,
prize_description: Optional[str] = None,
country_codes: Optional[Sequence[str]] = None,
premium_subscription_month_count: Optional[int] = None,
prize_star_count: Optional[int] = None,
*,
api_kwargs: Optional[JSONDict] = None,
):
super().__init__(api_kwargs=api_kwargs)
self.chats: tuple[Chat, ...] = tuple(chats)
self.winners_selection_date: dtm.datetime = winners_selection_date
self.winner_count: int = winner_count
self.only_new_members: Optional[bool] = only_new_members
self.has_public_winners: Optional[bool] = has_public_winners
self.prize_description: Optional[str] = prize_description
self.country_codes: tuple[str, ...] = parse_sequence_arg(country_codes)
self.premium_subscription_month_count: Optional[int] = premium_subscription_month_count
self.prize_star_count: Optional[int] = prize_star_count
self._id_attrs = (
self.chats,
self.winners_selection_date,
self.winner_count,
)
self._freeze()
@classmethod
def de_json(cls, data: JSONDict, bot: Optional["Bot"] = None) -> "Giveaway":
"""See :meth:`telegram.TelegramObject.de_json`."""
data = cls._parse_data(data)
# Get the local timezone from the bot if it has defaults
loc_tzinfo = extract_tzinfo_from_defaults(bot)
data["chats"] = de_list_optional(data.get("chats"), Chat, bot)
data["winners_selection_date"] = from_timestamp(
data.get("winners_selection_date"), tzinfo=loc_tzinfo
)
return super().de_json(data=data, bot=bot)
class GiveawayCreated(TelegramObject):
"""This object represents a service message about the creation of a scheduled giveaway.
Args:
prize_star_count (:obj:`int`, optional): The number of Telegram Stars to be
split between giveaway winners; for Telegram Star giveaways only.
.. versionadded:: 21.6
Attributes:
prize_star_count (:obj:`int`): Optional. The number of Telegram Stars to be
split between giveaway winners; for Telegram Star giveaways only.
.. versionadded:: 21.6
"""
__slots__ = ("prize_star_count",)
def __init__(
self, prize_star_count: Optional[int] = None, *, api_kwargs: Optional[JSONDict] = None
):
super().__init__(api_kwargs=api_kwargs)
self.prize_star_count: Optional[int] = prize_star_count
self._freeze()
class GiveawayWinners(TelegramObject):
"""This object represents a message about the completion of a giveaway with public winners.
Objects of this class are comparable in terms of equality. Two objects of this class are
considered equal, if their :attr:`chat`, :attr:`giveaway_message_id`,
:attr:`winners_selection_date`, :attr:`winner_count` and :attr:`winners` are equal.
.. versionadded:: 20.8
Args:
chat (:class:`telegram.Chat`): The chat that created the giveaway
giveaway_message_id (:obj:`int`): Identifier of the message with the giveaway in the chat
winners_selection_date (:class:`datetime.datetime`): Point in time when winners of the
giveaway were selected. |datetime_localization|
winner_count (:obj:`int`): Total number of winners in the giveaway
winners (Sequence[:class:`telegram.User`]): List of up to
:tg-const:`telegram.constants.GiveawayLimit.MAX_WINNERS` winners of the giveaway
prize_star_count (:obj:`int`, optional): The number of Telegram Stars to be split between
giveaway winners; for Telegram Star giveaways only.
.. versionadded:: 21.6
additional_chat_count (:obj:`int`, optional): The number of other chats the user had to
join in order to be eligible for the giveaway
premium_subscription_month_count (:obj:`int`, optional): The number of months the Telegram
Premium subscription won from the giveaway will be active for
unclaimed_prize_count (:obj:`int`, optional): Number of undistributed prizes
only_new_members (:obj:`True`, optional): :obj:`True`, if only users who had joined the
chats after the giveaway started were eligible to win
was_refunded (:obj:`True`, optional): :obj:`True`, if the giveaway was canceled because the
payment for it was refunded
prize_description (:obj:`str`, optional): Description of additional giveaway prize
Attributes:
chat (:class:`telegram.Chat`): The chat that created the giveaway
giveaway_message_id (:obj:`int`): Identifier of the message with the giveaway in the chat
winners_selection_date (:class:`datetime.datetime`): Point in time when winners of the
giveaway were selected. |datetime_localization|
winner_count (:obj:`int`): Total number of winners in the giveaway
winners (tuple[:class:`telegram.User`]): tuple of up to
:tg-const:`telegram.constants.GiveawayLimit.MAX_WINNERS` winners of the giveaway
additional_chat_count (:obj:`int`): Optional. The number of other chats the user had to
join in order to be eligible for the giveaway
prize_star_count (:obj:`int`): Optional. The number of Telegram Stars to be split between
giveaway winners; for Telegram Star giveaways only.
.. versionadded:: 21.6
premium_subscription_month_count (:obj:`int`): Optional. The number of months the Telegram
Premium subscription won from the giveaway will be active for
unclaimed_prize_count (:obj:`int`): Optional. Number of undistributed prizes
only_new_members (:obj:`True`): Optional. :obj:`True`, if only users who had joined the
chats after the giveaway started were eligible to win
was_refunded (:obj:`True`): Optional. :obj:`True`, if the giveaway was canceled because the
payment for it was refunded
prize_description (:obj:`str`): Optional. Description of additional giveaway prize
"""
__slots__ = (
"additional_chat_count",
"chat",
"giveaway_message_id",
"only_new_members",
"premium_subscription_month_count",
"prize_description",
"prize_star_count",
"unclaimed_prize_count",
"was_refunded",
"winner_count",
"winners",
"winners_selection_date",
)
def __init__(
self,
chat: Chat,
giveaway_message_id: int,
winners_selection_date: dtm.datetime,
winner_count: int,
winners: Sequence[User],
additional_chat_count: Optional[int] = None,
premium_subscription_month_count: Optional[int] = None,
unclaimed_prize_count: Optional[int] = None,
only_new_members: Optional[bool] = None,
was_refunded: Optional[bool] = None,
prize_description: Optional[str] = None,
prize_star_count: Optional[int] = None,
*,
api_kwargs: Optional[JSONDict] = None,
):
super().__init__(api_kwargs=api_kwargs)
self.chat: Chat = chat
self.giveaway_message_id: int = giveaway_message_id
self.winners_selection_date: dtm.datetime = winners_selection_date
self.winner_count: int = winner_count
self.winners: tuple[User, ...] = tuple(winners)
self.additional_chat_count: Optional[int] = additional_chat_count
self.premium_subscription_month_count: Optional[int] = premium_subscription_month_count
self.unclaimed_prize_count: Optional[int] = unclaimed_prize_count
self.only_new_members: Optional[bool] = only_new_members
self.was_refunded: Optional[bool] = was_refunded
self.prize_description: Optional[str] = prize_description
self.prize_star_count: Optional[int] = prize_star_count
self._id_attrs = (
self.chat,
self.giveaway_message_id,
self.winners_selection_date,
self.winner_count,
self.winners,
)
self._freeze()
@classmethod
def de_json(cls, data: JSONDict, bot: Optional["Bot"] = None) -> "GiveawayWinners":
"""See :meth:`telegram.TelegramObject.de_json`."""
data = cls._parse_data(data)
# Get the local timezone from the bot if it has defaults
loc_tzinfo = extract_tzinfo_from_defaults(bot)
data["chat"] = de_json_optional(data.get("chat"), Chat, bot)
data["winners"] = de_list_optional(data.get("winners"), User, bot)
data["winners_selection_date"] = from_timestamp(
data.get("winners_selection_date"), tzinfo=loc_tzinfo
)
return super().de_json(data=data, bot=bot)
class GiveawayCompleted(TelegramObject):
"""This object represents a service message about the completion of a giveaway without public
winners.
Objects of this class are comparable in terms of equality. Two objects of this class are
considered equal, if their :attr:`winner_count` and :attr:`unclaimed_prize_count` are equal.
.. versionadded:: 20.8
Args:
winner_count (:obj:`int`): Number of winners in the giveaway
unclaimed_prize_count (:obj:`int`, optional): Number of undistributed prizes
giveaway_message (:class:`telegram.Message`, optional): Message with the giveaway that was
completed, if it wasn't deleted
is_star_giveaway (:obj:`bool`, optional): :obj:`True`, if the giveaway is a Telegram Star
giveaway. Otherwise, currently, the giveaway is a Telegram Premium giveaway.
.. versionadded:: 21.6
Attributes:
winner_count (:obj:`int`): Number of winners in the giveaway
unclaimed_prize_count (:obj:`int`): Optional. Number of undistributed prizes
giveaway_message (:class:`telegram.Message`): Optional. Message with the giveaway that was
completed, if it wasn't deleted
is_star_giveaway (:obj:`bool`): Optional. :obj:`True`, if the giveaway is a Telegram Star
giveaway. Otherwise, currently, the giveaway is a Telegram Premium giveaway.
.. versionadded:: 21.6
"""
__slots__ = ("giveaway_message", "is_star_giveaway", "unclaimed_prize_count", "winner_count")
def __init__(
self,
winner_count: int,
unclaimed_prize_count: Optional[int] = None,
giveaway_message: Optional["Message"] = None,
is_star_giveaway: Optional[bool] = None,
*,
api_kwargs: Optional[JSONDict] = None,
):
super().__init__(api_kwargs=api_kwargs)
self.winner_count: int = winner_count
self.unclaimed_prize_count: Optional[int] = unclaimed_prize_count
self.giveaway_message: Optional[Message] = giveaway_message
self.is_star_giveaway: Optional[bool] = is_star_giveaway
self._id_attrs = (
self.winner_count,
self.unclaimed_prize_count,
)
self._freeze()
@classmethod
def de_json(cls, data: JSONDict, bot: Optional["Bot"] = None) -> "GiveawayCompleted":
"""See :meth:`telegram.TelegramObject.de_json`."""
data = cls._parse_data(data)
# Unfortunately, this needs to be here due to cyclic imports
from telegram._message import ( # noqa: PLC0415 # pylint: disable=import-outside-toplevel
Message,
)
data["giveaway_message"] = de_json_optional(data.get("giveaway_message"), Message, bot)
return super().de_json(data=data, bot=bot)

View File

@@ -0,0 +1,337 @@
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2025
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser Public License for more details.
#
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents a Telegram InlineKeyboardButton."""
from typing import TYPE_CHECKING, Final, Optional, Union
from telegram import constants
from telegram._copytextbutton import CopyTextButton
from telegram._games.callbackgame import CallbackGame
from telegram._loginurl import LoginUrl
from telegram._switchinlinequerychosenchat import SwitchInlineQueryChosenChat
from telegram._telegramobject import TelegramObject
from telegram._utils.argumentparsing import de_json_optional
from telegram._utils.types import JSONDict
from telegram._webappinfo import WebAppInfo
if TYPE_CHECKING:
from telegram import Bot
class InlineKeyboardButton(TelegramObject):
"""This object represents one button of an inline keyboard.
Objects of this class are comparable in terms of equality. Two objects of this class are
considered equal, if their :attr:`text`, :attr:`url`, :attr:`login_url`, :attr:`callback_data`,
:attr:`switch_inline_query`, :attr:`switch_inline_query_current_chat`, :attr:`callback_game`,
:attr:`web_app` and :attr:`pay` are equal.
Note:
* Exactly one of the optional fields must be used to specify type of the button.
* Mind that :attr:`callback_game` is not
working as expected. Putting a game short name in it might, but is not guaranteed to
work.
* If your bot allows for arbitrary callback data, in keyboards returned in a response
from telegram, :attr:`callback_data` may be an instance of
:class:`telegram.ext.InvalidCallbackData`. This will be the case, if the data
associated with the button was already deleted.
.. versionadded:: 13.6
* Since Bot API 5.5, it's now allowed to mention users by their ID in inline keyboards.
This will only work in Telegram versions released after December 7, 2021.
Older clients will display *unsupported message*.
Warning:
* If your bot allows your arbitrary callback data, buttons whose callback data is a
non-hashable object will become unhashable. Trying to evaluate ``hash(button)`` will
result in a :class:`TypeError`.
.. versionchanged:: 13.6
* After Bot API 6.1, only ``HTTPS`` links will be allowed in :paramref:`login_url`.
Examples:
* :any:`Inline Keyboard 1 <examples.inlinekeyboard>`
* :any:`Inline Keyboard 2 <examples.inlinekeyboard2>`
.. seealso:: :class:`telegram.InlineKeyboardMarkup`
.. versionchanged:: 20.0
:attr:`web_app` is considered as well when comparing objects of this type in terms of
equality.
Args:
text (:obj:`str`): Label text on the button.
url (:obj:`str`, optional): HTTP or tg:// url to be opened when the button is pressed.
Links ``tg://user?id=<user_id>`` can be used to mention a user by
their ID without using a username, if this is allowed by their privacy settings.
.. versionchanged:: 13.9
You can now mention a user using ``tg://user?id=<user_id>``.
login_url (:class:`telegram.LoginUrl`, optional): An ``HTTPS`` URL used to automatically
authorize the user. Can be used as a replacement for the Telegram Login Widget.
Caution:
Only ``HTTPS`` links are allowed after Bot API 6.1.
callback_data (:obj:`str` | :obj:`object`, optional): Data to be sent in a callback query
to the bot when the button is pressed, UTF-8
:tg-const:`telegram.InlineKeyboardButton.MIN_CALLBACK_DATA`-
:tg-const:`telegram.InlineKeyboardButton.MAX_CALLBACK_DATA` bytes.
If the bot instance allows arbitrary callback data, anything can be passed.
Tip:
The value entered here will be available in :attr:`telegram.CallbackQuery.data`.
.. seealso:: :wiki:`Arbitrary callback_data <Arbitrary-callback_data>`
web_app (:class:`telegram.WebAppInfo`, optional): Description of the `Web App
<https://core.telegram.org/bots/webapps>`_ that will be launched when the user presses
the button. The Web App will be able to send an arbitrary message on behalf of the user
using the method :meth:`~telegram.Bot.answer_web_app_query`. Available only in
private chats between a user and the bot. Not supported for messages sent on behalf of
a Telegram Business account.
.. versionadded:: 20.0
switch_inline_query (:obj:`str`, optional): 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. May be empty, in which case just the bot's
username will be inserted. Not supported for messages sent on behalf of a Telegram
Business account.
Tip:
This is similar to the parameter :paramref:`switch_inline_query_chosen_chat`,
but gives no control over which chats can be selected.
switch_inline_query_current_chat (:obj:`str`, optional): If set, pressing the button will
insert the bot's username and the specified inline query in the current chat's input
field. May 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. Not supported in channels and for
messages sent on behalf of a Telegram Business account.
copy_text (:class:`telegram.CopyTextButton`, optional): Description of the button that
copies the specified text to the clipboard.
.. versionadded:: 21.7
callback_game (:class:`telegram.CallbackGame`, optional): 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 (:obj:`bool`, optional): Specify :obj:`True`, to send a Pay button.
Substrings ``“⭐️”`` and ``“XTR”`` in the buttons's text will be replaced with a
Telegram Star icon.
Note:
This type of button **must** always be the first button in the first row and can
only be used in invoice messages.
switch_inline_query_chosen_chat (:class:`telegram.SwitchInlineQueryChosenChat`, optional):
If set, pressing the button will prompt the user to select one of their chats of the
specified type, open that chat and insert the bot's username and the specified inline
query in the input field. Not supported for messages sent on behalf of a Telegram
Business account.
.. versionadded:: 20.3
Tip:
This is similar to :paramref:`switch_inline_query`, but gives more control on
which chats can be selected.
Caution:
The PTB team has discovered that this field works correctly only if your Telegram
client is released after April 20th 2023.
Attributes:
text (:obj:`str`): Label text on the button.
url (:obj:`str`): Optional. HTTP or tg:// url to be opened when the button is pressed.
Links ``tg://user?id=<user_id>`` can be used to mention a user by
their ID without using a username, if this is allowed by their privacy settings.
.. versionchanged:: 13.9
You can now mention a user using ``tg://user?id=<user_id>``.
login_url (:class:`telegram.LoginUrl`): Optional. An ``HTTPS`` URL used to automatically
authorize the user. Can be used as a replacement for the Telegram Login Widget.
Caution:
Only ``HTTPS`` links are allowed after Bot API 6.1.
callback_data (:obj:`str` | :obj:`object`): Optional. Data to be sent in a callback query
to the bot when the button is pressed, UTF-8
:tg-const:`telegram.InlineKeyboardButton.MIN_CALLBACK_DATA`-
:tg-const:`telegram.InlineKeyboardButton.MAX_CALLBACK_DATA` bytes.
web_app (:class:`telegram.WebAppInfo`): Optional. Description of the `Web App
<https://core.telegram.org/bots/webapps>`_ that will be launched when the user presses
the button. The Web App will be able to send an arbitrary message on behalf of the user
using the method :meth:`~telegram.Bot.answer_web_app_query`. Available only in
private chats between a user and the bot. Not supported for messages sent on behalf of
a Telegram Business account.
.. versionadded:: 20.0
switch_inline_query (:obj:`str`): Optional. 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. May be empty, in which case just the bot's
username will be inserted. Not supported for messages sent on behalf of a Telegram
Business account.
Tip:
This is similar to the parameter :paramref:`switch_inline_query_chosen_chat`,
but gives no control over which chats can be selected.
switch_inline_query_current_chat (:obj:`str`): Optional. If set, pressing the button will
insert the bot's username and the specified inline query in the current chat's input
field. May 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. Not supported in channels and for
messages sent on behalf of a Telegram Business account.
copy_text (:class:`telegram.CopyTextButton`): Optional. Description of the button that
copies the specified text to the clipboard.
.. versionadded:: 21.7
callback_game (:class:`telegram.CallbackGame`): Optional. 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 (:obj:`bool`): Optional. Specify :obj:`True`, to send a Pay button.
Substrings ``“⭐️”`` and ``“XTR”`` in the buttons's text will be replaced with a
Telegram Star icon.
Note:
This type of button **must** always be the first button in the first row and can
only be used in invoice messages.
switch_inline_query_chosen_chat (:class:`telegram.SwitchInlineQueryChosenChat`): Optional.
If set, pressing the button will prompt the user to select one of their chats of the
specified type, open that chat and insert the bot's username and the specified inline
query in the input field. Not supported for messages sent on behalf of a Telegram
Business account.
.. versionadded:: 20.3
Tip:
This is similar to :attr:`switch_inline_query`, but gives more control on
which chats can be selected.
Caution:
The PTB team has discovered that this field works correctly only if your Telegram
client is released after April 20th 2023.
"""
__slots__ = (
"callback_data",
"callback_game",
"copy_text",
"login_url",
"pay",
"switch_inline_query",
"switch_inline_query_chosen_chat",
"switch_inline_query_current_chat",
"text",
"url",
"web_app",
)
def __init__(
self,
text: str,
url: Optional[str] = None,
callback_data: Optional[Union[str, object]] = None,
switch_inline_query: Optional[str] = None,
switch_inline_query_current_chat: Optional[str] = None,
callback_game: Optional[CallbackGame] = None,
pay: Optional[bool] = None,
login_url: Optional[LoginUrl] = None,
web_app: Optional[WebAppInfo] = None,
switch_inline_query_chosen_chat: Optional[SwitchInlineQueryChosenChat] = None,
copy_text: Optional[CopyTextButton] = None,
*,
api_kwargs: Optional[JSONDict] = None,
):
super().__init__(api_kwargs=api_kwargs)
# Required
self.text: str = text
# Optionals
self.url: Optional[str] = url
self.login_url: Optional[LoginUrl] = login_url
self.callback_data: Optional[Union[str, object]] = callback_data
self.switch_inline_query: Optional[str] = switch_inline_query
self.switch_inline_query_current_chat: Optional[str] = switch_inline_query_current_chat
self.callback_game: Optional[CallbackGame] = callback_game
self.pay: Optional[bool] = pay
self.web_app: Optional[WebAppInfo] = web_app
self.switch_inline_query_chosen_chat: Optional[SwitchInlineQueryChosenChat] = (
switch_inline_query_chosen_chat
)
self.copy_text: Optional[CopyTextButton] = copy_text
self._id_attrs = ()
self._set_id_attrs()
self._freeze()
def _set_id_attrs(self) -> None:
self._id_attrs = (
self.text,
self.url,
self.login_url,
self.callback_data,
self.web_app,
self.switch_inline_query,
self.switch_inline_query_current_chat,
self.callback_game,
self.pay,
)
@classmethod
def de_json(cls, data: JSONDict, bot: Optional["Bot"] = None) -> "InlineKeyboardButton":
"""See :meth:`telegram.TelegramObject.de_json`."""
data = cls._parse_data(data)
data["login_url"] = de_json_optional(data.get("login_url"), LoginUrl, bot)
data["web_app"] = de_json_optional(data.get("web_app"), WebAppInfo, bot)
data["callback_game"] = de_json_optional(data.get("callback_game"), CallbackGame, bot)
data["switch_inline_query_chosen_chat"] = de_json_optional(
data.get("switch_inline_query_chosen_chat"), SwitchInlineQueryChosenChat, bot
)
data["copy_text"] = de_json_optional(data.get("copy_text"), CopyTextButton, bot)
return super().de_json(data=data, bot=bot)
def update_callback_data(self, callback_data: Union[str, object]) -> None:
"""
Sets :attr:`callback_data` to the passed object. Intended to be used by
:class:`telegram.ext.CallbackDataCache`.
.. versionadded:: 13.6
Args:
callback_data (:class:`object`): The new callback data.
"""
with self._unfrozen():
self.callback_data = callback_data
self._set_id_attrs()
MIN_CALLBACK_DATA: Final[int] = constants.InlineKeyboardButtonLimit.MIN_CALLBACK_DATA
""":const:`telegram.constants.InlineKeyboardButtonLimit.MIN_CALLBACK_DATA`
.. versionadded:: 20.0
"""
MAX_CALLBACK_DATA: Final[int] = constants.InlineKeyboardButtonLimit.MAX_CALLBACK_DATA
""":const:`telegram.constants.InlineKeyboardButtonLimit.MAX_CALLBACK_DATA`
.. versionadded:: 20.0
"""

View File

@@ -0,0 +1,161 @@
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2025
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser Public License for more details.
#
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents a Telegram InlineKeyboardMarkup."""
from collections.abc import Sequence
from typing import TYPE_CHECKING, Optional
from telegram._inline.inlinekeyboardbutton import InlineKeyboardButton
from telegram._telegramobject import TelegramObject
from telegram._utils.markup import check_keyboard_type
from telegram._utils.types import JSONDict
if TYPE_CHECKING:
from telegram import Bot
class InlineKeyboardMarkup(TelegramObject):
"""
This object represents an inline keyboard that appears right next to the message it belongs to.
Objects of this class are comparable in terms of equality. Two objects of this class are
considered equal, if their size of :attr:`inline_keyboard` and all the buttons are equal.
.. figure:: https://core.telegram.org/file/464001863/110f3/I47qTXAD9Z4.120010/e0\
ea04f66357b640ec
:align: center
An inline keyboard on a message
.. seealso::
Another kind of keyboard would be the :class:`telegram.ReplyKeyboardMarkup`.
Examples:
* :any:`Inline Keyboard 1 <examples.inlinekeyboard>`
* :any:`Inline Keyboard 2 <examples.inlinekeyboard2>`
Args:
inline_keyboard (Sequence[Sequence[:class:`telegram.InlineKeyboardButton`]]): Sequence of
button rows, each represented by a sequence of :class:`~telegram.InlineKeyboardButton`
objects.
.. versionchanged:: 20.0
|sequenceclassargs|
Attributes:
inline_keyboard (tuple[tuple[:class:`telegram.InlineKeyboardButton`]]): Tuple of
button rows, each represented by a tuple of :class:`~telegram.InlineKeyboardButton`
objects.
.. versionchanged:: 20.0
|tupleclassattrs|
"""
__slots__ = ("inline_keyboard",)
def __init__(
self,
inline_keyboard: Sequence[Sequence[InlineKeyboardButton]],
*,
api_kwargs: Optional[JSONDict] = None,
):
super().__init__(api_kwargs=api_kwargs)
if not check_keyboard_type(inline_keyboard):
raise ValueError(
"The parameter `inline_keyboard` should be a sequence of sequences of "
"InlineKeyboardButtons"
)
# Required
self.inline_keyboard: tuple[tuple[InlineKeyboardButton, ...], ...] = tuple(
tuple(row) for row in inline_keyboard
)
self._id_attrs = (self.inline_keyboard,)
self._freeze()
@classmethod
def de_json(cls, data: JSONDict, bot: Optional["Bot"] = None) -> "InlineKeyboardMarkup":
"""See :meth:`telegram.TelegramObject.de_json`."""
keyboard = []
for row in data["inline_keyboard"]:
tmp = []
for col in row:
btn = InlineKeyboardButton.de_json(col, bot)
if btn:
tmp.append(btn)
keyboard.append(tmp)
return cls(keyboard)
@classmethod
def from_button(cls, button: InlineKeyboardButton, **kwargs: object) -> "InlineKeyboardMarkup":
"""Shortcut for::
InlineKeyboardMarkup([[button]], **kwargs)
Return an InlineKeyboardMarkup from a single InlineKeyboardButton
Args:
button (:class:`telegram.InlineKeyboardButton`): The button to use in the markup
"""
return cls([[button]], **kwargs) # type: ignore[arg-type]
@classmethod
def from_row(
cls, button_row: Sequence[InlineKeyboardButton], **kwargs: object
) -> "InlineKeyboardMarkup":
"""Shortcut for::
InlineKeyboardMarkup([button_row], **kwargs)
Return an InlineKeyboardMarkup from a single row of InlineKeyboardButtons
Args:
button_row (Sequence[:class:`telegram.InlineKeyboardButton`]): The button to use
in the markup
.. versionchanged:: 20.0
|sequenceargs|
"""
return cls([button_row], **kwargs) # type: ignore[arg-type]
@classmethod
def from_column(
cls, button_column: Sequence[InlineKeyboardButton], **kwargs: object
) -> "InlineKeyboardMarkup":
"""Shortcut for::
InlineKeyboardMarkup([[button] for button in button_column], **kwargs)
Return an InlineKeyboardMarkup from a single column of InlineKeyboardButtons
Args:
button_column (Sequence[:class:`telegram.InlineKeyboardButton`]): The button to use
in the markup
.. versionchanged:: 20.0
|sequenceargs|
"""
button_grid = [[button] for button in button_column]
return cls(button_grid, **kwargs) # type: ignore[arg-type]

View File

@@ -0,0 +1,220 @@
#!/usr/bin/env python
# pylint: disable=too-many-arguments
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2025
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser Public License for more details.
#
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents a Telegram InlineQuery."""
from collections.abc import Sequence
from typing import TYPE_CHECKING, Callable, Final, Optional, Union
from telegram import constants
from telegram._files.location import Location
from telegram._inline.inlinequeryresultsbutton import InlineQueryResultsButton
from telegram._telegramobject import TelegramObject
from telegram._user import User
from telegram._utils.argumentparsing import de_json_optional
from telegram._utils.defaultvalue import DEFAULT_NONE
from telegram._utils.types import JSONDict, ODVInput, TimePeriod
if TYPE_CHECKING:
from telegram import Bot, InlineQueryResult
class InlineQuery(TelegramObject):
"""
This object represents an incoming inline query. When the user sends an empty query, your bot
could return some default or trending results.
Objects of this class are comparable in terms of equality. Two objects of this class are
considered equal, if their :attr:`id` is equal.
.. figure:: https://core.telegram.org/file/464001466/10e4a/r4FKyQ7gw5g.134366/f2\
606a53d683374703
:align: center
Inline queries on Telegram
.. seealso::
The :class:`telegram.InlineQueryResult` classes represent the media the user can choose
from (see above figure).
Note:
In Python :keyword:`from` is a reserved word. Use :paramref:`from_user` instead.
.. versionchanged:: 20.0
The following are now keyword-only arguments in Bot methods:
``{read, write, connect, pool}_timeout``, :paramref:`answer.api_kwargs`,
``auto_pagination``. Use a named argument for those,
and notice that some positional arguments changed position as a result.
.. versionchanged:: 22.0
Removed constants ``MIN_START_PARAMETER_LENGTH`` and ``MAX_START_PARAMETER_LENGTH``.
Use :attr:`telegram.constants.InlineQueryResultsButtonLimit.MIN_START_PARAMETER_LENGTH` and
:attr:`telegram.constants.InlineQueryResultsButtonLimit.MAX_START_PARAMETER_LENGTH`
instead.
Args:
id (:obj:`str`): Unique identifier for this query.
from_user (:class:`telegram.User`): Sender.
query (:obj:`str`): Text of the query (up to
:tg-const:`telegram.InlineQuery.MAX_QUERY_LENGTH` characters).
offset (:obj:`str`): Offset of the results to be returned, can be controlled by the bot.
chat_type (:obj:`str`, optional): Type of the chat, from which the inline query was sent.
Can be either :tg-const:`telegram.Chat.SENDER` for a private chat with the inline query
sender, :tg-const:`telegram.Chat.PRIVATE`, :tg-const:`telegram.Chat.GROUP`,
:tg-const:`telegram.Chat.SUPERGROUP` or :tg-const:`telegram.Chat.CHANNEL`. The chat
type should be always known for requests sent from official clients and most
third-party clients, unless the request was sent from a secret chat.
.. versionadded:: 13.5
location (:class:`telegram.Location`, optional): Sender location, only for bots that
request user location.
Attributes:
id (:obj:`str`): Unique identifier for this query.
from_user (:class:`telegram.User`): Sender.
query (:obj:`str`): Text of the query (up to
:tg-const:`telegram.InlineQuery.MAX_QUERY_LENGTH` characters).
offset (:obj:`str`): Offset of the results to be returned, can be controlled by the bot.
chat_type (:obj:`str`): Optional. Type of the chat, from which the inline query was sent.
Can be either :tg-const:`telegram.Chat.SENDER` for a private chat with the inline query
sender, :tg-const:`telegram.Chat.PRIVATE`, :tg-const:`telegram.Chat.GROUP`,
:tg-const:`telegram.Chat.SUPERGROUP` or :tg-const:`telegram.Chat.CHANNEL`. The chat
type should be always known for requests sent from official clients and most
third-party clients, unless the request was sent from a secret chat.
.. versionadded:: 13.5
location (:class:`telegram.Location`): Optional. Sender location, only for bots that
request user location.
"""
__slots__ = ("chat_type", "from_user", "id", "location", "offset", "query")
def __init__(
self,
id: str, # pylint: disable=redefined-builtin
from_user: User,
query: str,
offset: str,
location: Optional[Location] = None,
chat_type: Optional[str] = None,
*,
api_kwargs: Optional[JSONDict] = None,
):
super().__init__(api_kwargs=api_kwargs)
# Required
self.id: str = id
self.from_user: User = from_user
self.query: str = query
self.offset: str = offset
# Optional
self.location: Optional[Location] = location
self.chat_type: Optional[str] = chat_type
self._id_attrs = (self.id,)
self._freeze()
@classmethod
def de_json(cls, data: JSONDict, bot: Optional["Bot"] = None) -> "InlineQuery":
"""See :meth:`telegram.TelegramObject.de_json`."""
data = cls._parse_data(data)
data["from_user"] = de_json_optional(data.pop("from", None), User, bot)
data["location"] = de_json_optional(data.get("location"), Location, bot)
return super().de_json(data=data, bot=bot)
async def answer(
self,
results: Union[
Sequence["InlineQueryResult"], Callable[[int], Optional[Sequence["InlineQueryResult"]]]
],
cache_time: Optional[TimePeriod] = None,
is_personal: Optional[bool] = None,
next_offset: Optional[str] = None,
button: Optional[InlineQueryResultsButton] = None,
*,
current_offset: Optional[str] = None,
auto_pagination: bool = False,
read_timeout: ODVInput[float] = DEFAULT_NONE,
write_timeout: ODVInput[float] = DEFAULT_NONE,
connect_timeout: ODVInput[float] = DEFAULT_NONE,
pool_timeout: ODVInput[float] = DEFAULT_NONE,
api_kwargs: Optional[JSONDict] = None,
) -> bool:
"""Shortcut for::
await bot.answer_inline_query(
update.inline_query.id,
*args,
current_offset=self.offset if auto_pagination else None,
**kwargs
)
For the documentation of the arguments, please see
:meth:`telegram.Bot.answer_inline_query`.
.. versionchanged:: 20.0
Raises :class:`ValueError` instead of :class:`TypeError`.
Keyword Args:
auto_pagination (:obj:`bool`, optional): If set to :obj:`True`, :attr:`offset` will be
passed as
:paramref:`current_offset <telegram.Bot.answer_inline_query.current_offset>` to
:meth:`telegram.Bot.answer_inline_query`.
Defaults to :obj:`False`.
Raises:
ValueError: If both :paramref:`~telegram.Bot.answer_inline_query.current_offset` and
:paramref:`auto_pagination` are supplied.
"""
if current_offset and auto_pagination:
raise ValueError("current_offset and auto_pagination are mutually exclusive!")
return await self.get_bot().answer_inline_query(
inline_query_id=self.id,
current_offset=self.offset if auto_pagination else current_offset,
results=results,
cache_time=cache_time,
is_personal=is_personal,
next_offset=next_offset,
button=button,
read_timeout=read_timeout,
write_timeout=write_timeout,
connect_timeout=connect_timeout,
pool_timeout=pool_timeout,
api_kwargs=api_kwargs,
)
MAX_RESULTS: Final[int] = constants.InlineQueryLimit.RESULTS
""":const:`telegram.constants.InlineQueryLimit.RESULTS`
.. versionadded:: 13.2
"""
MAX_OFFSET_LENGTH: Final[int] = constants.InlineQueryLimit.MAX_OFFSET_LENGTH
""":const:`telegram.constants.InlineQueryLimit.MAX_OFFSET_LENGTH`
.. versionadded:: 20.0
"""
MAX_QUERY_LENGTH: Final[int] = constants.InlineQueryLimit.MAX_QUERY_LENGTH
""":const:`telegram.constants.InlineQueryLimit.MAX_QUERY_LENGTH`
.. versionadded:: 20.0
"""

View File

@@ -0,0 +1,79 @@
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2025
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser Public License for more details.
#
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
# pylint: disable=redefined-builtin
"""This module contains the classes that represent Telegram InlineQueryResult."""
from typing import Final, Optional
from telegram import constants
from telegram._telegramobject import TelegramObject
from telegram._utils import enum
from telegram._utils.types import JSONDict
class InlineQueryResult(TelegramObject):
"""Baseclass for the InlineQueryResult* classes.
Objects of this class are comparable in terms of equality. Two objects of this class are
considered equal, if their :attr:`id` is equal.
Note:
All URLs passed in inline query results will be available to end users and therefore must
be assumed to be *public*.
Examples:
:any:`Inline Bot <examples.inlinebot>`
Args:
type (:obj:`str`): Type of the result.
id (:obj:`str`): Unique identifier for this result,
:tg-const:`telegram.InlineQueryResult.MIN_ID_LENGTH`-
:tg-const:`telegram.InlineQueryResult.MAX_ID_LENGTH` Bytes.
Attributes:
type (:obj:`str`): Type of the result.
id (:obj:`str`): Unique identifier for this result,
:tg-const:`telegram.InlineQueryResult.MIN_ID_LENGTH`-
:tg-const:`telegram.InlineQueryResult.MAX_ID_LENGTH` Bytes.
"""
__slots__ = ("id", "type")
def __init__(self, type: str, id: str, *, api_kwargs: Optional[JSONDict] = None):
super().__init__(api_kwargs=api_kwargs)
# Required
self.type: str = enum.get_member(constants.InlineQueryResultType, type, type)
self.id: str = str(id)
self._id_attrs = (self.id,)
self._freeze()
MIN_ID_LENGTH: Final[int] = constants.InlineQueryResultLimit.MIN_ID_LENGTH
""":const:`telegram.constants.InlineQueryResultLimit.MIN_ID_LENGTH`
.. versionadded:: 20.0
"""
MAX_ID_LENGTH: Final[int] = constants.InlineQueryResultLimit.MAX_ID_LENGTH
""":const:`telegram.constants.InlineQueryResultLimit.MAX_ID_LENGTH`
.. versionadded:: 20.0
"""

View File

@@ -0,0 +1,129 @@
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2025
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser Public License for more details.
#
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains the classes that represent Telegram InlineQueryResultArticle."""
from typing import TYPE_CHECKING, Optional
from telegram._inline.inlinekeyboardmarkup import InlineKeyboardMarkup
from telegram._inline.inlinequeryresult import InlineQueryResult
from telegram._utils.types import JSONDict
from telegram.constants import InlineQueryResultType
if TYPE_CHECKING:
from telegram import InputMessageContent
class InlineQueryResultArticle(InlineQueryResult):
"""This object represents a Telegram InlineQueryResultArticle.
Examples:
:any:`Inline Bot <examples.inlinebot>`
.. versionchanged:: 20.5
Removed the deprecated arguments and attributes ``thumb_*``.
.. versionchanged:: 21.11
Removed the deprecated argument and attribute ``hide_url``.
Args:
id (:obj:`str`): Unique identifier for this result,
:tg-const:`telegram.InlineQueryResult.MIN_ID_LENGTH`-
:tg-const:`telegram.InlineQueryResult.MAX_ID_LENGTH` Bytes.
title (:obj:`str`): Title of the result.
input_message_content (:class:`telegram.InputMessageContent`): Content of the message to
be sent.
reply_markup (:class:`telegram.InlineKeyboardMarkup`, optional): Inline keyboard attached
to the message.
url (:obj:`str`, optional): URL of the result.
Tip:
Pass an empty string as URL if you don't want the URL to be shown in the message.
description (:obj:`str`, optional): Short description of the result.
thumbnail_url (:obj:`str`, optional): Url of the thumbnail for the result.
.. versionadded:: 20.2
thumbnail_width (:obj:`int`, optional): Thumbnail width.
.. versionadded:: 20.2
thumbnail_height (:obj:`int`, optional): Thumbnail height.
.. versionadded:: 20.2
Attributes:
type (:obj:`str`): :tg-const:`telegram.constants.InlineQueryResultType.ARTICLE`.
id (:obj:`str`): Unique identifier for this result,
:tg-const:`telegram.InlineQueryResult.MIN_ID_LENGTH`-
:tg-const:`telegram.InlineQueryResult.MAX_ID_LENGTH` Bytes.
title (:obj:`str`): Title of the result.
input_message_content (:class:`telegram.InputMessageContent`): Content of the message to
be sent.
reply_markup (:class:`telegram.InlineKeyboardMarkup`): Optional. Inline keyboard attached
to the message.
url (:obj:`str`): Optional. URL of the result.
description (:obj:`str`): Optional. Short description of the result.
thumbnail_url (:obj:`str`): Optional. Url of the thumbnail for the result.
.. versionadded:: 20.2
thumbnail_width (:obj:`int`): Optional. Thumbnail width.
.. versionadded:: 20.2
thumbnail_height (:obj:`int`): Optional. Thumbnail height.
.. versionadded:: 20.2
"""
__slots__ = (
"description",
"input_message_content",
"reply_markup",
"thumbnail_height",
"thumbnail_url",
"thumbnail_width",
"title",
"url",
)
def __init__(
self,
id: str, # pylint: disable=redefined-builtin
title: str,
input_message_content: "InputMessageContent",
reply_markup: Optional[InlineKeyboardMarkup] = None,
url: Optional[str] = None,
description: Optional[str] = None,
thumbnail_url: Optional[str] = None,
thumbnail_width: Optional[int] = None,
thumbnail_height: Optional[int] = None,
*,
api_kwargs: Optional[JSONDict] = None,
):
# Required
super().__init__(InlineQueryResultType.ARTICLE, id, api_kwargs=api_kwargs)
with self._unfrozen():
self.title: str = title
self.input_message_content: InputMessageContent = input_message_content
# Optional
self.reply_markup: Optional[InlineKeyboardMarkup] = reply_markup
self.url: Optional[str] = url
self.description: Optional[str] = description
self.thumbnail_url: Optional[str] = thumbnail_url
self.thumbnail_width: Optional[int] = thumbnail_width
self.thumbnail_height: Optional[int] = thumbnail_height

View File

@@ -0,0 +1,144 @@
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2025
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser Public License for more details.
#
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains the classes that represent Telegram InlineQueryResultAudio."""
import datetime as dtm
from collections.abc import Sequence
from typing import TYPE_CHECKING, Optional, Union
from telegram._inline.inlinekeyboardmarkup import InlineKeyboardMarkup
from telegram._inline.inlinequeryresult import InlineQueryResult
from telegram._messageentity import MessageEntity
from telegram._utils.argumentparsing import parse_sequence_arg, to_timedelta
from telegram._utils.datetime import get_timedelta_value
from telegram._utils.defaultvalue import DEFAULT_NONE
from telegram._utils.types import JSONDict, ODVInput, TimePeriod
from telegram.constants import InlineQueryResultType
if TYPE_CHECKING:
from telegram import InputMessageContent
class InlineQueryResultAudio(InlineQueryResult):
"""
Represents a link to an mp3 audio file. By default, this audio file will be sent by the user.
Alternatively, you can use :attr:`input_message_content` to send a message with the specified
content instead of the audio.
.. seealso:: :wiki:`Working with Files and Media <Working-with-Files-and-Media>`
Args:
id (:obj:`str`): Unique identifier for this result,
:tg-const:`telegram.InlineQueryResult.MIN_ID_LENGTH`-
:tg-const:`telegram.InlineQueryResult.MAX_ID_LENGTH` Bytes.
audio_url (:obj:`str`): A valid URL for the audio file.
title (:obj:`str`): Title.
performer (:obj:`str`, optional): Performer.
audio_duration (:obj:`int` | :class:`datetime.timedelta`, optional): Audio duration
in seconds.
.. versionchanged:: v22.2
|time-period-input|
caption (:obj:`str`, optional): Caption,
0-:tg-const:`telegram.constants.MessageLimit.CAPTION_LENGTH` characters after entities
parsing.
parse_mode (:obj:`str`, optional): |parse_mode|
caption_entities (Sequence[:class:`telegram.MessageEntity`], optional): |caption_entities|
.. versionchanged:: 20.0
|sequenceclassargs|
reply_markup (:class:`telegram.InlineKeyboardMarkup`, optional): Inline keyboard attached
to the message.
input_message_content (:class:`telegram.InputMessageContent`, optional): Content of the
message to be sent instead of the audio.
Attributes:
type (:obj:`str`): :tg-const:`telegram.constants.InlineQueryResultType.AUDIO`.
id (:obj:`str`): Unique identifier for this result,
:tg-const:`telegram.InlineQueryResult.MIN_ID_LENGTH`-
:tg-const:`telegram.InlineQueryResult.MAX_ID_LENGTH` Bytes.
audio_url (:obj:`str`): A valid URL for the audio file.
title (:obj:`str`): Title.
performer (:obj:`str`): Optional. Performer.
audio_duration (:obj:`int` | :class:`datetime.timedelta`): Optional. Audio duration
in seconds.
.. deprecated:: v22.2
|time-period-int-deprecated|
caption (:obj:`str`): Optional. Caption,
0-:tg-const:`telegram.constants.MessageLimit.CAPTION_LENGTH` characters after entities
parsing.
parse_mode (:obj:`str`): Optional. |parse_mode|
caption_entities (tuple[:class:`telegram.MessageEntity`]): Optional. |captionentitiesattr|
.. versionchanged:: 20.0
* |tupleclassattrs|
* |alwaystuple|
reply_markup (:class:`telegram.InlineKeyboardMarkup`): Optional. Inline keyboard attached
to the message.
input_message_content (:class:`telegram.InputMessageContent`): Optional. Content of the
message to be sent instead of the audio.
"""
__slots__ = (
"_audio_duration",
"audio_url",
"caption",
"caption_entities",
"input_message_content",
"parse_mode",
"performer",
"reply_markup",
"title",
)
def __init__(
self,
id: str, # pylint: disable=redefined-builtin
audio_url: str,
title: str,
performer: Optional[str] = None,
audio_duration: Optional[TimePeriod] = None,
caption: Optional[str] = None,
reply_markup: Optional[InlineKeyboardMarkup] = None,
input_message_content: Optional["InputMessageContent"] = None,
parse_mode: ODVInput[str] = DEFAULT_NONE,
caption_entities: Optional[Sequence[MessageEntity]] = None,
*,
api_kwargs: Optional[JSONDict] = None,
):
# Required
super().__init__(InlineQueryResultType.AUDIO, id, api_kwargs=api_kwargs)
with self._unfrozen():
self.audio_url: str = audio_url
self.title: str = title
# Optionals
self.performer: Optional[str] = performer
self._audio_duration: Optional[dtm.timedelta] = to_timedelta(audio_duration)
self.caption: Optional[str] = caption
self.parse_mode: ODVInput[str] = parse_mode
self.caption_entities: tuple[MessageEntity, ...] = parse_sequence_arg(caption_entities)
self.reply_markup: Optional[InlineKeyboardMarkup] = reply_markup
self.input_message_content: Optional[InputMessageContent] = input_message_content
@property
def audio_duration(self) -> Optional[Union[int, dtm.timedelta]]:
return get_timedelta_value(self._audio_duration, attribute="audio_duration")

View File

@@ -0,0 +1,116 @@
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2025
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser Public License for more details.
#
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains the classes that represent Telegram InlineQueryResultCachedAudio."""
from collections.abc import Sequence
from typing import TYPE_CHECKING, Optional
from telegram._inline.inlinekeyboardmarkup import InlineKeyboardMarkup
from telegram._inline.inlinequeryresult import InlineQueryResult
from telegram._messageentity import MessageEntity
from telegram._utils.argumentparsing import parse_sequence_arg
from telegram._utils.defaultvalue import DEFAULT_NONE
from telegram._utils.types import JSONDict, ODVInput
from telegram.constants import InlineQueryResultType
if TYPE_CHECKING:
from telegram import InputMessageContent
class InlineQueryResultCachedAudio(InlineQueryResult):
"""
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 :attr:`input_message_content` to
send a message with the specified content instead of the audio.
.. seealso:: :wiki:`Working with Files and Media <Working-with-Files-and-Media>`
Args:
id (:obj:`str`): Unique identifier for this result,
:tg-const:`telegram.InlineQueryResult.MIN_ID_LENGTH`-
:tg-const:`telegram.InlineQueryResult.MAX_ID_LENGTH` Bytes.
audio_file_id (:obj:`str`): A valid file identifier for the audio file.
caption (:obj:`str`, optional): Caption,
0-:tg-const:`telegram.constants.MessageLimit.CAPTION_LENGTH` characters after entities
parsing.
parse_mode (:obj:`str`, optional): |parse_mode|
caption_entities (Sequence[:class:`telegram.MessageEntity`], optional): |caption_entities|
.. versionchanged:: 20.0
|sequenceclassargs|
reply_markup (:class:`telegram.InlineKeyboardMarkup`, optional): Inline keyboard attached
to the message.
input_message_content (:class:`telegram.InputMessageContent`, optional): Content of the
message to be sent instead of the audio.
Attributes:
type (:obj:`str`): :tg-const:`telegram.constants.InlineQueryResultType.AUDIO`.
id (:obj:`str`): Unique identifier for this result,
:tg-const:`telegram.InlineQueryResult.MIN_ID_LENGTH`-
:tg-const:`telegram.InlineQueryResult.MAX_ID_LENGTH` Bytes.
audio_file_id (:obj:`str`): A valid file identifier for the audio file.
caption (:obj:`str`): Optional. Caption,
0-:tg-const:`telegram.constants.MessageLimit.CAPTION_LENGTH` characters after entities
parsing.
parse_mode (:obj:`str`): Optional. |parse_mode|
caption_entities (tuple[:class:`telegram.MessageEntity`]): Optional. |captionentitiesattr|
.. versionchanged:: 20.0
* |tupleclassattrs|
* |alwaystuple|
reply_markup (:class:`telegram.InlineKeyboardMarkup`): Optional. Inline keyboard attached
to the message.
input_message_content (:class:`telegram.InputMessageContent`): Optional. Content of the
message to be sent instead of the audio.
"""
__slots__ = (
"audio_file_id",
"caption",
"caption_entities",
"input_message_content",
"parse_mode",
"reply_markup",
)
def __init__(
self,
id: str, # pylint: disable=redefined-builtin
audio_file_id: str,
caption: Optional[str] = None,
reply_markup: Optional[InlineKeyboardMarkup] = None,
input_message_content: Optional["InputMessageContent"] = None,
parse_mode: ODVInput[str] = DEFAULT_NONE,
caption_entities: Optional[Sequence[MessageEntity]] = None,
*,
api_kwargs: Optional[JSONDict] = None,
):
# Required
super().__init__(InlineQueryResultType.AUDIO, id, api_kwargs=api_kwargs)
with self._unfrozen():
self.audio_file_id: str = audio_file_id
# Optionals
self.caption: Optional[str] = caption
self.parse_mode: ODVInput[str] = parse_mode
self.caption_entities: tuple[MessageEntity, ...] = parse_sequence_arg(caption_entities)
self.reply_markup: Optional[InlineKeyboardMarkup] = reply_markup
self.input_message_content: Optional[InputMessageContent] = input_message_content

View File

@@ -0,0 +1,126 @@
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2025
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser Public License for more details.
#
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains the classes that represent Telegram InlineQueryResultCachedDocument."""
from collections.abc import Sequence
from typing import TYPE_CHECKING, Optional
from telegram._inline.inlinekeyboardmarkup import InlineKeyboardMarkup
from telegram._inline.inlinequeryresult import InlineQueryResult
from telegram._messageentity import MessageEntity
from telegram._utils.argumentparsing import parse_sequence_arg
from telegram._utils.defaultvalue import DEFAULT_NONE
from telegram._utils.types import JSONDict, ODVInput
from telegram.constants import InlineQueryResultType
if TYPE_CHECKING:
from telegram import InputMessageContent
class InlineQueryResultCachedDocument(InlineQueryResult):
"""
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 :attr:`input_message_content`
to send a message with the specified content instead of the file.
.. seealso:: :wiki:`Working with Files and Media <Working-with-Files-and-Media>`
Args:
id (:obj:`str`): Unique identifier for this result,
:tg-const:`telegram.InlineQueryResult.MIN_ID_LENGTH`-
:tg-const:`telegram.InlineQueryResult.MAX_ID_LENGTH` Bytes.
title (:obj:`str`): Title for the result.
document_file_id (:obj:`str`): A valid file identifier for the file.
description (:obj:`str`, optional): Short description of the result.
caption (:obj:`str`, optional): Caption of the document to be sent,
0-:tg-const:`telegram.constants.MessageLimit.CAPTION_LENGTH` characters
after entities parsing.
parse_mode (:obj:`str`, optional): |parse_mode|
caption_entities (Sequence[:class:`telegram.MessageEntity`], optional): |caption_entities|
.. versionchanged:: 20.0
|sequenceclassargs|
reply_markup (:class:`telegram.InlineKeyboardMarkup`, optional): Inline keyboard attached
to the message.
input_message_content (:class:`telegram.InputMessageContent`, optional): Content of the
message to be sent instead of the file.
Attributes:
type (:obj:`str`): :tg-const:`telegram.constants.InlineQueryResultType.DOCUMENT`.
id (:obj:`str`): Unique identifier for this result,
:tg-const:`telegram.InlineQueryResult.MIN_ID_LENGTH`-
:tg-const:`telegram.InlineQueryResult.MAX_ID_LENGTH` Bytes.
title (:obj:`str`): Title for the result.
document_file_id (:obj:`str`): A valid file identifier for the file.
description (:obj:`str`): Optional. Short description of the result.
caption (:obj:`str`): Optional. Caption of the document to be sent,
0-:tg-const:`telegram.constants.MessageLimit.CAPTION_LENGTH` characters
after entities parsing.
parse_mode (:obj:`str`): Optional. |parse_mode|
caption_entities (tuple[:class:`telegram.MessageEntity`]): Optional. |captionentitiesattr|
.. versionchanged:: 20.0
* |tupleclassattrs|
* |alwaystuple|
reply_markup (:class:`telegram.InlineKeyboardMarkup`): Optional. Inline keyboard attached
to the message.
input_message_content (:class:`telegram.InputMessageContent`): Optional. Content of the
message to be sent instead of the file.
"""
__slots__ = (
"caption",
"caption_entities",
"description",
"document_file_id",
"input_message_content",
"parse_mode",
"reply_markup",
"title",
)
def __init__(
self,
id: str, # pylint: disable=redefined-builtin
title: str,
document_file_id: str,
description: Optional[str] = None,
caption: Optional[str] = None,
reply_markup: Optional[InlineKeyboardMarkup] = None,
input_message_content: Optional["InputMessageContent"] = None,
parse_mode: ODVInput[str] = DEFAULT_NONE,
caption_entities: Optional[Sequence[MessageEntity]] = None,
*,
api_kwargs: Optional[JSONDict] = None,
):
# Required
super().__init__(InlineQueryResultType.DOCUMENT, id, api_kwargs=api_kwargs)
with self._unfrozen():
self.title: str = title
self.document_file_id: str = document_file_id
# Optionals
self.description: Optional[str] = description
self.caption: Optional[str] = caption
self.parse_mode: ODVInput[str] = parse_mode
self.caption_entities: tuple[MessageEntity, ...] = parse_sequence_arg(caption_entities)
self.reply_markup: Optional[InlineKeyboardMarkup] = reply_markup
self.input_message_content: Optional[InputMessageContent] = input_message_content

View File

@@ -0,0 +1,131 @@
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2025
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser Public License for more details.
#
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains the classes that represent Telegram InlineQueryResultCachedGif."""
from collections.abc import Sequence
from typing import TYPE_CHECKING, Optional
from telegram._inline.inlinekeyboardmarkup import InlineKeyboardMarkup
from telegram._inline.inlinequeryresult import InlineQueryResult
from telegram._messageentity import MessageEntity
from telegram._utils.argumentparsing import parse_sequence_arg
from telegram._utils.defaultvalue import DEFAULT_NONE
from telegram._utils.types import JSONDict, ODVInput
from telegram.constants import InlineQueryResultType
if TYPE_CHECKING:
from telegram import InputMessageContent
class InlineQueryResultCachedGif(InlineQueryResult):
"""
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 :attr:`input_message_content` to send a message with specified content instead of
the animation.
.. seealso:: :wiki:`Working with Files and Media <Working-with-Files-and-Media>`
Args:
id (:obj:`str`): Unique identifier for this result,
:tg-const:`telegram.InlineQueryResult.MIN_ID_LENGTH`-
:tg-const:`telegram.InlineQueryResult.MAX_ID_LENGTH` Bytes.
gif_file_id (:obj:`str`): A valid file identifier for the GIF file.
title (:obj:`str`, optional): Title for the result.
caption (:obj:`str`, optional): Caption of the GIF file to be sent,
0-:tg-const:`telegram.constants.MessageLimit.CAPTION_LENGTH` characters
after entities parsing.
parse_mode (:obj:`str`, optional): |parse_mode|
caption_entities (Sequence[:class:`telegram.MessageEntity`], optional): |caption_entities|
.. versionchanged:: 20.0
|sequenceclassargs|
reply_markup (:class:`telegram.InlineKeyboardMarkup`, optional): Inline keyboard attached
to the message.
input_message_content (:class:`telegram.InputMessageContent`, optional): Content of the
message to be sent instead of the gif.
show_caption_above_media (:obj:`bool`, optional): Pass |show_cap_above_med|
.. versionadded:: 21.3
Attributes:
type (:obj:`str`): :tg-const:`telegram.constants.InlineQueryResultType.GIF`.
id (:obj:`str`): Unique identifier for this result,
:tg-const:`telegram.InlineQueryResult.MIN_ID_LENGTH`-
:tg-const:`telegram.InlineQueryResult.MAX_ID_LENGTH` Bytes.
gif_file_id (:obj:`str`): A valid file identifier for the GIF file.
title (:obj:`str`): Optional. Title for the result.
caption (:obj:`str`): Optional. Caption of the GIF file to be sent,
0-:tg-const:`telegram.constants.MessageLimit.CAPTION_LENGTH` characters
after entities parsing.
parse_mode (:obj:`str`): Optional. |parse_mode|
caption_entities (tuple[:class:`telegram.MessageEntity`]): Optional. |captionentitiesattr|
.. versionchanged:: 20.0
* |tupleclassattrs|
* |alwaystuple|
reply_markup (:class:`telegram.InlineKeyboardMarkup`): Optional. Inline keyboard attached
to the message.
input_message_content (:class:`telegram.InputMessageContent`): Optional. Content of the
message to be sent instead of the gif.
show_caption_above_media (:obj:`bool`): Optional. |show_cap_above_med|
.. versionadded:: 21.3
"""
__slots__ = (
"caption",
"caption_entities",
"gif_file_id",
"input_message_content",
"parse_mode",
"reply_markup",
"show_caption_above_media",
"title",
)
def __init__(
self,
id: str, # pylint: disable=redefined-builtin
gif_file_id: str,
title: Optional[str] = None,
caption: Optional[str] = None,
reply_markup: Optional[InlineKeyboardMarkup] = None,
input_message_content: Optional["InputMessageContent"] = None,
parse_mode: ODVInput[str] = DEFAULT_NONE,
caption_entities: Optional[Sequence[MessageEntity]] = None,
show_caption_above_media: Optional[bool] = None,
*,
api_kwargs: Optional[JSONDict] = None,
):
# Required
super().__init__(InlineQueryResultType.GIF, id, api_kwargs=api_kwargs)
with self._unfrozen():
self.gif_file_id: str = gif_file_id
# Optionals
self.title: Optional[str] = title
self.caption: Optional[str] = caption
self.parse_mode: ODVInput[str] = parse_mode
self.caption_entities: tuple[MessageEntity, ...] = parse_sequence_arg(caption_entities)
self.reply_markup: Optional[InlineKeyboardMarkup] = reply_markup
self.input_message_content: Optional[InputMessageContent] = input_message_content
self.show_caption_above_media: Optional[bool] = show_caption_above_media

View File

@@ -0,0 +1,131 @@
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2025
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser Public License for more details.
#
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains the classes that represent Telegram InlineQueryResultMpeg4Gif."""
from collections.abc import Sequence
from typing import TYPE_CHECKING, Optional
from telegram._inline.inlinekeyboardmarkup import InlineKeyboardMarkup
from telegram._inline.inlinequeryresult import InlineQueryResult
from telegram._messageentity import MessageEntity
from telegram._utils.argumentparsing import parse_sequence_arg
from telegram._utils.defaultvalue import DEFAULT_NONE
from telegram._utils.types import JSONDict, ODVInput
from telegram.constants import InlineQueryResultType
if TYPE_CHECKING:
from telegram import InputMessageContent
class InlineQueryResultCachedMpeg4Gif(InlineQueryResult):
"""
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 :attr:`input_message_content` to send a message
with the specified content instead of the animation.
.. seealso:: :wiki:`Working with Files and Media <Working-with-Files-and-Media>`
Args:
id (:obj:`str`): Unique identifier for this result,
:tg-const:`telegram.InlineQueryResult.MIN_ID_LENGTH`-
:tg-const:`telegram.InlineQueryResult.MAX_ID_LENGTH` Bytes.
mpeg4_file_id (:obj:`str`): A valid file identifier for the MP4 file.
title (:obj:`str`, optional): Title for the result.
caption (:obj:`str`, optional): Caption of the MPEG-4 file to be sent,
0-:tg-const:`telegram.constants.MessageLimit.CAPTION_LENGTH` characters
after entities parsing.
parse_mode (:obj:`str`, optional): |parse_mode|
caption_entities (Sequence[:class:`telegram.MessageEntity`], optional): |caption_entities|
.. versionchanged:: 20.0
|sequenceclassargs|
reply_markup (:class:`telegram.InlineKeyboardMarkup`, optional): Inline keyboard attached
to the message.
input_message_content (:class:`telegram.InputMessageContent`, optional): Content of the
message to be sent instead of the MPEG-4 file.
show_caption_above_media (:obj:`bool`, optional): Pass |show_cap_above_med|
.. versionadded:: 21.3
Attributes:
type (:obj:`str`): :tg-const:`telegram.constants.InlineQueryResultType.MPEG4GIF`.
id (:obj:`str`): Unique identifier for this result,
:tg-const:`telegram.InlineQueryResult.MIN_ID_LENGTH`-
:tg-const:`telegram.InlineQueryResult.MAX_ID_LENGTH` Bytes.
mpeg4_file_id (:obj:`str`): A valid file identifier for the MP4 file.
title (:obj:`str`): Optional. Title for the result.
caption (:obj:`str`): Optional. Caption of the MPEG-4 file to be sent,
0-:tg-const:`telegram.constants.MessageLimit.CAPTION_LENGTH` characters
after entities parsing.
parse_mode (:obj:`str`): Optional. |parse_mode|
caption_entities (tuple[:class:`telegram.MessageEntity`]): Optional. |captionentitiesattr|
.. versionchanged:: 20.0
* |tupleclassattrs|
* |alwaystuple|
reply_markup (:class:`telegram.InlineKeyboardMarkup`): Optional. Inline keyboard attached
to the message.
input_message_content (:class:`telegram.InputMessageContent`): Optional. Content of the
message to be sent instead of the MPEG-4 file.
show_caption_above_media (:obj:`bool`): Optional. |show_cap_above_med|
.. versionadded:: 21.3
"""
__slots__ = (
"caption",
"caption_entities",
"input_message_content",
"mpeg4_file_id",
"parse_mode",
"reply_markup",
"show_caption_above_media",
"title",
)
def __init__(
self,
id: str, # pylint: disable=redefined-builtin
mpeg4_file_id: str,
title: Optional[str] = None,
caption: Optional[str] = None,
reply_markup: Optional[InlineKeyboardMarkup] = None,
input_message_content: Optional["InputMessageContent"] = None,
parse_mode: ODVInput[str] = DEFAULT_NONE,
caption_entities: Optional[Sequence[MessageEntity]] = None,
show_caption_above_media: Optional[bool] = None,
*,
api_kwargs: Optional[JSONDict] = None,
):
# Required
super().__init__(InlineQueryResultType.MPEG4GIF, id, api_kwargs=api_kwargs)
with self._unfrozen():
self.mpeg4_file_id: str = mpeg4_file_id
# Optionals
self.title: Optional[str] = title
self.caption: Optional[str] = caption
self.parse_mode: ODVInput[str] = parse_mode
self.caption_entities: tuple[MessageEntity, ...] = parse_sequence_arg(caption_entities)
self.reply_markup: Optional[InlineKeyboardMarkup] = reply_markup
self.input_message_content: Optional[InputMessageContent] = input_message_content
self.show_caption_above_media: Optional[bool] = show_caption_above_media

View File

@@ -0,0 +1,136 @@
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2025
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser Public License for more details.
#
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains the classes that represent Telegram InlineQueryResultPhoto"""
from collections.abc import Sequence
from typing import TYPE_CHECKING, Optional
from telegram._inline.inlinekeyboardmarkup import InlineKeyboardMarkup
from telegram._inline.inlinequeryresult import InlineQueryResult
from telegram._messageentity import MessageEntity
from telegram._utils.argumentparsing import parse_sequence_arg
from telegram._utils.defaultvalue import DEFAULT_NONE
from telegram._utils.types import JSONDict, ODVInput
from telegram.constants import InlineQueryResultType
if TYPE_CHECKING:
from telegram import InputMessageContent
class InlineQueryResultCachedPhoto(InlineQueryResult):
"""
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
:attr:`input_message_content` to send a message with the specified content instead
of the photo.
.. seealso:: :wiki:`Working with Files and Media <Working-with-Files-and-Media>`
Args:
id (:obj:`str`): Unique identifier for this result,
:tg-const:`telegram.InlineQueryResult.MIN_ID_LENGTH`-
:tg-const:`telegram.InlineQueryResult.MAX_ID_LENGTH` Bytes.
photo_file_id (:obj:`str`): A valid file identifier of the photo.
title (:obj:`str`, optional): Title for the result.
description (:obj:`str`, optional): Short description of the result.
caption (:obj:`str`, optional): Caption of the photo to be sent,
0-:tg-const:`telegram.constants.MessageLimit.CAPTION_LENGTH` characters after
entities parsing.
parse_mode (:obj:`str`, optional): |parse_mode|
caption_entities (Sequence[:class:`telegram.MessageEntity`], optional): |caption_entities|
.. versionchanged:: 20.0
|sequenceclassargs|
reply_markup (:class:`telegram.InlineKeyboardMarkup`, optional): Inline keyboard attached
to the message.
input_message_content (:class:`telegram.InputMessageContent`, optional): Content of the
message to be sent instead of the photo.
show_caption_above_media (:obj:`bool`, optional): Pass |show_cap_above_med|
.. versionadded:: 21.3
Attributes:
type (:obj:`str`): :tg-const:`telegram.constants.InlineQueryResultType.PHOTO`.
id (:obj:`str`): Unique identifier for this result,
:tg-const:`telegram.InlineQueryResult.MIN_ID_LENGTH`-
:tg-const:`telegram.InlineQueryResult.MAX_ID_LENGTH` Bytes.
photo_file_id (:obj:`str`): A valid file identifier of the photo.
title (:obj:`str`): Optional. Title for the result.
description (:obj:`str`): Optional. Short description of the result.
caption (:obj:`str`): Optional. Caption of the photo to be sent,
0-:tg-const:`telegram.constants.MessageLimit.CAPTION_LENGTH` characters after
entities parsing.
parse_mode (:obj:`str`): Optional. |parse_mode|
caption_entities (tuple[:class:`telegram.MessageEntity`]): Optional. |captionentitiesattr|
.. versionchanged:: 20.0
* |tupleclassattrs|
* |alwaystuple|
reply_markup (:class:`telegram.InlineKeyboardMarkup`): Optional. Inline keyboard attached
to the message.
input_message_content (:class:`telegram.InputMessageContent`): Optional. Content of the
message to be sent instead of the photo.
show_caption_above_media (:obj:`bool`): Optional. |show_cap_above_med|
.. versionadded:: 21.3
"""
__slots__ = (
"caption",
"caption_entities",
"description",
"input_message_content",
"parse_mode",
"photo_file_id",
"reply_markup",
"show_caption_above_media",
"title",
)
def __init__(
self,
id: str, # pylint: disable=redefined-builtin
photo_file_id: str,
title: Optional[str] = None,
description: Optional[str] = None,
caption: Optional[str] = None,
reply_markup: Optional[InlineKeyboardMarkup] = None,
input_message_content: Optional["InputMessageContent"] = None,
parse_mode: ODVInput[str] = DEFAULT_NONE,
caption_entities: Optional[Sequence[MessageEntity]] = None,
show_caption_above_media: Optional[bool] = None,
*,
api_kwargs: Optional[JSONDict] = None,
):
# Required
super().__init__(InlineQueryResultType.PHOTO, id, api_kwargs=api_kwargs)
with self._unfrozen():
self.photo_file_id: str = photo_file_id
# Optionals
self.title: Optional[str] = title
self.description: Optional[str] = description
self.caption: Optional[str] = caption
self.parse_mode: ODVInput[str] = parse_mode
self.caption_entities: tuple[MessageEntity, ...] = parse_sequence_arg(caption_entities)
self.reply_markup: Optional[InlineKeyboardMarkup] = reply_markup
self.input_message_content: Optional[InputMessageContent] = input_message_content
self.show_caption_above_media: Optional[bool] = show_caption_above_media

View File

@@ -0,0 +1,81 @@
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2025
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser Public License for more details.
#
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains the classes that represent Telegram InlineQueryResultCachedSticker."""
from typing import TYPE_CHECKING, Optional
from telegram._inline.inlinekeyboardmarkup import InlineKeyboardMarkup
from telegram._inline.inlinequeryresult import InlineQueryResult
from telegram._utils.types import JSONDict
from telegram.constants import InlineQueryResultType
if TYPE_CHECKING:
from telegram import InputMessageContent
class InlineQueryResultCachedSticker(InlineQueryResult):
"""
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 :attr:`input_message_content` to send a
message with the specified content instead of the sticker.
.. seealso:: :wiki:`Working with Files and Media <Working-with-Files-and-Media>`
Args:
id (:obj:`str`): Unique identifier for this result,
:tg-const:`telegram.InlineQueryResult.MIN_ID_LENGTH`-
:tg-const:`telegram.InlineQueryResult.MAX_ID_LENGTH` Bytes.
sticker_file_id (:obj:`str`): A valid file identifier of the sticker.
reply_markup (:class:`telegram.InlineKeyboardMarkup`, optional): Inline keyboard attached
to the message.
input_message_content (:class:`telegram.InputMessageContent`, optional): Content of the
message to be sent instead of the sticker.
Attributes:
type (:obj:`str`): :tg-const:`telegram.constants.InlineQueryResultType.STICKER`.
id (:obj:`str`): Unique identifier for this result,
:tg-const:`telegram.InlineQueryResult.MIN_ID_LENGTH`-
:tg-const:`telegram.InlineQueryResult.MAX_ID_LENGTH` Bytes.
sticker_file_id (:obj:`str`): A valid file identifier of the sticker.
reply_markup (:class:`telegram.InlineKeyboardMarkup`): Optional. Inline keyboard attached
to the message.
input_message_content (:class:`telegram.InputMessageContent`): Optional. Content of the
message to be sent instead of the sticker.
"""
__slots__ = ("input_message_content", "reply_markup", "sticker_file_id")
def __init__(
self,
id: str, # pylint: disable=redefined-builtin
sticker_file_id: str,
reply_markup: Optional[InlineKeyboardMarkup] = None,
input_message_content: Optional["InputMessageContent"] = None,
*,
api_kwargs: Optional[JSONDict] = None,
):
# Required
super().__init__(InlineQueryResultType.STICKER, id, api_kwargs=api_kwargs)
with self._unfrozen():
self.sticker_file_id: str = sticker_file_id
# Optionals
self.reply_markup: Optional[InlineKeyboardMarkup] = reply_markup
self.input_message_content: Optional[InputMessageContent] = input_message_content

View File

@@ -0,0 +1,132 @@
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2025
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser Public License for more details.
#
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains the classes that represent Telegram InlineQueryResultCachedVideo."""
from collections.abc import Sequence
from typing import TYPE_CHECKING, Optional
from telegram._inline.inlinekeyboardmarkup import InlineKeyboardMarkup
from telegram._inline.inlinequeryresult import InlineQueryResult
from telegram._messageentity import MessageEntity
from telegram._utils.argumentparsing import parse_sequence_arg
from telegram._utils.defaultvalue import DEFAULT_NONE
from telegram._utils.types import JSONDict, ODVInput
from telegram.constants import InlineQueryResultType
if TYPE_CHECKING:
from telegram import InputMessageContent
class InlineQueryResultCachedVideo(InlineQueryResult):
"""
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
:attr:`input_message_content` to send a message with the specified content instead
of the video.
.. seealso:: :wiki:`Working with Files and Media <Working-with-Files-and-Media>`
Args:
id (:obj:`str`): Unique identifier for this result,
:tg-const:`telegram.InlineQueryResult.MIN_ID_LENGTH`-
:tg-const:`telegram.InlineQueryResult.MAX_ID_LENGTH` Bytes.
video_file_id (:obj:`str`): A valid file identifier for the video file.
title (:obj:`str`): Title for the result.
description (:obj:`str`, optional): Short description of the result.
caption (:obj:`str`, optional): Caption of the video to be sent,
0-:tg-const:`telegram.constants.MessageLimit.CAPTION_LENGTH` characters after
entities parsing.
parse_mode (:obj:`str`, optional): |parse_mode|
caption_entities (Sequence[:class:`telegram.MessageEntity`], optional): |caption_entities|
reply_markup (:class:`telegram.InlineKeyboardMarkup`, optional): Inline keyboard attached
to the message.
input_message_content (:class:`telegram.InputMessageContent`, optional): Content of the
message to be sent instead of the video.
show_caption_above_media (:obj:`bool`, optional): Pass |show_cap_above_med|
.. versionadded:: 21.3
Attributes:
type (:obj:`str`): :tg-const:`telegram.constants.InlineQueryResultType.VIDEO`.
id (:obj:`str`): Unique identifier for this result,
:tg-const:`telegram.InlineQueryResult.MIN_ID_LENGTH`-
:tg-const:`telegram.InlineQueryResult.MAX_ID_LENGTH` Bytes.
video_file_id (:obj:`str`): A valid file identifier for the video file.
title (:obj:`str`): Title for the result.
description (:obj:`str`): Optional. Short description of the result.
caption (:obj:`str`): Optional. Caption of the video to be sent,
0-:tg-const:`telegram.constants.MessageLimit.CAPTION_LENGTH` characters after
entities parsing.
parse_mode (:obj:`str`): Optional. |parse_mode|
caption_entities (tuple[:class:`telegram.MessageEntity`]): Optional. |captionentitiesattr|
.. versionchanged:: 20.0
* |tupleclassattrs|
* |alwaystuple|
reply_markup (:class:`telegram.InlineKeyboardMarkup`): Optional. Inline keyboard attached
to the message.
input_message_content (:class:`telegram.InputMessageContent`): Optional. Content of the
message to be sent instead of the video.
show_caption_above_media (:obj:`bool`): Optional. |show_cap_above_med|
.. versionadded:: 21.3
"""
__slots__ = (
"caption",
"caption_entities",
"description",
"input_message_content",
"parse_mode",
"reply_markup",
"show_caption_above_media",
"title",
"video_file_id",
)
def __init__(
self,
id: str, # pylint: disable=redefined-builtin
video_file_id: str,
title: str,
description: Optional[str] = None,
caption: Optional[str] = None,
reply_markup: Optional[InlineKeyboardMarkup] = None,
input_message_content: Optional["InputMessageContent"] = None,
parse_mode: ODVInput[str] = DEFAULT_NONE,
caption_entities: Optional[Sequence[MessageEntity]] = None,
show_caption_above_media: Optional[bool] = None,
*,
api_kwargs: Optional[JSONDict] = None,
):
# Required
super().__init__(InlineQueryResultType.VIDEO, id, api_kwargs=api_kwargs)
with self._unfrozen():
self.video_file_id: str = video_file_id
self.title: str = title
# Optionals
self.description: Optional[str] = description
self.caption: Optional[str] = caption
self.parse_mode: ODVInput[str] = parse_mode
self.caption_entities: tuple[MessageEntity, ...] = parse_sequence_arg(caption_entities)
self.reply_markup: Optional[InlineKeyboardMarkup] = reply_markup
self.input_message_content: Optional[InputMessageContent] = input_message_content
self.show_caption_above_media: Optional[bool] = show_caption_above_media

View File

@@ -0,0 +1,121 @@
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2025
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser Public License for more details.
#
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains the classes that represent Telegram InlineQueryResultCachedVoice."""
from collections.abc import Sequence
from typing import TYPE_CHECKING, Optional
from telegram._inline.inlinekeyboardmarkup import InlineKeyboardMarkup
from telegram._inline.inlinequeryresult import InlineQueryResult
from telegram._messageentity import MessageEntity
from telegram._utils.argumentparsing import parse_sequence_arg
from telegram._utils.defaultvalue import DEFAULT_NONE
from telegram._utils.types import JSONDict, ODVInput
from telegram.constants import InlineQueryResultType
if TYPE_CHECKING:
from telegram import InputMessageContent
class InlineQueryResultCachedVoice(InlineQueryResult):
"""
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 :attr:`input_message_content` to
send a message with the specified content instead of the voice message.
.. seealso:: :wiki:`Working with Files and Media <Working-with-Files-and-Media>`
Args:
id (:obj:`str`): Unique identifier for this result,
:tg-const:`telegram.InlineQueryResult.MIN_ID_LENGTH`-
:tg-const:`telegram.InlineQueryResult.MAX_ID_LENGTH` Bytes.
voice_file_id (:obj:`str`): A valid file identifier for the voice message.
title (:obj:`str`): Voice message title.
caption (:obj:`str`, optional): Caption,
0-:tg-const:`telegram.constants.MessageLimit.CAPTION_LENGTH` characters after entities
parsing.
parse_mode (:obj:`str`, optional): |parse_mode|
caption_entities (Sequence[:class:`telegram.MessageEntity`], optional):
|captionentitiesattr|
.. versionchanged:: 20.0
|sequenceclassargs|
reply_markup (:class:`telegram.InlineKeyboardMarkup`, optional): Inline keyboard attached
to the message.
input_message_content (:class:`telegram.InputMessageContent`, optional): Content of the
message to be sent instead of the voice message.
Attributes:
type (:obj:`str`): :tg-const:`telegram.constants.InlineQueryResultType.VOICE`.
id (:obj:`str`): Unique identifier for this result,
:tg-const:`telegram.InlineQueryResult.MIN_ID_LENGTH`-
:tg-const:`telegram.InlineQueryResult.MAX_ID_LENGTH` Bytes.
voice_file_id (:obj:`str`): A valid file identifier for the voice message.
title (:obj:`str`): Voice message title.
caption (:obj:`str`): Optional. Caption,
0-:tg-const:`telegram.constants.MessageLimit.CAPTION_LENGTH` characters after entities
parsing.
parse_mode (:obj:`str`): Optional. |parse_mode|
caption_entities (tuple[:class:`telegram.MessageEntity`]): Optional. |caption_entities|
.. versionchanged:: 20.0
* |tupleclassattrs|
* |alwaystuple|
reply_markup (:class:`telegram.InlineKeyboardMarkup`): Optional. Inline keyboard attached
to the message.
input_message_content (:class:`telegram.InputMessageContent`): Optional. Content of the
message to be sent instead of the voice message.
"""
__slots__ = (
"caption",
"caption_entities",
"input_message_content",
"parse_mode",
"reply_markup",
"title",
"voice_file_id",
)
def __init__(
self,
id: str, # pylint: disable=redefined-builtin
voice_file_id: str,
title: str,
caption: Optional[str] = None,
reply_markup: Optional[InlineKeyboardMarkup] = None,
input_message_content: Optional["InputMessageContent"] = None,
parse_mode: ODVInput[str] = DEFAULT_NONE,
caption_entities: Optional[Sequence[MessageEntity]] = None,
*,
api_kwargs: Optional[JSONDict] = None,
):
# Required
super().__init__(InlineQueryResultType.VOICE, id, api_kwargs=api_kwargs)
with self._unfrozen():
self.voice_file_id: str = voice_file_id
self.title: str = title
# Optionals
self.caption: Optional[str] = caption
self.parse_mode: ODVInput[str] = parse_mode
self.caption_entities: tuple[MessageEntity, ...] = parse_sequence_arg(caption_entities)
self.reply_markup: Optional[InlineKeyboardMarkup] = reply_markup
self.input_message_content: Optional[InputMessageContent] = input_message_content

View File

@@ -0,0 +1,130 @@
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2025
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser Public License for more details.
#
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains the classes that represent Telegram InlineQueryResultContact."""
from typing import TYPE_CHECKING, Optional
from telegram._inline.inlinekeyboardmarkup import InlineKeyboardMarkup
from telegram._inline.inlinequeryresult import InlineQueryResult
from telegram._utils.types import JSONDict
from telegram.constants import InlineQueryResultType
if TYPE_CHECKING:
from telegram import InputMessageContent
class InlineQueryResultContact(InlineQueryResult):
"""
Represents a contact with a phone number. By default, this contact will be sent by the user.
Alternatively, you can use :attr:`input_message_content` to send a message with the specified
content instead of the contact.
.. versionchanged:: 20.5
|removed_thumb_wildcard_note|
Args:
id (:obj:`str`): Unique identifier for this result,
:tg-const:`telegram.InlineQueryResult.MIN_ID_LENGTH`-
:tg-const:`telegram.InlineQueryResult.MAX_ID_LENGTH` Bytes.
phone_number (:obj:`str`): Contact's phone number.
first_name (:obj:`str`): Contact's first name.
last_name (:obj:`str`, optional): Contact's last name.
vcard (:obj:`str`, optional): Additional data about the contact in the form of a vCard,
0-:tg-const:`telegram.constants.ContactLimit.VCARD` bytes.
reply_markup (:class:`telegram.InlineKeyboardMarkup`, optional): Inline keyboard attached
to the message.
input_message_content (:class:`telegram.InputMessageContent`, optional): Content of the
message to be sent instead of the contact.
thumbnail_url (:obj:`str`, optional): Url of the thumbnail for the result.
.. versionadded:: 20.2
thumbnail_width (:obj:`int`, optional): Thumbnail width.
.. versionadded:: 20.2
thumbnail_height (:obj:`int`, optional): Thumbnail height.
.. versionadded:: 20.2
Attributes:
type (:obj:`str`): :tg-const:`telegram.constants.InlineQueryResultType.CONTACT`.
id (:obj:`str`): Unique identifier for this result,
:tg-const:`telegram.InlineQueryResult.MIN_ID_LENGTH`-
:tg-const:`telegram.InlineQueryResult.MAX_ID_LENGTH` Bytes.
phone_number (:obj:`str`): Contact's phone number.
first_name (:obj:`str`): Contact's first name.
last_name (:obj:`str`): Optional. Contact's last name.
vcard (:obj:`str`): Optional. Additional data about the contact in the form of a vCard,
0-:tg-const:`telegram.constants.ContactLimit.VCARD` bytes.
reply_markup (:class:`telegram.InlineKeyboardMarkup`): Optional. Inline keyboard attached
to the message.
input_message_content (:class:`telegram.InputMessageContent`): Optional. Content of the
message to be sent instead of the contact.
thumbnail_url (:obj:`str`): Optional. Url of the thumbnail for the result.
.. versionadded:: 20.2
thumbnail_width (:obj:`int`): Optional. Thumbnail width.
.. versionadded:: 20.2
thumbnail_height (:obj:`int`): Optional. Thumbnail height.
.. versionadded:: 20.2
"""
__slots__ = (
"first_name",
"input_message_content",
"last_name",
"phone_number",
"reply_markup",
"thumbnail_height",
"thumbnail_url",
"thumbnail_width",
"vcard",
)
def __init__(
self,
id: str, # pylint: disable=redefined-builtin
phone_number: str,
first_name: str,
last_name: Optional[str] = None,
reply_markup: Optional[InlineKeyboardMarkup] = None,
input_message_content: Optional["InputMessageContent"] = None,
vcard: Optional[str] = None,
thumbnail_url: Optional[str] = None,
thumbnail_width: Optional[int] = None,
thumbnail_height: Optional[int] = None,
*,
api_kwargs: Optional[JSONDict] = None,
):
# Required
super().__init__(InlineQueryResultType.CONTACT, id, api_kwargs=api_kwargs)
with self._unfrozen():
self.phone_number: str = phone_number
self.first_name: str = first_name
# Optionals
self.last_name: Optional[str] = last_name
self.vcard: Optional[str] = vcard
self.reply_markup: Optional[InlineKeyboardMarkup] = reply_markup
self.input_message_content: Optional[InputMessageContent] = input_message_content
self.thumbnail_url: Optional[str] = thumbnail_url
self.thumbnail_width: Optional[int] = thumbnail_width
self.thumbnail_height: Optional[int] = thumbnail_height

View File

@@ -0,0 +1,165 @@
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2025
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser Public License for more details.
#
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains the classes that represent Telegram InlineQueryResultDocument"""
from collections.abc import Sequence
from typing import TYPE_CHECKING, Optional
from telegram._inline.inlinekeyboardmarkup import InlineKeyboardMarkup
from telegram._inline.inlinequeryresult import InlineQueryResult
from telegram._messageentity import MessageEntity
from telegram._utils.argumentparsing import parse_sequence_arg
from telegram._utils.defaultvalue import DEFAULT_NONE
from telegram._utils.types import JSONDict, ODVInput
from telegram.constants import InlineQueryResultType
if TYPE_CHECKING:
from telegram import InputMessageContent
class InlineQueryResultDocument(InlineQueryResult):
"""
Represents a link to a file. By default, this file will be sent by the user with an optional
caption. Alternatively, you can use :attr:`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.
.. seealso:: :wiki:`Working with Files and Media <Working-with-Files-and-Media>`
.. versionchanged:: 20.5
|removed_thumb_wildcard_note|
Args:
id (:obj:`str`): Unique identifier for this result,
:tg-const:`telegram.InlineQueryResult.MIN_ID_LENGTH`-
:tg-const:`telegram.InlineQueryResult.MAX_ID_LENGTH` Bytes.
title (:obj:`str`): Title for the result.
caption (:obj:`str`, optional): Caption of the document to be sent,
0-:tg-const:`telegram.constants.MessageLimit.CAPTION_LENGTH` characters
after entities parsing.
parse_mode (:obj:`str`, optional): |parse_mode|
caption_entities (Sequence[:class:`telegram.MessageEntity`], optional): |caption_entities|
.. versionchanged:: 20.0
|sequenceclassargs|
document_url (:obj:`str`): A valid URL for the file.
mime_type (:obj:`str`): Mime type of the content of the file, either "application/pdf"
or "application/zip".
description (:obj:`str`, optional): Short description of the result.
reply_markup (:class:`telegram.InlineKeyboardMarkup`, optional): Inline keyboard attached
to the message.
input_message_content (:class:`telegram.InputMessageContent`, optional): Content of the
message to be sent instead of the file.
thumbnail_url (:obj:`str`, optional): URL of the thumbnail (JPEG only) for the file.
.. versionadded:: 20.2
thumbnail_width (:obj:`int`, optional): Thumbnail width.
.. versionadded:: 20.2
thumbnail_height (:obj:`int`, optional): Thumbnail height.
.. versionadded:: 20.2
Attributes:
type (:obj:`str`): :tg-const:`telegram.constants.InlineQueryResultType.DOCUMENT`.
id (:obj:`str`): Unique identifier for this result,
:tg-const:`telegram.InlineQueryResult.MIN_ID_LENGTH`-
:tg-const:`telegram.InlineQueryResult.MAX_ID_LENGTH` Bytes.
title (:obj:`str`): Title for the result.
caption (:obj:`str`): Optional. Caption of the document to be sent,
0-:tg-const:`telegram.constants.MessageLimit.CAPTION_LENGTH` characters
after entities parsing.
parse_mode (:obj:`str`): Optional. |parse_mode|
caption_entities (tuple[:class:`telegram.MessageEntity`]): Optional. |captionentitiesattr|
.. versionchanged:: 20.0
* |tupleclassattrs|
* |alwaystuple|
document_url (:obj:`str`): A valid URL for the file.
mime_type (:obj:`str`): Mime type of the content of the file, either "application/pdf"
or "application/zip".
description (:obj:`str`): Optional. Short description of the result.
reply_markup (:class:`telegram.InlineKeyboardMarkup`): Optional. Inline keyboard attached
to the message.
input_message_content (:class:`telegram.InputMessageContent`): Optional. Content of the
message to be sent instead of the file.
thumbnail_url (:obj:`str`): Optional. URL of the thumbnail (JPEG only) for the file.
.. versionadded:: 20.2
thumbnail_width (:obj:`int`): Optional. Thumbnail width.
.. versionadded:: 20.2
thumbnail_height (:obj:`int`): Optional. Thumbnail height.
.. versionadded:: 20.2
"""
__slots__ = (
"caption",
"caption_entities",
"description",
"document_url",
"input_message_content",
"mime_type",
"parse_mode",
"reply_markup",
"thumbnail_height",
"thumbnail_url",
"thumbnail_width",
"title",
)
def __init__(
self,
id: str, # pylint: disable=redefined-builtin
document_url: str,
title: str,
mime_type: str,
caption: Optional[str] = None,
description: Optional[str] = None,
reply_markup: Optional[InlineKeyboardMarkup] = None,
input_message_content: Optional["InputMessageContent"] = None,
parse_mode: ODVInput[str] = DEFAULT_NONE,
caption_entities: Optional[Sequence[MessageEntity]] = None,
thumbnail_url: Optional[str] = None,
thumbnail_width: Optional[int] = None,
thumbnail_height: Optional[int] = None,
*,
api_kwargs: Optional[JSONDict] = None,
):
# Required
super().__init__(InlineQueryResultType.DOCUMENT, id, api_kwargs=api_kwargs)
with self._unfrozen():
self.document_url: str = document_url
self.title: str = title
self.mime_type: str = mime_type
# Optionals
self.caption: Optional[str] = caption
self.parse_mode: ODVInput[str] = parse_mode
self.caption_entities: tuple[MessageEntity, ...] = parse_sequence_arg(caption_entities)
self.description: Optional[str] = description
self.reply_markup: Optional[InlineKeyboardMarkup] = reply_markup
self.input_message_content: Optional[InputMessageContent] = input_message_content
self.thumbnail_url: Optional[str] = thumbnail_url
self.thumbnail_width: Optional[int] = thumbnail_width
self.thumbnail_height: Optional[int] = thumbnail_height

View File

@@ -0,0 +1,66 @@
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2025
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser Public License for more details.
#
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains the classes that represent Telegram InlineQueryResultGame."""
from typing import Optional
from telegram._inline.inlinekeyboardmarkup import InlineKeyboardMarkup
from telegram._inline.inlinequeryresult import InlineQueryResult
from telegram._utils.types import JSONDict
from telegram.constants import InlineQueryResultType
class InlineQueryResultGame(InlineQueryResult):
"""Represents a :class:`telegram.Game`.
Args:
id (:obj:`str`): Unique identifier for this result,
:tg-const:`telegram.InlineQueryResult.MIN_ID_LENGTH`-
:tg-const:`telegram.InlineQueryResult.MAX_ID_LENGTH` Bytes.
game_short_name (:obj:`str`): Short name of the game.
reply_markup (:class:`telegram.InlineKeyboardMarkup`, optional): Inline keyboard attached
to the message.
Attributes:
type (:obj:`str`): :tg-const:`telegram.constants.InlineQueryResultType.GAME`.
id (:obj:`str`): Unique identifier for this result,
:tg-const:`telegram.InlineQueryResult.MIN_ID_LENGTH`-
:tg-const:`telegram.InlineQueryResult.MAX_ID_LENGTH` Bytes.
game_short_name (:obj:`str`): Short name of the game.
reply_markup (:class:`telegram.InlineKeyboardMarkup`): Optional. Inline keyboard attached
to the message.
"""
__slots__ = ("game_short_name", "reply_markup")
def __init__(
self,
id: str, # pylint: disable=redefined-builtin
game_short_name: str,
reply_markup: Optional[InlineKeyboardMarkup] = None,
*,
api_kwargs: Optional[JSONDict] = None,
):
# Required
super().__init__(InlineQueryResultType.GAME, id, api_kwargs=api_kwargs)
with self._unfrozen():
self.id: str = id
self.game_short_name: str = game_short_name
self.reply_markup: Optional[InlineKeyboardMarkup] = reply_markup

View File

@@ -0,0 +1,188 @@
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2025
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser Public License for more details.
#
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains the classes that represent Telegram InlineQueryResultGif."""
import datetime as dtm
from collections.abc import Sequence
from typing import TYPE_CHECKING, Optional, Union
from telegram._inline.inlinekeyboardmarkup import InlineKeyboardMarkup
from telegram._inline.inlinequeryresult import InlineQueryResult
from telegram._messageentity import MessageEntity
from telegram._utils.argumentparsing import parse_sequence_arg, to_timedelta
from telegram._utils.datetime import get_timedelta_value
from telegram._utils.defaultvalue import DEFAULT_NONE
from telegram._utils.types import JSONDict, ODVInput, TimePeriod
from telegram.constants import InlineQueryResultType
if TYPE_CHECKING:
from telegram import InputMessageContent
class InlineQueryResultGif(InlineQueryResult):
"""
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 :attr:`input_message_content` to
send a message with the specified content instead of the animation.
.. seealso:: :wiki:`Working with Files and Media <Working-with-Files-and-Media>`
.. versionchanged:: 20.5
|removed_thumb_wildcard_note|
Args:
id (:obj:`str`): Unique identifier for this result,
:tg-const:`telegram.InlineQueryResult.MIN_ID_LENGTH`-
:tg-const:`telegram.InlineQueryResult.MAX_ID_LENGTH` Bytes.
gif_url (:obj:`str`): A valid URL for the GIF file.
gif_width (:obj:`int`, optional): Width of the GIF.
gif_height (:obj:`int`, optional): Height of the GIF.
gif_duration (:obj:`int` | :class:`datetime.timedelta`, optional): Duration of the GIF
in seconds.
.. versionchanged:: v22.2
|time-period-input|
thumbnail_url (:obj:`str`): URL of the static (JPEG or GIF) or animated (MPEG4)
thumbnail for the result.
.. versionadded:: 20.2
..versionchanged:: 20.5
|thumbnail_url_mandatory|
thumbnail_mime_type (:obj:`str`, optional): MIME type of the thumbnail, must be one of
``'image/jpeg'``, ``'image/gif'``, or ``'video/mp4'``. Defaults to ``'image/jpeg'``.
.. versionadded:: 20.2
title (:obj:`str`, optional): Title for the result.
caption (:obj:`str`, optional): Caption of the GIF file to be sent,
0-:tg-const:`telegram.constants.MessageLimit.CAPTION_LENGTH` characters
after entities parsing.
parse_mode (:obj:`str`, optional): |parse_mode|
caption_entities (Sequence[:class:`telegram.MessageEntity`], optional): |caption_entities|
.. versionchanged:: 20.0
|sequenceclassargs|
reply_markup (:class:`telegram.InlineKeyboardMarkup`, optional): Inline keyboard attached
to the message.
input_message_content (:class:`telegram.InputMessageContent`, optional): Content of the
message to be sent instead of the GIF animation.
show_caption_above_media (:obj:`bool`, optional): Pass |show_cap_above_med|
.. versionadded:: 21.3
Attributes:
type (:obj:`str`): :tg-const:`telegram.constants.InlineQueryResultType.GIF`.
id (:obj:`str`): Unique identifier for this result,
:tg-const:`telegram.InlineQueryResult.MIN_ID_LENGTH`-
:tg-const:`telegram.InlineQueryResult.MAX_ID_LENGTH` Bytes.
gif_url (:obj:`str`): A valid URL for the GIF file.
gif_width (:obj:`int`): Optional. Width of the GIF.
gif_height (:obj:`int`): Optional. Height of the GIF.
gif_duration (:obj:`int` | :class:`datetime.timedelta`): Optional. Duration of the GIF
in seconds.
.. deprecated:: v22.2
|time-period-int-deprecated|
thumbnail_url (:obj:`str`): URL of the static (JPEG or GIF) or animated (MPEG4) thumbnail
for the result.
.. versionadded:: 20.2
thumbnail_mime_type (:obj:`str`): Optional. MIME type of the thumbnail, must be one of
``'image/jpeg'``, ``'image/gif'``, or ``'video/mp4'``. Defaults to ``'image/jpeg'``.
.. versionadded:: 20.2
title (:obj:`str`): Optional. Title for the result.
caption (:obj:`str`): Optional. Caption of the GIF file to be sent,
0-:tg-const:`telegram.constants.MessageLimit.CAPTION_LENGTH` characters
after entities parsing.
parse_mode (:obj:`str`): Optional. |parse_mode|
caption_entities (tuple[:class:`telegram.MessageEntity`]): Optional. |captionentitiesattr|
.. versionchanged:: 20.0
* |tupleclassattrs|
* |alwaystuple|
reply_markup (:class:`telegram.InlineKeyboardMarkup`): Optional. Inline keyboard attached
to the message.
input_message_content (:class:`telegram.InputMessageContent`): Optional. Content of the
message to be sent instead of the GIF animation.
show_caption_above_media (:obj:`bool`): Optional. |show_cap_above_med|
.. versionadded:: 21.3
"""
__slots__ = (
"_gif_duration",
"caption",
"caption_entities",
"gif_height",
"gif_url",
"gif_width",
"input_message_content",
"parse_mode",
"reply_markup",
"show_caption_above_media",
"thumbnail_mime_type",
"thumbnail_url",
"title",
)
def __init__(
self,
id: str, # pylint: disable=redefined-builtin
gif_url: str,
thumbnail_url: str,
gif_width: Optional[int] = None,
gif_height: Optional[int] = None,
title: Optional[str] = None,
caption: Optional[str] = None,
reply_markup: Optional[InlineKeyboardMarkup] = None,
input_message_content: Optional["InputMessageContent"] = None,
gif_duration: Optional[TimePeriod] = None,
parse_mode: ODVInput[str] = DEFAULT_NONE,
caption_entities: Optional[Sequence[MessageEntity]] = None,
thumbnail_mime_type: Optional[str] = None,
show_caption_above_media: Optional[bool] = None,
*,
api_kwargs: Optional[JSONDict] = None,
):
# Required
super().__init__(InlineQueryResultType.GIF, id, api_kwargs=api_kwargs)
with self._unfrozen():
self.gif_url: str = gif_url
self.thumbnail_url: str = thumbnail_url
# Optionals
self.gif_width: Optional[int] = gif_width
self.gif_height: Optional[int] = gif_height
self._gif_duration: Optional[dtm.timedelta] = to_timedelta(gif_duration)
self.title: Optional[str] = title
self.caption: Optional[str] = caption
self.parse_mode: ODVInput[str] = parse_mode
self.caption_entities: tuple[MessageEntity, ...] = parse_sequence_arg(caption_entities)
self.reply_markup: Optional[InlineKeyboardMarkup] = reply_markup
self.input_message_content: Optional[InputMessageContent] = input_message_content
self.thumbnail_mime_type: Optional[str] = thumbnail_mime_type
self.show_caption_above_media: Optional[bool] = show_caption_above_media
@property
def gif_duration(self) -> Optional[Union[int, dtm.timedelta]]:
return get_timedelta_value(self._gif_duration, attribute="gif_duration")

View File

@@ -0,0 +1,220 @@
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2025
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser Public License for more details.
#
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains the classes that represent Telegram InlineQueryResultLocation."""
import datetime as dtm
from typing import TYPE_CHECKING, Final, Optional, Union
from telegram import constants
from telegram._inline.inlinekeyboardmarkup import InlineKeyboardMarkup
from telegram._inline.inlinequeryresult import InlineQueryResult
from telegram._utils.argumentparsing import to_timedelta
from telegram._utils.datetime import get_timedelta_value
from telegram._utils.types import JSONDict, TimePeriod
if TYPE_CHECKING:
from telegram import InputMessageContent
class InlineQueryResultLocation(InlineQueryResult):
"""
Represents a location on a map. By default, the location will be sent by the user.
Alternatively, you can use :attr:`input_message_content` to send a message with the specified
content instead of the location.
.. versionchanged:: 20.5
|removed_thumb_wildcard_note|
Args:
id (:obj:`str`): Unique identifier for this result,
:tg-const:`telegram.InlineQueryResult.MIN_ID_LENGTH`-
:tg-const:`telegram.InlineQueryResult.MAX_ID_LENGTH` Bytes.
latitude (:obj:`float`): Location latitude in degrees.
longitude (:obj:`float`): Location longitude in degrees.
title (:obj:`str`): Location title.
horizontal_accuracy (:obj:`float`, optional): The radius of uncertainty for the location,
measured in meters; 0-
:tg-const:`telegram.InlineQueryResultLocation.HORIZONTAL_ACCURACY`.
live_period (:obj:`int` | :class:`datetime.timedelta`, optional): Period in seconds for
which the location will be updated, should be between
:tg-const:`telegram.InlineQueryResultLocation.MIN_LIVE_PERIOD` and
:tg-const:`telegram.InlineQueryResultLocation.MAX_LIVE_PERIOD`.
.. versionchanged:: v22.2
|time-period-input|
heading (:obj:`int`, optional): For live locations, a direction in which the user is
moving, in degrees. Must be between
:tg-const:`telegram.InlineQueryResultLocation.MIN_HEADING` and
:tg-const:`telegram.InlineQueryResultLocation.MAX_HEADING` if specified.
proximity_alert_radius (:obj:`int`, optional): For live locations, a maximum distance
for proximity alerts about approaching another chat member, in meters. Must be
between :tg-const:`telegram.InlineQueryResultLocation.MIN_PROXIMITY_ALERT_RADIUS`
and :tg-const:`telegram.InlineQueryResultLocation.MAX_PROXIMITY_ALERT_RADIUS`
if specified.
reply_markup (:class:`telegram.InlineKeyboardMarkup`, optional): Inline keyboard attached
to the message.
input_message_content (:class:`telegram.InputMessageContent`, optional): Content of the
message to be sent instead of the location.
thumbnail_url (:obj:`str`, optional): Url of the thumbnail for the result.
.. versionadded:: 20.2
thumbnail_width (:obj:`int`, optional): Thumbnail width.
.. versionadded:: 20.2
thumbnail_height (:obj:`int`, optional): Thumbnail height.
.. versionadded:: 20.2
Attributes:
type (:obj:`str`): :tg-const:`telegram.constants.InlineQueryResultType.LOCATION`.
id (:obj:`str`): Unique identifier for this result,
:tg-const:`telegram.InlineQueryResult.MIN_ID_LENGTH`-
:tg-const:`telegram.InlineQueryResult.MAX_ID_LENGTH` Bytes.
latitude (:obj:`float`): Location latitude in degrees.
longitude (:obj:`float`): Location longitude in degrees.
title (:obj:`str`): Location title.
horizontal_accuracy (:obj:`float`): Optional. The radius of uncertainty for the location,
measured in meters; 0-
:tg-const:`telegram.InlineQueryResultLocation.HORIZONTAL_ACCURACY`.
live_period (:obj:`int` | :class:`datetime.timedelta`): Optional. Period in seconds for
which the location will be updated, should be between
:tg-const:`telegram.InlineQueryResultLocation.MIN_LIVE_PERIOD` and
:tg-const:`telegram.InlineQueryResultLocation.MAX_LIVE_PERIOD` or
:tg-const:`telegram.constants.LocationLimit.LIVE_PERIOD_FOREVER` for live
locations that can be edited indefinitely.
.. deprecated:: v22.2
|time-period-int-deprecated|
heading (:obj:`int`): Optional. For live locations, a direction in which the user is
moving, in degrees. Must be between
:tg-const:`telegram.InlineQueryResultLocation.MIN_HEADING` and
:tg-const:`telegram.InlineQueryResultLocation.MAX_HEADING` if specified.
proximity_alert_radius (:obj:`int`): Optional. For live locations, a maximum distance
for proximity alerts about approaching another chat member, in meters. Must be
between :tg-const:`telegram.InlineQueryResultLocation.MIN_PROXIMITY_ALERT_RADIUS`
and :tg-const:`telegram.InlineQueryResultLocation.MAX_PROXIMITY_ALERT_RADIUS`
if specified.
reply_markup (:class:`telegram.InlineKeyboardMarkup`): Optional. Inline keyboard attached
to the message.
input_message_content (:class:`telegram.InputMessageContent`): Optional. Content of the
message to be sent instead of the location.
thumbnail_url (:obj:`str`): Optional. Url of the thumbnail for the result.
.. versionadded:: 20.2
thumbnail_width (:obj:`int`): Optional. Thumbnail width.
.. versionadded:: 20.2
thumbnail_height (:obj:`int`): Optional. Thumbnail height.
.. versionadded:: 20.2
"""
__slots__ = (
"_live_period",
"heading",
"horizontal_accuracy",
"input_message_content",
"latitude",
"longitude",
"proximity_alert_radius",
"reply_markup",
"thumbnail_height",
"thumbnail_url",
"thumbnail_width",
"title",
)
def __init__(
self,
id: str, # pylint: disable=redefined-builtin
latitude: float,
longitude: float,
title: str,
live_period: Optional[TimePeriod] = None,
reply_markup: Optional[InlineKeyboardMarkup] = None,
input_message_content: Optional["InputMessageContent"] = None,
horizontal_accuracy: Optional[float] = None,
heading: Optional[int] = None,
proximity_alert_radius: Optional[int] = None,
thumbnail_url: Optional[str] = None,
thumbnail_width: Optional[int] = None,
thumbnail_height: Optional[int] = None,
*,
api_kwargs: Optional[JSONDict] = None,
):
# Required
super().__init__(constants.InlineQueryResultType.LOCATION, id, api_kwargs=api_kwargs)
with self._unfrozen():
self.latitude: float = latitude
self.longitude: float = longitude
self.title: str = title
# Optionals
self._live_period: Optional[dtm.timedelta] = to_timedelta(live_period)
self.reply_markup: Optional[InlineKeyboardMarkup] = reply_markup
self.input_message_content: Optional[InputMessageContent] = input_message_content
self.thumbnail_url: Optional[str] = thumbnail_url
self.thumbnail_width: Optional[int] = thumbnail_width
self.thumbnail_height: Optional[int] = thumbnail_height
self.horizontal_accuracy: Optional[float] = horizontal_accuracy
self.heading: Optional[int] = heading
self.proximity_alert_radius: Optional[int] = (
int(proximity_alert_radius) if proximity_alert_radius else None
)
@property
def live_period(self) -> Optional[Union[int, dtm.timedelta]]:
return get_timedelta_value(self._live_period, attribute="live_period")
HORIZONTAL_ACCURACY: Final[int] = constants.LocationLimit.HORIZONTAL_ACCURACY
""":const:`telegram.constants.LocationLimit.HORIZONTAL_ACCURACY`
.. versionadded:: 20.0
"""
MIN_HEADING: Final[int] = constants.LocationLimit.MIN_HEADING
""":const:`telegram.constants.LocationLimit.MIN_HEADING`
.. versionadded:: 20.0
"""
MAX_HEADING: Final[int] = constants.LocationLimit.MAX_HEADING
""":const:`telegram.constants.LocationLimit.MAX_HEADING`
.. versionadded:: 20.0
"""
MIN_LIVE_PERIOD: Final[int] = constants.LocationLimit.MIN_LIVE_PERIOD
""":const:`telegram.constants.LocationLimit.MIN_LIVE_PERIOD`
.. versionadded:: 20.0
"""
MAX_LIVE_PERIOD: Final[int] = constants.LocationLimit.MAX_LIVE_PERIOD
""":const:`telegram.constants.LocationLimit.MAX_LIVE_PERIOD`
.. versionadded:: 20.0
"""
MIN_PROXIMITY_ALERT_RADIUS: Final[int] = constants.LocationLimit.MIN_PROXIMITY_ALERT_RADIUS
""":const:`telegram.constants.LocationLimit.MIN_PROXIMITY_ALERT_RADIUS`
.. versionadded:: 20.0
"""
MAX_PROXIMITY_ALERT_RADIUS: Final[int] = constants.LocationLimit.MAX_PROXIMITY_ALERT_RADIUS
""":const:`telegram.constants.LocationLimit.MAX_PROXIMITY_ALERT_RADIUS`
.. versionadded:: 20.0
"""

View File

@@ -0,0 +1,190 @@
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2025
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser Public License for more details.
#
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains the classes that represent Telegram InlineQueryResultMpeg4Gif."""
import datetime as dtm
from collections.abc import Sequence
from typing import TYPE_CHECKING, Optional, Union
from telegram._inline.inlinekeyboardmarkup import InlineKeyboardMarkup
from telegram._inline.inlinequeryresult import InlineQueryResult
from telegram._messageentity import MessageEntity
from telegram._utils.argumentparsing import parse_sequence_arg, to_timedelta
from telegram._utils.datetime import get_timedelta_value
from telegram._utils.defaultvalue import DEFAULT_NONE
from telegram._utils.types import JSONDict, ODVInput, TimePeriod
from telegram.constants import InlineQueryResultType
if TYPE_CHECKING:
from telegram import InputMessageContent
class InlineQueryResultMpeg4Gif(InlineQueryResult):
"""
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 :attr:`input_message_content` to send a message with the specified content instead of the
animation.
.. seealso:: :wiki:`Working with Files and Media <Working-with-Files-and-Media>`
.. versionchanged:: 20.5
|removed_thumb_wildcard_note|
Args:
id (:obj:`str`): Unique identifier for this result,
:tg-const:`telegram.InlineQueryResult.MIN_ID_LENGTH`-
:tg-const:`telegram.InlineQueryResult.MAX_ID_LENGTH` Bytes.
mpeg4_url (:obj:`str`): A valid URL for the MP4 file.
mpeg4_width (:obj:`int`, optional): Video width.
mpeg4_height (:obj:`int`, optional): Video height.
mpeg4_duration (:obj:`int` | :class:`datetime.timedelta`, optional): Video duration
in seconds.
.. versionchanged:: v22.2
|time-period-input|
thumbnail_url (:obj:`str`): URL of the static (JPEG or GIF) or animated (MPEG4)
thumbnail for the result.
.. versionadded:: 20.2
..versionchanged:: 20.5
|thumbnail_url_mandatory|
thumbnail_mime_type (:obj:`str`, optional): MIME type of the thumbnail, must be one of
``'image/jpeg'``, ``'image/gif'``, or ``'video/mp4'``. Defaults to ``'image/jpeg'``.
.. versionadded:: 20.2
title (:obj:`str`, optional): Title for the result.
caption (:obj:`str`, optional): Caption of the MPEG-4 file to be sent,
0-:tg-const:`telegram.constants.MessageLimit.CAPTION_LENGTH` characters
after entities parsing.
parse_mode (:obj:`str`, optional): |parse_mode|
caption_entities (Sequence[:class:`telegram.MessageEntity`], optional):
|captionentitiesattr|
.. versionchanged:: 20.0
|sequenceclassargs|
reply_markup (:class:`telegram.InlineKeyboardMarkup`, optional): Inline keyboard attached
to the message.
input_message_content (:class:`telegram.InputMessageContent`, optional): Content of the
message to be sent instead of the video animation.
show_caption_above_media (:obj:`bool`, optional): Pass |show_cap_above_med|
.. versionadded:: 21.3
Attributes:
type (:obj:`str`): :tg-const:`telegram.constants.InlineQueryResultType.MPEG4GIF`.
id (:obj:`str`): Unique identifier for this result,
:tg-const:`telegram.InlineQueryResult.MIN_ID_LENGTH`-
:tg-const:`telegram.InlineQueryResult.MAX_ID_LENGTH` Bytes.
mpeg4_url (:obj:`str`): A valid URL for the MP4 file.
mpeg4_width (:obj:`int`): Optional. Video width.
mpeg4_height (:obj:`int`): Optional. Video height.
mpeg4_duration (:obj:`int` | :class:`datetime.timedelta`): Optional. Video duration
in seconds.
.. deprecated:: v22.2
|time-period-int-deprecated|
thumbnail_url (:obj:`str`): URL of the static (JPEG or GIF) or animated (MPEG4) thumbnail
for the result.
.. versionadded:: 20.2
thumbnail_mime_type (:obj:`str`): Optional. MIME type of the thumbnail, must be one of
``'image/jpeg'``, ``'image/gif'``, or ``'video/mp4'``. Defaults to ``'image/jpeg'``.
.. versionadded:: 20.2
title (:obj:`str`): Optional. Title for the result.
caption (:obj:`str`): Optional. Caption of the MPEG-4 file to be sent,
0-:tg-const:`telegram.constants.MessageLimit.CAPTION_LENGTH` characters
after entities parsing.
parse_mode (:obj:`str`): Optional. |parse_mode|
caption_entities (tuple[:class:`telegram.MessageEntity`]): Optional. |caption_entities|
.. versionchanged:: 20.0
* |tupleclassattrs|
* |alwaystuple|
reply_markup (:class:`telegram.InlineKeyboardMarkup`): Optional. Inline keyboard attached
to the message.
input_message_content (:class:`telegram.InputMessageContent`): Optional. Content of the
message to be sent instead of the video animation.
show_caption_above_media (:obj:`bool`): Optional. |show_cap_above_med|
.. versionadded:: 21.3
"""
__slots__ = (
"_mpeg4_duration",
"caption",
"caption_entities",
"input_message_content",
"mpeg4_height",
"mpeg4_url",
"mpeg4_width",
"parse_mode",
"reply_markup",
"show_caption_above_media",
"thumbnail_mime_type",
"thumbnail_url",
"title",
)
def __init__(
self,
id: str, # pylint: disable=redefined-builtin
mpeg4_url: str,
thumbnail_url: str,
mpeg4_width: Optional[int] = None,
mpeg4_height: Optional[int] = None,
title: Optional[str] = None,
caption: Optional[str] = None,
reply_markup: Optional[InlineKeyboardMarkup] = None,
input_message_content: Optional["InputMessageContent"] = None,
mpeg4_duration: Optional[TimePeriod] = None,
parse_mode: ODVInput[str] = DEFAULT_NONE,
caption_entities: Optional[Sequence[MessageEntity]] = None,
thumbnail_mime_type: Optional[str] = None,
show_caption_above_media: Optional[bool] = None,
*,
api_kwargs: Optional[JSONDict] = None,
):
# Required
super().__init__(InlineQueryResultType.MPEG4GIF, id, api_kwargs=api_kwargs)
with self._unfrozen():
self.mpeg4_url: str = mpeg4_url
self.thumbnail_url: str = thumbnail_url
# Optional
self.mpeg4_width: Optional[int] = mpeg4_width
self.mpeg4_height: Optional[int] = mpeg4_height
self._mpeg4_duration: Optional[dtm.timedelta] = to_timedelta(mpeg4_duration)
self.title: Optional[str] = title
self.caption: Optional[str] = caption
self.parse_mode: ODVInput[str] = parse_mode
self.caption_entities: tuple[MessageEntity, ...] = parse_sequence_arg(caption_entities)
self.reply_markup: Optional[InlineKeyboardMarkup] = reply_markup
self.input_message_content: Optional[InputMessageContent] = input_message_content
self.thumbnail_mime_type: Optional[str] = thumbnail_mime_type
self.show_caption_above_media: Optional[bool] = show_caption_above_media
@property
def mpeg4_duration(self) -> Optional[Union[int, dtm.timedelta]]:
return get_timedelta_value(self._mpeg4_duration, attribute="mpeg4_duration")

View File

@@ -0,0 +1,161 @@
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2025
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser Public License for more details.
#
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains the classes that represent Telegram InlineQueryResultPhoto."""
from collections.abc import Sequence
from typing import TYPE_CHECKING, Optional
from telegram._inline.inlinekeyboardmarkup import InlineKeyboardMarkup
from telegram._inline.inlinequeryresult import InlineQueryResult
from telegram._messageentity import MessageEntity
from telegram._utils.argumentparsing import parse_sequence_arg
from telegram._utils.defaultvalue import DEFAULT_NONE
from telegram._utils.types import JSONDict, ODVInput
from telegram.constants import InlineQueryResultType
if TYPE_CHECKING:
from telegram import InputMessageContent
class InlineQueryResultPhoto(InlineQueryResult):
"""
Represents a link to a photo. By default, this photo will be sent by the user with optional
caption. Alternatively, you can use :attr:`input_message_content` to send a message with the
specified content instead of the photo.
.. seealso:: :wiki:`Working with Files and Media <Working-with-Files-and-Media>`
.. versionchanged:: 20.5
|removed_thumb_url_note|
Args:
id (:obj:`str`): Unique identifier for this result,
:tg-const:`telegram.InlineQueryResult.MIN_ID_LENGTH`-
:tg-const:`telegram.InlineQueryResult.MAX_ID_LENGTH` Bytes.
photo_url (:obj:`str`): A valid URL of the photo. Photo must be in JPEG format. Photo size
must not exceed 5MB.
thumbnail_url (:obj:`str`): URL of the thumbnail for the photo.
.. versionadded:: 20.2
..versionchanged:: 20.5
|thumbnail_url_mandatory|
photo_width (:obj:`int`, optional): Width of the photo.
photo_height (:obj:`int`, optional): Height of the photo.
title (:obj:`str`, optional): Title for the result.
description (:obj:`str`, optional): Short description of the result.
caption (:obj:`str`, optional): Caption of the photo to be sent,
0-:tg-const:`telegram.constants.MessageLimit.CAPTION_LENGTH` characters after
entities parsing.
parse_mode (:obj:`str`, optional): |parse_mode|
caption_entities (Sequence[:class:`telegram.MessageEntity`], optional): |caption_entities|
.. versionchanged:: 20.0
|sequenceclassargs|
reply_markup (:class:`telegram.InlineKeyboardMarkup`, optional): Inline keyboard attached
to the message.
input_message_content (:class:`telegram.InputMessageContent`, optional): Content of the
message to be sent instead of the photo.
show_caption_above_media (:obj:`bool`, optional): Pass |show_cap_above_med|
.. versionadded:: 21.3
Attributes:
type (:obj:`str`): :tg-const:`telegram.constants.InlineQueryResultType.PHOTO`.
id (:obj:`str`): Unique identifier for this result,
:tg-const:`telegram.InlineQueryResult.MIN_ID_LENGTH`-
:tg-const:`telegram.InlineQueryResult.MAX_ID_LENGTH` Bytes.
photo_url (:obj:`str`): A valid URL of the photo. Photo must be in JPEG format. Photo size
must not exceed 5MB.
thumbnail_url (:obj:`str`): URL of the thumbnail for the photo.
photo_width (:obj:`int`): Optional. Width of the photo.
photo_height (:obj:`int`): Optional. Height of the photo.
title (:obj:`str`): Optional. Title for the result.
description (:obj:`str`): Optional. Short description of the result.
caption (:obj:`str`): Optional. Caption of the photo to be sent,
0-:tg-const:`telegram.constants.MessageLimit.CAPTION_LENGTH` characters after
entities parsing.
parse_mode (:obj:`str`): Optional. |parse_mode|
caption_entities (tuple[:class:`telegram.MessageEntity`]): Optional. |captionentitiesattr|
.. versionchanged:: 20.0
* |tupleclassattrs|
* |alwaystuple|
reply_markup (:class:`telegram.InlineKeyboardMarkup`): Optional. Inline keyboard attached
to the message.
input_message_content (:class:`telegram.InputMessageContent`): Optional. Content of the
message to be sent instead of the photo.
show_caption_above_media (:obj:`bool`): Optional. |show_cap_above_med|
.. versionadded:: 21.3
"""
__slots__ = (
"caption",
"caption_entities",
"description",
"input_message_content",
"parse_mode",
"photo_height",
"photo_url",
"photo_width",
"reply_markup",
"show_caption_above_media",
"thumbnail_url",
"title",
)
def __init__(
self,
id: str, # pylint: disable=redefined-builtin
photo_url: str,
thumbnail_url: str,
photo_width: Optional[int] = None,
photo_height: Optional[int] = None,
title: Optional[str] = None,
description: Optional[str] = None,
caption: Optional[str] = None,
reply_markup: Optional[InlineKeyboardMarkup] = None,
input_message_content: Optional["InputMessageContent"] = None,
parse_mode: ODVInput[str] = DEFAULT_NONE,
caption_entities: Optional[Sequence[MessageEntity]] = None,
show_caption_above_media: Optional[bool] = None,
*,
api_kwargs: Optional[JSONDict] = None,
):
# Required
super().__init__(InlineQueryResultType.PHOTO, id, api_kwargs=api_kwargs)
with self._unfrozen():
self.photo_url: str = photo_url
self.thumbnail_url: str = thumbnail_url
# Optionals
self.photo_width: Optional[int] = photo_width
self.photo_height: Optional[int] = photo_height
self.title: Optional[str] = title
self.description: Optional[str] = description
self.caption: Optional[str] = caption
self.parse_mode: ODVInput[str] = parse_mode
self.caption_entities: tuple[MessageEntity, ...] = parse_sequence_arg(caption_entities)
self.reply_markup: Optional[InlineKeyboardMarkup] = reply_markup
self.input_message_content: Optional[InputMessageContent] = input_message_content
self.show_caption_above_media: Optional[bool] = show_caption_above_media

View File

@@ -0,0 +1,116 @@
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2025
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser Public License for more details.
#
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains the class that represent a Telegram InlineQueryResultsButton."""
from typing import TYPE_CHECKING, Final, Optional
from telegram import constants
from telegram._telegramobject import TelegramObject
from telegram._utils.argumentparsing import de_json_optional
from telegram._utils.types import JSONDict
from telegram._webappinfo import WebAppInfo
if TYPE_CHECKING:
from telegram import Bot
class InlineQueryResultsButton(TelegramObject):
"""This object represents a button to be shown above inline query results. You **must** use
exactly one of the optional fields.
Objects of this class are comparable in terms of equality. Two objects of this class are
considered equal, if their :attr:`text`, :attr:`web_app` and :attr:`start_parameter` are equal.
Args:
text (:obj:`str`): Label text on the button.
web_app (:class:`telegram.WebAppInfo`, optional): Description of the
`Web App <https://core.telegram.org/bots/webapps>`_ that will be launched when the
user presses the button. The Web App will be able to switch back to the inline mode
using the method
`switchInlineQuery <https://core.telegram.org/bots/webapps#initializing-mini-apps>`_
inside the Web App.
start_parameter (:obj:`str`, optional): Deep-linking parameter for the
:guilabel:`/start` message sent to the bot when user presses the switch button.
:tg-const:`telegram.constants.InlineQueryResultsButtonLimit.MIN_START_PARAMETER_LENGTH`
-
:tg-const:`telegram.constants.InlineQueryResultsButtonLimit.MAX_START_PARAMETER_LENGTH`
characters, only ``A-Z``, ``a-z``, ``0-9``, ``_`` and ``-`` are allowed.
Example:
An inline bot that sends YouTube videos can ask the user to connect the bot to
their YouTube account to adapt search results accordingly. To do this, it displays
a 'Connect your YouTube account' button above the results, or even before showing
any. The user presses the button, switches to a private chat with the bot and, in
doing so, passes a start parameter that instructs the bot to return an OAuth link.
Once done, the bot can offer a switch_inline button so that the user can easily
return to the chat where they wanted to use the bot's inline capabilities.
Attributes:
text (:obj:`str`): Label text on the button.
web_app (:class:`telegram.WebAppInfo`): Optional. Description of the
`Web App <https://core.telegram.org/bots/webapps>`_ that will be launched when the
user presses the button. The Web App will be able to switch back to the inline mode
using the method ``web_app_switch_inline_query`` inside the Web App.
start_parameter (:obj:`str`): Optional. Deep-linking parameter for the
:tg-const:`telegram.constants.InlineQueryResultsButtonLimit.MIN_START_PARAMETER_LENGTH`
-
:tg-const:`telegram.constants.InlineQueryResultsButtonLimit.MAX_START_PARAMETER_LENGTH`
characters, only ``A-Z``, ``a-z``, ``0-9``, ``_`` and ``-`` are allowed.
"""
__slots__ = ("start_parameter", "text", "web_app")
def __init__(
self,
text: str,
web_app: Optional[WebAppInfo] = None,
start_parameter: Optional[str] = None,
*,
api_kwargs: Optional[JSONDict] = None,
):
super().__init__(api_kwargs=api_kwargs)
# Required
self.text: str = text
# Optional
self.web_app: Optional[WebAppInfo] = web_app
self.start_parameter: Optional[str] = start_parameter
self._id_attrs = (self.text, self.web_app, self.start_parameter)
self._freeze()
@classmethod
def de_json(cls, data: JSONDict, bot: Optional["Bot"] = None) -> "InlineQueryResultsButton":
"""See :meth:`telegram.TelegramObject.de_json`."""
data["web_app"] = de_json_optional(data.get("web_app"), WebAppInfo, bot)
return super().de_json(data=data, bot=bot)
MIN_START_PARAMETER_LENGTH: Final[int] = (
constants.InlineQueryResultsButtonLimit.MIN_START_PARAMETER_LENGTH
)
""":const:`telegram.constants.InlineQueryResultsButtonLimit.MIN_START_PARAMETER_LENGTH`"""
MAX_START_PARAMETER_LENGTH: Final[int] = (
constants.InlineQueryResultsButtonLimit.MAX_START_PARAMETER_LENGTH
)
""":const:`telegram.constants.InlineQueryResultsButtonLimit.MAX_START_PARAMETER_LENGTH`"""

View File

@@ -0,0 +1,160 @@
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2025
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser Public License for more details.
#
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains the classes that represent Telegram InlineQueryResultVenue."""
from typing import TYPE_CHECKING, Optional
from telegram._inline.inlinekeyboardmarkup import InlineKeyboardMarkup
from telegram._inline.inlinequeryresult import InlineQueryResult
from telegram._utils.types import JSONDict
from telegram.constants import InlineQueryResultType
if TYPE_CHECKING:
from telegram import InputMessageContent
class InlineQueryResultVenue(InlineQueryResult):
"""
Represents a venue. By default, the venue will be sent by the user. Alternatively, you can
use :attr:`input_message_content` to send a message with the specified content instead of the
venue.
Note:
Foursquare details and Google Pace details are mutually exclusive. However, this
behaviour is undocumented and might be changed by Telegram.
.. versionchanged:: 20.5
|removed_thumb_wildcard_note|
Args:
id (:obj:`str`): Unique identifier for this result,
:tg-const:`telegram.InlineQueryResult.MIN_ID_LENGTH`-
:tg-const:`telegram.InlineQueryResult.MAX_ID_LENGTH` Bytes.
latitude (:obj:`float`): Latitude of the venue location in degrees.
longitude (:obj:`float`): Longitude of the venue location in degrees.
title (:obj:`str`): Title of the venue.
address (:obj:`str`): Address of the venue.
foursquare_id (:obj:`str`, optional): Foursquare identifier of the venue if known.
foursquare_type (:obj:`str`, optional): Foursquare type of the venue, if known.
(For example, "arts_entertainment/default", "arts_entertainment/aquarium" or
"food/icecream".)
google_place_id (:obj:`str`, optional): Google Places identifier of the venue.
google_place_type (:obj:`str`, optional): Google Places type of the venue. (See
`supported types <https://developers.google.com/maps/documentation/places/web-service\
/supported_types>`_.)
reply_markup (:class:`telegram.InlineKeyboardMarkup`, optional): Inline keyboard attached
to the message.
input_message_content (:class:`telegram.InputMessageContent`, optional): Content of the
message to be sent instead of the venue.
thumbnail_url (:obj:`str`, optional): Url of the thumbnail for the result.
.. versionadded:: 20.2
thumbnail_width (:obj:`int`, optional): Thumbnail width.
.. versionadded:: 20.2
thumbnail_height (:obj:`int`, optional): Thumbnail height.
.. versionadded:: 20.2
Attributes:
type (:obj:`str`): :tg-const:`telegram.constants.InlineQueryResultType.VENUE`.
id (:obj:`str`): Unique identifier for this result,
:tg-const:`telegram.InlineQueryResult.MIN_ID_LENGTH`-
:tg-const:`telegram.InlineQueryResult.MAX_ID_LENGTH` Bytes.
latitude (:obj:`float`): Latitude of the venue location in degrees.
longitude (:obj:`float`): Longitude of the venue location in degrees.
title (:obj:`str`): Title of the venue.
address (:obj:`str`): Address of the venue.
foursquare_id (:obj:`str`): Optional. Foursquare identifier of the venue if known.
foursquare_type (:obj:`str`): Optional. Foursquare type of the venue, if known.
(For example, "arts_entertainment/default", "arts_entertainment/aquarium" or
"food/icecream".)
google_place_id (:obj:`str`): Optional. Google Places identifier of the venue.
google_place_type (:obj:`str`): Optional. Google Places type of the venue. (See
`supported types <https://developers.google.com/maps/documentation/places/web-service\
/supported_types>`_.)
reply_markup (:class:`telegram.InlineKeyboardMarkup`): Optional. Inline keyboard attached
to the message.
input_message_content (:class:`telegram.InputMessageContent`): Optional. Content of the
message to be sent instead of the venue.
thumbnail_url (:obj:`str`): Optional. Url of the thumbnail for the result.
.. versionadded:: 20.2
thumbnail_width (:obj:`int`): Optional. Thumbnail width.
.. versionadded:: 20.2
thumbnail_height (:obj:`int`): Optional. Thumbnail height.
.. versionadded:: 20.2
"""
__slots__ = (
"address",
"foursquare_id",
"foursquare_type",
"google_place_id",
"google_place_type",
"input_message_content",
"latitude",
"longitude",
"reply_markup",
"thumbnail_height",
"thumbnail_url",
"thumbnail_width",
"title",
)
def __init__(
self,
id: str, # pylint: disable=redefined-builtin
latitude: float,
longitude: float,
title: str,
address: str,
foursquare_id: Optional[str] = None,
foursquare_type: Optional[str] = None,
reply_markup: Optional[InlineKeyboardMarkup] = None,
input_message_content: Optional["InputMessageContent"] = None,
google_place_id: Optional[str] = None,
google_place_type: Optional[str] = None,
thumbnail_url: Optional[str] = None,
thumbnail_width: Optional[int] = None,
thumbnail_height: Optional[int] = None,
*,
api_kwargs: Optional[JSONDict] = None,
):
# Required
super().__init__(InlineQueryResultType.VENUE, id, api_kwargs=api_kwargs)
with self._unfrozen():
self.latitude: float = latitude
self.longitude: float = longitude
self.title: str = title
self.address: str = address
# Optional
self.foursquare_id: Optional[str] = foursquare_id
self.foursquare_type: Optional[str] = foursquare_type
self.google_place_id: Optional[str] = google_place_id
self.google_place_type: Optional[str] = google_place_type
self.reply_markup: Optional[InlineKeyboardMarkup] = reply_markup
self.input_message_content: Optional[InputMessageContent] = input_message_content
self.thumbnail_url: Optional[str] = thumbnail_url
self.thumbnail_width: Optional[int] = thumbnail_width
self.thumbnail_height: Optional[int] = thumbnail_height

View File

@@ -0,0 +1,196 @@
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2025
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser Public License for more details.
#
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains the classes that represent Telegram InlineQueryResultVideo."""
import datetime as dtm
from collections.abc import Sequence
from typing import TYPE_CHECKING, Optional, Union
from telegram._inline.inlinekeyboardmarkup import InlineKeyboardMarkup
from telegram._inline.inlinequeryresult import InlineQueryResult
from telegram._messageentity import MessageEntity
from telegram._utils.argumentparsing import parse_sequence_arg, to_timedelta
from telegram._utils.datetime import get_timedelta_value
from telegram._utils.defaultvalue import DEFAULT_NONE
from telegram._utils.types import JSONDict, ODVInput, TimePeriod
from telegram.constants import InlineQueryResultType
if TYPE_CHECKING:
from telegram import InputMessageContent
class InlineQueryResultVideo(InlineQueryResult):
"""
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
:attr:`input_message_content` to send a message with the specified content instead of
the video.
Note:
If an InlineQueryResultVideo message contains an embedded video (e.g., YouTube), you must
replace its content using :attr:`input_message_content`.
.. seealso:: :wiki:`Working with Files and Media <Working-with-Files-and-Media>`
.. versionchanged:: 20.5
|removed_thumb_url_note|
Args:
id (:obj:`str`): Unique identifier for this result,
:tg-const:`telegram.InlineQueryResult.MIN_ID_LENGTH`-
:tg-const:`telegram.InlineQueryResult.MAX_ID_LENGTH` Bytes.
video_url (:obj:`str`): A valid URL for the embedded video player or video file.
mime_type (:obj:`str`): Mime type of the content of video url, "text/html" or "video/mp4".
thumbnail_url (:obj:`str`, optional): URL of the thumbnail (JPEG only) for the video.
.. versionadded:: 20.2
..versionchanged:: 20.5
|thumbnail_url_mandatory|
title (:obj:`str`): Title for the result.
caption (:obj:`str`, optional): Caption of the video to be sent,
0-:tg-const:`telegram.constants.MessageLimit.CAPTION_LENGTH` characters after entities
parsing.
parse_mode (:obj:`str`, optional): |parse_mode|
caption_entities (Sequence[:class:`telegram.MessageEntity`], optional): |caption_entities|
.. versionchanged:: 20.0
|sequenceclassargs|
video_width (:obj:`int`, optional): Video width.
video_height (:obj:`int`, optional): Video height.
video_duration (:obj:`int` | :class:`datetime.timedelta`, optional): Video duration
in seconds.
.. versionchanged:: v22.2
|time-period-input|
description (:obj:`str`, optional): Short description of the result.
reply_markup (:class:`telegram.InlineKeyboardMarkup`, optional): Inline keyboard attached
to the message.
input_message_content (:class:`telegram.InputMessageContent`, optional): 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).
show_caption_above_media (:obj:`bool`, optional): Pass |show_cap_above_med|
.. versionadded:: 21.3
Attributes:
type (:obj:`str`): :tg-const:`telegram.constants.InlineQueryResultType.VIDEO`.
id (:obj:`str`): Unique identifier for this result,
:tg-const:`telegram.InlineQueryResult.MIN_ID_LENGTH`-
:tg-const:`telegram.InlineQueryResult.MAX_ID_LENGTH` Bytes.
video_url (:obj:`str`): A valid URL for the embedded video player or video file.
mime_type (:obj:`str`): Mime type of the content of video url, "text/html" or "video/mp4".
thumbnail_url (:obj:`str`): URL of the thumbnail (JPEG only) for the video.
.. versionadded:: 20.2
title (:obj:`str`): Title for the result.
caption (:obj:`str`): Optional. Caption of the video to be sent,
0-:tg-const:`telegram.constants.MessageLimit.CAPTION_LENGTH` characters after entities
parsing.
parse_mode (:obj:`str`): Optional. |parse_mode|
caption_entities (tuple[:class:`telegram.MessageEntity`]): Optional.
|captionentitiesattr|
.. versionchanged:: 20.0
* |tupleclassattrs|
* |alwaystuple|
video_width (:obj:`int`): Optional. Video width.
video_height (:obj:`int`): Optional. Video height.
video_duration (:obj:`int` | :class:`datetime.timedelta`): Optional. Video duration
in seconds.
.. deprecated:: v22.2
|time-period-int-deprecated|
description (:obj:`str`): Optional. Short description of the result.
reply_markup (:class:`telegram.InlineKeyboardMarkup`): Optional. Inline keyboard attached
to the message.
input_message_content (:class:`telegram.InputMessageContent`): Optional. 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).
show_caption_above_media (:obj:`bool`): Optional. |show_cap_above_med|
.. versionadded:: 21.3
"""
__slots__ = (
"_video_duration",
"caption",
"caption_entities",
"description",
"input_message_content",
"mime_type",
"parse_mode",
"reply_markup",
"show_caption_above_media",
"thumbnail_url",
"title",
"video_height",
"video_url",
"video_width",
)
def __init__(
self,
id: str, # pylint: disable=redefined-builtin
video_url: str,
mime_type: str,
thumbnail_url: str,
title: str,
caption: Optional[str] = None,
video_width: Optional[int] = None,
video_height: Optional[int] = None,
video_duration: Optional[TimePeriod] = None,
description: Optional[str] = None,
reply_markup: Optional[InlineKeyboardMarkup] = None,
input_message_content: Optional["InputMessageContent"] = None,
parse_mode: ODVInput[str] = DEFAULT_NONE,
caption_entities: Optional[Sequence[MessageEntity]] = None,
show_caption_above_media: Optional[bool] = None,
*,
api_kwargs: Optional[JSONDict] = None,
):
# Required
super().__init__(InlineQueryResultType.VIDEO, id, api_kwargs=api_kwargs)
with self._unfrozen():
self.video_url: str = video_url
self.mime_type: str = mime_type
self.thumbnail_url: str = thumbnail_url
self.title: str = title
# Optional
self.caption: Optional[str] = caption
self.parse_mode: ODVInput[str] = parse_mode
self.caption_entities: tuple[MessageEntity, ...] = parse_sequence_arg(caption_entities)
self.video_width: Optional[int] = video_width
self.video_height: Optional[int] = video_height
self._video_duration: Optional[dtm.timedelta] = to_timedelta(video_duration)
self.description: Optional[str] = description
self.reply_markup: Optional[InlineKeyboardMarkup] = reply_markup
self.input_message_content: Optional[InputMessageContent] = input_message_content
self.show_caption_above_media: Optional[bool] = show_caption_above_media
@property
def video_duration(self) -> Optional[Union[int, dtm.timedelta]]:
return get_timedelta_value(self._video_duration, attribute="video_duration")

View File

@@ -0,0 +1,141 @@
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2025
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser Public License for more details.
#
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains the classes that represent Telegram InlineQueryResultVoice."""
import datetime as dtm
from collections.abc import Sequence
from typing import TYPE_CHECKING, Optional, Union
from telegram._inline.inlinekeyboardmarkup import InlineKeyboardMarkup
from telegram._inline.inlinequeryresult import InlineQueryResult
from telegram._messageentity import MessageEntity
from telegram._utils.argumentparsing import parse_sequence_arg, to_timedelta
from telegram._utils.datetime import get_timedelta_value
from telegram._utils.defaultvalue import DEFAULT_NONE
from telegram._utils.types import JSONDict, ODVInput, TimePeriod
from telegram.constants import InlineQueryResultType
if TYPE_CHECKING:
from telegram import InputMessageContent
class InlineQueryResultVoice(InlineQueryResult):
"""
Represents a link to a voice recording in an .ogg container encoded with OPUS. By default,
this voice recording will be sent by the user. Alternatively, you can use
:attr:`input_message_content` to send a message with the specified content instead of
the voice message.
.. seealso:: :wiki:`Working with Files and Media <Working-with-Files-and-Media>`
Args:
id (:obj:`str`): Unique identifier for this result,
:tg-const:`telegram.InlineQueryResult.MIN_ID_LENGTH`-
:tg-const:`telegram.InlineQueryResult.MAX_ID_LENGTH` Bytes.
voice_url (:obj:`str`): A valid URL for the voice recording.
title (:obj:`str`): Recording title.
caption (:obj:`str`, optional): Caption,
0-:tg-const:`telegram.constants.MessageLimit.CAPTION_LENGTH` characters after entities
parsing.
parse_mode (:obj:`str`, optional): |parse_mode|
caption_entities (Sequence[:class:`telegram.MessageEntity`], optional): |caption_entities|
.. versionchanged:: 20.0
|sequenceclassargs|
voice_duration (:obj:`int` | :class:`datetime.timedelta`, optional): Recording duration
in seconds.
.. versionchanged:: v22.2
|time-period-input|
reply_markup (:class:`telegram.InlineKeyboardMarkup`, optional): Inline keyboard attached
to the message.
input_message_content (:class:`telegram.InputMessageContent`, optional): Content of the
message to be sent instead of the voice recording.
Attributes:
type (:obj:`str`): :tg-const:`telegram.constants.InlineQueryResultType.VOICE`.
id (:obj:`str`): Unique identifier for this result,
:tg-const:`telegram.InlineQueryResult.MIN_ID_LENGTH`-
:tg-const:`telegram.InlineQueryResult.MAX_ID_LENGTH` Bytes.
voice_url (:obj:`str`): A valid URL for the voice recording.
title (:obj:`str`): Recording title.
caption (:obj:`str`): Optional. Caption,
0-:tg-const:`telegram.constants.MessageLimit.CAPTION_LENGTH` characters after entities
parsing.
parse_mode (:obj:`str`): Optional. |parse_mode|
caption_entities (tuple[:class:`telegram.MessageEntity`]): Optional. |captionentitiesattr|
.. versionchanged:: 20.0
* |tupleclassattrs|
* |alwaystuple|
voice_duration (:obj:`int` | :class:`datetime.timedelta`): Optional. Recording duration
in seconds.
.. deprecated:: v22.2
|time-period-int-deprecated|
reply_markup (:class:`telegram.InlineKeyboardMarkup`): Optional. Inline keyboard attached
to the message.
input_message_content (:class:`telegram.InputMessageContent`): Optional. Content of the
message to be sent instead of the voice recording.
"""
__slots__ = (
"_voice_duration",
"caption",
"caption_entities",
"input_message_content",
"parse_mode",
"reply_markup",
"title",
"voice_url",
)
def __init__(
self,
id: str, # pylint: disable=redefined-builtin
voice_url: str,
title: str,
voice_duration: Optional[TimePeriod] = None,
caption: Optional[str] = None,
reply_markup: Optional[InlineKeyboardMarkup] = None,
input_message_content: Optional["InputMessageContent"] = None,
parse_mode: ODVInput[str] = DEFAULT_NONE,
caption_entities: Optional[Sequence[MessageEntity]] = None,
*,
api_kwargs: Optional[JSONDict] = None,
):
# Required
super().__init__(InlineQueryResultType.VOICE, id, api_kwargs=api_kwargs)
with self._unfrozen():
self.voice_url: str = voice_url
self.title: str = title
# Optional
self._voice_duration: Optional[dtm.timedelta] = to_timedelta(voice_duration)
self.caption: Optional[str] = caption
self.parse_mode: ODVInput[str] = parse_mode
self.caption_entities: tuple[MessageEntity, ...] = parse_sequence_arg(caption_entities)
self.reply_markup: Optional[InlineKeyboardMarkup] = reply_markup
self.input_message_content: Optional[InputMessageContent] = input_message_content
@property
def voice_duration(self) -> Optional[Union[int, dtm.timedelta]]:
return get_timedelta_value(self._voice_duration, attribute="voice_duration")

View File

@@ -0,0 +1,68 @@
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2025
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser Public License for more details.
#
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains the classes that represent Telegram InputContactMessageContent."""
from typing import Optional
from telegram._inline.inputmessagecontent import InputMessageContent
from telegram._utils.types import JSONDict
class InputContactMessageContent(InputMessageContent):
"""Represents the content of a contact message to be sent as the result of an inline query.
Objects of this class are comparable in terms of equality. Two objects of this class are
considered equal, if their :attr:`phone_number` is equal.
Args:
phone_number (:obj:`str`): Contact's phone number.
first_name (:obj:`str`): Contact's first name.
last_name (:obj:`str`, optional): Contact's last name.
vcard (:obj:`str`, optional): Additional data about the contact in the form of a vCard,
0-:tg-const:`telegram.constants.ContactLimit.VCARD` bytes.
Attributes:
phone_number (:obj:`str`): Contact's phone number.
first_name (:obj:`str`): Contact's first name.
last_name (:obj:`str`): Optional. Contact's last name.
vcard (:obj:`str`): Optional. Additional data about the contact in the form of a vCard,
0-:tg-const:`telegram.constants.ContactLimit.VCARD` bytes.
"""
__slots__ = ("first_name", "last_name", "phone_number", "vcard")
def __init__(
self,
phone_number: str,
first_name: str,
last_name: Optional[str] = None,
vcard: Optional[str] = None,
*,
api_kwargs: Optional[JSONDict] = None,
):
super().__init__(api_kwargs=api_kwargs)
with self._unfrozen():
# Required
self.phone_number: str = phone_number
self.first_name: str = first_name
# Optionals
self.last_name: Optional[str] = last_name
self.vcard: Optional[str] = vcard
self._id_attrs = (self.phone_number,)

View File

@@ -0,0 +1,264 @@
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2025
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser Public License for more details.
#
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains a class that represents a Telegram InputInvoiceMessageContent."""
from collections.abc import Sequence
from typing import TYPE_CHECKING, Optional
from telegram._inline.inputmessagecontent import InputMessageContent
from telegram._payment.labeledprice import LabeledPrice
from telegram._utils.argumentparsing import de_list_optional, parse_sequence_arg
from telegram._utils.types import JSONDict
if TYPE_CHECKING:
from telegram import Bot
class InputInvoiceMessageContent(InputMessageContent):
"""
Represents the content of a invoice message to be sent as the result of an inline query.
Objects of this class are comparable in terms of equality. Two objects of this class are
considered equal, if their :attr:`title`, :attr:`description`, :attr:`payload`,
:attr:`currency` and :attr:`prices` are equal.
.. versionadded:: 13.5
.. versionchanged:: 21.11
:attr:`provider_token` is no longer considered for equality comparison.
Args:
title (:obj:`str`): Product name. :tg-const:`telegram.Invoice.MIN_TITLE_LENGTH`-
:tg-const:`telegram.Invoice.MAX_TITLE_LENGTH` characters.
description (:obj:`str`): Product description.
:tg-const:`telegram.Invoice.MIN_DESCRIPTION_LENGTH`-
:tg-const:`telegram.Invoice.MAX_DESCRIPTION_LENGTH` characters.
payload (:obj:`str`): Bot-defined invoice payload.
:tg-const:`telegram.Invoice.MIN_PAYLOAD_LENGTH`-
:tg-const:`telegram.Invoice.MAX_PAYLOAD_LENGTH` bytes. This will not be displayed
to the user, use it for your internal processes.
provider_token (:obj:`str`, optional): Payment provider token, obtained via
`@Botfather <https://t.me/Botfather>`_. Pass an empty string for payments in
|tg_stars|.
.. versionchanged:: 21.11
Bot API 7.4 made this parameter is optional and this is now reflected in the
class signature.
currency (:obj:`str`): Three-letter ISO 4217 currency code, see more on
`currencies <https://core.telegram.org/bots/payments#supported-currencies>`_.
Pass ``XTR`` for payments in |tg_stars|.
prices (Sequence[:class:`telegram.LabeledPrice`]): Price breakdown, a list of
components (e.g. product price, tax, discount, delivery cost, delivery tax, bonus,
etc.). Must contain exactly one item for payments in |tg_stars|.
.. versionchanged:: 20.0
|sequenceclassargs|
max_tip_amount (:obj:`int`, optional): The maximum accepted amount for tips in the
*smallest units* of the currency (integer, **not** float/double). For example, for a
maximum tip of ``US$ 1.45`` pass ``max_tip_amount = 145``. See the ``exp`` parameter in
`currencies.json <https://core.telegram.org/bots/payments/currencies.json>`_, it
shows the number of digits past the decimal point for each currency (2 for the majority
of currencies). Defaults to ``0``. Not supported for payments in |tg_stars|.
suggested_tip_amounts (Sequence[:obj:`int`], optional): An array of suggested
amounts of tip in the *smallest units* of the currency (integer, **not** float/double).
At most 4 suggested tip amounts can be specified. The suggested tip amounts must be
positive, passed in a strictly increased order and must not exceed
:attr:`max_tip_amount`.
.. versionchanged:: 20.0
* |tupleclassattrs|
* |alwaystuple|
provider_data (:obj:`str`, optional): An object for data about the invoice,
which will be shared with the payment provider. A detailed description of the required
fields should be provided by the payment provider.
photo_url (:obj:`str`, optional): URL of the product photo for the invoice. Can be a photo
of the goods or a marketing image for a service. People like it better when they see
what they are paying for.
photo_size (:obj:`int`, optional): Photo size.
photo_width (:obj:`int`, optional): Photo width.
photo_height (:obj:`int`, optional): Photo height.
need_name (:obj:`bool`, optional): Pass :obj:`True`, if you require the user's full
name to complete the order. Ignored for payments in |tg_stars|.
need_phone_number (:obj:`bool`, optional): Pass :obj:`True`, if you require the user's
phone number to complete the order. Ignored for payments in |tg_stars|.
need_email (:obj:`bool`, optional): Pass :obj:`True`, if you require the user's email
address to complete the order. Ignored for payments in |tg_stars|.
need_shipping_address (:obj:`bool`, optional): Pass :obj:`True`, if you require the
user's shipping address to complete the order. Ignored for payments in |tg_stars|
send_phone_number_to_provider (:obj:`bool`, optional): Pass :obj:`True`, if user's
phone number should be sent to provider. Ignored for payments in |tg_stars|.
send_email_to_provider (:obj:`bool`, optional): Pass :obj:`True`, if user's email
address should be sent to provider. Ignored for payments in |tg_stars|.
is_flexible (:obj:`bool`, optional): Pass :obj:`True`, if the final price depends on
the shipping method. Ignored for payments in |tg_stars|.
Attributes:
title (:obj:`str`): Product name. :tg-const:`telegram.Invoice.MIN_TITLE_LENGTH`-
:tg-const:`telegram.Invoice.MAX_TITLE_LENGTH` characters.
description (:obj:`str`): Product description.
:tg-const:`telegram.Invoice.MIN_DESCRIPTION_LENGTH`-
:tg-const:`telegram.Invoice.MAX_DESCRIPTION_LENGTH` characters.
payload (:obj:`str`): Bot-defined invoice payload.
:tg-const:`telegram.Invoice.MIN_PAYLOAD_LENGTH`-
:tg-const:`telegram.Invoice.MAX_PAYLOAD_LENGTH` bytes. This will not be displayed
to the user, use it for your internal processes.
provider_token (:obj:`str`): Payment provider token, obtained via
`@Botfather <https://t.me/Botfather>`_. Pass an empty string for payments in `Telegram
Stars <https://t.me/BotNews/90>`_.
currency (:obj:`str`): Three-letter ISO 4217 currency code, see more on
`currencies <https://core.telegram.org/bots/payments#supported-currencies>`_.
Pass ``XTR`` for payments in |tg_stars|.
prices (tuple[:class:`telegram.LabeledPrice`]): Price breakdown, a list of
components (e.g. product price, tax, discount, delivery cost, delivery tax, bonus,
etc.). Must contain exactly one item for payments in |tg_stars|.
.. versionchanged:: 20.0
|tupleclassattrs|
max_tip_amount (:obj:`int`): Optional. The maximum accepted amount for tips in the
*smallest units* of the currency (integer, **not** float/double). For example, for a
maximum tip of ``US$ 1.45`` ``max_tip_amount`` is ``145``. See the ``exp`` parameter in
`currencies.json <https://core.telegram.org/bots/payments/currencies.json>`_, it
shows the number of digits past the decimal point for each currency (2 for the majority
of currencies). Defaults to ``0``. Not supported for payments in |tg_stars|.
suggested_tip_amounts (tuple[:obj:`int`]): Optional. An array of suggested
amounts of tip in the *smallest units* of the currency (integer, **not** float/double).
At most 4 suggested tip amounts can be specified. The suggested tip amounts must be
positive, passed in a strictly increased order and must not exceed
:attr:`max_tip_amount`.
.. versionchanged:: 20.0
|tupleclassattrs|
provider_data (:obj:`str`): Optional. An object for data about the invoice,
which will be shared with the payment provider. A detailed description of the required
fields should be provided by the payment provider.
photo_url (:obj:`str`): Optional. URL of the product photo for the invoice. Can be a photo
of the goods or a marketing image for a service. People like it better when they see
what they are paying for.
photo_size (:obj:`int`): Optional. Photo size.
photo_width (:obj:`int`): Optional. Photo width.
photo_height (:obj:`int`): Optional. Photo height.
need_name (:obj:`bool`): Optional. Pass :obj:`True`, if you require the user's full name to
complete the order. Ignored for payments in |tg_stars|.
need_phone_number (:obj:`bool`): Optional. Pass :obj:`True`, if you require the user's
phone number to complete the order. Ignored for payments in |tg_stars|.
need_email (:obj:`bool`): Optional. Pass :obj:`True`, if you require the user's email
address to complete the order. Ignored for payments in |tg_stars|.
need_shipping_address (:obj:`bool`): Optional. Pass :obj:`True`, if you require the user's
shipping address to complete the order. Ignored for payments in |tg_stars|.
send_phone_number_to_provider (:obj:`bool`): Optional. Pass :obj:`True`, if user's phone
number should be sent to provider. Ignored for payments in |tg_stars|.
send_email_to_provider (:obj:`bool`): Optional. Pass :obj:`True`, if user's email address
should be sent to provider. Ignored for payments in |tg_stars|.
is_flexible (:obj:`bool`): Optional. Pass :obj:`True`, if the final price depends on the
shipping method. Ignored for payments in |tg_stars|.
"""
__slots__ = (
"currency",
"description",
"is_flexible",
"max_tip_amount",
"need_email",
"need_name",
"need_phone_number",
"need_shipping_address",
"payload",
"photo_height",
"photo_size",
"photo_url",
"photo_width",
"prices",
"provider_data",
"provider_token",
"send_email_to_provider",
"send_phone_number_to_provider",
"suggested_tip_amounts",
"title",
)
def __init__(
self,
title: str,
description: str,
payload: str,
currency: str,
prices: Sequence[LabeledPrice],
provider_token: Optional[str] = None,
max_tip_amount: Optional[int] = None,
suggested_tip_amounts: Optional[Sequence[int]] = None,
provider_data: Optional[str] = None,
photo_url: Optional[str] = None,
photo_size: Optional[int] = None,
photo_width: Optional[int] = None,
photo_height: Optional[int] = None,
need_name: Optional[bool] = None,
need_phone_number: Optional[bool] = None,
need_email: Optional[bool] = None,
need_shipping_address: Optional[bool] = None,
send_phone_number_to_provider: Optional[bool] = None,
send_email_to_provider: Optional[bool] = None,
is_flexible: Optional[bool] = None,
*,
api_kwargs: Optional[JSONDict] = None,
):
super().__init__(api_kwargs=api_kwargs)
with self._unfrozen():
# Required
self.title: str = title
self.description: str = description
self.payload: str = payload
self.currency: str = currency
self.prices: tuple[LabeledPrice, ...] = parse_sequence_arg(prices)
# Optionals
self.provider_token: Optional[str] = provider_token
self.max_tip_amount: Optional[int] = max_tip_amount
self.suggested_tip_amounts: tuple[int, ...] = parse_sequence_arg(suggested_tip_amounts)
self.provider_data: Optional[str] = provider_data
self.photo_url: Optional[str] = photo_url
self.photo_size: Optional[int] = photo_size
self.photo_width: Optional[int] = photo_width
self.photo_height: Optional[int] = photo_height
self.need_name: Optional[bool] = need_name
self.need_phone_number: Optional[bool] = need_phone_number
self.need_email: Optional[bool] = need_email
self.need_shipping_address: Optional[bool] = need_shipping_address
self.send_phone_number_to_provider: Optional[bool] = send_phone_number_to_provider
self.send_email_to_provider: Optional[bool] = send_email_to_provider
self.is_flexible: Optional[bool] = is_flexible
self._id_attrs = (
self.title,
self.description,
self.payload,
self.currency,
self.prices,
)
@classmethod
def de_json(cls, data: JSONDict, bot: Optional["Bot"] = None) -> "InputInvoiceMessageContent":
"""See :meth:`telegram.TelegramObject.de_json`."""
data = cls._parse_data(data)
data["prices"] = de_list_optional(data.get("prices"), LabeledPrice, bot)
return super().de_json(data=data, bot=bot)

View File

@@ -0,0 +1,164 @@
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2025
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser Public License for more details.
#
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains the classes that represent Telegram InputLocationMessageContent."""
import datetime as dtm
from typing import Final, Optional, Union
from telegram import constants
from telegram._inline.inputmessagecontent import InputMessageContent
from telegram._utils.argumentparsing import to_timedelta
from telegram._utils.datetime import get_timedelta_value
from telegram._utils.types import JSONDict, TimePeriod
class InputLocationMessageContent(InputMessageContent):
# fmt: off
"""
Represents the content of a location message to be sent as the result of an inline query.
Objects of this class are comparable in terms of equality. Two objects of this class are
considered equal, if their :attr:`latitude` and :attr:`longitude` are equal.
Args:
latitude (:obj:`float`): Latitude of the location in degrees.
longitude (:obj:`float`): Longitude of the location in degrees.
horizontal_accuracy (:obj:`float`, optional): The radius of uncertainty for the location,
measured in meters; 0-
:tg-const:`telegram.InputLocationMessageContent.HORIZONTAL_ACCURACY`.
live_period (:obj:`int` | :class:`datetime.timedelta`, optional): Period in seconds for
which the location will be updated, should be between
:tg-const:`telegram.InputLocationMessageContent.MIN_LIVE_PERIOD` and
:tg-const:`telegram.InputLocationMessageContent.MAX_LIVE_PERIOD` or
:tg-const:`telegram.constants.LocationLimit.LIVE_PERIOD_FOREVER` for live
locations that can be edited indefinitely.
.. versionchanged:: v22.2
|time-period-input|
heading (:obj:`int`, optional): For live locations, a direction in which the user is
moving, in degrees. Must be between
:tg-const:`telegram.InputLocationMessageContent.MIN_HEADING` and
:tg-const:`telegram.InputLocationMessageContent.MAX_HEADING` if specified.
proximity_alert_radius (:obj:`int`, optional): For live locations, a maximum distance
for proximity alerts about approaching another chat member, in meters. Must be
between :tg-const:`telegram.InputLocationMessageContent.MIN_PROXIMITY_ALERT_RADIUS`
and :tg-const:`telegram.InputLocationMessageContent.MAX_PROXIMITY_ALERT_RADIUS`
if specified.
Attributes:
latitude (:obj:`float`): Latitude of the location in degrees.
longitude (:obj:`float`): Longitude of the location in degrees.
horizontal_accuracy (:obj:`float`): Optional. The radius of uncertainty for the location,
measured in meters; 0-
:tg-const:`telegram.InputLocationMessageContent.HORIZONTAL_ACCURACY`.
live_period (:obj:`int` | :class:`datetime.timedelta`): Optional. Period in seconds for
which the location can be updated, should be between
:tg-const:`telegram.InputLocationMessageContent.MIN_LIVE_PERIOD` and
:tg-const:`telegram.InputLocationMessageContent.MAX_LIVE_PERIOD`.
.. deprecated:: v22.2
|time-period-int-deprecated|
heading (:obj:`int`): Optional. For live locations, a direction in which the user is
moving, in degrees. Must be between
:tg-const:`telegram.InputLocationMessageContent.MIN_HEADING` and
:tg-const:`telegram.InputLocationMessageContent.MAX_HEADING` if specified.
proximity_alert_radius (:obj:`int`): Optional. For live locations, a maximum distance
for proximity alerts about approaching another chat member, in meters. Must be
between :tg-const:`telegram.InputLocationMessageContent.MIN_PROXIMITY_ALERT_RADIUS`
and :tg-const:`telegram.InputLocationMessageContent.MAX_PROXIMITY_ALERT_RADIUS`
if specified.
"""
__slots__ = (
"_live_period",
"heading",
"horizontal_accuracy",
"latitude",
"longitude",
"proximity_alert_radius",
)
# fmt: on
def __init__(
self,
latitude: float,
longitude: float,
live_period: Optional[TimePeriod] = None,
horizontal_accuracy: Optional[float] = None,
heading: Optional[int] = None,
proximity_alert_radius: Optional[int] = None,
*,
api_kwargs: Optional[JSONDict] = None,
):
super().__init__(api_kwargs=api_kwargs)
with self._unfrozen():
# Required
self.latitude: float = latitude
self.longitude: float = longitude
# Optionals
self._live_period: Optional[dtm.timedelta] = to_timedelta(live_period)
self.horizontal_accuracy: Optional[float] = horizontal_accuracy
self.heading: Optional[int] = heading
self.proximity_alert_radius: Optional[int] = (
int(proximity_alert_radius) if proximity_alert_radius else None
)
self._id_attrs = (self.latitude, self.longitude)
@property
def live_period(self) -> Optional[Union[int, dtm.timedelta]]:
return get_timedelta_value(self._live_period, attribute="live_period")
HORIZONTAL_ACCURACY: Final[int] = constants.LocationLimit.HORIZONTAL_ACCURACY
""":const:`telegram.constants.LocationLimit.HORIZONTAL_ACCURACY`
.. versionadded:: 20.0
"""
MIN_HEADING: Final[int] = constants.LocationLimit.MIN_HEADING
""":const:`telegram.constants.LocationLimit.MIN_HEADING`
.. versionadded:: 20.0
"""
MAX_HEADING: Final[int] = constants.LocationLimit.MAX_HEADING
""":const:`telegram.constants.LocationLimit.MAX_HEADING`
.. versionadded:: 20.0
"""
MIN_LIVE_PERIOD: Final[int] = constants.LocationLimit.MIN_LIVE_PERIOD
""":const:`telegram.constants.LocationLimit.MIN_LIVE_PERIOD`
.. versionadded:: 20.0
"""
MAX_LIVE_PERIOD: Final[int] = constants.LocationLimit.MAX_LIVE_PERIOD
""":const:`telegram.constants.LocationLimit.MAX_LIVE_PERIOD`
.. versionadded:: 20.0
"""
MIN_PROXIMITY_ALERT_RADIUS: Final[int] = constants.LocationLimit.MIN_PROXIMITY_ALERT_RADIUS
""":const:`telegram.constants.LocationLimit.MIN_PROXIMITY_ALERT_RADIUS`
.. versionadded:: 20.0
"""
MAX_PROXIMITY_ALERT_RADIUS: Final[int] = constants.LocationLimit.MAX_PROXIMITY_ALERT_RADIUS
""":const:`telegram.constants.LocationLimit.MAX_PROXIMITY_ALERT_RADIUS`
.. versionadded:: 20.0
"""

View File

@@ -0,0 +1,42 @@
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2025
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser Public License for more details.
#
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains the classes that represent Telegram InputMessageContent."""
from typing import Optional
from telegram._telegramobject import TelegramObject
from telegram._utils.types import JSONDict
class InputMessageContent(TelegramObject):
"""Base class for Telegram InputMessageContent Objects.
See: :class:`telegram.InputContactMessageContent`,
:class:`telegram.InputInvoiceMessageContent`,
:class:`telegram.InputLocationMessageContent`, :class:`telegram.InputTextMessageContent` and
:class:`telegram.InputVenueMessageContent` for more details.
"""
__slots__ = ()
def __init__(self, *, api_kwargs: Optional[JSONDict] = None) -> None:
super().__init__(api_kwargs=api_kwargs)
self._freeze()

View File

@@ -0,0 +1,116 @@
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2025
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser Public License for more details.
#
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains the classes that represent Telegram InputTextMessageContent."""
from collections.abc import Sequence
from typing import TYPE_CHECKING, Optional
from telegram._inline.inputmessagecontent import InputMessageContent
from telegram._messageentity import MessageEntity
from telegram._utils.argumentparsing import parse_lpo_and_dwpp, parse_sequence_arg
from telegram._utils.defaultvalue import DEFAULT_NONE
from telegram._utils.types import JSONDict, ODVInput
if TYPE_CHECKING:
from telegram._linkpreviewoptions import LinkPreviewOptions
class InputTextMessageContent(InputMessageContent):
"""
Represents the content of a text message to be sent as the result of an inline query.
Objects of this class are comparable in terms of equality. Two objects of this class are
considered equal, if their :attr:`message_text` is equal.
Examples:
:any:`Inline Bot <examples.inlinebot>`
Args:
message_text (:obj:`str`): Text of the message to be sent,
:tg-const:`telegram.constants.MessageLimit.MIN_TEXT_LENGTH`-
:tg-const:`telegram.constants.MessageLimit.MAX_TEXT_LENGTH` characters after entities
parsing.
parse_mode (:obj:`str`, optional): |parse_mode|
entities (Sequence[:class:`telegram.MessageEntity`], optional): |caption_entities|
.. versionchanged:: 20.0
|sequenceclassargs|
link_preview_options (:obj:`LinkPreviewOptions`, optional): Link preview generation
options for the message. Mutually exclusive with
:paramref:`disable_web_page_preview`.
.. versionadded:: 20.8
Keyword Args:
disable_web_page_preview (:obj:`bool`, optional): Disables link previews for links in the
sent message. Convenience parameter for setting :paramref:`link_preview_options`.
Mutually exclusive with :paramref:`link_preview_options`.
.. versionchanged:: 20.8
Bot API 7.0 introduced :paramref:`link_preview_options` replacing this
argument. PTB will automatically convert this argument to that one, but
for advanced options, please use :paramref:`link_preview_options` directly.
.. versionchanged:: 21.0
|keyword_only_arg|
Attributes:
message_text (:obj:`str`): Text of the message to be sent,
:tg-const:`telegram.constants.MessageLimit.MIN_TEXT_LENGTH`-
:tg-const:`telegram.constants.MessageLimit.MAX_TEXT_LENGTH` characters after entities
parsing.
parse_mode (:obj:`str`): Optional. |parse_mode|
entities (tuple[:class:`telegram.MessageEntity`]): Optional. |captionentitiesattr|
.. versionchanged:: 20.0
* |tupleclassattrs|
* |alwaystuple|
link_preview_options (:obj:`LinkPreviewOptions`): Optional. Link preview generation
options for the message.
.. versionadded:: 20.8
"""
__slots__ = ("entities", "link_preview_options", "message_text", "parse_mode")
def __init__(
self,
message_text: str,
parse_mode: ODVInput[str] = DEFAULT_NONE,
entities: Optional[Sequence[MessageEntity]] = None,
link_preview_options: ODVInput["LinkPreviewOptions"] = DEFAULT_NONE,
*,
disable_web_page_preview: Optional[bool] = None,
api_kwargs: Optional[JSONDict] = None,
):
super().__init__(api_kwargs=api_kwargs)
with self._unfrozen():
# Required
self.message_text: str = message_text
# Optionals
self.parse_mode: ODVInput[str] = parse_mode
self.entities: tuple[MessageEntity, ...] = parse_sequence_arg(entities)
self.link_preview_options: ODVInput[LinkPreviewOptions] = parse_lpo_and_dwpp(
disable_web_page_preview, link_preview_options
)
self._id_attrs = (self.message_text,)

View File

@@ -0,0 +1,108 @@
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2025
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser Public License for more details.
#
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains the classes that represent Telegram InputVenueMessageContent."""
from typing import Optional
from telegram._inline.inputmessagecontent import InputMessageContent
from telegram._utils.types import JSONDict
class InputVenueMessageContent(InputMessageContent):
"""Represents the content of a venue message to be sent as the result of an inline query.
Objects of this class are comparable in terms of equality. Two objects of this class are
considered equal, if their :attr:`latitude`, :attr:`longitude` and :attr:`title`
are equal.
Note:
Foursquare details and Google Pace details are mutually exclusive. However, this
behaviour is undocumented and might be changed by Telegram.
Args:
latitude (:obj:`float`): Latitude of the location in degrees.
longitude (:obj:`float`): Longitude of the location in degrees.
title (:obj:`str`): Name of the venue.
address (:obj:`str`): Address of the venue.
foursquare_id (:obj:`str`, optional): Foursquare identifier of the venue, if known.
foursquare_type (:obj:`str`, optional): Foursquare type of the venue, if known.
(For example, "arts_entertainment/default", "arts_entertainment/aquarium" or
"food/icecream".)
google_place_id (:obj:`str`, optional): Google Places identifier of the venue.
google_place_type (:obj:`str`, optional): Google Places type of the venue. (See
`supported types <https://developers.google.com/maps/documentation/places/web-service\
/supported_types>`_.)
Attributes:
latitude (:obj:`float`): Latitude of the location in degrees.
longitude (:obj:`float`): Longitude of the location in degrees.
title (:obj:`str`): Name of the venue.
address (:obj:`str`): Address of the venue.
foursquare_id (:obj:`str`): Optional. Foursquare identifier of the venue, if known.
foursquare_type (:obj:`str`): Optional. Foursquare type of the venue, if known.
(For example, "arts_entertainment/default", "arts_entertainment/aquarium" or
"food/icecream".)
google_place_id (:obj:`str`): Optional. Google Places identifier of the venue.
google_place_type (:obj:`str`): Optional. Google Places type of the venue. (See
`supported types <https://developers.google.com/maps/documentation/places/web-service\
/supported_types>`_.)
"""
__slots__ = (
"address",
"foursquare_id",
"foursquare_type",
"google_place_id",
"google_place_type",
"latitude",
"longitude",
"title",
)
def __init__(
self,
latitude: float,
longitude: float,
title: str,
address: str,
foursquare_id: Optional[str] = None,
foursquare_type: Optional[str] = None,
google_place_id: Optional[str] = None,
google_place_type: Optional[str] = None,
*,
api_kwargs: Optional[JSONDict] = None,
):
super().__init__(api_kwargs=api_kwargs)
with self._unfrozen():
# Required
self.latitude: float = latitude
self.longitude: float = longitude
self.title: str = title
self.address: str = address
# Optionals
self.foursquare_id: Optional[str] = foursquare_id
self.foursquare_type: Optional[str] = foursquare_type
self.google_place_id: Optional[str] = google_place_id
self.google_place_type: Optional[str] = google_place_type
self._id_attrs = (
self.latitude,
self.longitude,
self.title,
)

View File

@@ -0,0 +1,78 @@
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2025
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser Public License for more details.
#
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents a Telegram Prepared inline Message."""
import datetime as dtm
from typing import TYPE_CHECKING, Optional
from telegram._telegramobject import TelegramObject
from telegram._utils.datetime import extract_tzinfo_from_defaults, from_timestamp
from telegram._utils.types import JSONDict
if TYPE_CHECKING:
from telegram import Bot
class PreparedInlineMessage(TelegramObject):
"""Describes an inline message to be sent by a user of a Mini App.
Objects of this class are comparable in terms of equality. Two objects of this class are
considered equal, if their :attr:`id` is equal.
.. versionadded:: 21.8
Args:
id (:obj:`str`): Unique identifier of the prepared message
expiration_date (:class:`datetime.datetime`): Expiration date of the prepared message.
Expired prepared messages can no longer be used.
|datetime_localization|
Attributes:
id (:obj:`str`): Unique identifier of the prepared message
expiration_date (:class:`datetime.datetime`): Expiration date of the prepared message.
Expired prepared messages can no longer be used.
|datetime_localization|
"""
__slots__ = ("expiration_date", "id")
def __init__(
self,
id: str, # pylint: disable=redefined-builtin
expiration_date: dtm.datetime,
*,
api_kwargs: Optional[JSONDict] = None,
):
super().__init__(api_kwargs=api_kwargs)
self.id: str = id
self.expiration_date: dtm.datetime = expiration_date
self._id_attrs = (self.id,)
self._freeze()
@classmethod
def de_json(cls, data: JSONDict, bot: Optional["Bot"] = None) -> "PreparedInlineMessage":
"""See :meth:`telegram.TelegramObject.de_json`."""
data = cls._parse_data(data)
# Get the local timezone from the bot if it has defaults
loc_tzinfo = extract_tzinfo_from_defaults(bot)
data["expiration_date"] = from_timestamp(data.get("expiration_date"), tzinfo=loc_tzinfo)
return super().de_json(data=data, bot=bot)

View File

@@ -0,0 +1,186 @@
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2025
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser Public License for more details.
#
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an objects that are related to Telegram input checklists."""
from collections.abc import Sequence
from typing import Optional
from telegram._messageentity import MessageEntity
from telegram._telegramobject import TelegramObject
from telegram._utils.argumentparsing import parse_sequence_arg
from telegram._utils.defaultvalue import DEFAULT_NONE
from telegram._utils.types import JSONDict, ODVInput
class InputChecklistTask(TelegramObject):
"""
Describes a task to add to a checklist.
Objects of this class are comparable in terms of equality.
Two objects of this class are considered equal if their :attr:`id` is equal.
.. versionadded:: 22.3
Args:
id (:obj:`int`):
Unique identifier of the task; must be positive and unique among all task identifiers
currently present in the checklist.
text (:obj:`str`):
Text of the task;
:tg-const:`telegram.constants.InputChecklistLimit.MIN_TEXT_LENGTH`\
-:tg-const:`telegram.constants.InputChecklistLimit.MAX_TEXT_LENGTH` characters after
entities parsing.
parse_mode (:obj:`str`, optional):
|parse_mode|
text_entities (Sequence[:class:`telegram.MessageEntity`], optional):
List of special entities that appear in the text, which can be specified instead of
parse_mode. Currently, only bold, italic, underline, strikethrough, spoiler, and
custom_emoji entities are allowed.
Attributes:
id (:obj:`int`):
Unique identifier of the task; must be positive and unique among all task identifiers
currently present in the checklist.
text (:obj:`str`):
Text of the task;
:tg-const:`telegram.constants.InputChecklistLimit.MIN_TEXT_LENGTH`\
-:tg-const:`telegram.constants.InputChecklistLimit.MAX_TEXT_LENGTH` characters after
entities parsing.
parse_mode (:obj:`str`):
Optional. |parse_mode|
text_entities (Sequence[:class:`telegram.MessageEntity`]):
Optional. List of special entities that appear in the text, which can be specified
instead of parse_mode. Currently, only bold, italic, underline, strikethrough, spoiler,
and custom_emoji entities are allowed.
"""
__slots__ = (
"id",
"parse_mode",
"text",
"text_entities",
)
def __init__(
self,
id: int, # pylint: disable=redefined-builtin
text: str,
parse_mode: ODVInput[str] = DEFAULT_NONE,
text_entities: Optional[Sequence[MessageEntity]] = None,
*,
api_kwargs: Optional[JSONDict] = None,
):
super().__init__(api_kwargs=api_kwargs)
self.id: int = id
self.text: str = text
self.parse_mode: ODVInput[str] = parse_mode
self.text_entities: tuple[MessageEntity, ...] = parse_sequence_arg(text_entities)
self._id_attrs = (self.id,)
self._freeze()
class InputChecklist(TelegramObject):
"""
Describes a checklist to create.
Objects of this class are comparable in terms of equality.
Two objects of this class are considered equal if their :attr:`tasks` is equal.
.. versionadded:: 22.3
Args:
title (:obj:`str`):
Title of the checklist;
:tg-const:`telegram.constants.InputChecklistLimit.MIN_TITLE_LENGTH`\
-:tg-const:`telegram.constants.InputChecklistLimit.MAX_TITLE_LENGTH` characters after
entities parsing.
parse_mode (:obj:`str`, optional):
|parse_mode|
title_entities (Sequence[:class:`telegram.MessageEntity`], optional):
List of special entities that appear in the title, which
can be specified instead of :paramref:`parse_mode`. Currently, only bold, italic,
underline, strikethrough, spoiler, and custom_emoji entities are allowed.
tasks (Sequence[:class:`telegram.InputChecklistTask`]):
List of
:tg-const:`telegram.constants.InputChecklistLimit.MIN_TASK_NUMBER`\
-:tg-const:`telegram.constants.InputChecklistLimit.MAX_TASK_NUMBER` tasks in
the checklist.
others_can_add_tasks (:obj:`bool`, optional):
Pass :obj:`True` if other users can add tasks to the checklist.
others_can_mark_tasks_as_done (:obj:`bool`, optional):
Pass :obj:`True` if other users can mark tasks as done or not done in the checklist.
Attributes:
title (:obj:`str`):
Title of the checklist;
:tg-const:`telegram.constants.InputChecklistLimit.MIN_TITLE_LENGTH`\
-:tg-const:`telegram.constants.InputChecklistLimit.MAX_TITLE_LENGTH` characters after
entities parsing.
parse_mode (:obj:`str`):
Optional. |parse_mode|
title_entities (Sequence[:class:`telegram.MessageEntity`]):
Optional. List of special entities that appear in the title, which
can be specified instead of :paramref:`parse_mode`. Currently, only bold, italic,
underline, strikethrough, spoiler, and custom_emoji entities are allowed.
tasks (Sequence[:class:`telegram.InputChecklistTask`]):
List of
:tg-const:`telegram.constants.InputChecklistLimit.MIN_TASK_NUMBER`\
-:tg-const:`telegram.constants.InputChecklistLimit.MAX_TASK_NUMBER` tasks in
the checklist.
others_can_add_tasks (:obj:`bool`):
Optional. Pass :obj:`True` if other users can add tasks to the checklist.
others_can_mark_tasks_as_done (:obj:`bool`):
Optional. Pass :obj:`True` if other users can mark tasks as done or not done in
the checklist.
"""
__slots__ = (
"others_can_add_tasks",
"others_can_mark_tasks_as_done",
"parse_mode",
"tasks",
"title",
"title_entities",
)
def __init__(
self,
title: str,
tasks: Sequence[InputChecklistTask],
parse_mode: ODVInput[str] = DEFAULT_NONE,
title_entities: Optional[Sequence[MessageEntity]] = None,
others_can_add_tasks: Optional[bool] = None,
others_can_mark_tasks_as_done: Optional[bool] = None,
*,
api_kwargs: Optional[JSONDict] = None,
):
super().__init__(api_kwargs=api_kwargs)
self.title: str = title
self.tasks: tuple[InputChecklistTask, ...] = parse_sequence_arg(tasks)
self.parse_mode: ODVInput[str] = parse_mode
self.title_entities: tuple[MessageEntity, ...] = parse_sequence_arg(title_entities)
self.others_can_add_tasks: Optional[bool] = others_can_add_tasks
self.others_can_mark_tasks_as_done: Optional[bool] = others_can_mark_tasks_as_done
self._id_attrs = (self.tasks,)
self._freeze()

View File

@@ -0,0 +1,193 @@
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2025
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser Public License for more details.
#
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents a Telegram KeyboardButton."""
from typing import TYPE_CHECKING, Optional
from telegram._keyboardbuttonpolltype import KeyboardButtonPollType
from telegram._keyboardbuttonrequest import KeyboardButtonRequestChat, KeyboardButtonRequestUsers
from telegram._telegramobject import TelegramObject
from telegram._utils.argumentparsing import de_json_optional
from telegram._utils.types import JSONDict
from telegram._webappinfo import WebAppInfo
if TYPE_CHECKING:
from telegram import Bot
class KeyboardButton(TelegramObject):
"""
This object represents one button of the reply keyboard. At most one of the optional fields
must be used to specify type of the button. For simple text buttons, :obj:`str`
can be used instead of this object to specify text of the button.
Objects of this class are comparable in terms of equality. Two objects of this class are
considered equal, if their :attr:`text`, :attr:`request_contact`, :attr:`request_location`,
:attr:`request_poll`, :attr:`web_app`, :attr:`request_users` and :attr:`request_chat` are
equal.
Note:
* Optional fields are mutually exclusive.
* :attr:`request_contact` and :attr:`request_location` options will only work in Telegram
versions released after 9 April, 2016. Older clients will display unsupported message.
* :attr:`request_poll` option will only work in Telegram versions released after 23
January, 2020. Older clients will display unsupported message.
* :attr:`web_app` option will only work in Telegram versions released after 16 April, 2022.
Older clients will display unsupported message.
* :attr:`request_users` and :attr:`request_chat` options will only work in Telegram
versions released after 3 February, 2023. Older clients will display unsupported
message.
.. versionchanged:: 21.0
Removed deprecated argument and attribute ``request_user``.
.. versionchanged:: 20.0
:attr:`web_app` is considered as well when comparing objects of this type in terms of
equality.
.. versionchanged:: 20.5
:attr:`request_users` and :attr:`request_chat` are considered as well when
comparing objects of this type in terms of equality.
Args:
text (:obj:`str`): Text of the button. If none of the optional fields are used, it will be
sent to the bot as a message when the button is pressed.
request_contact (:obj:`bool`, optional): If :obj:`True`, the user's phone number will be
sent as a contact when the button is pressed. Available in private chats only.
request_location (:obj:`bool`, optional): If :obj:`True`, the user's current location will
be sent when the button is pressed. Available in private chats only.
request_poll (:class:`~telegram.KeyboardButtonPollType`, optional): If specified, the user
will be asked to create a poll and send it to the bot when the button is pressed.
Available in private chats only.
web_app (:class:`~telegram.WebAppInfo`, optional): If specified, the described `Web App
<https://core.telegram.org/bots/webapps>`_ will be launched when the button is pressed.
The Web App will be able to send a :attr:`Message.web_app_data` service message.
Available in private chats only.
.. versionadded:: 20.0
request_users (:class:`KeyboardButtonRequestUsers`, optional): If specified, pressing the
button will open a list of suitable users. Tapping on any user will send its
identifier to the bot in a :attr:`telegram.Message.users_shared` service message.
Available in private chats only.
.. versionadded:: 20.8
request_chat (:class:`KeyboardButtonRequestChat`, optional): If specified, pressing the
button will open a list of suitable chats. Tapping on a chat will send its
identifier to the bot in a :attr:`telegram.Message.chat_shared` service message.
Available in private chats only.
.. versionadded:: 20.1
Attributes:
text (:obj:`str`): Text of the button. If none of the optional fields are used, it will be
sent to the bot as a message when the button is pressed.
request_contact (:obj:`bool`): Optional. If :obj:`True`, the user's phone number will be
sent as a contact when the button is pressed. Available in private chats only.
request_location (:obj:`bool`): Optional. If :obj:`True`, the user's current location will
be sent when the button is pressed. Available in private chats only.
request_poll (:class:`~telegram.KeyboardButtonPollType`): Optional. If specified,
the user will be asked to create a poll and send it to the bot when the button is
pressed. Available in private chats only.
web_app (:class:`~telegram.WebAppInfo`): Optional. If specified, the described `Web App
<https://core.telegram.org/bots/webapps>`_ will be launched when the button is pressed.
The Web App will be able to send a :attr:`Message.web_app_data` service message.
Available in private chats only.
.. versionadded:: 20.0
request_users (:class:`KeyboardButtonRequestUsers`): Optional. If specified, pressing the
button will open a list of suitable users. Tapping on any user will send its
identifier to the bot in a :attr:`telegram.Message.users_shared` service message.
Available in private chats only.
.. versionadded:: 20.8
request_chat (:class:`KeyboardButtonRequestChat`): Optional. If specified, pressing the
button will open a list of suitable chats. Tapping on a chat will send its
identifier to the bot in a :attr:`telegram.Message.chat_shared` service message.
Available in private chats only.
.. versionadded:: 20.1
"""
__slots__ = (
"request_chat",
"request_contact",
"request_location",
"request_poll",
"request_users",
"text",
"web_app",
)
def __init__(
self,
text: str,
request_contact: Optional[bool] = None,
request_location: Optional[bool] = None,
request_poll: Optional[KeyboardButtonPollType] = None,
web_app: Optional[WebAppInfo] = None,
request_chat: Optional[KeyboardButtonRequestChat] = None,
request_users: Optional[KeyboardButtonRequestUsers] = None,
*,
api_kwargs: Optional[JSONDict] = None,
):
super().__init__(api_kwargs=api_kwargs)
# Required
self.text: str = text
# Optionals
self.request_contact: Optional[bool] = request_contact
self.request_location: Optional[bool] = request_location
self.request_poll: Optional[KeyboardButtonPollType] = request_poll
self.web_app: Optional[WebAppInfo] = web_app
self.request_users: Optional[KeyboardButtonRequestUsers] = request_users
self.request_chat: Optional[KeyboardButtonRequestChat] = request_chat
self._id_attrs = (
self.text,
self.request_contact,
self.request_location,
self.request_poll,
self.web_app,
self.request_users,
self.request_chat,
)
self._freeze()
@classmethod
def de_json(cls, data: JSONDict, bot: Optional["Bot"] = None) -> "KeyboardButton":
"""See :meth:`telegram.TelegramObject.de_json`."""
data = cls._parse_data(data)
data["request_poll"] = de_json_optional(
data.get("request_poll"), KeyboardButtonPollType, bot
)
data["request_users"] = de_json_optional(
data.get("request_users"), KeyboardButtonRequestUsers, bot
)
data["request_chat"] = de_json_optional(
data.get("request_chat"), KeyboardButtonRequestChat, bot
)
data["web_app"] = de_json_optional(data.get("web_app"), WebAppInfo, bot)
api_kwargs = {}
# This is a deprecated field that TG still returns for backwards compatibility
# Let's filter it out to speed up the de-json process
if request_user := data.get("request_user"):
api_kwargs = {"request_user": request_user}
return super()._de_json(data=data, bot=bot, api_kwargs=api_kwargs)

View File

@@ -0,0 +1,63 @@
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2025
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser Public License for more details.
#
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents a type of a Telegram Poll."""
from typing import Optional
from telegram._telegramobject import TelegramObject
from telegram._utils import enum
from telegram._utils.types import JSONDict
from telegram.constants import PollType
class KeyboardButtonPollType(TelegramObject):
"""This object represents type of a poll, which is allowed to be created
and sent when the corresponding button is pressed.
Objects of this class are comparable in terms of equality. Two objects of this class are
considered equal, if their :attr:`type` is equal.
Examples:
:any:`Poll Bot <examples.pollbot>`
Args:
type (:obj:`str`, optional): If :tg-const:`telegram.Poll.QUIZ` is passed, the user will be
allowed to create only polls in the quiz mode. If :tg-const:`telegram.Poll.REGULAR` is
passed, only regular polls will be allowed. Otherwise, the user will be allowed to
create a poll of any type.
Attributes:
type (:obj:`str`): Optional. If equals :tg-const:`telegram.Poll.QUIZ`, the user will
be allowed to create only polls in the quiz mode. If equals
:tg-const:`telegram.Poll.REGULAR`, only regular polls will be allowed.
Otherwise, the user will be allowed to create a poll of any type.
"""
__slots__ = ("type",)
def __init__(
self,
type: Optional[str] = None, # pylint: disable=redefined-builtin
*,
api_kwargs: Optional[JSONDict] = None,
):
super().__init__(api_kwargs=api_kwargs)
self.type: Optional[str] = enum.get_member(PollType, type, type)
self._id_attrs = (self.type,)
self._freeze()

View File

@@ -0,0 +1,272 @@
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2025
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser Public License for more details.
#
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains two objects to request chats/users."""
from typing import TYPE_CHECKING, Optional
from telegram._chatadministratorrights import ChatAdministratorRights
from telegram._telegramobject import TelegramObject
from telegram._utils.argumentparsing import de_json_optional
from telegram._utils.types import JSONDict
if TYPE_CHECKING:
from telegram import Bot
class KeyboardButtonRequestUsers(TelegramObject):
"""This object defines the criteria used to request a suitable user. The identifier of the
selected user will be shared with the bot when the corresponding button is pressed. `More
about requesting users » <https://core.telegram.org/bots/features#chat-and-user-selection>`_.
Objects of this class are comparable in terms of equality. Two objects of this class are
considered equal, if their :attr:`request_id` is equal.
.. versionadded:: 20.8
This class was previously named ``KeyboardButtonRequestUser``.
Args:
request_id (:obj:`int`): Signed 32-bit identifier of the request, which will be received
back in the :class:`telegram.UsersShared` object. Must be unique within the message.
user_is_bot (:obj:`bool`, optional): Pass :obj:`True` to request a bot, pass :obj:`False`
to request a regular user. If not specified, no additional restrictions are applied.
user_is_premium (:obj:`bool`, optional): Pass :obj:`True` to request a premium user, pass
:obj:`False` to request a non-premium user. If not specified, no additional
restrictions are applied.
max_quantity (:obj:`int`, optional): The maximum number of users to be selected;
:tg-const:`telegram.constants.KeyboardButtonRequestUsersLimit.MIN_QUANTITY` -
:tg-const:`telegram.constants.KeyboardButtonRequestUsersLimit.MAX_QUANTITY`.
Defaults to :tg-const:`telegram.constants.KeyboardButtonRequestUsersLimit.MIN_QUANTITY`
.
.. versionadded:: 20.8
request_name (:obj:`bool`, optional): Pass :obj:`True` to request the users' first and last
name.
.. versionadded:: 21.1
request_username (:obj:`bool`, optional): Pass :obj:`True` to request the users' username.
.. versionadded:: 21.1
request_photo (:obj:`bool`, optional): Pass :obj:`True` to request the users' photo.
.. versionadded:: 21.1
Attributes:
request_id (:obj:`int`): Identifier of the request.
user_is_bot (:obj:`bool`): Optional. Pass :obj:`True` to request a bot, pass :obj:`False`
to request a regular user. If not specified, no additional restrictions are applied.
user_is_premium (:obj:`bool`): Optional. Pass :obj:`True` to request a premium user, pass
:obj:`False` to request a non-premium user. If not specified, no additional
restrictions are applied.
max_quantity (:obj:`int`): Optional. The maximum number of users to be selected;
:tg-const:`telegram.constants.KeyboardButtonRequestUsersLimit.MIN_QUANTITY` -
:tg-const:`telegram.constants.KeyboardButtonRequestUsersLimit.MAX_QUANTITY`.
Defaults to :tg-const:`telegram.constants.KeyboardButtonRequestUsersLimit.MIN_QUANTITY`
.
.. versionadded:: 20.8
request_name (:obj:`bool`): Optional. Pass :obj:`True` to request the users' first and last
name.
.. versionadded:: 21.1
request_username (:obj:`bool`): Optional. Pass :obj:`True` to request the users' username.
.. versionadded:: 21.1
request_photo (:obj:`bool`): Optional. Pass :obj:`True` to request the users' photo.
.. versionadded:: 21.1
"""
__slots__ = (
"max_quantity",
"request_id",
"request_name",
"request_photo",
"request_username",
"user_is_bot",
"user_is_premium",
)
def __init__(
self,
request_id: int,
user_is_bot: Optional[bool] = None,
user_is_premium: Optional[bool] = None,
max_quantity: Optional[int] = None,
request_name: Optional[bool] = None,
request_username: Optional[bool] = None,
request_photo: Optional[bool] = None,
*,
api_kwargs: Optional[JSONDict] = None,
):
super().__init__(api_kwargs=api_kwargs)
# Required
self.request_id: int = request_id
# Optionals
self.user_is_bot: Optional[bool] = user_is_bot
self.user_is_premium: Optional[bool] = user_is_premium
self.max_quantity: Optional[int] = max_quantity
self.request_name: Optional[bool] = request_name
self.request_username: Optional[bool] = request_username
self.request_photo: Optional[bool] = request_photo
self._id_attrs = (self.request_id,)
self._freeze()
class KeyboardButtonRequestChat(TelegramObject):
"""This object defines the criteria used to request a suitable chat. The identifier of the
selected user will be shared with the bot when the corresponding button is pressed. `More
about requesting users » <https://core.telegram.org/bots/features#chat-and-user-selection>`_.
Objects of this class are comparable in terms of equality. Two objects of this class are
considered equal, if their :attr:`request_id` is equal.
.. versionadded:: 20.1
Args:
request_id (:obj:`int`): Signed 32-bit identifier of the request, which will be received
back in the :class:`telegram.ChatShared` object. Must be unique within the message.
chat_is_channel (:obj:`bool`): Pass :obj:`True` to request a channel chat, pass
:obj:`False` to request a group or a supergroup chat.
chat_is_forum (:obj:`bool`, optional): Pass :obj:`True` to request a forum supergroup, pass
:obj:`False` to request a non-forum chat. If not specified, no additional
restrictions are applied.
chat_has_username (:obj:`bool`, optional): Pass :obj:`True` to request a supergroup or a
channel with a username, pass :obj:`False` to request a chat without a username. If
not specified, no additional restrictions are applied.
chat_is_created (:obj:`bool`, optional): Pass :obj:`True` to request a chat owned by the
user. Otherwise, no additional restrictions are applied.
user_administrator_rights (:class:`ChatAdministratorRights`, optional): Specifies the
required administrator rights of the user in the chat. If not specified, no additional
restrictions are applied.
bot_administrator_rights (:class:`ChatAdministratorRights`, optional): Specifies the
required administrator rights of the bot in the chat. The rights must be a subset of
:paramref:`user_administrator_rights`. If not specified, no additional restrictions are
applied.
bot_is_member (:obj:`bool`, optional): Pass :obj:`True` to request a chat with the bot
as a member. Otherwise, no additional restrictions are applied.
request_title (:obj:`bool`, optional): Pass :obj:`True` to request the chat's title.
.. versionadded:: 21.1
request_username (:obj:`bool`, optional): Pass :obj:`True` to request the chat's username.
.. versionadded:: 21.1
request_photo (:obj:`bool`, optional): Pass :obj:`True` to request the chat's photo.
.. versionadded:: 21.1
Attributes:
request_id (:obj:`int`): Identifier of the request.
chat_is_channel (:obj:`bool`): Pass :obj:`True` to request a channel chat, pass
:obj:`False` to request a group or a supergroup chat.
chat_is_forum (:obj:`bool`): Optional. Pass :obj:`True` to request a forum supergroup, pass
:obj:`False` to request a non-forum chat. If not specified, no additional
restrictions are applied.
chat_has_username (:obj:`bool`): Optional. Pass :obj:`True` to request a supergroup or a
channel with a username, pass :obj:`False` to request a chat without a username. If
not specified, no additional restrictions are applied.
chat_is_created (:obj:`bool`) Optional. Pass :obj:`True` to request a chat owned by the
user. Otherwise, no additional restrictions are applied.
user_administrator_rights (:class:`ChatAdministratorRights`) Optional. Specifies the
required administrator rights of the user in the chat. If not specified, no additional
restrictions are applied.
bot_administrator_rights (:class:`ChatAdministratorRights`) Optional. Specifies the
required administrator rights of the bot in the chat. The rights must be a subset of
:attr:`user_administrator_rights`. If not specified, no additional restrictions are
applied.
bot_is_member (:obj:`bool`) Optional. Pass :obj:`True` to request a chat with the bot
as a member. Otherwise, no additional restrictions are applied.
request_title (:obj:`bool`): Optional. Pass :obj:`True` to request the chat's title.
.. versionadded:: 21.1
request_username (:obj:`bool`): Optional. Pass :obj:`True` to request the chat's username.
.. versionadded:: 21.1
request_photo (:obj:`bool`): Optional. Pass :obj:`True` to request the chat's photo.
.. versionadded:: 21.1
"""
__slots__ = (
"bot_administrator_rights",
"bot_is_member",
"chat_has_username",
"chat_is_channel",
"chat_is_created",
"chat_is_forum",
"request_id",
"request_photo",
"request_title",
"request_username",
"user_administrator_rights",
)
def __init__(
self,
request_id: int,
chat_is_channel: bool,
chat_is_forum: Optional[bool] = None,
chat_has_username: Optional[bool] = None,
chat_is_created: Optional[bool] = None,
user_administrator_rights: Optional[ChatAdministratorRights] = None,
bot_administrator_rights: Optional[ChatAdministratorRights] = None,
bot_is_member: Optional[bool] = None,
request_title: Optional[bool] = None,
request_username: Optional[bool] = None,
request_photo: Optional[bool] = None,
*,
api_kwargs: Optional[JSONDict] = None,
):
super().__init__(api_kwargs=api_kwargs)
# required
self.request_id: int = request_id
self.chat_is_channel: bool = chat_is_channel
# optional
self.chat_is_forum: Optional[bool] = chat_is_forum
self.chat_has_username: Optional[bool] = chat_has_username
self.chat_is_created: Optional[bool] = chat_is_created
self.user_administrator_rights: Optional[ChatAdministratorRights] = (
user_administrator_rights
)
self.bot_administrator_rights: Optional[ChatAdministratorRights] = bot_administrator_rights
self.bot_is_member: Optional[bool] = bot_is_member
self.request_title: Optional[bool] = request_title
self.request_username: Optional[bool] = request_username
self.request_photo: Optional[bool] = request_photo
self._id_attrs = (self.request_id,)
self._freeze()
@classmethod
def de_json(cls, data: JSONDict, bot: Optional["Bot"] = None) -> "KeyboardButtonRequestChat":
"""See :meth:`telegram.TelegramObject.de_json`."""
data = cls._parse_data(data)
data["user_administrator_rights"] = de_json_optional(
data.get("user_administrator_rights"), ChatAdministratorRights, bot
)
data["bot_administrator_rights"] = de_json_optional(
data.get("bot_administrator_rights"), ChatAdministratorRights, bot
)
return super().de_json(data=data, bot=bot)

View File

@@ -0,0 +1,103 @@
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2025
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser Public License for more details.
#
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains the LinkPreviewOptions class."""
from typing import Optional
from telegram._telegramobject import TelegramObject
from telegram._utils.defaultvalue import DEFAULT_NONE
from telegram._utils.types import JSONDict, ODVInput
class LinkPreviewOptions(TelegramObject):
"""
Describes the options used for link preview generation.
Objects of this class are comparable in terms of equality. Two objects of this class are
considered equal, if their :attr:`is_disabled`, :attr:`url`, :attr:`prefer_small_media`,
:attr:`prefer_large_media`, and :attr:`show_above_text` are equal.
.. versionadded:: 20.8
Args:
is_disabled (:obj:`bool`, optional): :obj:`True`, if the link preview is disabled.
url (:obj:`str`, optional): The URL to use for the link preview. If empty, then the first
URL found in the message text will be used.
prefer_small_media (:obj:`bool`, optional): :obj:`True`, if the media in the link preview
is supposed to be shrunk; ignored if the URL isn't explicitly specified or media size
change isn't supported for the preview.
prefer_large_media (:obj:`bool`, optional): :obj:`True`, if the media in the link preview
is supposed to be enlarged; ignored if the URL isn't explicitly specified or media
size change isn't supported for the preview.
show_above_text (:obj:`bool`, optional): :obj:`True`, if the link preview must be shown
above the message text; otherwise, the link preview will be shown below the message
text.
Attributes:
is_disabled (:obj:`bool`): Optional. :obj:`True`, if the link preview is disabled.
url (:obj:`str`): Optional. The URL to use for the link preview. If empty, then the first
URL found in the message text will be used.
prefer_small_media (:obj:`bool`): Optional. :obj:`True`, if the media in the link preview
is supposed to be shrunk; ignored if the URL isn't explicitly specified or media size
change isn't supported for the preview.
prefer_large_media (:obj:`bool`): Optional. :obj:`True`, if the media in the link preview
is supposed to be enlarged; ignored if the URL isn't explicitly specified or media size
change isn't supported for the preview.
show_above_text (:obj:`bool`): Optional. :obj:`True`, if the link preview must be shown
above the message text; otherwise, the link preview will be shown below the message
text.
"""
__slots__ = (
"is_disabled",
"prefer_large_media",
"prefer_small_media",
"show_above_text",
"url",
)
def __init__(
self,
is_disabled: ODVInput[bool] = DEFAULT_NONE,
url: ODVInput[str] = DEFAULT_NONE,
prefer_small_media: ODVInput[bool] = DEFAULT_NONE,
prefer_large_media: ODVInput[bool] = DEFAULT_NONE,
show_above_text: ODVInput[bool] = DEFAULT_NONE,
*,
api_kwargs: Optional[JSONDict] = None,
):
super().__init__(api_kwargs=api_kwargs)
# Optionals
self.is_disabled: ODVInput[bool] = is_disabled
self.url: ODVInput[str] = url
self.prefer_small_media: ODVInput[bool] = prefer_small_media
self.prefer_large_media: ODVInput[bool] = prefer_large_media
self.show_above_text: ODVInput[bool] = show_above_text
self._id_attrs = (
self.is_disabled,
self.url,
self.prefer_small_media,
self.prefer_large_media,
self.show_above_text,
)
self._freeze()

View File

@@ -0,0 +1,105 @@
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2025
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser Public License for more details.
#
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents a Telegram LoginUrl."""
from typing import Optional
from telegram._telegramobject import TelegramObject
from telegram._utils.types import JSONDict
class LoginUrl(TelegramObject):
"""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 <https://t.me/discussbot>`_
Objects of this class are comparable in terms of equality. Two objects of this class are
considered equal, if their :attr:`url` is equal.
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 <https://core.telegram.org/widgets/login#checking-authorization>`_
Args:
url (:obj:`str`): An HTTPS 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
<https://core.telegram.org/widgets/login#receiving-authorization-data>`_.
forward_text (:obj:`str`, optional): New text of the button in forwarded messages.
bot_username (:obj:`str`, optional): Username of a bot, which will be used for user
authorization. See
`Setting up a bot <https://core.telegram.org/widgets/login#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
<https://core.telegram.org/widgets/login#linking-your-domain-to-the-bot>`_
for more details.
request_write_access (:obj:`bool`, optional): Pass :obj:`True` to request the permission
for your bot to send messages to the user.
Attributes:
url (:obj:`str`): An HTTPS 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
<https://core.telegram.org/widgets/login#receiving-authorization-data>`_.
forward_text (:obj:`str`): Optional. New text of the button in forwarded messages.
bot_username (:obj:`str`): Optional. Username of a bot, which will be used for user
authorization. See
`Setting up a bot <https://core.telegram.org/widgets/login#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
<https://core.telegram.org/widgets/login#linking-your-domain-to-the-bot>`_
for more details.
request_write_access (:obj:`bool`): Optional. Pass :obj:`True` to request the permission
for your bot to send messages to the user.
"""
__slots__ = ("bot_username", "forward_text", "request_write_access", "url")
def __init__(
self,
url: str,
forward_text: Optional[str] = None,
bot_username: Optional[str] = None,
request_write_access: Optional[bool] = None,
*,
api_kwargs: Optional[JSONDict] = None,
):
super().__init__(api_kwargs=api_kwargs)
# Required
self.url: str = url
# Optional
self.forward_text: Optional[str] = forward_text
self.bot_username: Optional[str] = bot_username
self.request_write_access: Optional[bool] = request_write_access
self._id_attrs = (self.url,)
self._freeze()

View File

@@ -0,0 +1,189 @@
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2025
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser Public License for more details.
#
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains objects related to Telegram menu buttons."""
from typing import TYPE_CHECKING, Final, Optional
from telegram import constants
from telegram._telegramobject import TelegramObject
from telegram._utils import enum
from telegram._utils.argumentparsing import de_json_optional
from telegram._utils.types import JSONDict
from telegram._webappinfo import WebAppInfo
if TYPE_CHECKING:
from telegram import Bot
class MenuButton(TelegramObject):
"""This object describes the bot's menu button in a private chat. It should be one of
* :class:`telegram.MenuButtonCommands`
* :class:`telegram.MenuButtonWebApp`
* :class:`telegram.MenuButtonDefault`
If a menu button other than :class:`telegram.MenuButtonDefault` is set for a private chat,
then it is applied in the chat. Otherwise the default menu button is applied. By default, the
menu button opens the list of bot commands.
Objects of this class are comparable in terms of equality. Two objects of this class are
considered equal, if their :attr:`type` is equal. For subclasses with additional attributes,
the notion of equality is overridden.
.. versionadded:: 20.0
Args:
type (:obj:`str`): Type of menu button that the instance represents.
Attributes:
type (:obj:`str`): Type of menu button that the instance represents.
"""
__slots__ = ("type",)
def __init__(
self,
type: str,
*,
api_kwargs: Optional[JSONDict] = None,
): # pylint: disable=redefined-builtin
super().__init__(api_kwargs=api_kwargs)
self.type: str = enum.get_member(constants.MenuButtonType, type, type)
self._id_attrs = (self.type,)
self._freeze()
@classmethod
def de_json(cls, data: JSONDict, bot: Optional["Bot"] = None) -> "MenuButton":
"""Converts JSON data to the appropriate :class:`MenuButton` object, i.e. takes
care of selecting the correct subclass.
Args:
data (dict[:obj:`str`, ...]): The JSON data.
bot (:class:`telegram.Bot`, optional): The bot associated with this object. Defaults to
:obj:`None`, in which case shortcut methods will not be available.
.. versionchanged:: 21.4
:paramref:`bot` is now optional and defaults to :obj:`None`
Returns:
The Telegram object.
"""
data = cls._parse_data(data)
_class_mapping: dict[str, type[MenuButton]] = {
cls.COMMANDS: MenuButtonCommands,
cls.WEB_APP: MenuButtonWebApp,
cls.DEFAULT: MenuButtonDefault,
}
if cls is MenuButton and data.get("type") in _class_mapping:
return _class_mapping[data.pop("type")].de_json(data, bot=bot)
return super().de_json(data=data, bot=bot)
COMMANDS: Final[str] = constants.MenuButtonType.COMMANDS
""":const:`telegram.constants.MenuButtonType.COMMANDS`"""
WEB_APP: Final[str] = constants.MenuButtonType.WEB_APP
""":const:`telegram.constants.MenuButtonType.WEB_APP`"""
DEFAULT: Final[str] = constants.MenuButtonType.DEFAULT
""":const:`telegram.constants.MenuButtonType.DEFAULT`"""
class MenuButtonCommands(MenuButton):
"""Represents a menu button, which opens the bot's list of commands.
.. include:: inclusions/menu_button_command_video.rst
.. versionadded:: 20.0
Attributes:
type (:obj:`str`): :tg-const:`telegram.constants.MenuButtonType.COMMANDS`.
"""
__slots__ = ()
def __init__(self, *, api_kwargs: Optional[JSONDict] = None):
super().__init__(type=constants.MenuButtonType.COMMANDS, api_kwargs=api_kwargs)
self._freeze()
class MenuButtonWebApp(MenuButton):
"""Represents a menu button, which launches a
`Web App <https://core.telegram.org/bots/webapps>`_.
Objects of this class are comparable in terms of equality. Two objects of this class are
considered equal, if their :attr:`type`, :attr:`text` and :attr:`web_app`
are equal.
.. versionadded:: 20.0
Args:
text (:obj:`str`): Text of the button.
web_app (:class:`telegram.WebAppInfo`): Description of the Web App that will be launched
when the user presses the button. The Web App will be able to send an arbitrary
message on behalf of the user using the method :meth:`~telegram.Bot.answerWebAppQuery`
of :class:`~telegram.Bot`. Alternatively, a ``t.me`` link to a Web App of the bot can
be specified in the object instead of the Web App's URL, in which case the Web App
will be opened as if the user pressed the link.
Attributes:
type (:obj:`str`): :tg-const:`telegram.constants.MenuButtonType.WEB_APP`.
text (:obj:`str`): Text of the button.
web_app (:class:`telegram.WebAppInfo`): Description of the Web App that will be launched
when the user presses the button. The Web App will be able to send an arbitrary
message on behalf of the user using the method :meth:`~telegram.Bot.answerWebAppQuery`
of :class:`~telegram.Bot`. Alternatively, a ``t.me`` link to a Web App of the bot can
be specified in the object instead of the Web App's URL, in which case the Web App
will be opened as if the user pressed the link.
"""
__slots__ = ("text", "web_app")
def __init__(self, text: str, web_app: WebAppInfo, *, api_kwargs: Optional[JSONDict] = None):
super().__init__(type=constants.MenuButtonType.WEB_APP, api_kwargs=api_kwargs)
with self._unfrozen():
self.text: str = text
self.web_app: WebAppInfo = web_app
self._id_attrs = (self.type, self.text, self.web_app)
@classmethod
def de_json(cls, data: JSONDict, bot: Optional["Bot"] = None) -> "MenuButtonWebApp":
"""See :meth:`telegram.TelegramObject.de_json`."""
data = cls._parse_data(data)
data["web_app"] = de_json_optional(data.get("web_app"), WebAppInfo, bot)
return super().de_json(data=data, bot=bot) # type: ignore[return-value]
class MenuButtonDefault(MenuButton):
"""Describes that no specific value for the menu button was set.
.. versionadded:: 20.0
Attributes:
type (:obj:`str`): :tg-const:`telegram.constants.MenuButtonType.DEFAULT`.
"""
__slots__ = ()
def __init__(self, *, api_kwargs: Optional[JSONDict] = None):
super().__init__(type=constants.MenuButtonType.DEFAULT, api_kwargs=api_kwargs)
self._freeze()

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,75 @@
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2025
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser Public License for more details.
#
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents a change in the Telegram message auto
deletion.
"""
import datetime as dtm
from typing import Optional, Union
from telegram._telegramobject import TelegramObject
from telegram._utils.argumentparsing import to_timedelta
from telegram._utils.datetime import get_timedelta_value
from telegram._utils.types import JSONDict, TimePeriod
class MessageAutoDeleteTimerChanged(TelegramObject):
"""This object represents a service message about a change in auto-delete timer settings.
Objects of this class are comparable in terms of equality. Two objects of this class are
considered equal, if their :attr:`message_auto_delete_time` is equal.
.. versionadded:: 13.4
Args:
message_auto_delete_time (:obj:`int` | :class:`datetime.timedelta`): New auto-delete time
for messages in the chat.
.. versionchanged:: v22.2
|time-period-input|
Attributes:
message_auto_delete_time (:obj:`int` | :class:`datetime.timedelta`): New auto-delete time
for messages in the chat.
.. deprecated:: v22.2
|time-period-int-deprecated|
"""
__slots__ = ("_message_auto_delete_time",)
def __init__(
self,
message_auto_delete_time: TimePeriod,
*,
api_kwargs: Optional[JSONDict] = None,
):
super().__init__(api_kwargs=api_kwargs)
self._message_auto_delete_time: dtm.timedelta = to_timedelta(message_auto_delete_time)
self._id_attrs = (self.message_auto_delete_time,)
self._freeze()
@property
def message_auto_delete_time(self) -> Union[int, dtm.timedelta]:
return get_timedelta_value( # type: ignore[return-value]
self._message_auto_delete_time, attribute="message_auto_delete_time"
)

View File

@@ -0,0 +1,410 @@
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2025
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser Public License for more details.
#
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents a Telegram MessageEntity."""
import copy
import itertools
from collections.abc import Sequence
from typing import TYPE_CHECKING, Final, Optional, Union
from telegram import constants
from telegram._telegramobject import TelegramObject
from telegram._user import User
from telegram._utils import enum
from telegram._utils.argumentparsing import de_json_optional
from telegram._utils.strings import TextEncoding
from telegram._utils.types import JSONDict
if TYPE_CHECKING:
from telegram import Bot
_SEM = Sequence["MessageEntity"]
class MessageEntity(TelegramObject):
"""
This object represents one special entity in a text message. For example, hashtags,
usernames, URLs, etc.
Objects of this class are comparable in terms of equality. Two objects of this class are
considered equal, if their :attr:`type`, :attr:`offset` and :attr:`length` are equal.
Args:
type (:obj:`str`): Type of the entity. Can be :attr:`MENTION` (``@username``),
:attr:`HASHTAG` (``#hashtag`` or ``#hashtag@chatusername``), :attr:`CASHTAG` (``$USD``
or ``USD@chatusername``), :attr:`BOT_COMMAND` (``/start@jobs_bot``), :attr:`URL`
(``https://telegram.org``), :attr:`EMAIL` (``do-not-reply@telegram.org``),
:attr:`PHONE_NUMBER` (``+1-212-555-0123``),
:attr:`BOLD` (**bold text**), :attr:`ITALIC` (*italic text*), :attr:`UNDERLINE`
(underlined text), :attr:`STRIKETHROUGH`, :attr:`SPOILER` (spoiler message),
:attr:`BLOCKQUOTE` (block quotation), :attr:`CODE` (monowidth string), :attr:`PRE`
(monowidth block), :attr:`TEXT_LINK` (for clickable text URLs), :attr:`TEXT_MENTION`
(for users without usernames), :attr:`CUSTOM_EMOJI` (for inline custom emoji stickers).
.. versionadded:: 20.0
Added inline custom emoji
.. versionadded:: 20.8
Added block quotation
offset (:obj:`int`): Offset in UTF-16 code units to the start of the entity.
length (:obj:`int`): Length of the entity in UTF-16 code units.
url (:obj:`str`, optional): For :attr:`TEXT_LINK` only, url that will be opened after
user taps on the text.
user (:class:`telegram.User`, optional): For :attr:`TEXT_MENTION` only, the mentioned
user.
language (:obj:`str`, optional): For :attr:`PRE` only, the programming language of
the entity text.
custom_emoji_id (:obj:`str`, optional): For :attr:`CUSTOM_EMOJI` only, unique identifier
of the custom emoji. Use :meth:`telegram.Bot.get_custom_emoji_stickers` to get full
information about the sticker.
.. versionadded:: 20.0
Attributes:
type (:obj:`str`): Type of the entity. Can be :attr:`MENTION` (``@username``),
:attr:`HASHTAG` (``#hashtag`` or ``#hashtag@chatusername``), :attr:`CASHTAG` (``$USD``
or ``USD@chatusername``), :attr:`BOT_COMMAND` (``/start@jobs_bot``), :attr:`URL`
(``https://telegram.org``), :attr:`EMAIL` (``do-not-reply@telegram.org``),
:attr:`PHONE_NUMBER` (``+1-212-555-0123``),
:attr:`BOLD` (**bold text**), :attr:`ITALIC` (*italic text*), :attr:`UNDERLINE`
(underlined text), :attr:`STRIKETHROUGH`, :attr:`SPOILER` (spoiler message),
:attr:`BLOCKQUOTE` (block quotation), :attr:`CODE` (monowidth string), :attr:`PRE`
(monowidth block), :attr:`TEXT_LINK` (for clickable text URLs), :attr:`TEXT_MENTION`
(for users without usernames), :attr:`CUSTOM_EMOJI` (for inline custom emoji stickers).
.. versionadded:: 20.0
Added inline custom emoji
.. versionadded:: 20.8
Added block quotation
offset (:obj:`int`): Offset in UTF-16 code units to the start of the entity.
length (:obj:`int`): Length of the entity in UTF-16 code units.
url (:obj:`str`): Optional. For :attr:`TEXT_LINK` only, url that will be opened after
user taps on the text.
user (:class:`telegram.User`): Optional. For :attr:`TEXT_MENTION` only, the mentioned
user.
language (:obj:`str`): Optional. For :attr:`PRE` only, the programming language of
the entity text.
custom_emoji_id (:obj:`str`): Optional. For :attr:`CUSTOM_EMOJI` only, unique identifier
of the custom emoji. Use :meth:`telegram.Bot.get_custom_emoji_stickers` to get full
information about the sticker.
.. versionadded:: 20.0
"""
__slots__ = ("custom_emoji_id", "language", "length", "offset", "type", "url", "user")
def __init__(
self,
type: str, # pylint: disable=redefined-builtin
offset: int,
length: int,
url: Optional[str] = None,
user: Optional[User] = None,
language: Optional[str] = None,
custom_emoji_id: Optional[str] = None,
*,
api_kwargs: Optional[JSONDict] = None,
):
super().__init__(api_kwargs=api_kwargs)
# Required
self.type: str = enum.get_member(constants.MessageEntityType, type, type)
self.offset: int = offset
self.length: int = length
# Optionals
self.url: Optional[str] = url
self.user: Optional[User] = user
self.language: Optional[str] = language
self.custom_emoji_id: Optional[str] = custom_emoji_id
self._id_attrs = (self.type, self.offset, self.length)
self._freeze()
@classmethod
def de_json(cls, data: JSONDict, bot: Optional["Bot"] = None) -> "MessageEntity":
"""See :meth:`telegram.TelegramObject.de_json`."""
data = cls._parse_data(data)
data["user"] = de_json_optional(data.get("user"), User, bot)
return super().de_json(data=data, bot=bot)
@staticmethod
def adjust_message_entities_to_utf_16(text: str, entities: _SEM) -> _SEM:
"""Utility functionality for converting the offset and length of entities from
Unicode (:obj:`str`) to UTF-16 (``utf-16-le`` encoded :obj:`bytes`).
Tip:
Only the offsets and lengths calulated in UTF-16 is acceptable by the Telegram Bot API.
If they are calculated using the Unicode string (:obj:`str` object), errors may occur
when the text contains characters that are not in the Basic Multilingual Plane (BMP).
For more information, see `Unicode <https://en.wikipedia.org/wiki/Unicode>`_ and
`Plane (Unicode) <https://en.wikipedia.org/wiki/Plane_(Unicode)>`_.
.. versionadded:: 21.4
Examples:
Below is a snippet of code that demonstrates how to use this function to convert
entities from Unicode to UTF-16 space. The ``unicode_entities`` are calculated in
Unicode and the `utf_16_entities` are calculated in UTF-16.
.. code-block:: python
text = "𠌕 bold 𝄢 italic underlined: 𝛙𝌢𑁍"
unicode_entities = [
MessageEntity(offset=2, length=4, type=MessageEntity.BOLD),
MessageEntity(offset=9, length=6, type=MessageEntity.ITALIC),
MessageEntity(offset=28, length=3, type=MessageEntity.UNDERLINE),
]
utf_16_entities = MessageEntity.adjust_message_entities_to_utf_16(
text, unicode_entities
)
await bot.send_message(
chat_id=123,
text=text,
entities=utf_16_entities,
)
# utf_16_entities[0]: offset=3, length=4
# utf_16_entities[1]: offset=11, length=6
# utf_16_entities[2]: offset=30, length=6
Args:
text (:obj:`str`): The text that the entities belong to
entities (Sequence[:class:`telegram.MessageEntity`]): Sequence of entities
with offset and length calculated in Unicode
Returns:
Sequence[:class:`telegram.MessageEntity`]: Sequence of entities
with offset and length calculated in UTF-16 encoding
"""
# get sorted positions
positions = sorted(itertools.chain(*((x.offset, x.offset + x.length) for x in entities)))
accumulated_length = 0
# calculate the length of each slice text[:position] in utf-16 accordingly,
# store the position translations
position_translation: dict[int, int] = {}
for i, position in enumerate(positions):
last_position = positions[i - 1] if i > 0 else 0
text_slice = text[last_position:position]
accumulated_length += len(text_slice.encode(TextEncoding.UTF_16_LE)) // 2
position_translation[position] = accumulated_length
# get the final output entities
out = []
for entity in entities:
translated_positions = position_translation[entity.offset]
translated_length = (
position_translation[entity.offset + entity.length] - translated_positions
)
new_entity = copy.copy(entity)
with new_entity._unfrozen():
new_entity.offset = translated_positions
new_entity.length = translated_length
out.append(new_entity)
return out
@staticmethod
def shift_entities(by: Union[str, int], entities: _SEM) -> _SEM:
"""Utility functionality for shifting the offset of entities by a given amount.
Examples:
Shifting by an integer amount:
.. code-block:: python
text = "Hello, world!"
entities = [
MessageEntity(offset=0, length=5, type=MessageEntity.BOLD),
MessageEntity(offset=7, length=5, type=MessageEntity.ITALIC),
]
shifted_entities = MessageEntity.shift_entities(1, entities)
await bot.send_message(
chat_id=123,
text="!" + text,
entities=shifted_entities,
)
Shifting using a string:
.. code-block:: python
text = "Hello, world!"
prefix = "𝄢"
entities = [
MessageEntity(offset=0, length=5, type=MessageEntity.BOLD),
MessageEntity(offset=7, length=5, type=MessageEntity.ITALIC),
]
shifted_entities = MessageEntity.shift_entities(prefix, entities)
await bot.send_message(
chat_id=123,
text=prefix + text,
entities=shifted_entities,
)
Tip:
The :paramref:`entities` are *not* modified in place. The function returns a sequence
of new objects.
.. versionadded:: 21.5
Args:
by (:obj:`str` | :obj:`int`): Either the amount to shift the offset by or
a string whose length will be used as the amount to shift the offset by. In this
case, UTF-16 encoding will be used to calculate the length.
entities (Sequence[:class:`telegram.MessageEntity`]): Sequence of entities
Returns:
Sequence[:class:`telegram.MessageEntity`]: Sequence of entities with the offset shifted
"""
effective_shift = by if isinstance(by, int) else len(by.encode("utf-16-le")) // 2
out = []
for entity in entities:
new_entity = copy.copy(entity)
with new_entity._unfrozen():
new_entity.offset += effective_shift
out.append(new_entity)
return out
@classmethod
def concatenate(
cls,
*args: Union[tuple[str, _SEM], tuple[str, _SEM, bool]],
) -> tuple[str, _SEM]:
"""Utility functionality for concatenating two text along with their formatting entities.
Tip:
This function is useful for prefixing an already formatted text with a new text and its
formatting entities. In particular, it automatically correctly handles UTF-16 encoding.
Examples:
This example shows a callback function that can be used to add a prefix and suffix to
the message in a :class:`~telegram.ext.CallbackQueryHandler`:
.. code-block:: python
async def prefix_message(update: Update, context: ContextTypes.DEFAULT_TYPE):
prefix = "𠌕 bold 𝄢 italic underlined: 𝛙𝌢𑁍 | "
prefix_entities = [
MessageEntity(offset=2, length=4, type=MessageEntity.BOLD),
MessageEntity(offset=9, length=6, type=MessageEntity.ITALIC),
MessageEntity(offset=28, length=3, type=MessageEntity.UNDERLINE),
]
suffix = " | 𠌕 bold 𝄢 italic underlined: 𝛙𝌢𑁍"
suffix_entities = [
MessageEntity(offset=5, length=4, type=MessageEntity.BOLD),
MessageEntity(offset=12, length=6, type=MessageEntity.ITALIC),
MessageEntity(offset=31, length=3, type=MessageEntity.UNDERLINE),
]
message = update.effective_message
first = (prefix, prefix_entities, True)
second = (message.text, message.entities)
third = (suffix, suffix_entities, True)
new_text, new_entities = MessageEntity.concatenate(first, second, third)
await update.callback_query.edit_message_text(
text=new_text,
entities=new_entities,
)
Hint:
The entities are *not* modified in place. The function returns a
new sequence of objects.
.. versionadded:: 21.5
Args:
*args (tuple[:obj:`str`, Sequence[:class:`telegram.MessageEntity`]] | \
tuple[:obj:`str`, Sequence[:class:`telegram.MessageEntity`], :obj:`bool`]):
Arbitrary number of tuples containing the text and its entities to concatenate.
If the last element of the tuple is a :obj:`bool`, it is used to determine whether
to adjust the entities to UTF-16 via
:meth:`adjust_message_entities_to_utf_16`. UTF-16 adjustment is disabled by
default.
Returns:
tuple[:obj:`str`, Sequence[:class:`telegram.MessageEntity`]]: The concatenated text
and its entities
"""
output_text = ""
output_entities: list[MessageEntity] = []
for arg in args:
text, entities = arg[0], arg[1]
if len(arg) > 2 and arg[2] is True:
entities = cls.adjust_message_entities_to_utf_16(text, entities)
output_entities.extend(cls.shift_entities(output_text, entities))
output_text += text
return output_text, output_entities
ALL_TYPES: Final[list[str]] = list(constants.MessageEntityType)
"""list[:obj:`str`]: A list of all available message entity types."""
BLOCKQUOTE: Final[str] = constants.MessageEntityType.BLOCKQUOTE
""":const:`telegram.constants.MessageEntityType.BLOCKQUOTE`
.. versionadded:: 20.8
"""
BOLD: Final[str] = constants.MessageEntityType.BOLD
""":const:`telegram.constants.MessageEntityType.BOLD`"""
BOT_COMMAND: Final[str] = constants.MessageEntityType.BOT_COMMAND
""":const:`telegram.constants.MessageEntityType.BOT_COMMAND`"""
CASHTAG: Final[str] = constants.MessageEntityType.CASHTAG
""":const:`telegram.constants.MessageEntityType.CASHTAG`"""
CODE: Final[str] = constants.MessageEntityType.CODE
""":const:`telegram.constants.MessageEntityType.CODE`"""
CUSTOM_EMOJI: Final[str] = constants.MessageEntityType.CUSTOM_EMOJI
""":const:`telegram.constants.MessageEntityType.CUSTOM_EMOJI`
.. versionadded:: 20.0
"""
EMAIL: Final[str] = constants.MessageEntityType.EMAIL
""":const:`telegram.constants.MessageEntityType.EMAIL`"""
EXPANDABLE_BLOCKQUOTE: Final[str] = constants.MessageEntityType.EXPANDABLE_BLOCKQUOTE
""":const:`telegram.constants.MessageEntityType.EXPANDABLE_BLOCKQUOTE`
.. versionadded:: 21.3
"""
HASHTAG: Final[str] = constants.MessageEntityType.HASHTAG
""":const:`telegram.constants.MessageEntityType.HASHTAG`"""
ITALIC: Final[str] = constants.MessageEntityType.ITALIC
""":const:`telegram.constants.MessageEntityType.ITALIC`"""
MENTION: Final[str] = constants.MessageEntityType.MENTION
""":const:`telegram.constants.MessageEntityType.MENTION`"""
PHONE_NUMBER: Final[str] = constants.MessageEntityType.PHONE_NUMBER
""":const:`telegram.constants.MessageEntityType.PHONE_NUMBER`"""
PRE: Final[str] = constants.MessageEntityType.PRE
""":const:`telegram.constants.MessageEntityType.PRE`"""
SPOILER: Final[str] = constants.MessageEntityType.SPOILER
""":const:`telegram.constants.MessageEntityType.SPOILER`
.. versionadded:: 13.10
"""
STRIKETHROUGH: Final[str] = constants.MessageEntityType.STRIKETHROUGH
""":const:`telegram.constants.MessageEntityType.STRIKETHROUGH`"""
TEXT_LINK: Final[str] = constants.MessageEntityType.TEXT_LINK
""":const:`telegram.constants.MessageEntityType.TEXT_LINK`"""
TEXT_MENTION: Final[str] = constants.MessageEntityType.TEXT_MENTION
""":const:`telegram.constants.MessageEntityType.TEXT_MENTION`"""
UNDERLINE: Final[str] = constants.MessageEntityType.UNDERLINE
""":const:`telegram.constants.MessageEntityType.UNDERLINE`"""
URL: Final[str] = constants.MessageEntityType.URL
""":const:`telegram.constants.MessageEntityType.URL`"""

View File

@@ -0,0 +1,54 @@
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2025
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser Public License for more details.
#
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents an instance of a Telegram MessageId."""
from typing import Optional
from telegram._telegramobject import TelegramObject
from telegram._utils.types import JSONDict
class MessageId(TelegramObject):
"""This object represents a unique message identifier.
Objects of this class are comparable in terms of equality. Two objects of this class are
considered equal, if their :attr:`message_id` is equal.
Args:
message_id (:obj:`int`): Unique message identifier. In specific instances
(e.g., message containing a video sent to a big chat), the server might automatically
schedule a message instead of sending it immediately. In such cases, this field will be
``0`` and the relevant message will be unusable until it is actually sent.
Attributes:
message_id (:obj:`int`): Unique message identifier. In specific instances
(e.g., message containing a video sent to a big chat), the server might automatically
schedule a message instead of sending it immediately. In such cases, this field will be
``0`` and the relevant message will be unusable until it is actually sent.
"""
__slots__ = ("message_id",)
def __init__(self, message_id: int, *, api_kwargs: Optional[JSONDict] = None):
super().__init__(api_kwargs=api_kwargs)
self.message_id: int = message_id
self._id_attrs = (self.message_id,)
self._freeze()

View File

@@ -0,0 +1,282 @@
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2025
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser Public License for more details.
#
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains the classes that represent Telegram MessageOigin."""
import datetime as dtm
from typing import TYPE_CHECKING, Final, Optional
from telegram import constants
from telegram._chat import Chat
from telegram._telegramobject import TelegramObject
from telegram._user import User
from telegram._utils import enum
from telegram._utils.argumentparsing import de_json_optional
from telegram._utils.datetime import extract_tzinfo_from_defaults, from_timestamp
from telegram._utils.types import JSONDict
if TYPE_CHECKING:
from telegram import Bot
class MessageOrigin(TelegramObject):
"""
Base class for telegram MessageOrigin object, it can be one of:
* :class:`MessageOriginUser`
* :class:`MessageOriginHiddenUser`
* :class:`MessageOriginChat`
* :class:`MessageOriginChannel`
Objects of this class are comparable in terms of equality. Two objects of this class are
considered equal, if their :attr:`type` and :attr:`date` are equal.
.. versionadded:: 20.8
Args:
type (:obj:`str`): Type of the message origin, can be on of:
:attr:`~telegram.MessageOrigin.USER`, :attr:`~telegram.MessageOrigin.HIDDEN_USER`,
:attr:`~telegram.MessageOrigin.CHAT`, or :attr:`~telegram.MessageOrigin.CHANNEL`.
date (:obj:`datetime.datetime`): Date the message was sent originally.
|datetime_localization|
Attributes:
type (:obj:`str`): Type of the message origin, can be on of:
:attr:`~telegram.MessageOrigin.USER`, :attr:`~telegram.MessageOrigin.HIDDEN_USER`,
:attr:`~telegram.MessageOrigin.CHAT`, or :attr:`~telegram.MessageOrigin.CHANNEL`.
date (:obj:`datetime.datetime`): Date the message was sent originally.
|datetime_localization|
"""
__slots__ = (
"date",
"type",
)
USER: Final[str] = constants.MessageOriginType.USER
""":const:`telegram.constants.MessageOriginType.USER`"""
HIDDEN_USER: Final[str] = constants.MessageOriginType.HIDDEN_USER
""":const:`telegram.constants.MessageOriginType.HIDDEN_USER`"""
CHAT: Final[str] = constants.MessageOriginType.CHAT
""":const:`telegram.constants.MessageOriginType.CHAT`"""
CHANNEL: Final[str] = constants.MessageOriginType.CHANNEL
""":const:`telegram.constants.MessageOriginType.CHANNEL`"""
def __init__(
self,
type: str, # pylint: disable=W0622
date: dtm.datetime,
*,
api_kwargs: Optional[JSONDict] = None,
):
super().__init__(api_kwargs=api_kwargs)
# Required by all subclasses
self.type: str = enum.get_member(constants.MessageOriginType, type, type)
self.date: dtm.datetime = date
self._id_attrs = (
self.type,
self.date,
)
self._freeze()
@classmethod
def de_json(cls, data: JSONDict, bot: Optional["Bot"] = None) -> "MessageOrigin":
"""Converts JSON data to the appropriate :class:`MessageOrigin` object, i.e. takes
care of selecting the correct subclass.
"""
data = cls._parse_data(data)
_class_mapping: dict[str, type[MessageOrigin]] = {
cls.USER: MessageOriginUser,
cls.HIDDEN_USER: MessageOriginHiddenUser,
cls.CHAT: MessageOriginChat,
cls.CHANNEL: MessageOriginChannel,
}
if cls is MessageOrigin and data.get("type") in _class_mapping:
return _class_mapping[data.pop("type")].de_json(data=data, bot=bot)
loc_tzinfo = extract_tzinfo_from_defaults(bot)
data["date"] = from_timestamp(data.get("date"), tzinfo=loc_tzinfo)
if "sender_user" in data:
data["sender_user"] = de_json_optional(data.get("sender_user"), User, bot)
if "sender_chat" in data:
data["sender_chat"] = de_json_optional(data.get("sender_chat"), Chat, bot)
if "chat" in data:
data["chat"] = de_json_optional(data.get("chat"), Chat, bot)
return super().de_json(data=data, bot=bot)
class MessageOriginUser(MessageOrigin):
"""
The message was originally sent by a known user.
.. versionadded:: 20.8
Args:
date (:obj:`datetime.datetime`): Date the message was sent originally.
|datetime_localization|
sender_user (:class:`telegram.User`): User that sent the message originally.
Attributes:
type (:obj:`str`): Type of the message origin. Always
:tg-const:`~telegram.MessageOrigin.USER`.
date (:obj:`datetime.datetime`): Date the message was sent originally.
|datetime_localization|
sender_user (:class:`telegram.User`): User that sent the message originally.
"""
__slots__ = ("sender_user",)
def __init__(
self,
date: dtm.datetime,
sender_user: User,
*,
api_kwargs: Optional[JSONDict] = None,
):
super().__init__(type=self.USER, date=date, api_kwargs=api_kwargs)
with self._unfrozen():
self.sender_user: User = sender_user
class MessageOriginHiddenUser(MessageOrigin):
"""
The message was originally sent by an unknown user.
.. versionadded:: 20.8
Args:
date (:obj:`datetime.datetime`): Date the message was sent originally.
|datetime_localization|
sender_user_name (:obj:`str`): Name of the user that sent the message originally.
Attributes:
type (:obj:`str`): Type of the message origin. Always
:tg-const:`~telegram.MessageOrigin.HIDDEN_USER`.
date (:obj:`datetime.datetime`): Date the message was sent originally.
|datetime_localization|
sender_user_name (:obj:`str`): Name of the user that sent the message originally.
"""
__slots__ = ("sender_user_name",)
def __init__(
self,
date: dtm.datetime,
sender_user_name: str,
*,
api_kwargs: Optional[JSONDict] = None,
):
super().__init__(type=self.HIDDEN_USER, date=date, api_kwargs=api_kwargs)
with self._unfrozen():
self.sender_user_name: str = sender_user_name
class MessageOriginChat(MessageOrigin):
"""
The message was originally sent on behalf of a chat to a group chat.
.. versionadded:: 20.8
Args:
date (:obj:`datetime.datetime`): Date the message was sent originally.
|datetime_localization|
sender_chat (:class:`telegram.Chat`): Chat that sent the message originally.
author_signature (:obj:`str`, optional): For messages originally sent by an anonymous chat
administrator, original message author signature
Attributes:
type (:obj:`str`): Type of the message origin. Always
:tg-const:`~telegram.MessageOrigin.CHAT`.
date (:obj:`datetime.datetime`): Date the message was sent originally.
|datetime_localization|
sender_chat (:class:`telegram.Chat`): Chat that sent the message originally.
author_signature (:obj:`str`): Optional. For messages originally sent by an anonymous chat
administrator, original message author signature
"""
__slots__ = (
"author_signature",
"sender_chat",
)
def __init__(
self,
date: dtm.datetime,
sender_chat: Chat,
author_signature: Optional[str] = None,
*,
api_kwargs: Optional[JSONDict] = None,
):
super().__init__(type=self.CHAT, date=date, api_kwargs=api_kwargs)
with self._unfrozen():
self.sender_chat: Chat = sender_chat
self.author_signature: Optional[str] = author_signature
class MessageOriginChannel(MessageOrigin):
"""
The message was originally sent to a channel chat.
.. versionadded:: 20.8
Args:
date (:obj:`datetime.datetime`): Date the message was sent originally.
|datetime_localization|
chat (:class:`telegram.Chat`): Channel chat to which the message was originally sent.
message_id (:obj:`int`): Unique message identifier inside the chat.
author_signature (:obj:`str`, optional): Signature of the original post author.
Attributes:
type (:obj:`str`): Type of the message origin. Always
:tg-const:`~telegram.MessageOrigin.CHANNEL`.
date (:obj:`datetime.datetime`): Date the message was sent originally.
|datetime_localization|
chat (:class:`telegram.Chat`): Channel chat to which the message was originally sent.
message_id (:obj:`int`): Unique message identifier inside the chat.
author_signature (:obj:`str`): Optional. Signature of the original post author.
"""
__slots__ = (
"author_signature",
"chat",
"message_id",
)
def __init__(
self,
date: dtm.datetime,
chat: Chat,
message_id: int,
author_signature: Optional[str] = None,
*,
api_kwargs: Optional[JSONDict] = None,
):
super().__init__(type=self.CHANNEL, date=date, api_kwargs=api_kwargs)
with self._unfrozen():
self.chat: Chat = chat
self.message_id: int = message_id
self.author_signature: Optional[str] = author_signature

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