python-telegram-bot/telegram/base.py

115 lines
3.5 KiB
Python
Raw Normal View History

#!/usr/bin/env python
2015-08-11 21:58:17 +02:00
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2021
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
2015-08-11 21:58:17 +02:00
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser Public License for more details.
#
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""Base class for Telegram Objects."""
try:
import ujson as json
except ImportError:
2020-10-06 19:28:40 +02:00
import json # type: ignore[no-redef]
import warnings
from typing import TYPE_CHECKING, List, Optional, Tuple, Type, TypeVar
2020-10-06 19:28:40 +02:00
from telegram.utils.types import JSONDict
if TYPE_CHECKING:
from telegram import Bot
TO = TypeVar('TO', bound='TelegramObject', covariant=True)
2015-07-17 16:53:54 +02:00
class TelegramObject:
2017-09-01 08:43:08 +02:00
"""Base class for most telegram objects."""
_id_attrs: Tuple[object, ...] = ()
2020-10-06 19:28:40 +02:00
def __str__(self) -> str:
return str(self.to_dict())
2015-07-17 16:53:54 +02:00
def __getitem__(self, item: str) -> object:
return self.__dict__[item]
2015-07-17 16:53:54 +02:00
2020-10-06 19:28:40 +02:00
@staticmethod
def parse_data(data: Optional[JSONDict]) -> Optional[JSONDict]:
API 5.1 (#2424) * Feat: New invite links * Fix: doc strings Co-authored-by: Bibo-Joshi <hinrich.mahler@freenet.de> * new dice, new admin privilege, revoke_messages, update and fix some docs * add missing param to shortcut * Add ChatMemberUpdated * Add voicechat related objects Signed-off-by: starry69 <starry369126@outlook.com> * add versionadd tags Signed-off-by: starry69 <starry369126@outlook.com> * Fix filter tests * Update tg.Update * ChatMemberHandler * Add versioning directives * add can_manage_voice_chats attr and fix docs Signed-off-by: starry69 <starry369126@outlook.com> * fix chat shortcut Signed-off-by: starry69 <starry369126@outlook.com> * address review * MADTC * Chat.message_auto_delete_time * Some doc fixes * address review Signed-off-by: starry69 <starry369126@outlook.com> * welp Signed-off-by: starry69 <starry369126@outlook.com> * Add voicechat related filters Signed-off-by: starry69 <starry369126@outlook.com> * Fix: Addressing review change place of version adding, added obj:True as doc string, changing how member limit is initiated * feat: adding chat shortcuts for invite links * fix: changing equality of chatinviteobjects * Non-test comments * Some test fixes * A bit more tests * Bump API version in both readmes * Increase coverage * Add Bot API Version in telegram.constants (#2429) * add bot api version in constants Signed-off-by: starry69 <starry369126@outlook.com> * addressing review Signed-off-by: starry69 <starry369126@outlook.com> * add versioning directive Co-authored-by: Bibo-Joshi <hinrich.mahler@freenet.de> * pre-commit & coverage Co-authored-by: Bibo-Joshi <hinrich.mahler@freenet.de> Co-authored-by: Harshil <ilovebhagwan@gmail.com> Co-authored-by: starry69 <starry369126@outlook.com>
2021-03-14 16:41:35 +01:00
return None if data is None else data.copy()
2020-10-06 19:28:40 +02:00
@classmethod
2020-10-06 19:28:40 +02:00
def de_json(cls: Type[TO], data: Optional[JSONDict], bot: 'Bot') -> Optional[TO]:
data = cls.parse_data(data)
API 5.1 (#2424) * Feat: New invite links * Fix: doc strings Co-authored-by: Bibo-Joshi <hinrich.mahler@freenet.de> * new dice, new admin privilege, revoke_messages, update and fix some docs * add missing param to shortcut * Add ChatMemberUpdated * Add voicechat related objects Signed-off-by: starry69 <starry369126@outlook.com> * add versionadd tags Signed-off-by: starry69 <starry369126@outlook.com> * Fix filter tests * Update tg.Update * ChatMemberHandler * Add versioning directives * add can_manage_voice_chats attr and fix docs Signed-off-by: starry69 <starry369126@outlook.com> * fix chat shortcut Signed-off-by: starry69 <starry369126@outlook.com> * address review * MADTC * Chat.message_auto_delete_time * Some doc fixes * address review Signed-off-by: starry69 <starry369126@outlook.com> * welp Signed-off-by: starry69 <starry369126@outlook.com> * Add voicechat related filters Signed-off-by: starry69 <starry369126@outlook.com> * Fix: Addressing review change place of version adding, added obj:True as doc string, changing how member limit is initiated * feat: adding chat shortcuts for invite links * fix: changing equality of chatinviteobjects * Non-test comments * Some test fixes * A bit more tests * Bump API version in both readmes * Increase coverage * Add Bot API Version in telegram.constants (#2429) * add bot api version in constants Signed-off-by: starry69 <starry369126@outlook.com> * addressing review Signed-off-by: starry69 <starry369126@outlook.com> * add versioning directive Co-authored-by: Bibo-Joshi <hinrich.mahler@freenet.de> * pre-commit & coverage Co-authored-by: Bibo-Joshi <hinrich.mahler@freenet.de> Co-authored-by: Harshil <ilovebhagwan@gmail.com> Co-authored-by: starry69 <starry369126@outlook.com>
2021-03-14 16:41:35 +01:00
if data is None:
return None
2020-10-06 19:28:40 +02:00
if cls == TelegramObject:
return cls()
return cls(bot=bot, **data) # type: ignore[call-arg]
2020-10-06 19:28:40 +02:00
@classmethod
def de_list(cls: Type[TO], data: Optional[List[JSONDict]], bot: 'Bot') -> List[Optional[TO]]:
2020-10-06 19:28:40 +02:00
if not data:
return []
return [cls.de_json(d, bot) for d in data]
2015-07-17 16:53:54 +02:00
2020-10-06 19:28:40 +02:00
def to_json(self) -> str:
"""
Returns:
:obj:`str`
2017-09-01 08:43:08 +02:00
"""
return json.dumps(self.to_dict())
2020-10-06 19:28:40 +02:00
def to_dict(self) -> JSONDict:
data = {}
for key in iter(self.__dict__):
if key == 'bot' or key.startswith('_'):
continue
value = self.__dict__[key]
if value is not None:
if hasattr(value, 'to_dict'):
data[key] = value.to_dict()
else:
data[key] = value
if data.get('from_user'):
data['from'] = data.pop('from_user', None)
return data
2020-10-06 19:28:40 +02:00
def __eq__(self, other: object) -> bool:
if isinstance(other, self.__class__):
if self._id_attrs == ():
warnings.warn(
2020-11-23 22:09:29 +01:00
f"Objects of type {self.__class__.__name__} can not be meaningfully tested for"
" equivalence."
)
if other._id_attrs == ():
warnings.warn(
2020-11-23 22:09:29 +01:00
f"Objects of type {other.__class__.__name__} can not be meaningfully tested"
" for equivalence."
)
return self._id_attrs == other._id_attrs
return super().__eq__(other) # pylint: disable=no-member
2020-10-06 19:28:40 +02:00
def __hash__(self) -> int:
if self._id_attrs:
return hash((self.__class__, self._id_attrs)) # pylint: disable=no-member
return super().__hash__()