Compare commits

..

6 Commits

Author SHA1 Message Date
harshil21 75e700b4f3 Add chango fragment for PR #5267 2026-06-17 07:35:35 +00:00
Harshil 143b64581d Autogenerate Attribute docstrings (#5246) 2026-06-16 09:52:17 -04:00
Poolitzer afb9fc4898 Fix: Delete the chango here
I wasn't able to in the PR, it was too quick
2026-06-12 10:03:03 +02:00
Poolitzer 5d663af824 Bump version to v22.8 (#5262) 2026-06-12 10:02:13 +02:00
Harshil 0dd6afc177 Documentation Improvements (#5240)
Co-authored-by: Poolitzer <github@poolitzer.eu>
2026-06-12 09:46:44 +02:00
Harshil 4c710a3455 Support Python 3.15 beta (#5259) 2026-06-12 09:36:40 +02:00
218 changed files with 3715 additions and 6012 deletions
@@ -1,11 +1,11 @@
name: Test Admonitions Generation
name: Test Admonitions & Attributes Generation
on:
pull_request:
types: [synchronize, reopened, ready_for_review]
paths:
- src/telegram/**
- docs/**
- .github/workflows/docs-admonitions.yml
- .github/workflows/doc-tests.yml
push:
branches:
- master
@@ -13,8 +13,8 @@ on:
permissions: {}
jobs:
test-admonitions:
name: Test Admonitions Generation
test-admonitions-attributes:
name: Test Admonitions & Attributes Generation
runs-on: ${{matrix.os}}
permissions:
# for uploading artifacts
@@ -38,5 +38,5 @@ jobs:
run: |
python -W ignore -m pip install --upgrade pip
python -W ignore -m pip install .[all] --group all
- name: Test autogeneration of admonitions
run: pytest -v --tb=short tests/docs/admonition_inserter.py
- name: Test autogeneration of admonitions and attributes
run: pytest -v --tb=short tests/docs/admonition_inserter.py tests/docs/attribute_inserter.py
+1 -1
View File
@@ -19,7 +19,7 @@ jobs:
runs-on: ${{matrix.os}}
strategy:
matrix:
python-version: ['3.10', '3.11', '3.12', '3.13', '3.14']
python-version: ['3.10', '3.11', '3.12', '3.13', '3.14', '3.15.0-beta.2']
os: [ubuntu-latest, windows-latest, macos-latest]
include:
- python-version: '3.14t'
@@ -0,0 +1,6 @@
documentation = "Documentation Improvements"
pull_requests = [
{ uid = "5240", author_uids = ["harshil21", "Poolitzer"] },
{ uid = "5241", author_uids = ["harshil21"] },
]
@@ -0,0 +1,9 @@
other = """Support Python 3.15 Beta
* Python 3.15 free threading is not fully supported yet, as the optional dependency ``cryptography`` is not yet compatible with it.
"""
[[pull_requests]]
uid = "5259"
author_uids = ["harshil21"]
closes_threads = ["5231"]
@@ -0,0 +1,5 @@
other = "Bump Version to 22.8"
[[pull_requests]]
uid = "5262"
author_uids = ["Poolitzer"]
closes_threads = []
@@ -1,5 +1,5 @@
other = "Centralize `de_json` into `TelegramObject`"
documentation = "Autogenerate Attribute docstrings"
[[pull_requests]]
uid = "5186"
uid = "5246"
author_uids = ["harshil21"]
closes_threads = []
@@ -0,0 +1,5 @@
documentation = "Documentation Improvements"
[[pull_requests]]
uid = "5267"
author_uids = ["harshil21"]
closes_threads = []
+260
View File
@@ -0,0 +1,260 @@
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2026
# 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/].
"""Automatic generation of ``Attributes:`` section entries from ``Args:`` in class docstrings."""
import inspect
import re
import warnings
from dataclasses import dataclass
from telegram import TelegramObject
ENTRY_PATTERN: re.Pattern[str] = re.compile(r"^ (\w+) \((.+)\):\s*(.*)")
"""Matches a single entry like `` name (type): description`` in a docstring."""
KNOWN_SECTION_TITLES: frozenset[str] = frozenset(
{
"Args",
"Attributes",
"Returns",
"Raises",
"Note",
"Notes",
"Example",
"Examples",
"Keyword Args",
"Keyword Arguments",
}
)
def _is_section_header(line: str) -> bool:
return line.endswith(":") and line[:-1] in KNOWN_SECTION_TITLES
def _is_col0_noncontent(line: str) -> bool:
"""Non-blank col-0 line that is not a section header (e.g. RST substitution definitions)."""
return bool(line) and not line[0].isspace() and not _is_section_header(line)
def _save_entry(
entries: dict[str, "DocstringEntry"],
name: str,
raw_type: str,
raw_lines: list[str],
) -> None:
lines = list(raw_lines)
while lines and lines[-1] == "":
lines.pop()
is_optional = raw_type.endswith(", optional")
type_str = raw_type.removesuffix(", optional") if is_optional else raw_type
entries[name] = DocstringEntry(
name=name,
type_str=type_str,
is_optional=is_optional,
all_lines=tuple(lines),
)
@dataclass(frozen=True, slots=True)
class DocstringEntry:
name: str
type_str: str
is_optional: bool
all_lines: tuple[str, ...]
def to_attribute_lines(self) -> list[str]:
if not self.all_lines:
warnings.warn(
f"DocstringEntry {self.name!r} has no lines; skipping attribute generation.",
stacklevel=2,
)
return []
m = ENTRY_PATTERN.match(self.all_lines[0])
if m is None:
warnings.warn(
f"DocstringEntry {self.name!r}: first line does not match the entry pattern "
f"({self.all_lines[0]!r}); returning raw lines unchanged.",
stacklevel=2,
)
return list(self.all_lines)
desc: str = m.group(3)
new_type = self.type_str.replace("Sequence[", "tuple[")
new_desc = f"Optional. {desc}" if self.is_optional else desc
return [f" {self.name} ({new_type}): {new_desc}", *self.all_lines[1:]]
@dataclass(slots=True)
class DocstringSection:
title: str
entries: dict[str, DocstringEntry]
start_idx: int
end_idx: int
class DocstringParser:
"""Parse a Google-style docstring (list of lines) into sections and entries."""
__slots__ = ("_lines", "_sections")
def __init__(self, lines: list[str]) -> None:
self._lines = lines
self._sections: dict[str, DocstringSection] | None = None
@property
def sections(self) -> dict[str, DocstringSection]:
if self._sections is None:
self._sections = self._parse()
return self._sections
def get_section(self, title: str) -> DocstringSection | None:
return self.sections.get(title)
def _parse(self) -> dict[str, DocstringSection]:
sections: dict[str, DocstringSection] = {}
lines = self._lines
n = len(lines)
i = 0
while i < n:
line = lines[i]
if _is_section_header(line):
title = line[:-1]
start_idx = i
i += 1
entries, end_idx = self._parse_section_entries(i, n)
i = end_idx
sections[title] = DocstringSection(
title=title,
entries=entries,
start_idx=start_idx,
end_idx=end_idx,
)
else:
i += 1
return sections
def _parse_section_entries(
self,
start: int,
end: int,
) -> tuple[dict[str, DocstringEntry], int]:
entries: dict[str, DocstringEntry] = {}
current_name: str | None = None
current_raw_type: str = ""
current_lines: list[str] = []
lines = self._lines
i = start
while i < end:
line = lines[i]
# RST substitution definitions and other on-section content end the section.
if _is_section_header(line) or _is_col0_noncontent(line):
break
m = ENTRY_PATTERN.match(line)
if m:
if current_name is not None:
_save_entry(entries, current_name, current_raw_type, current_lines)
current_name = m.group(1)
current_raw_type = m.group(2)
current_lines = [line]
elif current_name is not None:
current_lines.append(line)
i += 1
if current_name is not None:
_save_entry(entries, current_name, current_raw_type, current_lines)
return entries, i
class AttributeInserter:
"""Inserts auto-generated ``Attributes:`` entries into class docstrings."""
def insert_attributes(self, obj: type, lines: list[str]) -> None:
"""Insert missing attribute entries derived from the ``Args:`` section in-place."""
parser = DocstringParser(lines)
args_section = parser.get_section("Args")
attrs_section = parser.get_section("Attributes")
already_documented: set[str] = (
set(attrs_section.entries.keys()) if attrs_section is not None else set()
)
args_entries: dict[str, DocstringEntry] = (
args_section.entries if args_section is not None else {}
)
args_names: set[str] = set(args_entries.keys())
properties_on_class: set[str] = {
name for name, _ in inspect.getmembers(obj, lambda o: isinstance(o, property))
}
# Raise when own public slots have no documentation source.
# Get slots from TGObject if it's a TGObj subclass:
if issubclass(obj, TelegramObject):
all_slots = {
s
for c in obj.__mro__[:-1]
if issubclass(c, TelegramObject)
for s in c.__slots__
if not s.startswith("_")
}
all_slots.remove("api_kwargs")
else:
all_slots = (s for s in getattr(obj, "__slots__", ()) if not s.startswith("_"))
for slot in all_slots:
if (
slot not in already_documented
and slot not in args_names
and slot not in properties_on_class
):
raise RuntimeError(
f"Class {obj.__qualname__!r}: public slot {slot!r} has no documentation "
f"source. Please add it to the 'Attributes:' section manually.",
)
new_attr_lines: list[str] = []
for name, entry in args_entries.items():
if name in already_documented or name in properties_on_class:
continue
new_attr_lines.extend(entry.to_attribute_lines())
new_attr_lines.append("")
if not new_attr_lines:
return
if attrs_section is not None:
insert_idx = attrs_section.end_idx
while insert_idx > attrs_section.start_idx + 1 and lines[insert_idx - 1] == "":
insert_idx -= 1
lines[insert_idx:insert_idx] = new_attr_lines
else:
if lines and lines[-1].strip():
lines.append("")
lines.append("Attributes:")
lines.extend(new_attr_lines)
@@ -83,16 +83,22 @@ get_updates_read_timeout_addition = [
" ``2``.",
]
def find_insert_pos_for_kwargs(lines: list[str]) -> int:
"""Finds the correct position to insert the keyword arguments and returns the index."""
for idx, value in reversed(list(enumerate(lines))): # reversed since :returns: is at the end
if value.startswith("Returns"):
return idx
return False
RAISES_BLOCK = [
"Raises:",
"",
" :class:`telegram.error.TelegramError`",
"",
]
def check_timeout_and_api_kwargs_presence(obj: object) -> int:
def find_insert_pos_for_raises(lines: list[str]) -> int:
"""Finds the correct position to insert the Raises block and returns the index."""
if "Raises:" in lines:
return -1 # Don't insert if there's already a Raises block
return len(lines) # Insert at the end if there's no Raises block
def check_timeout_and_api_kwargs_presence(obj: object) -> bool:
"""Checks if the method has timeout and api_kwargs keyword only parameters."""
sig = inspect.signature(obj)
params_to_check = (
+31 -11
View File
@@ -27,9 +27,10 @@ from sphinx.application import Sphinx
import telegram
import telegram.ext
from docs.auxil.admonition_inserter import AdmonitionInserter
from docs.auxil.kwargs_insertion import (
from docs.auxil.attribute_inserter import AttributeInserter, DocstringParser
from docs.auxil.bot_insertion import (
RAISES_BLOCK,
check_timeout_and_api_kwargs_presence,
find_insert_pos_for_kwargs,
get_updates_read_timeout_addition,
keyword_args,
media_write_timeout_change,
@@ -42,6 +43,7 @@ if TYPE_CHECKING:
ADMONITION_INSERTER = AdmonitionInserter()
ATTRIBUTE_INSERTER = AttributeInserter()
# Some base classes are implementation detail
# We want to instead show *their* base class
@@ -85,14 +87,15 @@ def autodoc_process_docstring(
app: Sphinx, what, name: str, obj: object, options, lines: list[str]
):
"""We do the following things:
1) Use this method to automatically insert the Keyword Args and "Shortcuts" admonitions
for the Bot methods.
1) Use this method to automatically insert the Keyword Args, "Shortcuts" admonitions,
and the Raises block, wherever applicable, for the Bot methods.
2) Use this method to automatically insert "Returned in" admonition into classes
that are returned from the Bot methods
3) Use this method to automatically insert "Available in" admonition into classes
whose instances are available as attributes of other classes
3) Use this method to automatically insert the Attributes block, wherever applicable,
for Telegram objects. The "Available in" admonition is then also inserted. These are
instances of a class which are available as attributes of other classes.
4) Use this method to automatically insert "Use in" admonition into classes
whose instances can be used as arguments of the Bot methods
@@ -101,19 +104,23 @@ def autodoc_process_docstring(
to the actual object here.
"""
# 1) Insert the Keyword Args and "Shortcuts" admonitions for the Bot methods
method_name = name.rsplit(".", maxsplit=1)[0]
# 1) Insert the Keyword Args, "Shortcuts" admonitions, and "Raises" block for the Bot methods
method_name = name.rsplit(".", maxsplit=1)[-1]
if (
name.startswith("telegram.Bot.")
and what == "method"
and method_name.islower()
and check_timeout_and_api_kwargs_presence(obj)
):
insert_index = find_insert_pos_for_kwargs(lines)
if not insert_index:
parser = DocstringParser(lines)
# Logic for inserting keyword args into docstrings:
# -------------------------------------------------
returns_section = parser.get_section("Returns")
if not returns_section:
raise ValueError(
f"Couldn't find the correct position to insert the keyword args for {obj}."
)
insert_index = returns_section.start_idx
get_updates: bool = method_name == "get_updates"
# The below can be done in 1 line with itertools.chain, but this must be modified in-place
@@ -134,6 +141,14 @@ def autodoc_process_docstring(
lines[insert_idx:insert_idx] = effective_insert
insert_idx += len(effective_insert)
# Logic for inserting Raises:
# -------------------------------------------------
# We will only insert the Raises block if there isn't already one.
if parser.get_section("Raises") is None:
lines.extend(RAISES_BLOCK)
# Logic for inserting "Shortcuts" admonition:
# -------------------------------------------
ADMONITION_INSERTER.insert_admonitions(
obj=typing.cast("collections.abc.Callable", obj),
docstring_lines=lines,
@@ -141,7 +156,12 @@ def autodoc_process_docstring(
# 2-4) Insert "Returned in", "Available in", "Use in" admonitions into classes
# (where applicable)
if what == "class":
if what in ("class", "exception"):
# Auto-generate Attributes section entries from Args before admonitions are inserted
ATTRIBUTE_INSERTER.insert_attributes(
obj=typing.cast("type", obj),
lines=lines,
)
ADMONITION_INSERTER.insert_admonitions(
obj=typing.cast("type", obj), # since "what" == class, we know it's not just object
docstring_lines=lines,
+1
View File
@@ -165,6 +165,7 @@ Available Types
telegram.poll
telegram.pollanswer
telegram.pollmedia
telegram.polloption
telegram.polloptionadded
telegram.polloptiondeleted
telegram.preparedkeyboardbutton
+1
View File
@@ -36,6 +36,7 @@ classifiers = [
"Programming Language :: Python :: 3.12",
"Programming Language :: Python :: 3.13",
"Programming Language :: Python :: 3.14",
"Programming Language :: Python :: 3.15",
]
dependencies = [
"httpx >=0.27,<0.29",
+19 -18
View File
@@ -343,19 +343,7 @@ __all__ = (
"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,
)
__lazy_modules__: list[str] = ["constants", "error", "helpers", "request", "warnings"]
from . import _version, constants, error, helpers, request, warnings
from ._birthdate import Birthdate
@@ -431,11 +419,6 @@ from ._copytextbutton import CopyTextButton
from ._dice import Dice
from ._directmessagepricechanged import DirectMessagePriceChanged
from ._directmessagestopic import DirectMessagesTopic
from ._files._inputstorycontent import (
InputStoryContent,
InputStoryContentPhoto,
InputStoryContentVideo,
)
from ._files.animation import Animation
from ._files.audio import Audio
from ._files.chatphoto import ChatPhoto
@@ -467,6 +450,11 @@ from ._files.inputprofilephoto import (
InputProfilePhotoStatic,
)
from ._files.inputsticker import InputSticker
from ._files.inputstorycontent import (
InputStoryContent,
InputStoryContentPhoto,
InputStoryContentVideo,
)
from ._files.livephoto import LivePhoto
from ._files.location import Location
from ._files.photosize import PhotoSize
@@ -523,6 +511,7 @@ from ._inline.inputmessagecontent import InputMessageContent
from ._inline.inputtextmessagecontent import InputTextMessageContent
from ._inline.inputvenuemessagecontent import InputVenueMessageContent
from ._inline.preparedinlinemessage import PreparedInlineMessage
from ._inputchecklist import InputChecklist, InputChecklistTask
from ._keyboardbutton import KeyboardButton
from ._keyboardbuttonpolltype import KeyboardButtonPollType
from ._keyboardbuttonrequest import (
@@ -596,6 +585,18 @@ from ._payment.stars.revenuewithdrawalstate import (
RevenueWithdrawalStatePending,
RevenueWithdrawalStateSucceeded,
)
from ._payment.stars.staramount import StarAmount
from ._payment.stars.startransactions import StarTransaction, StarTransactions
from ._payment.stars.transactionpartner import (
TransactionPartner,
TransactionPartnerAffiliateProgram,
TransactionPartnerChat,
TransactionPartnerFragment,
TransactionPartnerOther,
TransactionPartnerTelegramAds,
TransactionPartnerTelegramApi,
TransactionPartnerUser,
)
from ._payment.successfulpayment import SuccessfulPayment
from ._poll import (
InputPollOption,
-6
View File
@@ -37,12 +37,6 @@ class Birthdate(TelegramObject):
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")
+46 -621
View File
File diff suppressed because it is too large Load Diff
+14 -2
View File
@@ -19,12 +19,16 @@
"""This module contains an object that represents a Telegram Bot Access Settings."""
from collections.abc import Sequence
from typing import TYPE_CHECKING
from telegram._telegramobject import TelegramObject
from telegram._user import User
from telegram._utils.argumentparsing import parse_sequence_arg
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 BotAccessSettings(TelegramObject):
"""
@@ -33,7 +37,7 @@ class BotAccessSettings(TelegramObject):
Objects of this class are comparable in terms of equality. Two objects of this class are
considered equal, if their :attr:`is_access_restricted` and :attr:`added_users` are equal.
.. versionadded:: NEXT.VERSION
.. versionadded:: 22.8
Args:
is_access_restricted (:obj:`bool`): :obj:`True`, if only selected users can access the bot.
@@ -63,3 +67,11 @@ class BotAccessSettings(TelegramObject):
self._id_attrs = (self.is_access_restricted, self.added_users)
self._freeze()
@classmethod
def de_json(cls, data: JSONDict, bot: "Bot | None" = None) -> "BotAccessSettings":
"""See :meth:`telegram.TelegramObject.de_json`."""
data = cls._parse_data(data)
data["added_users"] = de_list_optional(data.get("added_users"), User, bot)
return super().de_json(data=data, bot=bot)
-9
View File
@@ -39,15 +39,6 @@ class BotCommand(TelegramObject):
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")
+37 -21
View File
@@ -19,13 +19,16 @@
# pylint: disable=redefined-builtin
"""This module contains objects representing Telegram bot command scopes."""
from typing import ClassVar, Final
from typing import TYPE_CHECKING, Final
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.
@@ -52,26 +55,10 @@ class BotCommandScope(TelegramObject):
Args:
type (:obj:`str`): Scope type.
Attributes:
type (:obj:`str`): Scope type.
"""
__slots__ = ("type",)
__DE_JSON_DISPATCH__: ClassVar[tuple[str, dict[str, str]] | None] = (
"type",
{
"default": "BotCommandScopeDefault",
"all_private_chats": "BotCommandScopeAllPrivateChats",
"all_group_chats": "BotCommandScopeAllGroupChats",
"all_chat_administrators": "BotCommandScopeAllChatAdministrators",
"chat": "BotCommandScopeChat",
"chat_administrators": "BotCommandScopeChatAdministrators",
"chat_member": "BotCommandScopeChatMember",
},
)
DEFAULT: Final[str] = constants.BotCommandScopeType.DEFAULT
""":const:`telegram.constants.BotCommandScopeType.DEFAULT`"""
ALL_PRIVATE_CHATS: Final[str] = constants.BotCommandScopeType.ALL_PRIVATE_CHATS
@@ -94,6 +81,39 @@ class BotCommandScope(TelegramObject):
self._freeze()
@classmethod
def de_json(cls, data: JSONDict, bot: "Bot | None" = 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
@@ -172,7 +192,6 @@ class BotCommandScopeChat(BotCommandScope):
Attributes:
type (:obj:`str`): Scope type :tg-const:`telegram.BotCommandScope.CHAT`.
chat_id (:obj:`str` | :obj:`int`): |chat_id_group|
"""
__slots__ = ("chat_id",)
@@ -199,7 +218,6 @@ class BotCommandScopeChatAdministrators(BotCommandScope):
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",)
@@ -228,8 +246,6 @@ class BotCommandScopeChatMember(BotCommandScope):
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")
-8
View File
@@ -32,10 +32,6 @@ class BotDescription(TelegramObject):
Args:
description (:obj:`str`): The bot's description.
Attributes:
description (:obj:`str`): The bot's description.
"""
__slots__ = ("description",)
@@ -59,10 +55,6 @@ class BotShortDescription(TelegramObject):
Args:
short_description (:obj:`str`): The bot's short description.
Attributes:
short_description (:obj:`str`): The bot's short description.
"""
__slots__ = ("short_description",)
-4
View File
@@ -35,10 +35,6 @@ class BotName(TelegramObject):
Args:
name (:obj:`str`): The bot's name.
Attributes:
name (:obj:`str`): The bot's name.
"""
__slots__ = ("name",)
+60 -75
View File
@@ -25,19 +25,24 @@ from typing import TYPE_CHECKING
from zoneinfo import ZoneInfo
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,
get_zone_info,
)
from telegram._utils.types import JSONDict
if TYPE_CHECKING:
from telegram._files.location import Location
from telegram._user import User
from telegram import Bot
class BusinessBotRights(TelegramObject):
@@ -79,37 +84,6 @@ class BusinessBotRights(TelegramObject):
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__ = (
@@ -209,17 +183,6 @@ class BusinessConnection(TelegramObject):
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__ = (
@@ -261,6 +224,20 @@ class BusinessConnection(TelegramObject):
self._freeze()
@classmethod
def de_json(cls, data: JSONDict, bot: "Bot | None" = 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):
"""
@@ -278,13 +255,6 @@ class BusinessMessagesDeleted(TelegramObject):
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__ = (
@@ -314,6 +284,15 @@ class BusinessMessagesDeleted(TelegramObject):
self._freeze()
@classmethod
def de_json(cls, data: JSONDict, bot: "Bot | None" = 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):
"""
@@ -329,11 +308,6 @@ class BusinessIntro(TelegramObject):
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__ = (
@@ -359,6 +333,15 @@ class BusinessIntro(TelegramObject):
self._freeze()
@classmethod
def de_json(cls, data: JSONDict, bot: "Bot | None" = 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):
"""
@@ -373,10 +356,6 @@ class BusinessLocation(TelegramObject):
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__ = (
@@ -399,6 +378,15 @@ class BusinessLocation(TelegramObject):
self._freeze()
@classmethod
def de_json(cls, data: JSONDict, bot: "Bot | None" = 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):
"""
@@ -432,14 +420,6 @@ class BusinessOpeningHoursInterval(TelegramObject):
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")
@@ -507,12 +487,6 @@ class BusinessOpeningHours(TelegramObject):
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__ = ("_cached_zone_info", "opening_hours", "time_zone_name")
@@ -526,7 +500,7 @@ class BusinessOpeningHours(TelegramObject):
):
super().__init__(api_kwargs=api_kwargs)
self.time_zone_name: str = time_zone_name
self.opening_hours: Sequence[BusinessOpeningHoursInterval] = parse_sequence_arg(
self.opening_hours: tuple[BusinessOpeningHoursInterval, ...] = parse_sequence_arg(
opening_hours
)
@@ -632,3 +606,14 @@ class BusinessOpeningHours(TelegramObject):
return True
return False
@classmethod
def de_json(cls, data: JSONDict, bot: "Bot | None" = 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)
+12 -16
View File
@@ -27,11 +27,13 @@ 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, TimePeriod
if TYPE_CHECKING:
from telegram import (
Bot,
GameHighScore,
InlineKeyboardMarkup,
InputMedia,
@@ -89,16 +91,6 @@ class CallbackQuery(TelegramObject):
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.
@@ -106,12 +98,6 @@ class CallbackQuery(TelegramObject):
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__ = (
@@ -151,6 +137,16 @@ class CallbackQuery(TelegramObject):
self._freeze()
@classmethod
def de_json(cls, data: JSONDict, bot: "Bot | None" = 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: str | None = None,
+4 -22
View File
@@ -1110,7 +1110,7 @@ class _ChatBase(TelegramObject):
For the documentation of the arguments, please see :meth:`telegram.Bot.send_message_draft`.
.. versionchanged:: NEXT.VERSION
.. versionchanged:: 22.8
Bot API 10.0 makes the ``text`` argument optional.
Returns:
@@ -1392,7 +1392,7 @@ class _ChatBase(TelegramObject):
For the documentation of the arguments, please see :meth:`telegram.Bot.send_live_photo`.
.. versionadded:: NEXT.VERSION
.. versionadded:: 22.8
Returns:
:class:`telegram.Message`: On success, instance representing the message posted.
@@ -4155,7 +4155,7 @@ class _ChatBase(TelegramObject):
For the documentation of the arguments, please see
:meth:`telegram.Bot.delete_message_reaction`.
.. versionadded:: NEXT.VERSION
.. versionadded:: 22.8
Returns:
:obj:`bool`: On success, :obj:`True` is returned.
@@ -4195,7 +4195,7 @@ class _ChatBase(TelegramObject):
For the documentation of the arguments, please see
:meth:`telegram.Bot.delete_all_message_reactions`.
.. versionadded:: NEXT.VERSION
.. versionadded:: 22.8
Returns:
:obj:`bool`: On success, :obj:`True` is returned.
@@ -4253,24 +4253,6 @@ class Chat(_ChatBase):
.. versionadded:: 22.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`.
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
is_direct_messages (:obj:`bool`): Optional. :obj:`True`, if the chat is the direct messages
chat of a channel.
.. versionadded:: 22.4
.. _topics: https://telegram.org/blog/topics-in-groups-collectible-usernames#topics-in-groups
"""
-58
View File
@@ -113,64 +113,6 @@ class ChatAdministratorRights(TelegramObject):
tags of regular members; for groups and supergroups only. If omitted defaults to the
value of :attr:`can_pin_messages`.
.. versionadded:: 22.7
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
can_manage_direct_messages (:obj:`bool`): Optional. :obj:`True`, if the administrator can
manage direct messages of the channel and decline suggested posts; for channels only.
.. versionadded:: 22.4
can_manage_tags (:obj:`bool`): Optional. :obj:`True`, if the administrator can edit the
tags of regular members; for groups and supergroups only. If omitted defaults to the
value of :attr:`can_pin_messages`.
.. versionadded:: 22.7
"""
+53 -68
View File
@@ -19,15 +19,18 @@
"""This module contains objects related to chat backgrounds."""
from collections.abc import Sequence
from typing import ClassVar, Final
from typing import TYPE_CHECKING, Final
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 parse_sequence_arg
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:
@@ -45,24 +48,10 @@ class BackgroundFill(TelegramObject):
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",)
__DE_JSON_DISPATCH__: ClassVar[tuple[str, dict[str, str]] | None] = (
"type",
{
"solid": "BackgroundFillSolid",
"gradient": "BackgroundFillGradient",
"freeform_gradient": "BackgroundFillFreeformGradient",
},
)
SOLID: Final[constants.BackgroundFillType] = constants.BackgroundFillType.SOLID
""":const:`telegram.constants.BackgroundFillType.SOLID`"""
GRADIENT: Final[constants.BackgroundFillType] = constants.BackgroundFillType.GRADIENT
@@ -85,6 +74,22 @@ class BackgroundFill(TelegramObject):
self._id_attrs = (self.type,)
self._freeze()
@classmethod
def de_json(cls, data: JSONDict, bot: "Bot | None" = 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):
"""
@@ -101,7 +106,6 @@ class BackgroundFillSolid(BackgroundFill):
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",)
@@ -141,11 +145,6 @@ class BackgroundFillGradient(BackgroundFill):
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")
@@ -184,8 +183,6 @@ class BackgroundFillFreeformGradient(BackgroundFill):
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",)
@@ -222,27 +219,10 @@ class BackgroundType(TelegramObject):
: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",)
__DE_JSON_DISPATCH__: ClassVar[tuple[str, dict[str, str]] | None] = (
"type",
{
"fill": "BackgroundTypeFill",
"wallpaper": "BackgroundTypeWallpaper",
"pattern": "BackgroundTypePattern",
"chat_theme": "BackgroundTypeChatTheme",
},
)
FILL: Final[constants.BackgroundTypeType] = constants.BackgroundTypeType.FILL
""":const:`telegram.constants.BackgroundTypeType.FILL`"""
WALLPAPER: Final[constants.BackgroundTypeType] = constants.BackgroundTypeType.WALLPAPER
@@ -265,6 +245,29 @@ class BackgroundType(TelegramObject):
self._id_attrs = (self.type,)
self._freeze()
@classmethod
def de_json(cls, data: JSONDict, bot: "Bot | None" = 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):
"""
@@ -284,10 +287,6 @@ class BackgroundTypeFill(BackgroundType):
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")
@@ -330,14 +329,6 @@ class BackgroundTypeWallpaper(BackgroundType):
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")
@@ -391,17 +382,6 @@ class BackgroundTypePattern(BackgroundType):
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__ = (
@@ -451,7 +431,6 @@ class BackgroundTypeChatTheme(BackgroundType):
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",)
@@ -481,9 +460,6 @@ class ChatBackground(TelegramObject):
Args:
type (:class:`telegram.BackgroundType`): Type of the background.
Attributes:
type (:class:`telegram.BackgroundType`): Type of the background.
"""
__slots__ = ("type",)
@@ -499,3 +475,12 @@ class ChatBackground(TelegramObject):
self._id_attrs = (self.type,)
self._freeze()
@classmethod
def de_json(cls, data: JSONDict, bot: "Bot | None" = 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)
+68 -52
View File
@@ -20,16 +20,20 @@
import datetime as dtm
from collections.abc import Sequence
from typing import ClassVar, Final
from typing import TYPE_CHECKING, Final
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 parse_sequence_arg
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):
"""
@@ -43,10 +47,6 @@ class ChatBoostAdded(TelegramObject):
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",)
@@ -81,24 +81,10 @@ class ChatBoostSource(TelegramObject):
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",)
__DE_JSON_DISPATCH__: ClassVar[tuple[str, dict[str, str]] | None] = (
"source",
{
"premium": "ChatBoostSourcePremium",
"gift_code": "ChatBoostSourceGiftCode",
"giveaway": "ChatBoostSourceGiveaway",
},
)
PREMIUM: Final[str] = constants.ChatBoostSources.PREMIUM
""":const:`telegram.constants.ChatBoostSources.PREMIUM`"""
GIFT_CODE: Final[str] = constants.ChatBoostSources.GIFT_CODE
@@ -115,6 +101,25 @@ class ChatBoostSource(TelegramObject):
self._id_attrs = (self.source,)
self._freeze()
@classmethod
def de_json(cls, data: JSONDict, bot: "Bot | None" = 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):
"""
@@ -129,7 +134,6 @@ class ChatBoostSourcePremium(ChatBoostSource):
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",)
@@ -155,7 +159,6 @@ class ChatBoostSourceGiftCode(ChatBoostSource):
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",)
@@ -191,15 +194,6 @@ class ChatBoostSourceGiveaway(ChatBoostSource):
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")
@@ -233,14 +227,6 @@ class ChatBoost(TelegramObject):
.. 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|
@@ -271,6 +257,18 @@ class ChatBoost(TelegramObject):
self._id_attrs = (self.boost_id, self.add_date, self.expiration_date, self.source)
self._freeze()
@classmethod
def de_json(cls, data: JSONDict, bot: "Bot | None" = 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.
@@ -283,10 +281,6 @@ class ChatBoostUpdated(TelegramObject):
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")
@@ -306,6 +300,16 @@ class ChatBoostUpdated(TelegramObject):
self._id_attrs = (self.chat.id, self.boost)
self._freeze()
@classmethod
def de_json(cls, data: JSONDict, bot: "Bot | None" = 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):
"""
@@ -316,12 +320,6 @@ class ChatBoostRemoved(TelegramObject):
: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.
@@ -350,6 +348,18 @@ class ChatBoostRemoved(TelegramObject):
self._id_attrs = (self.chat, self.boost_id, self.remove_date, self.source)
self._freeze()
@classmethod
def de_json(cls, data: JSONDict, bot: "Bot | None" = 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.
@@ -362,9 +372,6 @@ class UserChatBoosts(TelegramObject):
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",)
@@ -381,3 +388,12 @@ class UserChatBoosts(TelegramObject):
self._id_attrs = (self.boosts,)
self._freeze()
@classmethod
def de_json(cls, data: JSONDict, bot: "Bot | None" = 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)
+54 -177
View File
@@ -34,16 +34,20 @@ from telegram._reaction import ReactionType
from telegram._uniquegift import UniqueGiftColors
from telegram._userrating import UserRating
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 BusinessIntro, BusinessLocation, BusinessOpeningHours, Message
from telegram import Bot, BusinessIntro, BusinessLocation, BusinessOpeningHours, Message
class ChatFullInfo(_ChatBase):
@@ -249,129 +253,12 @@ class ChatFullInfo(_ChatBase):
.. versionadded:: 22.7
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.
@@ -379,65 +266,6 @@ class ChatFullInfo(_ChatBase):
.. 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
is_direct_messages (:obj:`bool`): Optional. :obj:`True`, if the chat is the direct messages
chat of a channel.
.. versionadded:: 22.4
parent_chat (:obj:`telegram.Chat`): Optional. Information about the corresponding channel
chat; for direct messages chats only.
.. versionadded:: 22.4
rating (:class:`telegram.UserRating`): Optional. For private chats, the rating of the user
if any.
.. versionadded:: 22.6
unique_gift_colors (:class:`telegram.UniqueGiftColors`): Optional. The color scheme based
on a unique gift that must be used for the chat's name, message replies and link
previews
.. versionadded:: 22.6
paid_message_star_count (:obj:`int`): Optional. The number of Telegram Stars a general user
have to pay to send a message to the chat
.. versionadded:: 22.6
first_profile_audio (:obj:`telegram.Audio`): Optional. For private chats, the first audio
added to the profile of the user.
.. versionadded:: 22.7
.. _accent colors: https://core.telegram.org/bots/api#accent-colors
.. _topics: https://telegram.org/blog/topics-in-groups-collectible-usernames#topics-in-groups
@@ -619,3 +447,52 @@ class ChatFullInfo(_ChatBase):
return get_timedelta_value(
self._message_auto_delete_time, attribute="message_auto_delete_time"
)
@classmethod
def de_json(cls, data: JSONDict, bot: "Bot | None" = 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
)
data["parent_chat"] = de_json_optional(data.get("parent_chat"), Chat, bot)
data["rating"] = de_json_optional(data.get("rating"), UserRating, bot)
data["unique_gift_colors"] = de_json_optional(
data.get("unique_gift_colors"), UniqueGiftColors, bot
)
data["first_profile_audio"] = de_json_optional(data.get("first_profile_audio"), Audio, bot)
return super().de_json(data=data, bot=bot)
+23 -34
View File
@@ -19,13 +19,21 @@
"""This module contains an object that represents an invite link for a chat."""
import datetime as dtm
from typing import TYPE_CHECKING
from telegram._telegramobject import TelegramObject
from telegram._user import User
from telegram._utils.argumentparsing import to_timedelta
from telegram._utils.datetime import get_timedelta_value
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.
@@ -81,32 +89,6 @@ class ChatInviteLink(TelegramObject):
.. 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.
@@ -114,12 +96,6 @@ class ChatInviteLink(TelegramObject):
.. 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__ = (
@@ -183,3 +159,16 @@ class ChatInviteLink(TelegramObject):
@property
def subscription_period(self) -> int | dtm.timedelta | None:
return get_timedelta_value(self._subscription_period, attribute="subscription_period")
@classmethod
def de_json(cls, data: JSONDict, bot: "Bot | None" = 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)
+23 -21
View File
@@ -19,14 +19,20 @@
"""This module contains an object that represents a Telegram ChatJoinRequest."""
import datetime as dtm
from typing import TYPE_CHECKING
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.
@@ -56,10 +62,7 @@ class ChatJoinRequest(TelegramObject):
.. 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
request. 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.
@@ -69,28 +72,12 @@ class ChatJoinRequest(TelegramObject):
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 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.
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.
be present. However, this behavior is undocumented and may be subject to change.
See `this GitHub thread <https://github.com/tdlib/telegram-bot-api/issues/428>`_
for some discussion.
@@ -124,6 +111,21 @@ class ChatJoinRequest(TelegramObject):
self._freeze()
@classmethod
def de_json(cls, data: JSONDict, bot: "Bot | None" = 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,
*,
+14 -8
View File
@@ -18,13 +18,17 @@
# 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 Final
from typing import TYPE_CHECKING, Final
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.
@@ -38,13 +42,6 @@ class ChatLocation(TelegramObject):
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")
@@ -64,6 +61,15 @@ class ChatLocation(TelegramObject):
self._freeze()
@classmethod
def de_json(cls, data: JSONDict, bot: "Bot | None" = 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`
+40 -170
View File
@@ -19,14 +19,19 @@
"""This module contains an object that represents a Telegram ChatMember."""
import datetime as dtm
from typing import ClassVar, Final
from typing import TYPE_CHECKING, Final
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.
@@ -60,30 +65,10 @@ class ChatMember(TelegramObject):
: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")
__DE_JSON_DISPATCH__: ClassVar[tuple[str, dict[str, str]] | None] = (
"status",
{
"creator": "ChatMemberOwner",
"administrator": "ChatMemberAdministrator",
"member": "ChatMemberMember",
"restricted": "ChatMemberRestricted",
"left": "ChatMemberLeft",
"kicked": "ChatMemberBanned",
},
)
ADMINISTRATOR: Final[str] = constants.ChatMemberStatus.ADMINISTRATOR
""":const:`telegram.constants.ChatMemberStatus.ADMINISTRATOR`"""
OWNER: Final[str] = constants.ChatMemberStatus.OWNER
@@ -113,6 +98,38 @@ class ChatMember(TelegramObject):
self._freeze()
@classmethod
def de_json(cls, data: JSONDict, bot: "Bot | None" = 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):
"""
@@ -130,11 +147,6 @@ class ChatMemberOwner(ChatMember):
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")
@@ -241,71 +253,6 @@ class ChatMemberAdministrator(ChatMember):
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.
can_manage_direct_messages (:obj:`bool`): Optional. :obj:`True`, if the administrator can
manage direct messages of the channel and decline suggested posts; for channels only.
.. versionadded:: 22.4
can_manage_tags (:obj:`bool`): Optional. :obj:`True`, if the administrator can edit the
tags of regular members; for groups and supergroups only. If omitted defaults to the
value of :attr:`can_pin_messages`.
.. versionadded:: 22.7
"""
__slots__ = (
@@ -399,15 +346,6 @@ class ChatMemberMember(ChatMember):
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
tag (:obj:`str`): Optional. Tag of the member.
.. versionadded:: 22.7
"""
__slots__ = (
@@ -496,7 +434,7 @@ class ChatMemberRestricted(ChatMember):
can_react_to_messages (:obj:`bool`): :obj:`True`, if the user is allowed to react to
messages.
.. versionadded:: NEXT.VERSION
.. versionadded:: 22.8
tag (:obj:`str`, optional): Tag of the member.
.. versionadded:: 22.7
@@ -504,64 +442,6 @@ class ChatMemberRestricted(ChatMember):
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
can_edit_tag (:obj:`bool`): :obj:`True`, if the user is allowed to edit their own tag.
If omitted, defaults to the value of :attr:`can_pin_messages`.
.. versionadded:: 22.7
can_react_to_messages (:obj:`bool`): :obj:`True`, if the user is allowed to react to
messages.
.. versionadded:: NEXT.VERSION
tag (:obj:`str`): Optional. Tag of the member.
.. versionadded:: 22.7
"""
__slots__ = (
@@ -586,8 +466,6 @@ class ChatMemberRestricted(ChatMember):
"until_date",
)
__REMOVED_API_FIELDS__: ClassVar[frozenset[str]] = frozenset({"can_send_media_messages"})
def __init__(
self,
user: User,
@@ -609,7 +487,7 @@ class ChatMemberRestricted(ChatMember):
can_send_voice_notes: bool,
can_edit_tag: bool,
tag: str | None = None,
# tags: NEXT.VERSION
# tags: 22.8
# temporarily optional to make it not breaking
can_react_to_messages: bool | None = None,
*,
@@ -655,7 +533,6 @@ class ChatMemberLeft(ChatMember):
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__ = ()
@@ -688,13 +565,6 @@ class ChatMemberBanned(ChatMember):
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",)
+23 -23
View File
@@ -19,14 +19,20 @@
"""This module contains an object that represents a Telegram ChatMemberUpdated."""
import datetime as dtm
from typing import TYPE_CHECKING
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.
@@ -64,29 +70,6 @@ class ChatMemberUpdated(TelegramObject):
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__ = (
@@ -136,6 +119,23 @@ class ChatMemberUpdated(TelegramObject):
self._freeze()
@classmethod
def de_json(cls, data: JSONDict, bot: "Bot | None" = 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]
+24 -9
View File
@@ -18,10 +18,16 @@
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents a chat owner change in the chat."""
from typing import TYPE_CHECKING
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 ChatOwnerChanged(TelegramObject):
"""This object represents a service message about an ownership change in the chat.
@@ -33,10 +39,6 @@ class ChatOwnerChanged(TelegramObject):
Args:
new_owner (:class:`telegram.User`): The new owner of the chat
Attributes:
new_owner (:class:`telegram.User`): The new owner of the chat
"""
__slots__ = ("new_owner",)
@@ -54,6 +56,15 @@ class ChatOwnerChanged(TelegramObject):
self._freeze()
@classmethod
def de_json(cls, data: JSONDict, bot: "Bot | None" = None) -> "ChatOwnerChanged":
"""See :meth:`telegram.TelegramObject.de_json`."""
data = cls._parse_data(data)
data["new_owner"] = de_json_optional(data.get("new_owner"), User, bot)
return super().de_json(data=data, bot=bot)
class ChatOwnerLeft(TelegramObject):
"""This object represents a service message about the chat owner leaving the chat.
@@ -66,11 +77,6 @@ class ChatOwnerLeft(TelegramObject):
Args:
new_owner (:class:`telegram.User`, optional): The user who will become the new owner of the
chat if the previous owner does not return to the chat
Attributes:
new_owner (:class:`telegram.User`): Optional. The user who will become the new owner of the
chat if the previous owner does not return to the chat
"""
__slots__ = ("new_owner",)
@@ -87,3 +93,12 @@ class ChatOwnerLeft(TelegramObject):
self._id_attrs = (self.new_owner,)
self._freeze()
@classmethod
def de_json(cls, data: JSONDict, bot: "Bot | None" = None) -> "ChatOwnerLeft":
"""See :meth:`telegram.TelegramObject.de_json`."""
data = cls._parse_data(data)
data["new_owner"] = de_json_optional(data.get("new_owner"), User, bot)
return super().de_json(data=data, bot=bot)
+22 -59
View File
@@ -18,9 +18,14 @@
# 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
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.
@@ -42,14 +47,14 @@ class ChatPermissions(TelegramObject):
: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``.
.. versionchanged:: 22.7
:attr:`can_edit_tag` is considered as well when comparing objects of
this type in terms of equality.
.. versionchanged:: NEXT.VERSION
.. versionchanged:: 22.8
:attr:`can_react_to_messages` is considered as well when comparing objects of
this type in terms of equality.
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
@@ -98,60 +103,11 @@ class ChatPermissions(TelegramObject):
tag.
.. versionadded:: 22.7
can_react_to_messages (:obj:`bool`, optional): :obj:`True`, if the user is allowed to react
to messages. If omitted, defaults to the value of :attr:`can_send_messages`.
.. versionadded:: NEXT.VERSION
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
can_edit_tag (:obj:`bool`): Optional. :obj:`True`, if the user is allowed to edit their own
tag.
.. versionadded:: 22.7
can_react_to_messages (:obj:`bool`): Optional. :obj:`True`, if the user is allowed to react
to messages. If omitted, defaults to the value of :attr:`can_send_messages`.
.. versionadded:: NEXT.VERSION
.. versionadded:: 22.8
"""
__slots__ = (
@@ -173,12 +129,6 @@ class ChatPermissions(TelegramObject):
"can_send_voice_notes",
)
__REMOVED_API_FIELDS__ = frozenset(
{
"can_send_media_messages",
}
)
def __init__(
self,
can_send_messages: bool | None = None,
@@ -261,3 +211,16 @@ class ChatPermissions(TelegramObject):
.. versionadded:: 20.0
"""
return cls(*(False,) * len(cls.__slots__))
@classmethod
def de_json(cls, data: JSONDict, bot: "Bot | None" = 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)
+64 -52
View File
@@ -20,18 +20,20 @@
import datetime as dtm
from collections.abc import Sequence
from typing import TYPE_CHECKING
from typing import TYPE_CHECKING, Optional
from telegram._chat import Chat
from telegram._messageentity import MessageEntity
from telegram._telegramobject import TelegramObject
from telegram._user import User
from telegram._utils.argumentparsing import parse_sequence_arg
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 Message
from telegram import Bot, Message
class ChecklistTask(TelegramObject):
@@ -58,23 +60,6 @@ class ChecklistTask(TelegramObject):
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
completed_by_chat (:class:`telegram.Chat`): Optional. Chat that completed the task; omitted
if the task wasn't completed by a chat
.. versionadded:: 22.6
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|
"""
@@ -110,6 +95,25 @@ class ChecklistTask(TelegramObject):
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["completed_by_chat"] = de_json_optional(data.get("completed_by_chat"), Chat, 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`.
@@ -169,16 +173,6 @@ class Checklist(TelegramObject):
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__ = (
@@ -210,6 +204,16 @@ class Checklist(TelegramObject):
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`.
@@ -267,19 +271,9 @@ class ChecklistTasksDone(TelegramObject):
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
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
were marked as not done.
"""
__slots__ = (
@@ -290,7 +284,7 @@ class ChecklistTasksDone(TelegramObject):
def __init__(
self,
checklist_message: "Message | None" = None,
checklist_message: Optional["Message"] = None,
marked_as_done_task_ids: Sequence[int] | None = None,
marked_as_not_done_task_ids: Sequence[int] | None = None,
*,
@@ -307,6 +301,18 @@ class ChecklistTasksDone(TelegramObject):
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):
"""
@@ -322,14 +328,7 @@ class ChecklistTasksAdded(TelegramObject):
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
tasks (Sequence[:class:`telegram.ChecklistTask`]): List of tasks added to the checklist.
"""
__slots__ = ("checklist_message", "tasks")
@@ -337,7 +336,7 @@ class ChecklistTasksAdded(TelegramObject):
def __init__(
self,
tasks: Sequence[ChecklistTask],
checklist_message: "Message | None" = None,
checklist_message: Optional["Message"] = None,
*,
api_kwargs: JSONDict | None = None,
):
@@ -348,3 +347,16 @@ class ChecklistTasksAdded(TelegramObject):
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)
+15 -12
View File
@@ -21,12 +21,14 @@
from typing import TYPE_CHECKING
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._files.location import Location
from telegram import Bot
class ChosenInlineResult(TelegramObject):
@@ -51,17 +53,6 @@ class ChosenInlineResult(TelegramObject):
only if there is an inline keyboard attached to the message. Will be also received in
callback queries and can be used to edit the message.
query (:obj:`str`): The query that was used to obtain the result.
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")
@@ -89,3 +80,15 @@ class ChosenInlineResult(TelegramObject):
self._id_attrs = (self.result_id,)
self._freeze()
@classmethod
def de_json(cls, data: JSONDict, bot: "Bot | None" = 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)
+1 -7
View File
@@ -34,13 +34,7 @@ class CopyTextButton(TelegramObject):
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
:tg-const:`telegram.constants.InlineKeyboardButtonLimit.MAX_COPY_TEXT` characters.
"""
__slots__ = ("text",)
-13
View File
@@ -73,19 +73,6 @@ class Dice(TelegramObject):
: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")
@@ -41,15 +41,6 @@ class DirectMessagePriceChanged(TelegramObject):
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")
+16 -15
View File
@@ -18,10 +18,16 @@
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains the DirectMessagesTopic class."""
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._bot import Bot
class DirectMessagesTopic(TelegramObject):
"""
@@ -33,25 +39,11 @@ class DirectMessagesTopic(TelegramObject):
.. versionadded:: 22.4
Args:
topic_id (:obj:`int`): Unique identifier of the topic. 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.
topic_id (:obj:`int`): Unique identifier of the topic.
user (:class:`telegram.User`, optional): Information about the user that created the topic.
.. hint::
According to Telegram, this field is always present as of Bot API 9.2.
Attributes:
topic_id (:obj:`int`): Unique identifier of the topic. 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.
user (:class:`telegram.User`): Optional. Information about the user that created the topic.
.. hint::
According to Telegram, this field is always present as of Bot API 9.2.
"""
__slots__ = ("topic_id", "user")
@@ -69,3 +61,12 @@ class DirectMessagesTopic(TelegramObject):
self._id_attrs = (self.topic_id, self.user)
self._freeze()
@classmethod
def de_json(cls, data: JSONDict, bot: Optional["Bot"] = None) -> "DirectMessagesTopic":
"""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)
+1
View File
@@ -48,6 +48,7 @@ class _BaseMedium(TelegramObject):
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")
+22 -6
View File
@@ -18,12 +18,16 @@
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""Common base class for media objects with thumbnails"""
from typing import TypeVar
from typing import TYPE_CHECKING, 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)
@@ -59,11 +63,6 @@ class _BaseThumbedMedium(_BaseMedium):
"""
__slots__ = ("thumbnail",)
__REMOVED_API_FIELDS__ = frozenset(
{
"thumb",
}
)
def __init__(
self,
@@ -82,3 +81,20 @@ class _BaseThumbedMedium(_BaseMedium):
)
self.thumbnail: PhotoSize | None = thumbnail
@classmethod
def de_json(cls: type[ThumbedMT_co], data: JSONDict, bot: "Bot | None" = 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)
-15
View File
@@ -58,26 +58,11 @@ class Animation(_BaseThumbedMedium):
.. 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")
-17
View File
@@ -36,7 +36,6 @@ class Audio(_BaseThumbedMedium):
.. 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.
@@ -59,27 +58,11 @@ class Audio(_BaseThumbedMedium):
.. 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")
-19
View File
@@ -53,25 +53,6 @@ class ChatPhoto(TelegramObject):
(: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__ = (
-8
View File
@@ -34,14 +34,6 @@ class Contact(TelegramObject):
last_name (:obj:`str`, optional): Contact's last name.
user_id (:obj:`int`, optional): Contact's user identifier in Telegram.
vcard (:obj:`str`, optional): Additional data about the contact in the form of a vCard.
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")
-14
View File
@@ -45,20 +45,6 @@ class Document(_BaseThumbedMedium):
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")
-10
View File
@@ -62,16 +62,6 @@ class File(TelegramObject):
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__ = (
-1
View File
@@ -86,7 +86,6 @@ class InputFile:
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.
"""
+35 -164
View File
@@ -95,26 +95,11 @@ class InputMedia(_BaseInputMedia):
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")
@@ -165,7 +150,6 @@ class InputPaidMedia(TelegramObject):
to send. |fileinputnopath|
Attributes:
type (:obj:`str`): Type of the input media.
media (:obj:`str` | :class:`telegram.InputFile`): Media to send.
"""
@@ -176,7 +160,7 @@ class InputPaidMedia(TelegramObject):
LIVE_PHOTO: Final[str] = constants.InputPaidMediaType.LIVE_PHOTO
""":const:`telegram.constants.InputPaidMediaType.LIVE_PHOTO`
.. versionadded:: NEXT.VERSION
.. versionadded:: 22.8
"""
__slots__ = ("media", "type")
@@ -270,20 +254,12 @@ class InputPaidMediaVideo(InputPaidMedia):
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__ = (
@@ -342,7 +318,7 @@ class InputPaidMediaLivePhoto(InputPaidMedia):
.. seealso:: :wiki:`Working with Files and Media <Working-with-Files-and-Media>`
.. versionadded:: NEXT.VERSION
.. versionadded:: 22.8
Args:
media (:obj:`str` | :term:`file object` | :class:`~telegram.InputFile` | :obj:`bytes` \
@@ -404,18 +380,14 @@ class InputMediaAnimation(InputMedia):
filename_depr (:obj:`str`, optional): Positional placeholder for keyword only parameter
:paramref:`filename`. For backward compatibility.
.. versionadded:: NEXT.VERSION
.. deprecated:: NEXT.VERSION
.. versionadded:: 22.8
.. deprecated:: 22.8
This parameter is deprecated, use :paramref:`filename` instead.
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
@@ -441,39 +413,20 @@ class InputMediaAnimation(InputMedia):
:obj:`tempfile` module.
.. versionadded:: 13.1
.. versionchanged:: NEXT.VERSION
.. versionchanged:: 22.8
This parameter is now keyword-only.
Attributes:
type (:obj:`str`): :tg-const:`telegram.constants.BaseInputMediaType.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__ = (
@@ -494,7 +447,7 @@ class InputMediaAnimation(InputMedia):
height: int | None = None,
duration: TimePeriod | None = None,
caption_entities: Sequence[MessageEntity] | None = None,
# tag: deprecated NEXT.VERSION
# tag: deprecated 22.8
filename_depr: str | None = None,
# -
has_spoiler: bool | None = None,
@@ -509,7 +462,7 @@ class InputMediaAnimation(InputMedia):
if filename_depr is not None:
warn(
PTBDeprecationWarning(
"NEXT.VERSION",
"22.8",
"Positional passing of `filename` or keyword usage of `filename_depr`"
" is deprecated. `filename` will become a keyword-only argument.",
),
@@ -565,22 +518,19 @@ class InputMediaPhoto(InputMedia):
filename_depr (:obj:`str`, optional): Positional placeholder for keyword only parameter
:paramref:`filename`. For backward compatibility.
.. versionadded:: NEXT.VERSION
.. deprecated:: NEXT.VERSION
.. versionadded:: 22.8
.. deprecated:: 22.8
This parameter is deprecated, use :paramref:`filename` instead.
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|
show_caption_above_media (:obj:`bool`, optional): |show_cap_above_med|
.. versionadded:: 21.3
@@ -590,29 +540,12 @@ class InputMediaPhoto(InputMedia):
:obj:`tempfile` module.
.. versionadded:: 13.1
.. versionchanged:: NEXT.VERSION
.. versionchanged:: 22.8
This parameter is now keyword-only.
Attributes:
type (:obj:`str`): :tg-const:`telegram.constants.BaseInputMediaType.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__ = (
@@ -626,7 +559,7 @@ class InputMediaPhoto(InputMedia):
caption: str | None = None,
parse_mode: ODVInput[str] = DEFAULT_NONE,
caption_entities: Sequence[MessageEntity] | None = None,
# tag: deprecated NEXT.VERSION
# tag: deprecated 22.8
filename_depr: str | None = None,
# -
has_spoiler: bool | None = None,
@@ -640,7 +573,7 @@ class InputMediaPhoto(InputMedia):
if filename_depr is not None:
warn(
PTBDeprecationWarning(
"NEXT.VERSION",
"22.8",
"Positional passing of `filename` or keyword usage of `filename_depr`"
" is deprecated. `filename` will become a keyword-only argument.",
),
@@ -693,18 +626,14 @@ class InputMediaVideo(InputMedia):
filename_depr (:obj:`str`, optional): Positional placeholder for keyword only parameter
:paramref:`filename`. For backward compatibility.
.. versionadded:: NEXT.VERSION
.. deprecated:: NEXT.VERSION
.. versionadded:: 22.8
.. deprecated:: 22.8
This parameter is deprecated, use :paramref:`filename` instead.
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.
@@ -728,7 +657,7 @@ class InputMediaVideo(InputMedia):
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|
show_caption_above_media (:obj:`bool`, optional): |show_cap_above_med|
.. versionadded:: 21.3
@@ -738,46 +667,22 @@ class InputMediaVideo(InputMedia):
:obj:`tempfile` module.
.. versionadded:: 13.1
.. versionchanged:: NEXT.VERSION
.. versionchanged:: 22.8
This parameter is now keyword-only.
Attributes:
type (:obj:`str`): :tg-const:`telegram.constants.BaseInputMediaType.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
"""
@@ -803,7 +708,7 @@ class InputMediaVideo(InputMedia):
supports_streaming: bool | None = None,
parse_mode: ODVInput[str] = DEFAULT_NONE,
caption_entities: Sequence[MessageEntity] | None = None,
# tag: deprecated NEXT.VERSION
# tag: deprecated 22.8
filename_depr: str | None = None,
# -
has_spoiler: bool | None = None,
@@ -820,7 +725,7 @@ class InputMediaVideo(InputMedia):
if filename_depr is not None:
warn(
PTBDeprecationWarning(
"NEXT.VERSION",
"22.8",
"Positional passing of `filename` or keyword usage of `filename_depr`"
" is deprecated. `filename` will become a keyword-only argument.",
),
@@ -869,7 +774,7 @@ class InputMediaVideo(InputMedia):
class InputMediaLocation(_BaseInputMedia):
"""Represents a location to be sent.
.. versionadded:: NEXT.VERSION
.. versionadded:: 22.8
Args:
latitude (:obj:`float`): Latitude of the location.
@@ -905,7 +810,7 @@ class InputMediaLocation(_BaseInputMedia):
class InputMediaVenue(_BaseInputMedia):
"""Represents a venue to be sent.
.. versionadded:: NEXT.VERSION
.. versionadded:: 22.8
Args:
latitude (:obj:`float`): Latitude of the location.
@@ -976,7 +881,7 @@ class InputMediaSticker(_BaseInputMedia):
.. seealso:: :wiki:`Working with Files and Media <Working-with-Files-and-Media>`
.. versionadded:: NEXT.VERSION
.. versionadded:: 22.8
Args:
media (:obj:`str` | :term:`file object` | :class:`~telegram.InputFile` | :obj:`bytes` | \
@@ -1039,18 +944,14 @@ class InputMediaAudio(InputMedia):
filename_depr (:obj:`str`, optional): Positional placeholder for keyword only parameter
:paramref:`filename`. For backward compatibility.
.. versionadded:: NEXT.VERSION
.. deprecated:: NEXT.VERSION
.. versionadded:: 22.8
.. deprecated:: 22.8
This parameter is deprecated, use :paramref:`filename` instead.
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.
@@ -1070,30 +971,17 @@ class InputMediaAudio(InputMedia):
:obj:`tempfile` module.
.. versionadded:: 13.1
.. versionchanged:: NEXT.VERSION
.. versionchanged:: 22.8
This parameter is now keyword-only.
Attributes:
type (:obj:`str`): :tg-const:`telegram.constants.BaseInputMediaType.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
@@ -1111,7 +999,7 @@ class InputMediaAudio(InputMedia):
performer: str | None = None,
title: str | None = None,
caption_entities: Sequence[MessageEntity] | None = None,
# tag: deprecated NEXT.VERSION
# tag: deprecated 22.8
filename_depr: str | None = None,
# -
thumbnail: "FileInput | None" = None,
@@ -1124,7 +1012,7 @@ class InputMediaAudio(InputMedia):
if filename_depr is not None:
warn(
PTBDeprecationWarning(
"NEXT.VERSION",
"22.8",
"Positional passing of `filename` or keyword usage of `filename_depr`"
" is deprecated. `filename` will become a keyword-only argument.",
),
@@ -1181,18 +1069,14 @@ class InputMediaDocument(InputMedia):
filename_depr (:obj:`str`, optional): Positional placeholder for keyword only parameter
:paramref:`filename`. For backward compatibility.
.. versionadded:: NEXT.VERSION
.. deprecated:: NEXT.VERSION
.. versionadded:: 22.8
.. deprecated:: 22.8
This parameter is deprecated, use :paramref:`filename` instead.
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.
@@ -1207,25 +1091,12 @@ class InputMediaDocument(InputMedia):
:obj:`tempfile` module.
.. versionadded:: 13.1
.. versionchanged:: NEXT.VERSION
.. versionchanged:: 22.8
This parameter is now keyword-only.
Attributes:
type (:obj:`str`): :tg-const:`telegram.constants.BaseInputMediaType.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
@@ -1240,7 +1111,7 @@ class InputMediaDocument(InputMedia):
parse_mode: ODVInput[str] = DEFAULT_NONE,
disable_content_type_detection: bool | None = None,
caption_entities: Sequence[MessageEntity] | None = None,
# tag: deprecated NEXT.VERSION
# tag: deprecated 22.8
filename_depr: str | None = None,
# -
thumbnail: "FileInput | None" = None,
@@ -1253,7 +1124,7 @@ class InputMediaDocument(InputMedia):
if filename_depr is not None:
warn(
PTBDeprecationWarning(
"NEXT.VERSION",
"22.8",
"Positional passing of `filename` or keyword usage of `filename_depr`"
" is deprecated. `filename` will become a keyword-only argument.",
),
@@ -1285,7 +1156,7 @@ class InputMediaLivePhoto(InputMedia):
.. seealso:: :wiki:`Working with Files and Media <Working-with-Files-and-Media>`
.. versionadded:: NEXT.VERSION
.. versionadded:: 22.8
Args:
media (:obj:`str` | :term:`file object` | :class:`~telegram.InputFile` | :obj:`bytes` \
@@ -1364,7 +1235,7 @@ InputPollMedia: TypeAlias = (
)
"""Type alias for InputPollMedia objects.
versionadded:: NEXT.VERSION
versionadded:: 22.8
"""
InputPollOptionMedia: TypeAlias = (
@@ -1378,5 +1249,5 @@ InputPollOptionMedia: TypeAlias = (
)
"""Type alias for InputPollOptionMedia objects.
.. versionadded:: NEXT.VERSION
.. versionadded:: 22.8
"""
-4
View File
@@ -42,10 +42,6 @@ class InputProfilePhoto(TelegramObject):
Args:
type (:obj:`str`): Type of the profile photo.
Attributes:
type (:obj:`str`): Type of the profile photo.
"""
STATIC = constants.InputProfilePhotoType.STATIC
-20
View File
@@ -68,26 +68,6 @@ class InputSticker(TelegramObject):
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")
@@ -40,9 +40,6 @@ class InputStoryContent(TelegramObject):
Args:
type (:obj:`str`): Type of the content.
Attributes:
type (:obj:`str`): Type of the content.
"""
__slots__ = ("type",)
@@ -127,7 +124,7 @@ class InputStoryContentVideo(InputStoryContent):
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
is_animation (:obj:`bool`, optional): :obj:`True`, if the video has no sound.
Attributes:
type (:obj:`str`): Type of the content, must be :attr:`~telegram.InputStoryContent.VIDEO`.
@@ -141,7 +138,6 @@ class InputStoryContentVideo(InputStoryContent):
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")
+13 -2
View File
@@ -23,12 +23,14 @@ from typing import TYPE_CHECKING
from telegram._files._basemedium import _BaseMedium
from telegram._files.photosize import PhotoSize
from telegram._utils.argumentparsing import parse_sequence_arg, to_timedelta
from telegram._utils.argumentparsing import de_list_optional, parse_sequence_arg, to_timedelta
from telegram._utils.types import JSONDict, TimePeriod
if TYPE_CHECKING:
import datetime as dtm
from telegram import Bot
class LivePhoto(_BaseMedium):
"""
@@ -37,7 +39,7 @@ class LivePhoto(_BaseMedium):
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.
.. versionadded:: NEXT.VERSION
.. versionadded:: 22.8
Args:
file_id (:obj:`str`): Identifier for the video file which can be used to download or reuse
@@ -106,3 +108,12 @@ class LivePhoto(_BaseMedium):
# Optional
self.photo: Sequence[PhotoSize] | None = parse_sequence_arg(photo)
self.mime_type: str | None = mime_type
@classmethod
def de_json(cls, data: JSONDict, bot: "Bot | None" = None) -> "LivePhoto":
"""See :meth:`telegram.TelegramObject.de_json`."""
data = cls._parse_data(data)
data["photo"] = de_list_optional(data.get("photo"), PhotoSize, bot)
return super().de_json(data=data, bot=bot)
-10
View File
@@ -52,22 +52,12 @@ class Location(TelegramObject):
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__ = (
-12
View File
@@ -37,18 +37,6 @@ class PhotoSize(_BaseMedium):
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")
+39 -86
View File
@@ -23,14 +23,15 @@ from typing import TYPE_CHECKING, Final
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 parse_sequence_arg
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._files.file import File
from telegram import Bot
class Sticker(_BaseThumbedMedium):
@@ -86,47 +87,6 @@ class Sticker(_BaseThumbedMedium):
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
"""
@@ -143,11 +103,6 @@ class Sticker(_BaseThumbedMedium):
"type",
"width",
)
__REMOVED_API_FIELDS__ = frozenset(
{
"thumb",
}
)
def __init__(
self,
@@ -198,6 +153,23 @@ class Sticker(_BaseThumbedMedium):
CUSTOM_EMOJI: Final[str] = constants.StickerType.CUSTOM_EMOJI
""":const:`telegram.constants.StickerType.CUSTOM_EMOJI`"""
@classmethod
def de_json(cls, data: JSONDict, bot: "Bot | None" = 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.
@@ -213,14 +185,13 @@ class StickerSet(TelegramObject):
.. versionchanged:: 20.0
The parameter ``contains_masks`` has been removed. Use :paramref:`sticker_type` instead.
.. versionchanged:: 20.5
|removed_thumb_note|
.. 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``.
@@ -228,10 +199,6 @@ class StickerSet(TelegramObject):
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`.
@@ -240,24 +207,6 @@ class StickerSet(TelegramObject):
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
"""
@@ -268,7 +217,6 @@ class StickerSet(TelegramObject):
"thumbnail",
"title",
)
__REMOVED_API_FIELDS__ = frozenset({"contains_masks", "is_animated", "is_video", "thumb"})
def __init__(
self,
@@ -291,6 +239,23 @@ class StickerSet(TelegramObject):
self._freeze()
@classmethod
def de_json(cls, data: JSONDict, bot: "Bot | None" = 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: JSONDict = {}
# 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.
@@ -309,18 +274,6 @@ class MaskPosition(TelegramObject):
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")
+15 -13
View File
@@ -18,10 +18,16 @@
# 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
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.
@@ -44,19 +50,6 @@ class Venue(TelegramObject):
google_place_type (:obj:`str`, optional): Google Places type of the venue. (See
`supported types <https://developers.google.com/maps/documentation/places/web-service\
/place-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\
/place-types>`_.)
"""
__slots__ = (
@@ -96,3 +89,12 @@ class Venue(TelegramObject):
self._id_attrs = (self.location, self.title)
self._freeze()
@classmethod
def de_json(cls, data: JSONDict, bot: "Bot | None" = 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)
+15 -22
View File
@@ -20,14 +20,18 @@
import datetime as dtm
from collections.abc import Sequence
from typing import TYPE_CHECKING
from telegram._files._basethumbedmedium import _BaseThumbedMedium
from telegram._files.photosize import PhotoSize
from telegram._files.videoquality import VideoQuality
from telegram._utils.argumentparsing import parse_sequence_arg, to_timedelta
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.
@@ -73,38 +77,17 @@ class Video(_BaseThumbedMedium):
.. versionadded:: 22.7
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|
qualities (Sequence[:class:`telegram.VideoQuality`]): Optional. List of available qualities
of the video
.. versionadded:: 22.7
"""
__slots__ = (
@@ -163,3 +146,13 @@ class Video(_BaseThumbedMedium):
@property
def start_timestamp(self) -> dtm.timedelta | None | int:
return get_timedelta_value(self._start_timestamp, attribute="start_timestamp")
@classmethod
def de_json(cls, data: JSONDict, bot: "Bot | None" = None) -> "Video":
"""See :meth:`telegram.TelegramObject.de_json`."""
data = cls._parse_data(data)
data["cover"] = de_list_optional(data.get("cover"), PhotoSize, bot)
data["qualities"] = de_list_optional(data.get("qualities"), VideoQuality, bot)
return super().de_json(data=data, bot=bot)
-12
View File
@@ -55,23 +55,11 @@ class VideoNote(_BaseThumbedMedium):
.. 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")
-13
View File
@@ -41,19 +41,6 @@ class VideoQuality(_BaseMedium):
codec (:obj:`str`): Codec that was used to encode the video,
for example, ``h264``, ``h265``, or ``av01``
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`): Video width.
height (:obj:`int`): Video height.
codec (:obj:`str`): Codec that was used to encode the video,
for example, ``h264``, ``h265``, or ``av01``
file_size (:obj:`int`): Optional. File size in bytes.
"""
__slots__ = ("codec", "height", "width")
-8
View File
@@ -47,19 +47,11 @@ class Voice(_BaseMedium):
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")
-14
View File
@@ -60,20 +60,6 @@ class ForceReply(TelegramObject):
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")
-26
View File
@@ -41,17 +41,6 @@ class ForumTopic(TelegramObject):
is_name_implicit (:obj:`bool`, optional): :obj:`True`, if the name of the topic wasn't
specified explicitly by its creator and likely needs to be changed by the bot.
.. versionadded:: 22.6
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.
is_name_implicit (:obj:`bool`): Optional. :obj:`True`, if the name of the topic wasn't
specified explicitly by its creator and likely needs to be changed by the bot.
.. versionadded:: 22.6
"""
@@ -103,16 +92,6 @@ class ForumTopicCreated(TelegramObject):
is_name_implicit (:obj:`bool`, optional): :obj:`True`, if the name of the topic wasn't
specified explicitly by its creator and likely needs to be changed by the bot.
.. versionadded:: 22.6
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.
is_name_implicit (:obj:`bool`): Optional. :obj:`True`, if the name of the topic wasn't
specified explicitly by its creator and likely needs to be changed by the bot.
.. versionadded:: 22.6
"""
@@ -183,11 +162,6 @@ class ForumTopicEdited(TelegramObject):
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")
+16 -34
View File
@@ -19,15 +19,19 @@
"""This module contains an object that represents a Telegram Game."""
from collections.abc import Sequence
from typing import TYPE_CHECKING
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 parse_sequence_arg
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):
"""
@@ -42,10 +46,6 @@ class Game(TelegramObject):
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
@@ -53,37 +53,8 @@ class Game(TelegramObject):
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__ = (
@@ -120,6 +91,17 @@ class Game(TelegramObject):
self._freeze()
@classmethod
def de_json(cls, data: JSONDict, bot: "Bot | None" = 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`.

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