From a2150b3751290f71272da6bc6ad28e43a0eefad3 Mon Sep 17 00:00:00 2001 From: Bibo-Joshi <22366557+Bibo-Joshi@users.noreply.github.com> Date: Sun, 2 Feb 2025 09:31:18 +0100 Subject: [PATCH] Accept `datetime.timedelta` Input in `Bot` Method Parameters (#4651) --- docs/substitutions/global.rst | 4 +- telegram/_bot.py | 97 ++++++++++++++++++-------- telegram/_callbackquery.py | 6 +- telegram/_chat.py | 25 ++++--- telegram/_inline/inlinequery.py | 4 +- telegram/_message.py | 17 ++--- telegram/_user.py | 23 +++--- telegram/_utils/types.py | 3 + telegram/ext/_extbot.py | 25 +++---- telegram/request/_requestparameter.py | 8 +++ tests/_files/test_animation.py | 8 ++- tests/_files/test_audio.py | 6 +- tests/_files/test_location.py | 13 ++-- tests/_files/test_video.py | 6 +- tests/_files/test_videonote.py | 8 ++- tests/_files/test_voice.py | 6 +- tests/_payment/test_invoice.py | 6 +- tests/request/test_requestparameter.py | 14 ++++ tests/test_bot.py | 25 ++++--- tests/test_official/exceptions.py | 7 ++ 20 files changed, 214 insertions(+), 97 deletions(-) diff --git a/docs/substitutions/global.rst b/docs/substitutions/global.rst index b71ac1f0eac..11945d3fc09 100644 --- a/docs/substitutions/global.rst +++ b/docs/substitutions/global.rst @@ -96,4 +96,6 @@ .. |allow_paid_broadcast| replace:: Pass True to allow up to :tg-const:`telegram.constants.FloodLimit.PAID_MESSAGES_PER_SECOND` messages per second, ignoring `broadcasting limits `__ for a fee of 0.1 Telegram Stars per message. The relevant Stars will be withdrawn from the bot's balance. -.. |tz-naive-dtms| replace:: For timezone naive :obj:`datetime.datetime` objects, the default timezone of the bot will be used, which is UTC unless :attr:`telegram.ext.Defaults.tzinfo` is used. \ No newline at end of file +.. |tz-naive-dtms| replace:: For timezone naive :obj:`datetime.datetime` objects, the default timezone of the bot will be used, which is UTC unless :attr:`telegram.ext.Defaults.tzinfo` is used. + +.. |time-period-input| replace:: :class:`datetime.timedelta` objects are accepted in addition to plain :obj:`int` values. \ No newline at end of file diff --git a/telegram/_bot.py b/telegram/_bot.py index 6cba7dbf803..f1d4be176f0 100644 --- a/telegram/_bot.py +++ b/telegram/_bot.py @@ -103,6 +103,7 @@ JSONDict, ODVInput, ReplyMarkup, + TimePeriod, ) from telegram._utils.warnings import warn from telegram._webhookinfo import WebhookInfo @@ -1492,7 +1493,7 @@ async def send_audio( self, chat_id: Union[int, str], audio: Union[FileInput, "Audio"], - duration: Optional[int] = None, + duration: Optional[TimePeriod] = None, performer: Optional[str] = None, title: Optional[str] = None, caption: Optional[str] = None, @@ -1554,7 +1555,11 @@ async def send_audio( .. versionchanged:: 20.0 |sequenceargs| - duration (:obj:`int`, optional): Duration of sent audio in seconds. + duration (:obj:`int` | :class:`datetime.timedelta`, optional): Duration of sent audio + in seconds. + + .. versionchanged:: NEXT.VERSION + |time-period-input| performer (:obj:`str`, optional): Performer. title (:obj:`str`, optional): Track name. disable_notification (:obj:`bool`, optional): |disable_notification| @@ -1932,7 +1937,7 @@ async def send_video( self, chat_id: Union[int, str], video: Union[FileInput, "Video"], - duration: Optional[int] = None, + duration: Optional[TimePeriod] = None, caption: Optional[str] = None, disable_notification: ODVInput[bool] = DEFAULT_NONE, reply_markup: Optional[ReplyMarkup] = None, @@ -1990,7 +1995,11 @@ async def send_video( .. versionchanged:: 20.0 File paths as input is also accepted for bots *not* running in :paramref:`~telegram.Bot.local_mode`. - duration (:obj:`int`, optional): Duration of sent video in seconds. + duration (:obj:`int` | :class:`datetime.timedelta`, optional): Duration of sent video + in seconds. + + .. versionchanged:: NEXT.VERSION + |time-period-input| width (:obj:`int`, optional): Video width. height (:obj:`int`, optional): Video height. caption (:obj:`str`, optional): Video caption (may also be used when resending videos @@ -2111,7 +2120,7 @@ async def send_video_note( self, chat_id: Union[int, str], video_note: Union[FileInput, "VideoNote"], - duration: Optional[int] = None, + duration: Optional[TimePeriod] = None, length: Optional[int] = None, disable_notification: ODVInput[bool] = DEFAULT_NONE, reply_markup: Optional[ReplyMarkup] = None, @@ -2163,7 +2172,11 @@ async def send_video_note( .. versionchanged:: 20.0 File paths as input is also accepted for bots *not* running in :paramref:`~telegram.Bot.local_mode`. - duration (:obj:`int`, optional): Duration of sent video in seconds. + duration (:obj:`int` | :class:`datetime.timedelta`, optional): Duration of sent video + in seconds. + + .. versionchanged:: NEXT.VERSION + |time-period-input| length (:obj:`int`, optional): Video width and height, i.e. diameter of the video message. disable_notification (:obj:`bool`, optional): |disable_notification| @@ -2259,7 +2272,7 @@ async def send_animation( self, chat_id: Union[int, str], animation: Union[FileInput, "Animation"], - duration: Optional[int] = None, + duration: Optional[TimePeriod] = None, width: Optional[int] = None, height: Optional[int] = None, caption: Optional[str] = None, @@ -2311,7 +2324,11 @@ async def send_animation( .. versionchanged:: 13.2 Accept :obj:`bytes` as input. - duration (:obj:`int`, optional): Duration of sent animation in seconds. + duration (:obj:`int` | :class:`datetime.timedelta`, optional): Duration of sent + animation in seconds. + + .. versionchanged:: NEXT.VERSION + |time-period-input| width (:obj:`int`, optional): Animation width. height (:obj:`int`, optional): Animation height. caption (:obj:`str`, optional): Animation caption (may also be used when resending @@ -2430,7 +2447,7 @@ async def send_voice( self, chat_id: Union[int, str], voice: Union[FileInput, "Voice"], - duration: Optional[int] = None, + duration: Optional[TimePeriod] = None, caption: Optional[str] = None, disable_notification: ODVInput[bool] = DEFAULT_NONE, reply_markup: Optional[ReplyMarkup] = None, @@ -2491,7 +2508,11 @@ async def send_voice( .. versionchanged:: 20.0 |sequenceargs| - duration (:obj:`int`, optional): Duration of the voice message in seconds. + duration (:obj:`int` | :class:`datetime.timedelta`, optional): Duration of the voice + message in seconds. + + .. versionchanged:: NEXT.VERSION + |time-period-input| disable_notification (:obj:`bool`, optional): |disable_notification| protect_content (:obj:`bool`, optional): |protect_content| @@ -2763,7 +2784,7 @@ async def send_location( longitude: Optional[float] = None, disable_notification: ODVInput[bool] = DEFAULT_NONE, reply_markup: Optional[ReplyMarkup] = None, - live_period: Optional[int] = None, + live_period: Optional[TimePeriod] = None, horizontal_accuracy: Optional[float] = None, heading: Optional[int] = None, proximity_alert_radius: Optional[int] = None, @@ -2796,12 +2817,16 @@ async def send_location( horizontal_accuracy (:obj:`int`, optional): The radius of uncertainty for the location, measured in meters; 0-:tg-const:`telegram.constants.LocationLimit.HORIZONTAL_ACCURACY`. - live_period (:obj:`int`, optional): Period in seconds for which the location will be + live_period (:obj:`int` | :class:`datetime.timedelta`, optional): Period in seconds for + which the location will be updated, should be between :tg-const:`telegram.constants.LocationLimit.MIN_LIVE_PERIOD` and :tg-const:`telegram.constants.LocationLimit.MAX_LIVE_PERIOD`, or :tg-const:`telegram.constants.LocationLimit.LIVE_PERIOD_FOREVER` for live locations that can be edited indefinitely. + + .. versionchanged:: NEXT.VERSION + |time-period-input| heading (:obj:`int`, optional): For live locations, a direction in which the user is moving, in degrees. Must be between :tg-const:`telegram.constants.LocationLimit.MIN_HEADING` and @@ -2919,7 +2944,7 @@ async def edit_message_live_location( horizontal_accuracy: Optional[float] = None, heading: Optional[int] = None, proximity_alert_radius: Optional[int] = None, - live_period: Optional[int] = None, + live_period: Optional[TimePeriod] = None, business_connection_id: Optional[str] = None, *, location: Optional[Location] = None, @@ -2959,7 +2984,8 @@ async def edit_message_live_location( if specified. reply_markup (:class:`telegram.InlineKeyboardMarkup`, optional): An object for a new inline keyboard. - live_period (:obj:`int`, optional): New period in seconds during which the location + live_period (:obj:`int` | :class:`datetime.timedelta`, optional): New period in seconds + during which the location can be updated, starting from the message send date. If :tg-const:`telegram.constants.LocationLimit.LIVE_PERIOD_FOREVER` is specified, then the location can be updated forever. Otherwise, the new value must not exceed @@ -2968,6 +2994,9 @@ async def edit_message_live_location( remains unchanged .. versionadded:: 21.2. + + .. versionchanged:: NEXT.VERSION + |time-period-input| business_connection_id (:obj:`str`, optional): |business_id_str_edit| .. versionadded:: 21.4 @@ -3623,7 +3652,7 @@ async def answer_inline_query( results: Union[ Sequence["InlineQueryResult"], Callable[[int], Optional[Sequence["InlineQueryResult"]]] ], - cache_time: Optional[int] = None, + cache_time: Optional[TimePeriod] = None, is_personal: Optional[bool] = None, next_offset: Optional[str] = None, button: Optional[InlineQueryResultsButton] = None, @@ -3659,8 +3688,12 @@ async def answer_inline_query( a callable that accepts the current page index starting from 0. It must return either a list of :class:`telegram.InlineQueryResult` instances or :obj:`None` if there are no more results. - cache_time (:obj:`int`, optional): The maximum amount of time in seconds that the + cache_time (:obj:`int` | :class:`datetime.timedelta`, optional): The maximum amount of + time in seconds that the result of the inline query may be cached on the server. Defaults to ``300``. + + .. versionchanged:: NEXT.VERSION + |time-period-input| is_personal (:obj:`bool`, optional): Pass :obj:`True`, if results may be cached on the server side only for the user that sent the query. By default, results may be returned to any user who sends the same query. @@ -4076,7 +4109,7 @@ async def answer_callback_query( text: Optional[str] = None, show_alert: Optional[bool] = None, url: Optional[str] = None, - cache_time: Optional[int] = None, + cache_time: Optional[TimePeriod] = None, *, read_timeout: ODVInput[float] = DEFAULT_NONE, write_timeout: ODVInput[float] = DEFAULT_NONE, @@ -4107,9 +4140,13 @@ async def answer_callback_query( opens your game - note that this will only work if the query comes from a callback game button. Otherwise, you may use links like t.me/your_bot?start=XXXX that open your bot with a parameter. - cache_time (:obj:`int`, optional): The maximum amount of time in seconds that the + cache_time (:obj:`int` | :class:`datetime.timedelta`, optional): The maximum amount of + time in seconds that the result of the callback query may be cached client-side. Defaults to 0. + .. versionchanged:: NEXT.VERSION + |time-period-input| + Returns: :obj:`bool` On success, :obj:`True` is returned. @@ -7261,7 +7298,7 @@ async def send_poll( reply_markup: Optional[ReplyMarkup] = None, explanation: Optional[str] = None, explanation_parse_mode: ODVInput[str] = DEFAULT_NONE, - open_period: Optional[int] = None, + open_period: Optional[TimePeriod] = None, close_date: Optional[Union[int, dtm.datetime]] = None, explanation_entities: Optional[Sequence["MessageEntity"]] = None, protect_content: ODVInput[bool] = DEFAULT_NONE, @@ -7324,10 +7361,14 @@ async def send_poll( .. versionchanged:: 20.0 |sequenceargs| - open_period (:obj:`int`, optional): Amount of time in seconds the poll will be active + open_period (:obj:`int` | :class:`datetime.timedelta`, optional): Amount of time in + seconds the poll will be active after creation, :tg-const:`telegram.Poll.MIN_OPEN_PERIOD`- :tg-const:`telegram.Poll.MAX_OPEN_PERIOD`. Can't be used together with :paramref:`close_date`. + + .. versionchanged:: NEXT.VERSION + |time-period-input| close_date (:obj:`int` | :obj:`datetime.datetime`, optional): Point in time (Unix timestamp) when the poll will be automatically closed. Must be at least :tg-const:`telegram.Poll.MIN_OPEN_PERIOD` and no more than @@ -8228,7 +8269,7 @@ async def create_invoice_link( send_phone_number_to_provider: Optional[bool] = None, send_email_to_provider: Optional[bool] = None, is_flexible: Optional[bool] = None, - subscription_period: Optional[Union[int, dtm.timedelta]] = None, + subscription_period: Optional[TimePeriod] = None, business_connection_id: Optional[str] = None, *, read_timeout: ODVInput[float] = DEFAULT_NONE, @@ -8349,11 +8390,7 @@ async def create_invoice_link( "is_flexible": is_flexible, "send_phone_number_to_provider": send_phone_number_to_provider, "send_email_to_provider": send_email_to_provider, - "subscription_period": ( - subscription_period.total_seconds() - if isinstance(subscription_period, dtm.timedelta) - else subscription_period - ), + "subscription_period": subscription_period, "business_connection_id": business_connection_id, } @@ -9644,7 +9681,7 @@ async def send_paid_media( async def create_chat_subscription_invite_link( self, chat_id: Union[str, int], - subscription_period: int, + subscription_period: TimePeriod, subscription_price: int, name: Optional[str] = None, *, @@ -9665,9 +9702,13 @@ async def create_chat_subscription_invite_link( Args: chat_id (:obj:`int` | :obj:`str`): |chat_id_channel| - subscription_period (:obj:`int`): The number of seconds the subscription will be + subscription_period (:obj:`int` | :class:`datetime.timedelta`): The number of seconds + the subscription will be active for before the next payment. Currently, it must always be :tg-const:`telegram.constants.ChatSubscriptionLimit.SUBSCRIPTION_PERIOD` (30 days). + + .. versionchanged:: NEXT.VERSION + |time-period-input| subscription_price (:obj:`int`): The number of Telegram Stars a user must pay initially and after each subsequent subscription period to be a member of the chat; :tg-const:`telegram.constants.ChatSubscriptionLimit.MIN_PRICE`- diff --git a/telegram/_callbackquery.py b/telegram/_callbackquery.py index 83efbfaa675..c1ba637546f 100644 --- a/telegram/_callbackquery.py +++ b/telegram/_callbackquery.py @@ -28,7 +28,7 @@ from telegram._user import User from telegram._utils.argumentparsing import de_json_optional from telegram._utils.defaultvalue import DEFAULT_NONE -from telegram._utils.types import JSONDict, ODVInput, ReplyMarkup +from telegram._utils.types import JSONDict, ODVInput, ReplyMarkup, TimePeriod if TYPE_CHECKING: from telegram import ( @@ -164,7 +164,7 @@ async def answer( text: Optional[str] = None, show_alert: Optional[bool] = None, url: Optional[str] = None, - cache_time: Optional[int] = None, + cache_time: Optional[TimePeriod] = None, *, read_timeout: ODVInput[float] = DEFAULT_NONE, write_timeout: ODVInput[float] = DEFAULT_NONE, @@ -471,7 +471,7 @@ async def edit_message_live_location( horizontal_accuracy: Optional[float] = None, heading: Optional[int] = None, proximity_alert_radius: Optional[int] = None, - live_period: Optional[int] = None, + live_period: Optional[TimePeriod] = None, *, location: Optional[Location] = None, read_timeout: ODVInput[float] = DEFAULT_NONE, diff --git a/telegram/_chat.py b/telegram/_chat.py index 16c12056709..ee4c25f59b6 100644 --- a/telegram/_chat.py +++ b/telegram/_chat.py @@ -31,7 +31,14 @@ from telegram._telegramobject import TelegramObject from telegram._utils import enum from telegram._utils.defaultvalue import DEFAULT_NONE -from telegram._utils.types import CorrectOptionID, FileInput, JSONDict, ODVInput, ReplyMarkup +from telegram._utils.types import ( + CorrectOptionID, + FileInput, + JSONDict, + ODVInput, + ReplyMarkup, + TimePeriod, +) from telegram.helpers import escape_markdown from telegram.helpers import mention_html as helpers_mention_html from telegram.helpers import mention_markdown as helpers_mention_markdown @@ -1339,7 +1346,7 @@ async def send_contact( async def send_audio( self, audio: Union[FileInput, "Audio"], - duration: Optional[int] = None, + duration: Optional[TimePeriod] = None, performer: Optional[str] = None, title: Optional[str] = None, caption: Optional[str] = None, @@ -1668,7 +1675,7 @@ async def send_location( longitude: Optional[float] = None, disable_notification: ODVInput[bool] = DEFAULT_NONE, reply_markup: Optional[ReplyMarkup] = None, - live_period: Optional[int] = None, + live_period: Optional[TimePeriod] = None, horizontal_accuracy: Optional[float] = None, heading: Optional[int] = None, proximity_alert_radius: Optional[int] = None, @@ -1727,7 +1734,7 @@ async def send_location( async def send_animation( self, animation: Union[FileInput, "Animation"], - duration: Optional[int] = None, + duration: Optional[TimePeriod] = None, width: Optional[int] = None, height: Optional[int] = None, caption: Optional[str] = None, @@ -1915,7 +1922,7 @@ async def send_venue( async def send_video( self, video: Union[FileInput, "Video"], - duration: Optional[int] = None, + duration: Optional[TimePeriod] = None, caption: Optional[str] = None, disable_notification: ODVInput[bool] = DEFAULT_NONE, reply_markup: Optional[ReplyMarkup] = None, @@ -1987,7 +1994,7 @@ async def send_video( async def send_video_note( self, video_note: Union[FileInput, "VideoNote"], - duration: Optional[int] = None, + duration: Optional[TimePeriod] = None, length: Optional[int] = None, disable_notification: ODVInput[bool] = DEFAULT_NONE, reply_markup: Optional[ReplyMarkup] = None, @@ -2045,7 +2052,7 @@ async def send_video_note( async def send_voice( self, voice: Union[FileInput, "Voice"], - duration: Optional[int] = None, + duration: Optional[TimePeriod] = None, caption: Optional[str] = None, disable_notification: ODVInput[bool] = DEFAULT_NONE, reply_markup: Optional[ReplyMarkup] = None, @@ -2115,7 +2122,7 @@ async def send_poll( reply_markup: Optional[ReplyMarkup] = None, explanation: Optional[str] = None, explanation_parse_mode: ODVInput[str] = DEFAULT_NONE, - open_period: Optional[int] = None, + open_period: Optional[TimePeriod] = None, close_date: Optional[Union[int, dtm.datetime]] = None, explanation_entities: Optional[Sequence["MessageEntity"]] = None, protect_content: ODVInput[bool] = DEFAULT_NONE, @@ -2708,7 +2715,7 @@ async def revoke_invite_link( async def create_subscription_invite_link( self, - subscription_period: int, + subscription_period: TimePeriod, subscription_price: int, name: Optional[str] = None, *, diff --git a/telegram/_inline/inlinequery.py b/telegram/_inline/inlinequery.py index 4cf7f5a7366..1aa80014d77 100644 --- a/telegram/_inline/inlinequery.py +++ b/telegram/_inline/inlinequery.py @@ -29,7 +29,7 @@ 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 +from telegram._utils.types import JSONDict, ODVInput, TimePeriod if TYPE_CHECKING: from telegram import Bot, InlineQueryResult @@ -141,7 +141,7 @@ async def answer( results: Union[ Sequence["InlineQueryResult"], Callable[[int], Optional[Sequence["InlineQueryResult"]]] ], - cache_time: Optional[int] = None, + cache_time: Optional[TimePeriod] = None, is_personal: Optional[bool] = None, next_offset: Optional[str] = None, button: Optional[InlineQueryResultsButton] = None, diff --git a/telegram/_message.py b/telegram/_message.py index f089851e969..e5e5ce7ed4f 100644 --- a/telegram/_message.py +++ b/telegram/_message.py @@ -77,6 +77,7 @@ MarkdownVersion, ODVInput, ReplyMarkup, + TimePeriod, ) from telegram._utils.warnings import warn from telegram._videochat import ( @@ -2232,7 +2233,7 @@ async def reply_photo( async def reply_audio( self, audio: Union[FileInput, "Audio"], - duration: Optional[int] = None, + duration: Optional[TimePeriod] = None, performer: Optional[str] = None, title: Optional[str] = None, caption: Optional[str] = None, @@ -2406,7 +2407,7 @@ async def reply_document( async def reply_animation( self, animation: Union[FileInput, "Animation"], - duration: Optional[int] = None, + duration: Optional[TimePeriod] = None, width: Optional[int] = None, height: Optional[int] = None, caption: Optional[str] = None, @@ -2574,7 +2575,7 @@ async def reply_sticker( async def reply_video( self, video: Union[FileInput, "Video"], - duration: Optional[int] = None, + duration: Optional[TimePeriod] = None, caption: Optional[str] = None, disable_notification: ODVInput[bool] = DEFAULT_NONE, reply_markup: Optional[ReplyMarkup] = None, @@ -2669,7 +2670,7 @@ async def reply_video( async def reply_video_note( self, video_note: Union[FileInput, "VideoNote"], - duration: Optional[int] = None, + duration: Optional[TimePeriod] = None, length: Optional[int] = None, disable_notification: ODVInput[bool] = DEFAULT_NONE, reply_markup: Optional[ReplyMarkup] = None, @@ -2750,7 +2751,7 @@ async def reply_video_note( async def reply_voice( self, voice: Union[FileInput, "Voice"], - duration: Optional[int] = None, + duration: Optional[TimePeriod] = None, caption: Optional[str] = None, disable_notification: ODVInput[bool] = DEFAULT_NONE, reply_markup: Optional[ReplyMarkup] = None, @@ -2836,7 +2837,7 @@ async def reply_location( longitude: Optional[float] = None, disable_notification: ODVInput[bool] = DEFAULT_NONE, reply_markup: Optional[ReplyMarkup] = None, - live_period: Optional[int] = None, + live_period: Optional[TimePeriod] = None, horizontal_accuracy: Optional[float] = None, heading: Optional[int] = None, proximity_alert_radius: Optional[int] = None, @@ -3098,7 +3099,7 @@ async def reply_poll( reply_markup: Optional[ReplyMarkup] = None, explanation: Optional[str] = None, explanation_parse_mode: ODVInput[str] = DEFAULT_NONE, - open_period: Optional[int] = None, + open_period: Optional[TimePeriod] = None, close_date: Optional[Union[int, dtm.datetime]] = None, explanation_entities: Optional[Sequence["MessageEntity"]] = None, protect_content: ODVInput[bool] = DEFAULT_NONE, @@ -3980,7 +3981,7 @@ async def edit_live_location( horizontal_accuracy: Optional[float] = None, heading: Optional[int] = None, proximity_alert_radius: Optional[int] = None, - live_period: Optional[int] = None, + live_period: Optional[TimePeriod] = None, *, location: Optional[Location] = None, read_timeout: ODVInput[float] = DEFAULT_NONE, diff --git a/telegram/_user.py b/telegram/_user.py index 0e9ce1f2b5c..0ef1d8d66d4 100644 --- a/telegram/_user.py +++ b/telegram/_user.py @@ -26,7 +26,14 @@ from telegram._menubutton import MenuButton from telegram._telegramobject import TelegramObject from telegram._utils.defaultvalue import DEFAULT_NONE -from telegram._utils.types import CorrectOptionID, FileInput, JSONDict, ODVInput, ReplyMarkup +from telegram._utils.types import ( + CorrectOptionID, + FileInput, + JSONDict, + ODVInput, + ReplyMarkup, + TimePeriod, +) from telegram.helpers import mention_html as helpers_mention_html from telegram.helpers import mention_markdown as helpers_mention_markdown @@ -668,7 +675,7 @@ async def send_media_group( async def send_audio( self, audio: Union[FileInput, "Audio"], - duration: Optional[int] = None, + duration: Optional[TimePeriod] = None, performer: Optional[str] = None, title: Optional[str] = None, caption: Optional[str] = None, @@ -1113,7 +1120,7 @@ async def send_location( longitude: Optional[float] = None, disable_notification: ODVInput[bool] = DEFAULT_NONE, reply_markup: Optional[ReplyMarkup] = None, - live_period: Optional[int] = None, + live_period: Optional[TimePeriod] = None, horizontal_accuracy: Optional[float] = None, heading: Optional[int] = None, proximity_alert_radius: Optional[int] = None, @@ -1175,7 +1182,7 @@ async def send_location( async def send_animation( self, animation: Union[FileInput, "Animation"], - duration: Optional[int] = None, + duration: Optional[TimePeriod] = None, width: Optional[int] = None, height: Optional[int] = None, caption: Optional[str] = None, @@ -1303,7 +1310,7 @@ async def send_sticker( async def send_video( self, video: Union[FileInput, "Video"], - duration: Optional[int] = None, + duration: Optional[TimePeriod] = None, caption: Optional[str] = None, disable_notification: ODVInput[bool] = DEFAULT_NONE, reply_markup: Optional[ReplyMarkup] = None, @@ -1447,7 +1454,7 @@ async def send_venue( async def send_video_note( self, video_note: Union[FileInput, "VideoNote"], - duration: Optional[int] = None, + duration: Optional[TimePeriod] = None, length: Optional[int] = None, disable_notification: ODVInput[bool] = DEFAULT_NONE, reply_markup: Optional[ReplyMarkup] = None, @@ -1508,7 +1515,7 @@ async def send_video_note( async def send_voice( self, voice: Union[FileInput, "Voice"], - duration: Optional[int] = None, + duration: Optional[TimePeriod] = None, caption: Optional[str] = None, disable_notification: ODVInput[bool] = DEFAULT_NONE, reply_markup: Optional[ReplyMarkup] = None, @@ -1581,7 +1588,7 @@ async def send_poll( reply_markup: Optional[ReplyMarkup] = None, explanation: Optional[str] = None, explanation_parse_mode: ODVInput[str] = DEFAULT_NONE, - open_period: Optional[int] = None, + open_period: Optional[TimePeriod] = None, close_date: Optional[Union[int, dtm.datetime]] = None, explanation_entities: Optional[Sequence["MessageEntity"]] = None, protect_content: ODVInput[bool] = DEFAULT_NONE, diff --git a/telegram/_utils/types.py b/telegram/_utils/types.py index 29377df5bae..925fba94cad 100644 --- a/telegram/_utils/types.py +++ b/telegram/_utils/types.py @@ -23,6 +23,7 @@ user. Changes to this module are not considered breaking changes and may not be documented in the changelog. """ +import datetime as dtm from collections.abc import Collection from pathlib import Path from typing import IO, TYPE_CHECKING, Any, Callable, Literal, Optional, TypeVar, Union @@ -93,3 +94,5 @@ ] BaseUrl = Union[str, Callable[[str], str]] + +TimePeriod = Union[int, dtm.timedelta] diff --git a/telegram/ext/_extbot.py b/telegram/ext/_extbot.py index db19ec806bb..e8f207e24ef 100644 --- a/telegram/ext/_extbot.py +++ b/telegram/ext/_extbot.py @@ -100,6 +100,7 @@ JSONDict, ODVInput, ReplyMarkup, + TimePeriod, ) from telegram.ext._callbackdatacache import CallbackDataCache from telegram.ext._utils.types import RLARGS @@ -933,7 +934,7 @@ async def answer_callback_query( text: Optional[str] = None, show_alert: Optional[bool] = None, url: Optional[str] = None, - cache_time: Optional[int] = None, + cache_time: Optional[TimePeriod] = None, *, read_timeout: ODVInput[float] = DEFAULT_NONE, write_timeout: ODVInput[float] = DEFAULT_NONE, @@ -961,7 +962,7 @@ async def answer_inline_query( results: Union[ Sequence["InlineQueryResult"], Callable[[int], Optional[Sequence["InlineQueryResult"]]] ], - cache_time: Optional[int] = None, + cache_time: Optional[TimePeriod] = None, is_personal: Optional[bool] = None, next_offset: Optional[str] = None, button: Optional[InlineQueryResultsButton] = None, @@ -1211,7 +1212,7 @@ async def create_invoice_link( send_phone_number_to_provider: Optional[bool] = None, send_email_to_provider: Optional[bool] = None, is_flexible: Optional[bool] = None, - subscription_period: Optional[Union[int, dtm.timedelta]] = None, + subscription_period: Optional[TimePeriod] = None, business_connection_id: Optional[str] = None, *, read_timeout: ODVInput[float] = DEFAULT_NONE, @@ -1596,7 +1597,7 @@ async def edit_message_live_location( horizontal_accuracy: Optional[float] = None, heading: Optional[int] = None, proximity_alert_radius: Optional[int] = None, - live_period: Optional[int] = None, + live_period: Optional[TimePeriod] = None, business_connection_id: Optional[str] = None, *, location: Optional[Location] = None, @@ -2431,7 +2432,7 @@ async def send_animation( self, chat_id: Union[int, str], animation: Union[FileInput, "Animation"], - duration: Optional[int] = None, + duration: Optional[TimePeriod] = None, width: Optional[int] = None, height: Optional[int] = None, caption: Optional[str] = None, @@ -2493,7 +2494,7 @@ async def send_audio( self, chat_id: Union[int, str], audio: Union[FileInput, "Audio"], - duration: Optional[int] = None, + duration: Optional[TimePeriod] = None, performer: Optional[str] = None, title: Optional[str] = None, caption: Optional[str] = None, @@ -2848,7 +2849,7 @@ async def send_location( longitude: Optional[float] = None, disable_notification: ODVInput[bool] = DEFAULT_NONE, reply_markup: Optional[ReplyMarkup] = None, - live_period: Optional[int] = None, + live_period: Optional[TimePeriod] = None, horizontal_accuracy: Optional[float] = None, heading: Optional[int] = None, proximity_alert_radius: Optional[int] = None, @@ -3061,7 +3062,7 @@ async def send_poll( reply_markup: Optional[ReplyMarkup] = None, explanation: Optional[str] = None, explanation_parse_mode: ODVInput[str] = DEFAULT_NONE, - open_period: Optional[int] = None, + open_period: Optional[TimePeriod] = None, close_date: Optional[Union[int, dtm.datetime]] = None, explanation_entities: Optional[Sequence["MessageEntity"]] = None, protect_content: ODVInput[bool] = DEFAULT_NONE, @@ -3221,7 +3222,7 @@ async def send_video( self, chat_id: Union[int, str], video: Union[FileInput, "Video"], - duration: Optional[int] = None, + duration: Optional[TimePeriod] = None, caption: Optional[str] = None, disable_notification: ODVInput[bool] = DEFAULT_NONE, reply_markup: Optional[ReplyMarkup] = None, @@ -3285,7 +3286,7 @@ async def send_video_note( self, chat_id: Union[int, str], video_note: Union[FileInput, "VideoNote"], - duration: Optional[int] = None, + duration: Optional[TimePeriod] = None, length: Optional[int] = None, disable_notification: ODVInput[bool] = DEFAULT_NONE, reply_markup: Optional[ReplyMarkup] = None, @@ -3335,7 +3336,7 @@ async def send_voice( self, chat_id: Union[int, str], voice: Union[FileInput, "Voice"], - duration: Optional[int] = None, + duration: Optional[TimePeriod] = None, caption: Optional[str] = None, disable_notification: ODVInput[bool] = DEFAULT_NONE, reply_markup: Optional[ReplyMarkup] = None, @@ -4400,7 +4401,7 @@ async def send_paid_media( async def create_chat_subscription_invite_link( self, chat_id: Union[str, int], - subscription_period: int, + subscription_period: TimePeriod, subscription_price: int, name: Optional[str] = None, *, diff --git a/telegram/request/_requestparameter.py b/telegram/request/_requestparameter.py index 51f9b618709..89796713772 100644 --- a/telegram/request/_requestparameter.py +++ b/telegram/request/_requestparameter.py @@ -115,6 +115,14 @@ def _value_and_input_files_from_input( # pylint: disable=too-many-return-statem """ if isinstance(value, dtm.datetime): return to_timestamp(value), [] + if isinstance(value, dtm.timedelta): + seconds = value.total_seconds() + # We convert to int for completeness for whole seconds + if seconds.is_integer(): + return int(seconds), [] + # The Bot API doesn't document behavior for fractions of seconds so far, but we don't + # want to silently drop them + return seconds, [] if isinstance(value, StringEnum): return value.value, [] if isinstance(value, InputFile): diff --git a/tests/_files/test_animation.py b/tests/_files/test_animation.py index 62c7e79ab17..5ae93dd61ef 100644 --- a/tests/_files/test_animation.py +++ b/tests/_files/test_animation.py @@ -17,6 +17,7 @@ # You should have received a copy of the GNU Lesser Public License # along with this program. If not, see [http://www.gnu.org/licenses/]. import asyncio +import datetime as dtm import os from pathlib import Path @@ -213,11 +214,14 @@ async def make_assertion(url, request_data: RequestData, *args, **kwargs): class TestAnimationWithRequest(AnimationTestBase): - async def test_send_all_args(self, bot, chat_id, animation_file, animation, thumb_file): + @pytest.mark.parametrize("duration", [1, dtm.timedelta(seconds=1)]) + async def test_send_all_args( + self, bot, chat_id, animation_file, animation, thumb_file, duration + ): message = await bot.send_animation( chat_id, animation_file, - duration=self.duration, + duration=duration, width=self.width, height=self.height, caption=self.caption, diff --git a/tests/_files/test_audio.py b/tests/_files/test_audio.py index 108cd1d10d4..78112058cdd 100644 --- a/tests/_files/test_audio.py +++ b/tests/_files/test_audio.py @@ -17,6 +17,7 @@ # You should have received a copy of the GNU Lesser Public License # along with this program. If not, see [http://www.gnu.org/licenses/]. import asyncio +import datetime as dtm import os from pathlib import Path @@ -214,12 +215,13 @@ async def make_assertion(url, request_data: RequestData, *args, **kwargs): class TestAudioWithRequest(AudioTestBase): - async def test_send_all_args(self, bot, chat_id, audio_file, thumb_file): + @pytest.mark.parametrize("duration", [3, dtm.timedelta(seconds=3)]) + async def test_send_all_args(self, bot, chat_id, audio_file, thumb_file, duration): message = await bot.send_audio( chat_id, audio=audio_file, caption=self.caption, - duration=self.duration, + duration=duration, performer=self.performer, title=self.title, disable_notification=False, diff --git a/tests/_files/test_location.py b/tests/_files/test_location.py index 7664c765feb..5ccddbac527 100644 --- a/tests/_files/test_location.py +++ b/tests/_files/test_location.py @@ -17,6 +17,7 @@ # You should have received a copy of the GNU Lesser Public License # along with this program. If not, see [http://www.gnu.org/licenses/]. import asyncio +import datetime as dtm import pytest @@ -238,12 +239,16 @@ async def test_send_location_default_protect_content(self, chat_id, default_bot, assert not unprotected.has_protected_content @pytest.mark.xfail - async def test_send_live_location(self, bot, chat_id): + @pytest.mark.parametrize( + ("live_period", "edit_live_period"), + [(80, 200), (dtm.timedelta(seconds=80), dtm.timedelta(seconds=200))], + ) + async def test_send_live_location(self, bot, chat_id, live_period, edit_live_period): message = await bot.send_location( chat_id=chat_id, latitude=52.223880, longitude=5.166146, - live_period=80, + live_period=live_period, horizontal_accuracy=50, heading=90, proximity_alert_radius=1000, @@ -266,7 +271,7 @@ async def test_send_live_location(self, bot, chat_id): horizontal_accuracy=30, heading=10, proximity_alert_radius=500, - live_period=200, + live_period=edit_live_period, ) assert pytest.approx(message2.location.latitude, rel=1e-5) == 52.223098 @@ -276,7 +281,7 @@ async def test_send_live_location(self, bot, chat_id): assert message2.location.proximity_alert_radius == 500 assert message2.location.live_period == 200 - await bot.stop_message_live_location(message.chat_id, message.message_id) + assert await bot.stop_message_live_location(message.chat_id, message.message_id) with pytest.raises(BadRequest, match="Message can't be edited"): await bot.edit_message_live_location( message.chat_id, message.message_id, latitude=52.223880, longitude=5.164306 diff --git a/tests/_files/test_video.py b/tests/_files/test_video.py index e53e8c6ba0b..65d7ee8c354 100644 --- a/tests/_files/test_video.py +++ b/tests/_files/test_video.py @@ -17,6 +17,7 @@ # You should have received a copy of the GNU Lesser Public License # along with this program. If not, see [http://www.gnu.org/licenses/]. import asyncio +import datetime as dtm import os from pathlib import Path @@ -221,11 +222,12 @@ async def make_assertion(url, request_data: RequestData, *args, **kwargs): class TestVideoWithRequest(VideoTestBase): - async def test_send_all_args(self, bot, chat_id, video_file, video, thumb_file): + @pytest.mark.parametrize("duration", [dtm.timedelta(seconds=5), 5]) + async def test_send_all_args(self, bot, chat_id, video_file, video, thumb_file, duration): message = await bot.send_video( chat_id, video_file, - duration=self.duration, + duration=duration, caption=self.caption, supports_streaming=self.supports_streaming, disable_notification=False, diff --git a/tests/_files/test_videonote.py b/tests/_files/test_videonote.py index 38d6b7dd280..5edab597806 100644 --- a/tests/_files/test_videonote.py +++ b/tests/_files/test_videonote.py @@ -17,6 +17,7 @@ # You should have received a copy of the GNU Lesser Public License # along with this program. If not, see [http://www.gnu.org/licenses/]. import asyncio +import datetime as dtm import os from pathlib import Path @@ -224,11 +225,14 @@ async def make_assertion(url, request_data: RequestData, *args, **kwargs): class TestVideoNoteWithRequest(VideoNoteTestBase): - async def test_send_all_args(self, bot, chat_id, video_note_file, video_note, thumb_file): + @pytest.mark.parametrize("duration", [3, dtm.timedelta(seconds=3)]) + async def test_send_all_args( + self, bot, chat_id, video_note_file, video_note, thumb_file, duration + ): message = await bot.send_video_note( chat_id, video_note_file, - duration=self.duration, + duration=duration, length=self.length, disable_notification=False, protect_content=True, diff --git a/tests/_files/test_voice.py b/tests/_files/test_voice.py index c5fa99094bd..c06b1218139 100644 --- a/tests/_files/test_voice.py +++ b/tests/_files/test_voice.py @@ -17,6 +17,7 @@ # You should have received a copy of the GNU Lesser Public License # along with this program. If not, see [http://www.gnu.org/licenses/]. import asyncio +import datetime as dtm import os from pathlib import Path @@ -207,11 +208,12 @@ async def make_assertion(url, request_data: RequestData, *args, **kwargs): class TestVoiceWithRequest(VoiceTestBase): - async def test_send_all_args(self, bot, chat_id, voice_file, voice): + @pytest.mark.parametrize("duration", [3, dtm.timedelta(seconds=3)]) + async def test_send_all_args(self, bot, chat_id, voice_file, voice, duration): message = await bot.send_voice( chat_id, voice_file, - duration=self.duration, + duration=duration, caption=self.caption, disable_notification=False, protect_content=True, diff --git a/tests/_payment/test_invoice.py b/tests/_payment/test_invoice.py index 501ba353744..e3506632fe5 100644 --- a/tests/_payment/test_invoice.py +++ b/tests/_payment/test_invoice.py @@ -127,12 +127,12 @@ async def make_assertion(*args, **_): async def test_send_all_args_create_invoice_link( self, offline_bot, monkeypatch, subscription_period ): - async def make_assertion(*args, **_): - kwargs = args[1] + async def make_assertion(url, request_data: RequestData, *args, **kwargs): + kwargs = request_data.parameters sp = kwargs.pop("subscription_period") == 42 return all(kwargs[i] == i for i in kwargs) and sp - monkeypatch.setattr(offline_bot, "_post", make_assertion) + monkeypatch.setattr(offline_bot.request, "post", make_assertion) assert await offline_bot.create_invoice_link( title="title", description="description", diff --git a/tests/request/test_requestparameter.py b/tests/request/test_requestparameter.py index c124e5281fc..9082a58eae2 100644 --- a/tests/request/test_requestparameter.py +++ b/tests/request/test_requestparameter.py @@ -83,6 +83,7 @@ def test_multiple_multipart_data(self): (ChatType.PRIVATE, "private"), (MessageEntity("type", 1, 1), {"type": "type", "offset": 1, "length": 1}), (dtm.datetime(2019, 11, 11, 0, 26, 16, 10**5), 1573431976), + (dtm.timedelta(days=42), 42 * 24 * 60 * 60), ( [ True, @@ -100,6 +101,19 @@ def test_from_input_no_media(self, value, expected_value): assert request_parameter.value == expected_value assert request_parameter.input_files is None + @pytest.mark.parametrize( + ("value", "expected_type", "expected_value"), + [ + (dtm.timedelta(seconds=1), int, 1), + (dtm.timedelta(milliseconds=1), float, 0.001), + ], + ) + def test_from_input_timedelta(self, value, expected_type, expected_value): + request_parameter = RequestParameter.from_input("key", value) + assert request_parameter.value == expected_value + assert request_parameter.input_files is None + assert isinstance(request_parameter.value, expected_type) + def test_from_input_inputfile(self): inputfile_1 = InputFile("data1", filename="inputfile_1", attach=True) inputfile_2 = InputFile("data2", filename="inputfile_2") diff --git a/tests/test_bot.py b/tests/test_bot.py index 6f5dc0ade0a..2c9ba6abed0 100644 --- a/tests/test_bot.py +++ b/tests/test_bot.py @@ -787,11 +787,14 @@ async def make_assertion(url, request_data: RequestData, *args, **kwargs): # TODO: Needs improvement. We need incoming inline query to test answer. @pytest.mark.parametrize("button_type", ["start", "web_app"]) - async def test_answer_inline_query(self, monkeypatch, offline_bot, raw_bot, button_type): + @pytest.mark.parametrize("cache_time", [74, dtm.timedelta(seconds=74)]) + async def test_answer_inline_query( + self, monkeypatch, offline_bot, raw_bot, button_type, cache_time + ): # For now just test that our internals pass the correct data async def make_assertion(url, request_data: RequestData, *args, **kwargs): expected = { - "cache_time": 300, + "cache_time": 74, "results": [ { "title": "first", @@ -871,7 +874,7 @@ async def make_assertion(url, request_data: RequestData, *args, **kwargs): assert await bot_type.answer_inline_query( 1234, results=results, - cache_time=300, + cache_time=cache_time, is_personal=True, next_offset="42", button=button, @@ -1327,21 +1330,22 @@ async def make_assertion(url, request_data: RequestData, *args, **kwargs): assert await offline_bot.set_chat_administrator_custom_title(2, 32, "custom_title") # TODO: Needs improvement. Need an incoming callbackquery to test - async def test_answer_callback_query(self, monkeypatch, offline_bot): + @pytest.mark.parametrize("cache_time", [74, dtm.timedelta(seconds=74)]) + async def test_answer_callback_query(self, monkeypatch, offline_bot, cache_time): # For now just test that our internals pass the correct data async def make_assertion(url, request_data: RequestData, *args, **kwargs): return request_data.parameters == { "callback_query_id": 23, "show_alert": True, "url": "no_url", - "cache_time": 1, + "cache_time": 74, "text": "answer", } monkeypatch.setattr(offline_bot.request, "post", make_assertion) assert await offline_bot.answer_callback_query( - 23, text="answer", show_alert=True, url="no_url", cache_time=1 + 23, text="answer", show_alert=True, url="no_url", cache_time=cache_time ) @pytest.mark.parametrize("drop_pending_updates", [True, False]) @@ -2783,7 +2787,9 @@ async def test_send_and_stop_poll(self, bot, super_group_id, reply_markup): assert quiz_task.done() @pytest.mark.parametrize( - ("open_period", "close_date"), [(5, None), (None, True)], ids=["open_period", "close_date"] + ("open_period", "close_date"), + [(5, None), (dtm.timedelta(seconds=5), None), (None, True)], + ids=["open_period", "open_period-dtm", "close_date"], ) async def test_send_open_period(self, bot, super_group_id, open_period, close_date): question = "Is this a test?" @@ -4485,13 +4491,14 @@ async def test_get_star_transactions(self, bot): assert isinstance(transactions, StarTransactions) assert len(transactions.transactions) == 0 + @pytest.mark.parametrize("subscription_period", [2592000, dtm.timedelta(days=30)]) async def test_create_edit_chat_subscription_link( - self, bot, subscription_channel_id, channel_id + self, bot, subscription_channel_id, channel_id, subscription_period ): sub_link = await bot.create_chat_subscription_invite_link( subscription_channel_id, name="sub_name", - subscription_period=2592000, + subscription_period=subscription_period, subscription_price=13, ) assert sub_link.name == "sub_name" diff --git a/tests/test_official/exceptions.py b/tests/test_official/exceptions.py index e86056a8733..8bc2c84500a 100644 --- a/tests/test_official/exceptions.py +++ b/tests/test_official/exceptions.py @@ -17,6 +17,7 @@ # You should have received a copy of the GNU Lesser Public License # along with this program. If not, see [http://www.gnu.org/licenses/]. """This module contains exceptions to our API compared to the official API.""" +import datetime as dtm from telegram import Animation, Audio, Document, Gift, PhotoSize, Sticker, Video, VideoNote, Voice from tests.test_official.helpers import _get_params_base @@ -54,6 +55,12 @@ class ParamTypeCheckingExceptions: "replace_sticker_in_set": { "old_sticker$": Sticker, }, + # The underscore will match any method + r"\w+_[\w_]+": { + "duration": dtm.timedelta, + r"\w+_period": dtm.timedelta, + "cache_time": dtm.timedelta, + }, } # TODO: Look into merging this with COMPLEX_TYPES