2017-08-11 23:58:41 +02:00
|
|
|
#!/usr/bin/env python
|
|
|
|
#
|
|
|
|
# A library that provides a Python interface to the Telegram Bot API
|
2023-01-01 21:31:29 +01:00
|
|
|
# Copyright (C) 2015-2023
|
2017-08-11 23:58:41 +02:00
|
|
|
# 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/].
|
2017-06-14 13:42:57 +02:00
|
|
|
import inspect
|
2022-05-05 09:27:54 +02:00
|
|
|
import os
|
2023-03-25 11:47:26 +01:00
|
|
|
import re
|
|
|
|
from typing import Dict, List, Set
|
2017-06-14 13:42:57 +02:00
|
|
|
|
2022-04-24 12:38:09 +02:00
|
|
|
import httpx
|
2022-05-05 09:27:54 +02:00
|
|
|
import pytest
|
2017-06-14 13:42:57 +02:00
|
|
|
from bs4 import BeautifulSoup
|
Bot API 4.0 (#1168)
Telegram Passport (#1174):
- Add full support for telegram passport.
- New types: PassportData, PassportFile, EncryptedPassportElement, EncryptedCredentials, PassportElementError, PassportElementErrorDataField, PassportElementErrorFrontSide, PassportElementErrorReverseSide, PassportElementErrorSelfie, PassportElementErrorFile and PassportElementErrorFiles.
- New bot method: set_passport_data_errors
- New filter: Filters.passport_data
- Field passport_data field on Message
- PassportData is automagically decrypted when you specify your private key when creating Updater or Bot.
- PassportFiles is also automagically decrypted as you download/retrieve them.
- See new passportbot.py example for details on how to use, or go to our telegram passport wiki page for more info
- NOTE: Passport decryption requires new dependency `cryptography`.
Inputfile rework (#1184):
- Change how Inputfile is handled internally
- This allows support for specifying the thumbnails of photos and videos using the thumb= argument in the different send_ methods.
- Also allows Bot.send_media_group to actually finally send more than one media.
- Add thumb to Audio, Video and Videonote
- Add Bot.edit_message_media together with InputMediaAnimation, InputMediaAudio, and inputMediaDocument.
Other Bot API 4.0 changes:
- Add forusquare_type to Venue, InlineQueryResultVenue, InputVenueMessageContent, and Bot.send_venue. (#1170)
- Add vCard support by adding vcard field to Contact, InlineQueryResultContact, InputContactMessageContent, and Bot.send_contact. (#1166)
- Support new message entities: CASHTAG and PHONE_NUMBER. (#1179)
- Cashtag seems to be things like $USD and $GBP, but it seems telegram doesn't currently send them to bots.
- Phone number also seems to have limited support for now
- Add Bot.send_animation, add width, height, and duration to Animation, and add Filters.animation. (#1172)
Co-authored-by: Jasmin Bom <jsmnbom@gmail.com>
Co-authored-by: code1mountain <32801117+code1mountain@users.noreply.github.com>
Co-authored-by: Eldinnie <pieter.schutz+github@gmail.com>
Co-authored-by: mathefreak1 <mathefreak@hi2.in>
2018-08-29 14:18:58 +02:00
|
|
|
|
2017-06-14 13:42:57 +02:00
|
|
|
import telegram
|
2022-05-09 19:30:46 +02:00
|
|
|
from telegram._utils.defaultvalue import DefaultValue
|
2023-02-22 20:19:46 +01:00
|
|
|
from tests.auxil.envvars import env_var_2_bool
|
2017-06-14 13:42:57 +02:00
|
|
|
|
|
|
|
IGNORED_OBJECTS = ("ResponseParameters", "CallbackGame")
|
2023-03-25 11:47:26 +01:00
|
|
|
GLOBALLY_IGNORED_PARAMETERS = {
|
2020-06-30 22:07:38 +02:00
|
|
|
"self",
|
2022-04-24 12:38:09 +02:00
|
|
|
"read_timeout",
|
|
|
|
"write_timeout",
|
|
|
|
"connect_timeout",
|
|
|
|
"pool_timeout",
|
2020-06-30 22:07:38 +02:00
|
|
|
"bot",
|
|
|
|
"api_kwargs",
|
|
|
|
}
|
2017-06-14 13:42:57 +02:00
|
|
|
|
2023-03-25 11:47:26 +01:00
|
|
|
# Arguments *added* to the official API
|
|
|
|
PTB_EXTRA_PARAMS = {
|
|
|
|
"send_contact": {"contact"},
|
|
|
|
"send_location": {"location"},
|
|
|
|
"edit_message_live_location": {"location"},
|
|
|
|
"send_venue": {"venue"},
|
|
|
|
"answer_inline_query": {"current_offset"},
|
|
|
|
"send_media_group": {"caption", "parse_mode", "caption_entities"},
|
|
|
|
"send_(animation|audio|document|photo|video(_note)?|voice)": {"filename"},
|
|
|
|
"InlineQueryResult": {"id", "type"}, # attributes common to all subclasses
|
|
|
|
"ChatMember": {"user", "status"}, # attributes common to all subclasses
|
|
|
|
"BotCommandScope": {"type"}, # attributes common to all subclasses
|
|
|
|
"MenuButton": {"type"}, # attributes common to all subclasses
|
|
|
|
"PassportFile": {"credentials"},
|
|
|
|
"EncryptedPassportElement": {"credentials"},
|
|
|
|
"PassportElementError": {"source", "type", "message"},
|
|
|
|
"InputMedia": {"caption", "caption_entities", "media", "media_type", "parse_mode"},
|
|
|
|
"InputMedia(Animation|Audio|Document|Photo|Video|VideoNote|Voice)": {"filename"},
|
|
|
|
"InputFile": {"attach", "filename", "obj"},
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
def _get_params_base(object_name: str, search_dict: Dict[str, Set[str]]) -> Set[str]:
|
|
|
|
"""Helper function for the *_params functions below.
|
|
|
|
Given an object name and a search dict, goes through the keys of the search dict and checks if
|
|
|
|
the object name matches any of the regexes (keys). The union of all the sets (values) of the
|
|
|
|
matching regexes is returned. `object_name` may be a CamelCase or snake_case name.
|
|
|
|
"""
|
|
|
|
out = set()
|
|
|
|
for regex, params in search_dict.items():
|
|
|
|
if re.fullmatch(regex, object_name):
|
|
|
|
out.update(params)
|
|
|
|
# also check the snake_case version
|
|
|
|
snake_case_name = re.sub(r"(?<!^)(?=[A-Z])", "_", object_name).lower()
|
|
|
|
if re.fullmatch(regex, snake_case_name):
|
|
|
|
out.update(params)
|
|
|
|
return out
|
|
|
|
|
|
|
|
|
|
|
|
def ptb_extra_params(object_name) -> Set[str]:
|
|
|
|
return _get_params_base(object_name, PTB_EXTRA_PARAMS)
|
|
|
|
|
|
|
|
|
|
|
|
# Arguments *removed* from the official API
|
|
|
|
PTB_IGNORED_PARAMS = {
|
|
|
|
r"InlineQueryResult\w+": {"type"},
|
|
|
|
r"ChatMember\w+": {"status"},
|
|
|
|
r"PassportElementError\w+": {"source"},
|
|
|
|
"ForceReply": {"force_reply"},
|
|
|
|
"ReplyKeyboardRemove": {"remove_keyboard"},
|
|
|
|
r"BotCommandScope\w+": {"type"},
|
|
|
|
r"MenuButton\w+": {"type"},
|
|
|
|
r"InputMedia\w+": {"type"},
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
def ptb_ignored_params(object_name) -> Set[str]:
|
|
|
|
return _get_params_base(object_name, PTB_IGNORED_PARAMS)
|
|
|
|
|
|
|
|
|
|
|
|
IGNORED_PARAM_REQUIREMENTS = {
|
|
|
|
# Ignore these since there's convenience params in them (eg. Venue)
|
|
|
|
# <----
|
2021-08-29 18:17:06 +02:00
|
|
|
"send_location": {"latitude", "longitude"},
|
|
|
|
"edit_message_live_location": {"latitude", "longitude"},
|
|
|
|
"send_venue": {"latitude", "longitude", "title", "address"},
|
|
|
|
"send_contact": {"phone_number", "first_name"},
|
2023-03-25 11:47:26 +01:00
|
|
|
# ---->
|
|
|
|
# These are optional for now for backwards compatibility
|
|
|
|
# <----
|
|
|
|
"InlineQueryResult(Article|Photo|Gif|Mpeg4Gif|Video|Document|Location|Venue)": {
|
|
|
|
"thumbnail_url",
|
|
|
|
},
|
|
|
|
"InlineQueryResultVideo": {"title"},
|
|
|
|
# ---->
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
def ignored_param_requirements(object_name) -> Set[str]:
|
|
|
|
return _get_params_base(object_name, IGNORED_PARAM_REQUIREMENTS)
|
|
|
|
|
|
|
|
|
|
|
|
# Arguments that are optional arguments for now for backwards compatibility
|
|
|
|
BACKWARDS_COMPAT_KWARGS = {
|
|
|
|
"create_new_sticker_set": {
|
|
|
|
"stickers",
|
|
|
|
"sticker_format",
|
|
|
|
"emojis",
|
|
|
|
"png_sticker",
|
|
|
|
"tgs_sticker",
|
|
|
|
"mask_position",
|
|
|
|
"webm_sticker",
|
|
|
|
},
|
|
|
|
"add_sticker_to_set": {
|
|
|
|
"sticker",
|
|
|
|
"tgs_sticker",
|
|
|
|
"png_sticker",
|
|
|
|
"webm_sticker",
|
|
|
|
"mask_position",
|
|
|
|
"emojis",
|
|
|
|
},
|
|
|
|
"upload_sticker_file": {"sticker", "sticker_format", "png_sticker"},
|
|
|
|
"send_(animation|audio|document|video(_note)?)": {"thumb"},
|
|
|
|
"(Animation|Audio|Document|Photo|Sticker(Set)?|Video|VideoNote|Voice)": {"thumb"},
|
|
|
|
"InputMedia(Animation|Audio|Document|Video)": {"thumb"},
|
|
|
|
"Chat(MemberRestricted|Permissions)": {"can_send_media_messages"},
|
|
|
|
"InlineQueryResult(Article|Contact|Document|Location|Venue)": {
|
|
|
|
"thumb_height",
|
|
|
|
"thumb_width",
|
|
|
|
},
|
|
|
|
"InlineQueryResult(Article|Photo|Gif|Mpeg4Gif|Video|Contact|Document|Location|Venue)": {
|
|
|
|
"thumb_url",
|
|
|
|
},
|
|
|
|
"InlineQueryResult(Game|Gif|Mpeg4Gif)": {"thumb_mime_type"},
|
2021-08-29 18:17:06 +02:00
|
|
|
}
|
|
|
|
|
2017-06-14 13:42:57 +02:00
|
|
|
|
2023-03-25 11:47:26 +01:00
|
|
|
def backwards_compat_kwargs(object_name: str) -> Set[str]:
|
|
|
|
return _get_params_base(object_name, BACKWARDS_COMPAT_KWARGS)
|
|
|
|
|
|
|
|
|
|
|
|
IGNORED_PARAM_REQUIREMENTS.update(BACKWARDS_COMPAT_KWARGS)
|
|
|
|
|
|
|
|
|
2017-06-14 13:42:57 +02:00
|
|
|
def find_next_sibling_until(tag, name, until):
|
|
|
|
for sibling in tag.next_siblings:
|
|
|
|
if sibling is until:
|
|
|
|
return
|
|
|
|
if sibling.name == name:
|
|
|
|
return sibling
|
|
|
|
|
|
|
|
|
2021-08-29 18:17:06 +02:00
|
|
|
def parse_table(h4) -> List[List[str]]:
|
|
|
|
"""Parses the Telegram doc table and has an output of a 2D list."""
|
2017-06-14 13:42:57 +02:00
|
|
|
table = find_next_sibling_until(h4, "table", h4.find_next_sibling("h4"))
|
|
|
|
if not table:
|
|
|
|
return []
|
|
|
|
t = []
|
|
|
|
for tr in table.find_all("tr")[1:]:
|
2017-10-14 20:03:02 +02:00
|
|
|
t.append([td.text for td in tr.find_all("td")])
|
2017-06-14 13:42:57 +02:00
|
|
|
return t
|
|
|
|
|
|
|
|
|
|
|
|
def check_method(h4):
|
2021-08-29 18:17:06 +02:00
|
|
|
name = h4.text # name of the method in telegram's docs.
|
|
|
|
method = getattr(telegram.Bot, name) # Retrieve our lib method
|
2017-06-14 13:42:57 +02:00
|
|
|
table = parse_table(h4)
|
|
|
|
|
|
|
|
# Check arguments based on source
|
|
|
|
sig = inspect.signature(method, follow_wrapped=True)
|
|
|
|
checked = []
|
2022-05-09 19:30:46 +02:00
|
|
|
for tg_parameter in table: # Iterates through each row in the table
|
2023-03-25 11:47:26 +01:00
|
|
|
# Check if parameter is present in our method
|
2022-05-09 19:30:46 +02:00
|
|
|
param = sig.parameters.get(
|
|
|
|
tg_parameter[0] # parameter[0] is first element (the param name)
|
|
|
|
)
|
2023-03-25 11:47:26 +01:00
|
|
|
if param is None:
|
|
|
|
raise AssertionError(f"Parameter {tg_parameter[0]} not found in {method.__name__}")
|
2021-08-29 18:17:06 +02:00
|
|
|
|
2017-06-14 13:42:57 +02:00
|
|
|
# TODO: Check type via docstring
|
2023-03-25 11:47:26 +01:00
|
|
|
# Now check if the parameter is required or not
|
|
|
|
if not check_required_param(tg_parameter, param, method.__name__):
|
|
|
|
raise AssertionError(
|
|
|
|
f"Param {param.name!r} of method {method.__name__!r} requirement mismatch!"
|
|
|
|
)
|
2022-05-09 19:30:46 +02:00
|
|
|
|
|
|
|
# Now we will check that we don't pass default values if the parameter is not required.
|
|
|
|
if param.default is not inspect.Parameter.empty: # If there is a default argument...
|
|
|
|
default_arg_none = check_defaults_type(param) # check if it's None
|
2023-03-25 11:47:26 +01:00
|
|
|
if not default_arg_none:
|
|
|
|
raise AssertionError(f"Param {param.name!r} of {method.__name__!r} should be None")
|
2022-05-09 19:30:46 +02:00
|
|
|
checked.append(tg_parameter[0])
|
2017-06-14 13:42:57 +02:00
|
|
|
|
2023-03-25 11:47:26 +01:00
|
|
|
expected_additional_args = GLOBALLY_IGNORED_PARAMETERS.copy()
|
|
|
|
expected_additional_args |= ptb_extra_params(name)
|
|
|
|
expected_additional_args |= backwards_compat_kwargs(name)
|
|
|
|
|
|
|
|
unexpected_args = (sig.parameters.keys() ^ checked) - expected_additional_args
|
|
|
|
if unexpected_args != set():
|
|
|
|
raise AssertionError(
|
|
|
|
f"In {method.__qualname__}, unexpected args were found: {unexpected_args}."
|
|
|
|
)
|
2017-06-14 13:42:57 +02:00
|
|
|
|
2022-05-18 17:18:44 +02:00
|
|
|
kw_or_positional_args = [
|
|
|
|
p.name for p in sig.parameters.values() if p.kind != inspect.Parameter.KEYWORD_ONLY
|
|
|
|
]
|
2023-03-25 11:47:26 +01:00
|
|
|
non_kw_only_args = set(kw_or_positional_args).difference(checked).difference(["self"])
|
|
|
|
non_kw_only_args -= backwards_compat_kwargs(name)
|
|
|
|
if non_kw_only_args != set():
|
|
|
|
raise AssertionError(
|
|
|
|
f"In {method.__qualname__}, extra args should be keyword only "
|
|
|
|
f"(compared to {name} in API)"
|
|
|
|
)
|
2022-05-18 17:18:44 +02:00
|
|
|
|
2017-06-14 13:42:57 +02:00
|
|
|
|
|
|
|
def check_object(h4):
|
|
|
|
name = h4.text
|
|
|
|
obj = getattr(telegram, name)
|
|
|
|
table = parse_table(h4)
|
|
|
|
|
2021-08-19 22:01:10 +02:00
|
|
|
# Check arguments based on source. Makes sure to only check __init__'s signature & nothing else
|
|
|
|
sig = inspect.signature(obj.__init__, follow_wrapped=True)
|
2017-06-14 13:42:57 +02:00
|
|
|
|
2021-08-29 18:17:06 +02:00
|
|
|
checked = set()
|
2023-03-25 11:47:26 +01:00
|
|
|
fields_removed_by_ptb = ptb_ignored_params(name)
|
2022-05-09 19:30:46 +02:00
|
|
|
for tg_parameter in table:
|
|
|
|
field: str = tg_parameter[0] # From telegram docs
|
2023-03-25 11:47:26 +01:00
|
|
|
|
|
|
|
if field in fields_removed_by_ptb:
|
|
|
|
continue
|
|
|
|
|
2017-06-14 13:42:57 +02:00
|
|
|
if field == "from":
|
|
|
|
field = "from_user"
|
|
|
|
|
|
|
|
param = sig.parameters.get(field)
|
2023-03-25 11:47:26 +01:00
|
|
|
if param is None:
|
|
|
|
raise AssertionError(f"Attribute {field} not found in {obj.__name__}")
|
2017-06-14 13:42:57 +02:00
|
|
|
# TODO: Check type via docstring
|
2023-03-25 11:47:26 +01:00
|
|
|
if not check_required_param(tg_parameter, param, obj.__name__):
|
|
|
|
raise AssertionError(f"{obj.__name__!r} parameter {param.name!r} requirement mismatch")
|
2022-05-09 19:30:46 +02:00
|
|
|
|
|
|
|
if param.default is not inspect.Parameter.empty: # If there is a default argument...
|
|
|
|
default_arg_none = check_defaults_type(param) # check if its None
|
2023-03-25 11:47:26 +01:00
|
|
|
if not default_arg_none:
|
|
|
|
raise AssertionError(f"Param {param.name!r} of {obj.__name__!r} should be `None`")
|
2022-05-09 19:30:46 +02:00
|
|
|
|
2021-08-29 18:17:06 +02:00
|
|
|
checked.add(field)
|
2017-06-14 13:42:57 +02:00
|
|
|
|
2023-03-25 11:47:26 +01:00
|
|
|
expected_additional_args = GLOBALLY_IGNORED_PARAMETERS.copy()
|
|
|
|
expected_additional_args |= ptb_extra_params(name)
|
|
|
|
expected_additional_args |= backwards_compat_kwargs(name)
|
|
|
|
|
|
|
|
unexpected_args = (sig.parameters.keys() ^ checked) - expected_additional_args
|
|
|
|
if unexpected_args != set():
|
|
|
|
raise AssertionError(f"In {name}, unexpected args were found: {unexpected_args}.")
|
2017-06-14 13:42:57 +02:00
|
|
|
|
|
|
|
|
2022-05-09 19:30:46 +02:00
|
|
|
def is_parameter_required_by_tg(field: str) -> bool:
|
|
|
|
if field in {"Required", "Yes"}:
|
|
|
|
return True
|
|
|
|
if field.split(".", 1)[0] == "Optional": # splits the sentence and extracts first word
|
|
|
|
return False
|
|
|
|
else:
|
|
|
|
return True
|
|
|
|
|
|
|
|
|
2021-08-29 18:17:06 +02:00
|
|
|
def check_required_param(
|
2022-05-09 19:30:46 +02:00
|
|
|
param_desc: List[str], param: inspect.Parameter, method_or_obj_name: str
|
2021-08-29 18:17:06 +02:00
|
|
|
) -> bool:
|
2022-05-09 19:30:46 +02:00
|
|
|
"""Checks if the method/class parameter is a required/optional param as per Telegram docs.
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
:obj:`bool`: The boolean returned represents whether our parameter's requirement (optional
|
|
|
|
or required) is the same as Telegram's or not.
|
|
|
|
"""
|
|
|
|
is_ours_required = param.default is inspect.Parameter.empty
|
|
|
|
telegram_requires = is_parameter_required_by_tg(param_desc[2])
|
|
|
|
# Handle cases where we provide convenience intentionally-
|
2023-03-25 11:47:26 +01:00
|
|
|
if param.name in ignored_param_requirements(method_or_obj_name):
|
2022-05-09 19:30:46 +02:00
|
|
|
return True
|
|
|
|
return telegram_requires is is_ours_required
|
|
|
|
|
2021-08-29 18:17:06 +02:00
|
|
|
|
2022-05-09 19:30:46 +02:00
|
|
|
def check_defaults_type(ptb_param: inspect.Parameter) -> bool:
|
|
|
|
return True if DefaultValue.get_value(ptb_param.default) is None else False
|
2021-08-29 18:17:06 +02:00
|
|
|
|
2022-05-09 19:30:46 +02:00
|
|
|
|
|
|
|
to_run = env_var_2_bool(os.getenv("TEST_OFFICIAL"))
|
2017-08-11 23:58:41 +02:00
|
|
|
argvalues = []
|
|
|
|
names = []
|
|
|
|
|
2022-05-09 19:30:46 +02:00
|
|
|
if to_run:
|
|
|
|
argvalues = []
|
|
|
|
names = []
|
|
|
|
request = httpx.get("https://core.telegram.org/bots/api")
|
|
|
|
soup = BeautifulSoup(request.text, "html.parser")
|
|
|
|
|
|
|
|
for thing in soup.select("h4 > a.anchor"):
|
|
|
|
# Methods and types don't have spaces in them, luckily all other sections of the docs do
|
|
|
|
# TODO: don't depend on that
|
|
|
|
if "-" not in thing["name"]:
|
|
|
|
h4 = thing.parent
|
2017-08-11 23:58:41 +02:00
|
|
|
|
2022-05-09 19:30:46 +02:00
|
|
|
# Is it a method
|
|
|
|
if h4.text[0].lower() == h4.text[0]:
|
|
|
|
argvalues.append((check_method, h4))
|
|
|
|
names.append(h4.text)
|
|
|
|
elif h4.text not in IGNORED_OBJECTS: # Or a type/object
|
|
|
|
argvalues.append((check_object, h4))
|
|
|
|
names.append(h4.text)
|
2017-08-11 23:58:41 +02:00
|
|
|
|
|
|
|
|
2022-05-09 19:30:46 +02:00
|
|
|
@pytest.mark.skipif(not to_run, reason="test_official is not enabled")
|
2017-08-11 23:58:41 +02:00
|
|
|
@pytest.mark.parametrize(("method", "data"), argvalues=argvalues, ids=names)
|
|
|
|
def test_official(method, data):
|
|
|
|
method(data)
|