telegram.utils.helpers Module¶
This module contains helper functions.
-
telegram.utils.helpers.DEFAULT_FALSE: telegram.utils.helpers.DefaultValue = <telegram.utils.helpers.DefaultValue object>¶ Default False
- Type
-
telegram.utils.helpers.DEFAULT_NONE: telegram.utils.helpers.DefaultValue = <telegram.utils.helpers.DefaultValue object>¶ Default None
- Type
-
class
telegram.utils.helpers.DefaultValue(value: Any = None)¶ Bases:
objectWrapper for immutable default arguments that allows to check, if the default value was set explicitly. Usage:
DefaultOne = DefaultValue(1) def f(arg=DefaultOne): if arg is DefaultOne: print('`arg` is the default') arg = arg.value else: print('`arg` was set explicitly') print('`arg` = ' + str(arg))
This yields:
>>> f() `arg` is the default `arg` = 1 >>> f(1) `arg` was set explicitly `arg` = 1 >>> f(2) `arg` was set explicitly `arg` = 2
Also allows to evaluate truthiness:
default = DefaultValue(value) if default: ...
is equivalent to:
default = DefaultValue(value) if value: ...
-
value¶ The value of the default argument
- Type
obj
- Parameters
value (
obj) – The value of the default argument
-
-
telegram.utils.helpers.create_deep_linked_url(bot_username: str, payload: str = None, group: bool = False) → str¶ Creates a deep-linked URL for this
bot_usernamewith the specifiedpayload. See https://core.telegram.org/bots#deep-linking to learn more.The
payloadmay consist of the following characters:A-Z, a-z, 0-9, _, -Note
Works well in conjunction with
CommandHandler("start", callback, filters = Filters.regex('payload'))Examples
create_deep_linked_url(bot.get_me().username, "some-params")- Parameters
bot_username (
str) – The username to link topayload (
str, optional) – Parameters to encode in the created URLgroup (
bool, optional) – IfTruethe user is prompted to select a group to add the bot to. IfFalse, opens a one-on-one conversation with the bot. Defaults toFalse.
- Returns
An URL to start the bot with specific parameters
- Return type
str
-
telegram.utils.helpers.decode_conversations_from_json(json_string: str) → Dict[str, Dict[Tuple, Any]]¶ Helper method to decode a conversations dict (that uses tuples as keys) from a JSON-string created with
_encode_conversations_to_json.- Parameters
json_string (
str) – The conversations dict as JSON string.- Returns
The conversations dict after decoding
- Return type
dict
-
telegram.utils.helpers.decode_user_chat_data_from_json(data: str) → DefaultDict[int, Dict[Any, Any]]¶ Helper method to decode chat or user data (that uses ints as keys) from a JSON-string.
- Parameters
data (
str) – The user/chat_data dict as JSON string.- Returns
The user/chat_data defaultdict after decoding
- Return type
dict
-
telegram.utils.helpers.effective_message_type(entity: Union[Message, Update]) → Optional[str]¶ Extracts the type of message as a string identifier from a
telegram.Messageor atelegram.Update.- Parameters
entity (
Update|Message) –- Returns
One of
Message.MESSAGE_TYPES- Return type
str
-
telegram.utils.helpers.encode_conversations_to_json(conversations: Dict[str, Dict[Tuple, Any]]) → str¶ Helper method to encode a conversations dict (that uses tuples as keys) to a JSON-serializable way. Use
_decode_conversations_from_jsonto decode.- Parameters
conversations (
dict) – The conversations dict to transform to JSON.- Returns
The JSON-serialized conversations dict
- Return type
str
-
telegram.utils.helpers.escape_markdown(text: str, version: int = 1, entity_type: str = None) → str¶ Helper function to escape telegram markup symbols.
- Parameters
text (
str) – The text.version (
int|str) – Use to specify the version of telegrams Markdown. Either1or2. Defaults to1.entity_type (
str, optional) – For the entity typesPRE,CODEand the link part ofTEXT_LINKS, only certain characters need to be escaped inMarkdownV2. See the official API documentation for details. Only valid in combination withversion=2, will be ignored else.
-
telegram.utils.helpers.from_timestamp(unixtime: Optional[int], tzinfo: datetime.tzinfo = <UTC>) → Optional[datetime.datetime]¶ Converts an (integer) unix timestamp to a timezone aware datetime object.
None`s are left alone (i.e. ``from_timestamp(None)`isNone).- Parameters
unixtime (int) – Integer POSIX timestamp.
tzinfo (
datetime.tzinfo, optional) – The timezone, the timestamp is to be converted to. Defaults to UTC.
- Returns
timezone aware equivalent
datetime.datetimevalue iftimestampis notNone; elseNone
-
telegram.utils.helpers.get_signal_name(signum: int) → str¶ Returns the signal name of the given signal number.
-
telegram.utils.helpers.is_local_file(obj: Optional[Union[str, pathlib.Path]]) → bool¶ Checks if a given string is a file on local system.
- Parameters
obj (
str) – The string to check.
-
telegram.utils.helpers.mention_html(user_id: Union[int, str], name: str) → str¶ - Parameters
user_id (
int) –name (
str) –
- Returns
The inline mention for the user as html.
- Return type
str
-
telegram.utils.helpers.mention_markdown(user_id: Union[int, str], name: str, version: int = 1) → str¶ - Parameters
user_id (
int) –name (
str) –version (
int|str) – Use to specify the version of telegrams Markdown. Either1or2. Defaults to1
- Returns
The inline mention for the user as markdown.
- Return type
str
-
telegram.utils.helpers.parse_file_input(file_input: Union[str, IO, InputFile, pathlib.Path, TelegramObject], tg_type: Type[TelegramObject] = None, attach: bool = None, filename: str = None) → Union[str, InputFile, Any]¶ Parses input for sending files:
For string input, if the input is an absolute path of a local file, adds the
file://prefix. If the input is a relative path of a local file, computes the absolute path and adds thefile://prefix. Returns the input unchanged, otherwise.pathlib.Pathobjects are treated the same way as strings.For IO input, returns an
telegram.InputFile.If
tg_typeis specified and the input is of that type, returns thefile_idattribute.
- Parameters
file_input (
str| filelike object | Telegram media object) – The input to parse.tg_type (
type, optional) – The Telegram media type the input can be. E.g.telegram.Animation.attach (
bool, optional) – Whether this file should be send as one file or is part of a collection of files. Only relevant in case antelegram.InputFileis returned.filename (
str, optional) – The filename. Only relevant in case antelegram.InputFileis returned.
- Returns
- The parsed input or the untouched
file_input, in case it’s no valid file input.
- Return type
str|telegram.InputFile|object
-
telegram.utils.helpers.to_float_timestamp(time_object: Union[int, float, datetime.timedelta, datetime.datetime, datetime.time], reference_timestamp: float = None, tzinfo: pytz.tzinfo.BaseTzInfo = None) → float¶ Converts a given time object to a float POSIX timestamp. Used to convert different time specifications to a common format. The time object can be relative (i.e. indicate a time increment, or a time of day) or absolute. Any objects from the
datetimemodule that are timezone-naive will be assumed to be in UTC, ifbotis not passed orbot.defaultsisNone.- Parameters
time_object (int | float | datetime.timedelta | datetime.datetime | datetime.time) –
Time value to convert. The semantics of this parameter will depend on its type:
intorfloatwill be interpreted as “seconds fromreference_t”datetime.timedeltawill be interpreted as “time increment fromreference_t”datetime.datetimewill be interpreted as an absolute date/time valuedatetime.timewill be interpreted as a specific time of day
reference_timestamp (float, optional) –
POSIX timestamp that indicates the absolute time from which relative calculations are to be performed (e.g. when
tis given as anint, indicating “seconds fromreference_t”). Defaults to now (the time at which this function is called).If
tis given as an absolute representation of date & time (i.e. adatetime.datetimeobject),reference_timestampis not relevant and so its value should beNone. If this is not the case, aValueErrorwill be raised.tzinfo (
datetime.tzinfo, optional) – Iftis a naive object from thedatetimemodule, it will be interpreted as this timezone. Defaults topytz.utc.
- Returns
- (float | None) The return value depends on the type of argument
t. Iftis given as a time increment (i.e. as a obj:int,
floatordatetime.timedelta), then the return value will bereference_t+t.Else if it is given as an absolute date/time value (i.e. a
datetime.datetimeobject), the equivalent value as a POSIX timestamp will be returned.Finally, if it is a time of the day without date (i.e. a
datetime.timeobject), the return value is the nearest future occurrence of that time of day.
- (float | None) The return value depends on the type of argument
- Raises
TypeError – if t’s type is not one of those described above
-
telegram.utils.helpers.to_timestamp(dt_obj: Optional[Union[int, float, datetime.timedelta, datetime.datetime, datetime.time]], reference_timestamp: float = None, tzinfo: pytz.tzinfo.BaseTzInfo = None) → Optional[int]¶ Wrapper over
to_float_timestamp()which returns an integer (the float value truncated down to the nearest integer).See the documentation for
to_float_timestamp()for more details.