2015-06-26 09:55:13 +03:00
# -*- coding: utf-8 -*-
2021-06-21 18:39:13 +03:00
from datetime import datetime
2015-06-26 09:55:13 +03:00
2018-08-17 12:54:26 +03:00
import logging
import re
import sys
import threading
import time
2021-01-14 03:44:37 +03:00
import traceback
2021-06-21 18:39:13 +03:00
from typing import Any , Callable , List , Optional , Union
2018-05-20 23:40:25 +03:00
2022-01-24 22:38:35 +03:00
# these imports are used to avoid circular import error
2021-06-18 23:35:49 +03:00
import telebot . util
import telebot . types
2021-06-21 18:39:13 +03:00
2022-01-24 16:15:04 +03:00
# storage
from telebot . storage import StatePickleStorage , StateMemoryStorage
2021-11-27 17:04:03 +03:00
2022-03-06 16:39:41 +03:00
2015-09-08 20:47:55 +03:00
logger = logging . getLogger ( ' TeleBot ' )
2021-11-20 13:47:55 +03:00
2015-10-01 23:03:54 +03:00
formatter = logging . Formatter (
2016-02-27 06:17:35 +03:00
' %(asctime)s ( %(filename)s : %(lineno)d %(threadName)s ) %(levelname)s - %(name)s : " %(message)s " '
2015-10-01 23:03:54 +03:00
)
2015-09-05 13:12:52 +03:00
2022-03-06 16:39:41 +03:00
import inspect
2015-09-08 20:56:05 +03:00
console_output_handler = logging . StreamHandler ( sys . stderr )
console_output_handler . setFormatter ( formatter )
logger . addHandler ( console_output_handler )
2015-09-08 20:47:55 +03:00
2020-08-02 18:58:22 +03:00
logger . setLevel ( logging . ERROR )
2015-08-31 12:46:18 +03:00
2021-11-27 21:41:39 +03:00
from telebot import apihelper , util , types
2022-03-06 16:39:41 +03:00
from telebot . handler_backends import MemoryHandlerBackend , FileHandlerBackend , BaseMiddleware , CancelUpdate , SkipHandler
2021-11-20 13:47:55 +03:00
from telebot . custom_filters import SimpleCustomFilter , AdvancedCustomFilter
2015-06-30 06:49:35 +03:00
2021-06-21 18:39:13 +03:00
REPLY_MARKUP_TYPES = Union [
types . InlineKeyboardMarkup , types . ReplyKeyboardMarkup ,
types . ReplyKeyboardRemove , types . ForceReply ]
2015-06-26 09:55:13 +03:00
"""
Module : telebot
"""
2015-09-30 18:18:26 +03:00
2018-05-25 20:57:22 +03:00
class Handler :
2018-05-27 01:23:20 +03:00
"""
Class for ( next step | reply ) handlers
"""
2018-08-17 13:01:03 +03:00
2018-05-27 16:54:56 +03:00
def __init__ ( self , callback , * args , * * kwargs ) :
2018-05-27 01:23:20 +03:00
self . callback = callback
2018-05-25 20:57:22 +03:00
self . args = args
self . kwargs = kwargs
def __getitem__ ( self , item ) :
return getattr ( self , item )
2020-08-21 17:36:08 +03:00
class ExceptionHandler :
"""
Class for handling exceptions while Polling
"""
2021-01-09 21:22:49 +03:00
# noinspection PyMethodMayBeStatic,PyUnusedLocal
2020-08-21 17:36:08 +03:00
def handle ( self , exception ) :
return False
2015-06-26 09:55:13 +03:00
class TeleBot :
2022-03-06 21:23:33 +03:00
"""
2022-03-06 22:18:11 +03:00
This is the main synchronous class for Bot .
2022-03-06 21:23:33 +03:00
It allows you to add handlers for different kind of updates .
Usage :
2022-03-06 22:18:11 +03:00
2022-03-06 21:23:33 +03:00
. . code - block : : python
from telebot import TeleBot
bot = TeleBot ( ' token ' ) # get token from @BotFather
See more examples in examples / directory :
https : / / github . com / eternnoir / pyTelegramBotAPI / tree / master / examples
"""
2015-06-26 09:55:13 +03:00
2020-04-12 20:41:32 +03:00
def __init__ (
2020-07-04 21:07:42 +03:00
self , token , parse_mode = None , threaded = True , skip_pending = False , num_threads = 2 ,
2021-04-18 18:31:24 +03:00
next_step_backend = None , reply_backend = None , exception_handler = None , last_update_id = 0 ,
2022-03-06 16:39:41 +03:00
suppress_middleware_excepions = False , state_storage = StateMemoryStorage ( ) , use_class_middlewares = False
2020-04-12 20:41:32 +03:00
) :
2015-07-04 12:00:42 +03:00
"""
: param token : bot API token
2020-07-04 21:07:42 +03:00
: param parse_mode : default parse_mode
2015-07-20 04:56:17 +03:00
: return : Telebot object .
2015-07-04 12:00:42 +03:00
"""
2015-06-26 09:55:13 +03:00
self . token = token
2020-07-04 21:07:42 +03:00
self . parse_mode = parse_mode
2015-06-26 13:02:30 +03:00
self . update_listener = [ ]
2015-12-01 17:05:52 +03:00
self . skip_pending = skip_pending
2021-04-18 18:31:24 +03:00
self . suppress_middleware_excepions = suppress_middleware_excepions
2015-10-01 23:03:54 +03:00
2015-07-18 12:27:16 +03:00
self . __stop_polling = threading . Event ( )
2020-08-25 21:26:28 +03:00
self . last_update_id = last_update_id
2015-10-01 23:03:54 +03:00
self . exc_info = None
2015-06-30 02:44:14 +03:00
2020-04-12 20:41:32 +03:00
self . next_step_backend = next_step_backend
if not self . next_step_backend :
self . next_step_backend = MemoryHandlerBackend ( )
2015-07-24 14:44:01 +03:00
2020-04-12 20:41:32 +03:00
self . reply_backend = reply_backend
if not self . reply_backend :
self . reply_backend = MemoryHandlerBackend ( )
2018-05-20 23:40:25 +03:00
2020-08-21 17:36:08 +03:00
self . exception_handler = exception_handler
2015-07-02 23:32:18 +03:00
self . message_handlers = [ ]
2016-06-07 14:29:12 +03:00
self . edited_message_handlers = [ ]
2016-12-03 08:28:22 +03:00
self . channel_post_handlers = [ ]
self . edited_channel_post_handlers = [ ]
2016-01-04 18:10:32 +03:00
self . inline_handlers = [ ]
2016-01-05 08:18:32 +03:00
self . chosen_inline_handlers = [ ]
2016-04-16 09:18:19 +03:00
self . callback_query_handlers = [ ]
2017-05-25 06:22:40 +03:00
self . shipping_query_handlers = [ ]
self . pre_checkout_query_handlers = [ ]
2020-03-09 13:25:54 +03:00
self . poll_handlers = [ ]
2020-05-12 03:09:34 +03:00
self . poll_answer_handlers = [ ]
2021-06-23 17:10:48 +03:00
self . my_chat_member_handlers = [ ]
self . chat_member_handlers = [ ]
2021-11-05 21:22:03 +03:00
self . chat_join_request_handlers = [ ]
2021-09-11 19:47:59 +03:00
self . custom_filters = { }
2021-09-25 15:12:32 +03:00
self . state_handlers = [ ]
2022-01-24 16:15:04 +03:00
self . current_states = state_storage
2021-10-13 16:34:36 +03:00
2022-03-06 16:39:41 +03:00
self . use_class_middlewares = use_class_middlewares
if apihelper . ENABLE_MIDDLEWARE and not use_class_middlewares :
2020-08-24 16:02:35 +03:00
self . typed_middleware_handlers = {
' message ' : [ ] ,
' edited_message ' : [ ] ,
' channel_post ' : [ ] ,
' edited_channel_post ' : [ ] ,
' inline_query ' : [ ] ,
' chosen_inline_result ' : [ ] ,
' callback_query ' : [ ] ,
' shipping_query ' : [ ] ,
' pre_checkout_query ' : [ ] ,
' poll ' : [ ] ,
2021-06-23 17:10:48 +03:00
' poll_answer ' : [ ] ,
' my_chat_member ' : [ ] ,
2021-11-05 21:22:03 +03:00
' chat_member ' : [ ] ,
' chat_join_request ' : [ ]
2020-08-24 16:02:35 +03:00
}
self . default_middleware_handlers = [ ]
2022-03-06 16:39:41 +03:00
if apihelper . ENABLE_MIDDLEWARE and use_class_middlewares :
logger . warning (
' You are using class based middlewares, but you have '
' ENABLE_MIDDLEWARE set to True. This is not recommended. '
)
self . middlewares = [ ] if use_class_middlewares else None
2020-04-08 21:13:19 +03:00
2015-10-02 01:00:54 +03:00
self . threaded = threaded
if self . threaded :
2022-02-01 23:58:57 +03:00
self . worker_pool = util . ThreadPool ( self , num_threads = num_threads )
2021-09-20 15:31:00 +03:00
@property
def user ( self ) - > types . User :
"""
The User object representing this bot .
Equivalent to bot . get_me ( ) but the result is cached so only one API call is needed
"""
if not hasattr ( self , " _user " ) :
2022-01-30 19:53:55 +03:00
self . _user = self . get_me ( )
2021-09-20 15:31:00 +03:00
return self . _user
2015-07-02 04:38:31 +03:00
2018-05-27 01:30:14 +03:00
def enable_save_next_step_handlers ( self , delay = 120 , filename = " ./.handler-saves/step.save " ) :
2018-05-27 01:37:06 +03:00
"""
2020-04-12 20:41:32 +03:00
Enable saving next step handlers ( by default saving disabled )
This function explicitly assigns FileHandlerBackend ( instead of Saver ) just to keep backward
compatibility whose purpose was to enable file saving capability for handlers . And the same
implementation is now available with FileHandlerBackend
Most probably this function should be deprecated in future major releases
2018-05-27 01:37:06 +03:00
: param delay : Delay between changes in handlers and saving
: param filename : Filename of save file
"""
2020-04-12 20:41:32 +03:00
self . next_step_backend = FileHandlerBackend ( self . next_step_backend . handlers , filename , delay )
2018-05-20 23:40:25 +03:00
2021-10-13 16:34:36 +03:00
def enable_saving_states ( self , filename = " ./.state-save/states.pkl " ) :
"""
Enable saving states ( by default saving disabled )
: param filename : Filename of saving file
"""
2022-01-24 22:38:35 +03:00
self . current_states = StatePickleStorage ( file_path = filename )
2022-01-10 14:38:28 +03:00
self . current_states . create_dir ( )
2021-10-13 16:34:36 +03:00
2018-05-27 01:30:14 +03:00
def enable_save_reply_handlers ( self , delay = 120 , filename = " ./.handler-saves/reply.save " ) :
2018-05-27 01:37:06 +03:00
"""
Enable saving reply handlers ( by default saving disable )
2020-04-12 20:41:32 +03:00
This function explicitly assigns FileHandlerBackend ( instead of Saver ) just to keep backward
compatibility whose purpose was to enable file saving capability for handlers . And the same
implementation is now available with FileHandlerBackend
Most probably this function should be deprecated in future major releases
2018-05-27 01:37:06 +03:00
: param delay : Delay between changes in handlers and saving
: param filename : Filename of save file
"""
2020-04-12 20:41:32 +03:00
self . reply_backend = FileHandlerBackend ( self . reply_backend . handlers , filename , delay )
2018-05-20 23:40:25 +03:00
2018-05-25 08:56:31 +03:00
def disable_save_next_step_handlers ( self ) :
2018-05-27 01:37:06 +03:00
"""
Disable saving next step handlers ( by default saving disable )
2020-04-12 20:41:32 +03:00
This function is left to keep backward compatibility whose purpose was to disable file saving capability
for handlers . For the same purpose , MemoryHandlerBackend is reassigned as a new next_step_backend backend
instead of FileHandlerBackend .
Most probably this function should be deprecated in future major releases
2018-05-27 01:37:06 +03:00
"""
2020-04-12 20:41:32 +03:00
self . next_step_backend = MemoryHandlerBackend ( self . next_step_backend . handlers )
2018-05-20 23:40:25 +03:00
2018-05-25 08:56:31 +03:00
def disable_save_reply_handlers ( self ) :
2018-05-27 01:37:06 +03:00
"""
Disable saving next step handlers ( by default saving disable )
2020-04-12 20:41:32 +03:00
This function is left to keep backward compatibility whose purpose was to disable file saving capability
for handlers . For the same purpose , MemoryHandlerBackend is reassigned as a new reply_backend backend
instead of FileHandlerBackend .
Most probably this function should be deprecated in future major releases
2018-05-27 01:37:06 +03:00
"""
2020-04-12 20:41:32 +03:00
self . reply_backend = MemoryHandlerBackend ( self . reply_backend . handlers )
2018-05-20 23:40:25 +03:00
2018-05-27 01:30:14 +03:00
def load_next_step_handlers ( self , filename = " ./.handler-saves/step.save " , del_file_after_loading = True ) :
2018-05-27 01:37:06 +03:00
"""
Load next step handlers from save file
2020-04-12 20:41:32 +03:00
This function is left to keep backward compatibility whose purpose was to load handlers from file with the
help of FileHandlerBackend and is only recommended to use if next_step_backend was assigned as
FileHandlerBackend before entering this function
Most probably this function should be deprecated in future major releases
2018-05-27 01:37:06 +03:00
: param filename : Filename of the file where handlers was saved
: param del_file_after_loading : Is passed True , after loading save file will be deleted
"""
2020-04-12 20:41:32 +03:00
self . next_step_backend . load_handlers ( filename , del_file_after_loading )
2018-05-20 23:40:25 +03:00
2018-05-27 01:30:14 +03:00
def load_reply_handlers ( self , filename = " ./.handler-saves/reply.save " , del_file_after_loading = True ) :
2018-05-27 01:37:06 +03:00
"""
Load reply handlers from save file
2020-04-12 20:41:32 +03:00
This function is left to keep backward compatibility whose purpose was to load handlers from file with the
help of FileHandlerBackend and is only recommended to use if reply_backend was assigned as
FileHandlerBackend before entering this function
Most probably this function should be deprecated in future major releases
2018-05-27 01:37:06 +03:00
: param filename : Filename of the file where handlers was saved
: param del_file_after_loading : Is passed True , after loading save file will be deleted
"""
2020-04-12 20:41:32 +03:00
self . reply_backend . load_handlers ( filename , del_file_after_loading )
2018-05-20 23:40:25 +03:00
2021-01-09 21:22:49 +03:00
def set_webhook ( self , url = None , certificate = None , max_connections = None , allowed_updates = None , ip_address = None ,
drop_pending_updates = None , timeout = None ) :
2020-12-29 19:24:41 +03:00
"""
Use this method to specify a url and receive incoming updates via an outgoing webhook . Whenever there is an
2021-06-19 18:59:55 +03:00
update for the bot , we will send an HTTPS POST request to the specified url ,
containing a JSON - serialized Update .
In case of an unsuccessful request , we will give up after a reasonable amount of attempts .
Returns True on success .
2020-12-29 19:24:41 +03:00
2022-03-06 21:14:07 +03:00
Telegram documentation : https : / / core . telegram . org / bots / api #setwebhook
2020-12-29 19:24:41 +03:00
: param url : HTTPS url to send updates to . Use an empty string to remove webhook integration
2021-06-19 18:59:55 +03:00
: param certificate : Upload your public key certificate so that the root certificate in use can be checked .
See our self - signed guide for details .
: param max_connections : Maximum allowed number of simultaneous HTTPS connections to the webhook
for update delivery , 1 - 100. Defaults to 40. Use lower values to limit the load on your bot ' s server,
and higher values to increase your bot ' s throughput.
: param allowed_updates : A JSON - serialized list of the update types you want your bot to receive .
For example , specify [ “ message ” , “ edited_channel_post ” , “ callback_query ” ] to only receive updates
of these types . See Update for a complete list of available update types .
Specify an empty list to receive all updates regardless of type ( default ) .
If not specified , the previous setting will be used .
: param ip_address : The fixed IP address which will be used to send webhook requests instead of the IP address
resolved through DNS
2021-01-09 21:22:49 +03:00
: param drop_pending_updates : Pass True to drop all pending updates
2021-01-07 00:13:44 +03:00
: param timeout : Integer . Request connection timeout
2022-03-06 21:14:07 +03:00
: return : API reply .
2020-12-29 19:24:41 +03:00
"""
2021-06-19 18:59:55 +03:00
return apihelper . set_webhook ( self . token , url , certificate , max_connections , allowed_updates , ip_address ,
drop_pending_updates , timeout )
2015-09-18 21:12:53 +03:00
2021-01-07 00:13:44 +03:00
def delete_webhook ( self , drop_pending_updates = None , timeout = None ) :
2016-12-06 06:52:16 +03:00
"""
Use this method to remove webhook integration if you decide to switch back to getUpdates .
2020-12-29 19:24:41 +03:00
2022-03-06 21:14:07 +03:00
Telegram documentation : https : / / core . telegram . org / bots / api #deletewebhook
2020-12-29 19:24:41 +03:00
: param drop_pending_updates : Pass True to drop all pending updates
2021-01-07 00:13:44 +03:00
: param timeout : Integer . Request connection timeout
2016-12-06 06:52:16 +03:00
: return : bool
"""
2021-01-07 00:13:44 +03:00
return apihelper . delete_webhook ( self . token , drop_pending_updates , timeout )
2016-12-06 06:52:16 +03:00
2021-10-13 17:02:17 +03:00
def get_webhook_info ( self , timeout : Optional [ int ] = None ) :
2020-12-29 19:24:41 +03:00
"""
Use this method to get current webhook status . Requires no parameters .
If the bot is using getUpdates , will return an object with the url field empty .
2022-03-06 21:14:07 +03:00
Telegram documentation : https : / / core . telegram . org / bots / api #getwebhookinfo
2021-01-07 00:13:44 +03:00
: param timeout : Integer . Request connection timeout
2020-12-29 19:24:41 +03:00
: return : On success , returns a WebhookInfo object .
"""
2021-01-07 00:13:44 +03:00
result = apihelper . get_webhook_info ( self . token , timeout )
2016-10-20 10:52:38 +03:00
return types . WebhookInfo . de_json ( result )
2015-09-18 21:12:53 +03:00
def remove_webhook ( self ) :
2015-10-02 01:00:54 +03:00
return self . set_webhook ( ) # No params resets webhook
2015-09-18 21:12:53 +03:00
2021-06-21 18:39:13 +03:00
def get_updates ( self , offset : Optional [ int ] = None , limit : Optional [ int ] = None ,
timeout : Optional [ int ] = 20 , allowed_updates : Optional [ List [ str ] ] = None ,
long_polling_timeout : int = 20 ) - > List [ types . Update ] :
2015-09-05 13:10:11 +03:00
"""
Use this method to receive incoming updates using long polling ( wiki ) . An Array of Update objects is returned .
2022-03-06 17:41:54 +03:00
2022-03-06 21:14:07 +03:00
Telegram documentation : https : / / core . telegram . org / bots / api #getupdates
2016-12-06 06:44:30 +03:00
: param allowed_updates : Array of string . List the types of updates you want your bot to receive .
2015-09-05 13:10:11 +03:00
: param offset : Integer . Identifier of the first update to be returned .
: param limit : Integer . Limits the number of updates to be retrieved .
2020-11-07 14:02:11 +03:00
: param timeout : Integer . Request connection timeout
2022-03-07 12:24:28 +03:00
: param long_polling_timeout : Timeout in seconds for long polling .
2015-09-05 13:10:11 +03:00
: return : array of Updates
"""
2020-11-07 14:02:11 +03:00
json_updates = apihelper . get_updates ( self . token , offset , limit , timeout , allowed_updates , long_polling_timeout )
2021-07-19 20:01:37 +03:00
return [ types . Update . de_json ( ju ) for ju in json_updates ]
2015-09-05 13:10:11 +03:00
2015-12-01 17:05:52 +03:00
def __skip_updates ( self ) :
"""
Get and discard all pending updates before first poll of the bot
2022-03-06 17:41:54 +03:00
2021-08-15 12:32:11 +03:00
: return :
2015-12-01 17:05:52 +03:00
"""
2021-08-16 13:48:21 +03:00
self . get_updates ( offset = - 1 )
2015-12-01 17:05:52 +03:00
2021-06-23 20:29:36 +03:00
def __retrieve_updates ( self , timeout = 20 , long_polling_timeout = 20 , allowed_updates = None ) :
2015-07-02 14:43:49 +03:00
"""
Retrieves any updates from the Telegram API .
Registered listeners and applicable message handlers will be notified when a new message arrives .
2022-03-06 17:41:54 +03:00
2015-07-02 14:43:49 +03:00
: raises ApiException when a call has failed .
"""
2015-12-01 17:05:52 +03:00
if self . skip_pending :
2021-08-16 13:48:21 +03:00
self . __skip_updates ( )
logger . debug ( ' Skipped all pending messages ' )
2015-12-01 17:05:52 +03:00
self . skip_pending = False
2021-06-23 17:10:48 +03:00
updates = self . get_updates ( offset = ( self . last_update_id + 1 ) ,
2021-06-23 20:29:36 +03:00
allowed_updates = allowed_updates ,
2021-06-19 18:59:55 +03:00
timeout = timeout , long_polling_timeout = long_polling_timeout )
2016-02-07 18:45:54 +03:00
self . process_new_updates ( updates )
def process_new_updates ( self , updates ) :
2022-03-06 17:41:54 +03:00
"""
Processes new updates . Just pass list of subclasses of Update to this method .
: param updates : List of Update objects
"""
2020-08-24 16:02:35 +03:00
upd_count = len ( updates )
logger . debug ( ' Received {0} new updates ' . format ( upd_count ) )
2021-06-19 18:59:55 +03:00
if upd_count == 0 : return
2020-08-24 16:02:35 +03:00
new_messages = None
new_edited_messages = None
new_channel_posts = None
new_edited_channel_posts = None
new_inline_queries = None
new_chosen_inline_results = None
new_callback_queries = None
new_shipping_queries = None
new_pre_checkout_queries = None
new_polls = None
new_poll_answers = None
2021-06-23 17:10:48 +03:00
new_my_chat_members = None
new_chat_members = None
2021-11-05 21:22:03 +03:00
chat_join_request = None
2021-04-18 15:56:52 +03:00
2015-06-26 13:02:30 +03:00
for update in updates :
2020-04-11 11:02:50 +03:00
if apihelper . ENABLE_MIDDLEWARE :
2021-04-18 15:56:52 +03:00
try :
self . process_middlewares ( update )
except Exception as e :
logger . error ( str ( e ) )
2021-04-18 18:31:24 +03:00
if not self . suppress_middleware_excepions :
raise
2021-04-18 18:41:28 +03:00
else :
if update . update_id > self . last_update_id : self . last_update_id = update . update_id
continue
2022-03-06 16:39:41 +03:00
2021-04-18 15:56:52 +03:00
2015-09-05 16:54:54 +03:00
if update . update_id > self . last_update_id :
self . last_update_id = update . update_id
2016-01-04 18:10:32 +03:00
if update . message :
2020-08-24 16:02:35 +03:00
if new_messages is None : new_messages = [ ]
2016-01-04 18:10:32 +03:00
new_messages . append ( update . message )
2016-06-07 14:29:12 +03:00
if update . edited_message :
2020-08-24 16:02:35 +03:00
if new_edited_messages is None : new_edited_messages = [ ]
2020-04-24 18:19:30 +03:00
new_edited_messages . append ( update . edited_message )
2016-12-03 08:28:22 +03:00
if update . channel_post :
2020-08-24 16:02:35 +03:00
if new_channel_posts is None : new_channel_posts = [ ]
2016-12-03 08:28:22 +03:00
new_channel_posts . append ( update . channel_post )
if update . edited_channel_post :
2020-08-24 16:02:35 +03:00
if new_edited_channel_posts is None : new_edited_channel_posts = [ ]
2016-12-03 08:28:22 +03:00
new_edited_channel_posts . append ( update . edited_channel_post )
2016-01-04 18:10:32 +03:00
if update . inline_query :
2020-08-24 16:02:35 +03:00
if new_inline_queries is None : new_inline_queries = [ ]
new_inline_queries . append ( update . inline_query )
2016-01-05 08:18:32 +03:00
if update . chosen_inline_result :
2020-08-24 16:02:35 +03:00
if new_chosen_inline_results is None : new_chosen_inline_results = [ ]
2016-01-05 08:18:32 +03:00
new_chosen_inline_results . append ( update . chosen_inline_result )
2016-04-16 09:18:19 +03:00
if update . callback_query :
2020-08-24 16:02:35 +03:00
if new_callback_queries is None : new_callback_queries = [ ]
new_callback_queries . append ( update . callback_query )
2017-05-25 06:22:40 +03:00
if update . shipping_query :
2020-08-24 16:02:35 +03:00
if new_shipping_queries is None : new_shipping_queries = [ ]
new_shipping_queries . append ( update . shipping_query )
2017-05-25 06:22:40 +03:00
if update . pre_checkout_query :
2020-08-24 16:02:35 +03:00
if new_pre_checkout_queries is None : new_pre_checkout_queries = [ ]
new_pre_checkout_queries . append ( update . pre_checkout_query )
2020-03-09 13:25:54 +03:00
if update . poll :
2020-08-24 16:02:35 +03:00
if new_polls is None : new_polls = [ ]
2020-03-09 13:25:54 +03:00
new_polls . append ( update . poll )
2020-05-12 03:09:34 +03:00
if update . poll_answer :
2020-08-24 16:02:35 +03:00
if new_poll_answers is None : new_poll_answers = [ ]
2020-05-12 03:09:34 +03:00
new_poll_answers . append ( update . poll_answer )
2021-06-23 17:10:48 +03:00
if update . my_chat_member :
if new_my_chat_members is None : new_my_chat_members = [ ]
new_my_chat_members . append ( update . my_chat_member )
if update . chat_member :
if new_chat_members is None : new_chat_members = [ ]
new_chat_members . append ( update . chat_member )
2021-11-05 21:22:03 +03:00
if update . chat_join_request :
if chat_join_request is None : chat_join_request = [ ]
chat_join_request . append ( update . chat_join_request )
2017-05-25 06:22:40 +03:00
2020-08-24 16:02:35 +03:00
if new_messages :
2015-07-14 08:28:39 +03:00
self . process_new_messages ( new_messages )
2020-08-24 16:02:35 +03:00
if new_edited_messages :
2020-04-24 18:19:30 +03:00
self . process_new_edited_messages ( new_edited_messages )
2020-08-24 16:02:35 +03:00
if new_channel_posts :
2016-12-03 08:28:22 +03:00
self . process_new_channel_posts ( new_channel_posts )
2020-08-24 16:02:35 +03:00
if new_edited_channel_posts :
2016-12-03 08:28:22 +03:00
self . process_new_edited_channel_posts ( new_edited_channel_posts )
2020-08-24 16:02:35 +03:00
if new_inline_queries :
self . process_new_inline_query ( new_inline_queries )
if new_chosen_inline_results :
2016-01-05 08:18:32 +03:00
self . process_new_chosen_inline_query ( new_chosen_inline_results )
2020-08-24 16:02:35 +03:00
if new_callback_queries :
self . process_new_callback_query ( new_callback_queries )
if new_shipping_queries :
self . process_new_shipping_query ( new_shipping_queries )
if new_pre_checkout_queries :
self . process_new_pre_checkout_query ( new_pre_checkout_queries )
if new_polls :
2020-03-09 13:25:54 +03:00
self . process_new_poll ( new_polls )
2020-08-24 16:02:35 +03:00
if new_poll_answers :
2020-05-12 03:09:34 +03:00
self . process_new_poll_answer ( new_poll_answers )
2021-06-23 17:10:48 +03:00
if new_my_chat_members :
self . process_new_my_chat_member ( new_my_chat_members )
if new_chat_members :
self . process_new_chat_member ( new_chat_members )
2021-11-05 21:22:03 +03:00
if chat_join_request :
2021-11-06 17:59:44 +03:00
self . process_new_chat_join_request ( chat_join_request )
2015-07-14 08:28:39 +03:00
def process_new_messages ( self , new_messages ) :
2018-04-12 13:45:32 +03:00
self . _notify_next_handlers ( new_messages )
self . _notify_reply_handlers ( new_messages )
2015-07-14 08:28:39 +03:00
self . __notify_update ( new_messages )
2022-03-06 16:39:41 +03:00
self . _notify_command_handlers ( self . message_handlers , new_messages , ' message ' )
2015-06-26 13:02:30 +03:00
2016-06-07 14:29:12 +03:00
def process_new_edited_messages ( self , edited_message ) :
2022-03-06 16:39:41 +03:00
self . _notify_command_handlers ( self . edited_message_handlers , edited_message , ' edited_message ' )
2016-06-07 14:29:12 +03:00
2016-12-03 08:28:22 +03:00
def process_new_channel_posts ( self , channel_post ) :
2022-03-06 16:39:41 +03:00
self . _notify_command_handlers ( self . channel_post_handlers , channel_post , ' channel_post ' )
2016-12-03 08:28:22 +03:00
def process_new_edited_channel_posts ( self , edited_channel_post ) :
2022-03-06 16:39:41 +03:00
self . _notify_command_handlers ( self . edited_channel_post_handlers , edited_channel_post , ' edited_channel_post ' )
2016-12-03 08:28:22 +03:00
2016-01-04 18:10:32 +03:00
def process_new_inline_query ( self , new_inline_querys ) :
2022-03-06 16:39:41 +03:00
self . _notify_command_handlers ( self . inline_handlers , new_inline_querys , ' inline_query ' )
2016-01-05 08:18:32 +03:00
def process_new_chosen_inline_query ( self , new_chosen_inline_querys ) :
2022-03-06 16:39:41 +03:00
self . _notify_command_handlers ( self . chosen_inline_handlers , new_chosen_inline_querys , ' chosen_inline_query ' )
2016-01-04 18:10:32 +03:00
2016-04-16 09:18:19 +03:00
def process_new_callback_query ( self , new_callback_querys ) :
2022-03-06 16:39:41 +03:00
self . _notify_command_handlers ( self . callback_query_handlers , new_callback_querys , ' callback_query ' )
2016-04-16 09:18:19 +03:00
2017-05-25 06:45:44 +03:00
def process_new_shipping_query ( self , new_shipping_querys ) :
2022-03-06 16:39:41 +03:00
self . _notify_command_handlers ( self . shipping_query_handlers , new_shipping_querys , ' shipping_query ' )
2017-05-25 06:45:44 +03:00
def process_new_pre_checkout_query ( self , pre_checkout_querys ) :
2022-03-06 16:39:41 +03:00
self . _notify_command_handlers ( self . pre_checkout_query_handlers , pre_checkout_querys , ' pre_checkout_query ' )
2017-05-25 06:45:44 +03:00
2020-03-09 13:25:54 +03:00
def process_new_poll ( self , polls ) :
2022-03-06 16:39:41 +03:00
self . _notify_command_handlers ( self . poll_handlers , polls , ' poll ' )
2020-03-09 13:25:54 +03:00
2020-05-12 03:09:34 +03:00
def process_new_poll_answer ( self , poll_answers ) :
2022-03-06 16:39:41 +03:00
self . _notify_command_handlers ( self . poll_answer_handlers , poll_answers , ' poll_answer ' )
2021-06-23 17:10:48 +03:00
def process_new_my_chat_member ( self , my_chat_members ) :
2022-03-06 16:39:41 +03:00
self . _notify_command_handlers ( self . my_chat_member_handlers , my_chat_members , ' my_chat_member ' )
2021-06-23 17:10:48 +03:00
def process_new_chat_member ( self , chat_members ) :
2022-03-06 16:39:41 +03:00
self . _notify_command_handlers ( self . chat_member_handlers , chat_members , ' chat_member ' )
2020-05-12 03:09:34 +03:00
2021-11-06 17:59:44 +03:00
def process_new_chat_join_request ( self , chat_join_request ) :
2022-03-06 16:39:41 +03:00
self . _notify_command_handlers ( self . chat_join_request_handlers , chat_join_request , ' chat_join_request ' )
2021-11-05 21:22:03 +03:00
2020-04-08 21:13:19 +03:00
def process_middlewares ( self , update ) :
for update_type , middlewares in self . typed_middleware_handlers . items ( ) :
2020-04-20 09:30:03 +03:00
if getattr ( update , update_type ) is not None :
2020-04-08 21:13:19 +03:00
for typed_middleware_handler in middlewares :
2021-04-18 15:56:52 +03:00
try :
typed_middleware_handler ( self , getattr ( update , update_type ) )
except Exception as e :
2021-04-19 18:20:42 +03:00
e . args = e . args + ( f ' Typed middleware handler " { typed_middleware_handler . __qualname__ } " ' , )
2021-04-18 15:56:52 +03:00
raise
2020-04-08 21:13:19 +03:00
if len ( self . default_middleware_handlers ) > 0 :
for default_middleware_handler in self . default_middleware_handlers :
2021-04-18 15:56:52 +03:00
try :
default_middleware_handler ( self , update )
except Exception as e :
2021-04-19 18:20:42 +03:00
e . args = e . args + ( f ' Default middleware handler " { default_middleware_handler . __qualname__ } " ' , )
2021-04-18 15:56:52 +03:00
raise
2020-04-08 21:13:19 +03:00
2015-06-26 13:02:30 +03:00
def __notify_update ( self , new_messages ) :
2020-08-24 16:02:35 +03:00
if len ( self . update_listener ) == 0 :
return
2015-06-26 13:02:30 +03:00
for listener in self . update_listener :
2016-06-13 16:47:15 +03:00
self . _exec_task ( listener , new_messages )
2015-06-26 13:02:30 +03:00
2021-09-28 19:17:09 +03:00
def infinity_polling ( self , timeout : int = 20 , skip_pending : bool = False , long_polling_timeout : int = 20 , logger_level = logging . ERROR ,
allowed_updates : Optional [ List [ str ] ] = None , * args , * * kwargs ) :
2021-01-30 14:41:19 +03:00
"""
Wrap polling with infinite loop and exception handling to avoid bot stops polling .
: param timeout : Request connection timeout
: param long_polling_timeout : Timeout in seconds for long polling ( see API docs )
2021-08-16 21:00:08 +03:00
: param skip_pending : skip old updates
2021-06-19 18:59:55 +03:00
: param logger_level : Custom logging level for infinity_polling logging .
Use logger levels from logging as a value . None / NOTSET = no error logging
2021-06-23 20:29:36 +03:00
: param allowed_updates : A list of the update types you want your bot to receive .
For example , specify [ “ message ” , “ edited_channel_post ” , “ callback_query ” ] to only receive updates of these types .
2021-06-23 20:57:44 +03:00
See util . update_types for a complete list of available update types .
2021-06-23 20:29:36 +03:00
Specify an empty list to receive all update types except chat_member ( default ) .
If not specified , the previous setting will be used .
Please note that this parameter doesn ' t affect updates created before the call to the get_updates,
so unwanted updates may be received for a short period of time .
2021-01-30 14:41:19 +03:00
"""
2021-08-16 21:00:08 +03:00
if skip_pending :
self . __skip_updates ( )
2018-04-04 10:47:37 +03:00
while not self . __stop_polling . is_set ( ) :
try :
2021-06-19 18:59:55 +03:00
self . polling ( none_stop = True , timeout = timeout , long_polling_timeout = long_polling_timeout ,
2021-06-27 20:40:16 +03:00
allowed_updates = allowed_updates , * args , * * kwargs )
2020-12-29 19:24:41 +03:00
except Exception as e :
2021-01-30 14:41:19 +03:00
if logger_level and logger_level > = logging . ERROR :
logger . error ( " Infinity polling exception: %s " , str ( e ) )
if logger_level and logger_level > = logging . DEBUG :
logger . error ( " Exception traceback: \n %s " , traceback . format_exc ( ) )
2020-11-07 14:43:17 +03:00
time . sleep ( 3 )
2021-01-07 00:13:44 +03:00
continue
2021-01-30 14:41:19 +03:00
if logger_level and logger_level > = logging . INFO :
logger . error ( " Infinity polling: polling exited " )
if logger_level and logger_level > = logging . INFO :
logger . error ( " Break infinity polling " )
2018-04-04 10:47:37 +03:00
2021-08-18 18:52:09 +03:00
def polling ( self , non_stop : bool = False , skip_pending = False , interval : int = 0 , timeout : int = 20 ,
2021-08-18 18:47:38 +03:00
long_polling_timeout : int = 20 , allowed_updates : Optional [ List [ str ] ] = None ,
none_stop : Optional [ bool ] = None ) :
2015-06-26 13:02:30 +03:00
"""
2015-10-01 23:03:54 +03:00
This function creates a new Thread that calls an internal __retrieve_updates function .
2015-07-02 23:32:18 +03:00
This allows the bot to retrieve Updates automagically and notify listeners and message handlers accordingly .
2015-10-01 23:03:54 +03:00
Warning : Do not call this function more than once !
2021-08-16 21:41:27 +03:00
2015-06-26 13:02:30 +03:00
Always get updates .
2022-03-06 17:41:54 +03:00
2021-01-30 14:41:19 +03:00
: param interval : Delay between two update retrivals
2021-08-18 18:47:38 +03:00
: param non_stop : Do not stop polling when an ApiException occurs .
2021-01-30 14:41:19 +03:00
: param timeout : Request connection timeout
2021-08-16 21:00:08 +03:00
: param skip_pending : skip old updates
2021-01-30 14:41:19 +03:00
: param long_polling_timeout : Timeout in seconds for long polling ( see API docs )
2021-06-23 20:29:36 +03:00
: param allowed_updates : A list of the update types you want your bot to receive .
For example , specify [ “ message ” , “ edited_channel_post ” , “ callback_query ” ] to only receive updates of these types .
2021-06-23 20:57:44 +03:00
See util . update_types for a complete list of available update types .
2021-06-23 20:29:36 +03:00
Specify an empty list to receive all update types except chat_member ( default ) .
If not specified , the previous setting will be used .
Please note that this parameter doesn ' t affect updates created before the call to the get_updates,
so unwanted updates may be received for a short period of time .
2021-08-18 18:47:38 +03:00
: param none_stop : Deprecated , use non_stop . Old typo f * * * up compatibility
2015-06-26 13:02:30 +03:00
: return :
"""
2021-08-18 18:47:38 +03:00
if none_stop is not None :
non_stop = none_stop
2021-08-16 21:00:08 +03:00
if skip_pending :
self . __skip_updates ( )
2015-10-02 01:00:54 +03:00
if self . threaded :
2021-08-18 18:47:38 +03:00
self . __threaded_polling ( non_stop , interval , timeout , long_polling_timeout , allowed_updates )
2015-10-02 01:00:54 +03:00
else :
2021-08-18 18:47:38 +03:00
self . __non_threaded_polling ( non_stop , interval , timeout , long_polling_timeout , allowed_updates )
2015-08-31 03:13:21 +03:00
2021-06-23 20:29:36 +03:00
def __threaded_polling ( self , non_stop = False , interval = 0 , timeout = None , long_polling_timeout = None , allowed_updates = None ) :
2015-10-02 01:00:54 +03:00
logger . info ( ' Started polling. ' )
self . __stop_polling . clear ( )
2020-01-08 20:06:40 +03:00
error_interval = 0.25
2015-10-01 23:03:54 +03:00
polling_thread = util . WorkerThread ( name = " PollingThread " )
or_event = util . OrEvent (
2016-02-27 06:17:35 +03:00
polling_thread . done_event ,
polling_thread . exception_event ,
self . worker_pool . exception_event
2015-10-01 23:03:54 +03:00
)
2015-07-18 12:27:16 +03:00
while not self . __stop_polling . wait ( interval ) :
2015-10-01 23:03:54 +03:00
or_event . clear ( )
2015-06-27 17:31:40 +03:00
try :
2021-06-23 20:29:36 +03:00
polling_thread . put ( self . __retrieve_updates , timeout , long_polling_timeout , allowed_updates = allowed_updates )
2015-10-03 13:48:56 +03:00
or_event . wait ( ) # wait for polling thread finish, polling thread error or thread pool error
2015-10-01 23:03:54 +03:00
polling_thread . raise_exceptions ( )
self . worker_pool . raise_exceptions ( )
2020-01-08 20:06:40 +03:00
error_interval = 0.25
2015-08-31 03:13:21 +03:00
except apihelper . ApiException as e :
2020-08-21 17:36:08 +03:00
if self . exception_handler is not None :
handled = self . exception_handler . handle ( e )
else :
handled = False
if not handled :
logger . error ( e )
2020-11-07 14:43:17 +03:00
if not non_stop :
2020-08-21 17:36:08 +03:00
self . __stop_polling . set ( )
logger . info ( " Exception occurred. Stopping. " )
else :
2020-12-24 23:55:12 +03:00
# polling_thread.clear_exceptions()
# self.worker_pool.clear_exceptions()
2020-08-21 17:36:08 +03:00
logger . info ( " Waiting for {0} seconds until retry " . format ( error_interval ) )
time . sleep ( error_interval )
2021-09-28 19:17:09 +03:00
if error_interval * 2 < 60 :
error_interval * = 2
else :
error_interval = 60
2015-08-31 03:13:21 +03:00
else :
2020-12-24 23:55:12 +03:00
# polling_thread.clear_exceptions()
# self.worker_pool.clear_exceptions()
2015-08-31 03:13:21 +03:00
time . sleep ( error_interval )
2020-12-24 23:55:12 +03:00
polling_thread . clear_exceptions ( ) #*
self . worker_pool . clear_exceptions ( ) #*
2015-10-02 01:00:54 +03:00
except KeyboardInterrupt :
logger . info ( " KeyboardInterrupt received. " )
self . __stop_polling . set ( )
break
2020-08-21 17:36:08 +03:00
except Exception as e :
if self . exception_handler is not None :
handled = self . exception_handler . handle ( e )
else :
handled = False
if not handled :
2020-12-24 23:55:12 +03:00
polling_thread . stop ( )
polling_thread . clear_exceptions ( ) #*
self . worker_pool . clear_exceptions ( ) #*
2020-08-21 17:36:08 +03:00
raise e
else :
polling_thread . clear_exceptions ( )
self . worker_pool . clear_exceptions ( )
time . sleep ( error_interval )
2015-06-26 13:02:30 +03:00
2018-03-23 14:58:43 +03:00
polling_thread . stop ( )
2020-12-24 23:55:12 +03:00
polling_thread . clear_exceptions ( ) #*
self . worker_pool . clear_exceptions ( ) #*
2015-09-08 20:47:55 +03:00
logger . info ( ' Stopped polling. ' )
2015-06-26 13:02:30 +03:00
2021-06-23 20:29:36 +03:00
def __non_threaded_polling ( self , non_stop = False , interval = 0 , timeout = None , long_polling_timeout = None , allowed_updates = None ) :
2015-10-02 01:00:54 +03:00
logger . info ( ' Started polling. ' )
self . __stop_polling . clear ( )
2020-01-08 20:06:40 +03:00
error_interval = 0.25
2015-10-02 01:00:54 +03:00
while not self . __stop_polling . wait ( interval ) :
try :
2021-06-23 20:29:36 +03:00
self . __retrieve_updates ( timeout , long_polling_timeout , allowed_updates = allowed_updates )
2020-01-08 20:06:40 +03:00
error_interval = 0.25
2015-10-02 01:00:54 +03:00
except apihelper . ApiException as e :
2020-08-21 17:36:08 +03:00
if self . exception_handler is not None :
handled = self . exception_handler . handle ( e )
else :
handled = False
if not handled :
logger . error ( e )
2020-11-07 14:43:17 +03:00
if not non_stop :
2020-08-21 17:36:08 +03:00
self . __stop_polling . set ( )
logger . info ( " Exception occurred. Stopping. " )
else :
logger . info ( " Waiting for {0} seconds until retry " . format ( error_interval ) )
time . sleep ( error_interval )
error_interval * = 2
2015-10-02 01:00:54 +03:00
else :
time . sleep ( error_interval )
except KeyboardInterrupt :
logger . info ( " KeyboardInterrupt received. " )
self . __stop_polling . set ( )
break
2020-08-21 17:36:08 +03:00
except Exception as e :
if self . exception_handler is not None :
handled = self . exception_handler . handle ( e )
else :
handled = False
if not handled :
raise e
else :
time . sleep ( error_interval )
2015-10-02 01:00:54 +03:00
logger . info ( ' Stopped polling. ' )
2016-06-13 16:47:15 +03:00
def _exec_task ( self , task , * args , * * kwargs ) :
2022-01-24 22:38:35 +03:00
if kwargs and kwargs . get ( ' task_type ' ) == ' handler ' :
2022-01-24 16:15:04 +03:00
pass_bot = kwargs . get ( ' pass_bot ' )
kwargs . pop ( ' pass_bot ' )
kwargs . pop ( ' task_type ' )
if pass_bot :
kwargs [ ' bot ' ] = self
2015-10-02 01:00:54 +03:00
if self . threaded :
self . worker_pool . put ( task , * args , * * kwargs )
else :
2022-02-01 23:58:57 +03:00
try :
task ( * args , * * kwargs )
except Exception as e :
if self . exception_handler is not None :
handled = self . exception_handler . handle ( e )
else :
handled = False
if not handled :
raise e
2015-10-02 01:00:54 +03:00
2015-06-26 13:02:30 +03:00
def stop_polling ( self ) :
2015-07-18 12:27:16 +03:00
self . __stop_polling . set ( )
2015-06-26 13:02:30 +03:00
2018-03-23 14:58:43 +03:00
def stop_bot ( self ) :
self . stop_polling ( )
2021-07-13 22:09:56 +03:00
if self . threaded and self . worker_pool :
2018-03-23 14:58:43 +03:00
self . worker_pool . close ( )
2015-06-26 13:02:30 +03:00
def set_update_listener ( self , listener ) :
self . update_listener . append ( listener )
2015-06-26 09:55:13 +03:00
2021-06-17 21:28:53 +03:00
def get_me ( self ) - > types . User :
"""
Returns basic information about the bot in form of a User object .
2022-03-06 21:14:07 +03:00
Telegram documentation : https : / / core . telegram . org / bots / api #getme
2021-06-17 21:28:53 +03:00
"""
2015-06-26 10:46:02 +03:00
result = apihelper . get_me ( self . token )
2015-07-01 23:16:13 +03:00
return types . User . de_json ( result )
2015-06-30 17:40:44 +03:00
2021-06-21 18:39:13 +03:00
def get_file ( self , file_id : str ) - > types . File :
2021-06-17 21:28:53 +03:00
"""
Use this method to get basic info about a file and prepare it for downloading .
For the moment , bots can download files of up to 20 MB in size .
On success , a File object is returned .
It is guaranteed that the link will be valid for at least 1 hour .
When the link expires , a new one can be requested by calling get_file again .
2022-03-06 17:41:54 +03:00
2022-03-06 21:14:07 +03:00
Telegram documentation : https : / / core . telegram . org / bots / api #getfile
2022-03-06 17:41:54 +03:00
: param file_id : File identifier
2021-06-17 21:28:53 +03:00
"""
2015-09-18 21:31:29 +03:00
return types . File . de_json ( apihelper . get_file ( self . token , file_id ) )
2021-06-21 18:39:13 +03:00
def get_file_url ( self , file_id : str ) - > str :
2022-03-06 17:41:54 +03:00
"""
Get a valid URL for downloading a file .
: param file_id : File identifier to get download URL for .
"""
2018-03-25 13:22:35 +03:00
return apihelper . get_file_url ( self . token , file_id )
2021-06-21 18:39:13 +03:00
def download_file ( self , file_path : str ) - > bytes :
2015-09-18 21:53:10 +03:00
return apihelper . download_file ( self . token , file_path )
2021-06-17 21:28:53 +03:00
def log_out ( self ) - > bool :
"""
Use this method to log out from the cloud Bot API server before launching the bot locally .
2021-06-19 18:59:55 +03:00
You MUST log out the bot before running it locally , otherwise there is no guarantee
that the bot will receive updates .
2021-06-17 21:28:53 +03:00
After a successful call , you can immediately log in on a local server ,
but will not be able to log in back to the cloud Bot API server for 10 minutes .
Returns True on success .
2022-03-06 21:14:07 +03:00
Telegram documentation : https : / / core . telegram . org / bots / api #logout
2021-06-17 21:28:53 +03:00
"""
return apihelper . log_out ( self . token )
def close ( self ) - > bool :
"""
Use this method to close the bot instance before moving it from one local server to another .
2021-06-19 18:59:55 +03:00
You need to delete the webhook before calling this method to ensure that the bot isn ' t launched again
after server restart .
2021-06-17 21:28:53 +03:00
The method will return error 429 in the first 10 minutes after the bot is launched .
Returns True on success .
2022-03-06 21:14:07 +03:00
Telegram documentation : https : / / core . telegram . org / bots / api #close
2021-06-17 21:28:53 +03:00
"""
return apihelper . close ( self . token )
2021-06-21 18:39:13 +03:00
def get_user_profile_photos ( self , user_id : int , offset : Optional [ int ] = None ,
limit : Optional [ int ] = None ) - > types . UserProfilePhotos :
2015-06-30 17:40:44 +03:00
"""
Retrieves the user profile photos of the person with ' user_id '
2022-03-06 21:14:07 +03:00
Telegram documentation : https : / / core . telegram . org / bots / api #getuserprofilephotos
2022-03-06 17:41:54 +03:00
: param user_id : Integer - Unique identifier of the target user
2015-06-30 17:40:44 +03:00
: param offset :
: param limit :
2015-07-02 23:32:18 +03:00
: return : API reply .
2015-06-30 17:40:44 +03:00
"""
result = apihelper . get_user_profile_photos ( self . token , user_id , offset , limit )
2015-07-01 23:16:13 +03:00
return types . UserProfilePhotos . de_json ( result )
2015-06-26 09:55:13 +03:00
2021-06-21 18:39:13 +03:00
def get_chat ( self , chat_id : Union [ int , str ] ) - > types . Chat :
2016-06-07 14:44:30 +03:00
"""
Use this method to get up to date information about the chat ( current name of the user for one - on - one
conversations , current username of a user , group or channel , etc . ) . Returns a Chat object on success .
2022-03-06 17:41:54 +03:00
2022-03-06 21:14:07 +03:00
Telegram documentation : https : / / core . telegram . org / bots / api #getchat
2016-06-07 14:44:30 +03:00
: param chat_id :
2022-03-06 21:14:07 +03:00
: return : API reply .
2016-06-07 14:44:30 +03:00
"""
2016-06-07 14:00:44 +03:00
result = apihelper . get_chat ( self . token , chat_id )
return types . Chat . de_json ( result )
2021-06-21 18:39:13 +03:00
def leave_chat ( self , chat_id : Union [ int , str ] ) - > bool :
2016-06-07 14:44:30 +03:00
"""
Use this method for your bot to leave a group , supergroup or channel . Returns True on success .
2022-03-06 17:41:54 +03:00
2022-03-06 21:14:07 +03:00
Telegram documentation : https : / / core . telegram . org / bots / api #leavechat
2016-06-07 14:44:30 +03:00
: param chat_id :
2022-03-06 21:14:07 +03:00
: return : API reply .
2016-06-07 14:44:30 +03:00
"""
2016-06-07 14:00:44 +03:00
result = apihelper . leave_chat ( self . token , chat_id )
return result
2021-06-21 18:39:13 +03:00
def get_chat_administrators ( self , chat_id : Union [ int , str ] ) - > List [ types . ChatMember ] :
2016-06-07 14:44:30 +03:00
"""
2020-05-11 16:38:09 +03:00
Use this method to get a list of administrators in a chat .
On success , returns an Array of ChatMember objects that contains
2022-03-07 12:24:28 +03:00
information about all chat administrators except other bots .
2022-03-06 17:41:54 +03:00
2022-03-06 21:14:07 +03:00
Telegram documentation : https : / / core . telegram . org / bots / api #getchatadministrators
2020-05-11 16:38:09 +03:00
: param chat_id : Unique identifier for the target chat or username
of the target supergroup or channel ( in the format @channelusername )
2022-03-06 21:14:07 +03:00
: return : API reply .
2016-06-07 14:44:30 +03:00
"""
2016-06-07 14:00:44 +03:00
result = apihelper . get_chat_administrators ( self . token , chat_id )
2021-07-19 20:01:37 +03:00
return [ types . ChatMember . de_json ( r ) for r in result ]
2016-06-07 14:00:44 +03:00
2021-06-21 18:39:13 +03:00
def get_chat_members_count ( self , chat_id : Union [ int , str ] ) - > int :
2016-06-07 14:44:30 +03:00
"""
2021-06-28 13:02:40 +03:00
This function is deprecated . Use ` get_chat_member_count ` instead
2016-06-07 14:44:30 +03:00
"""
2021-06-28 12:59:21 +03:00
logger . info ( ' get_chat_members_count is deprecated. Use get_chat_member_count instead. ' )
result = apihelper . get_chat_member_count ( self . token , chat_id )
2016-06-07 14:00:44 +03:00
return result
2021-06-28 10:31:06 +03:00
def get_chat_member_count ( self , chat_id : Union [ int , str ] ) - > int :
"""
Use this method to get the number of members in a chat . Returns Int on success .
2022-03-06 17:41:54 +03:00
2022-03-06 21:14:07 +03:00
Telegram documentation : https : / / core . telegram . org / bots / api #getchatmembercount
2021-06-28 10:31:06 +03:00
: param chat_id :
2022-03-06 21:14:07 +03:00
: return : API reply .
2021-06-28 10:31:06 +03:00
"""
result = apihelper . get_chat_member_count ( self . token , chat_id )
return result
2016-06-07 14:00:44 +03:00
2021-06-21 18:39:13 +03:00
def set_chat_sticker_set ( self , chat_id : Union [ int , str ] , sticker_set_name : str ) - > types . StickerSet :
2017-10-22 19:50:51 +03:00
"""
Use this method to set a new group sticker set for a supergroup . The bot must be an administrator
in the chat for this to work and must have the appropriate admin rights .
Use the field can_set_sticker_set optionally returned in getChat requests to check
if the bot can use this method . Returns True on success .
2022-03-06 17:41:54 +03:00
2022-03-06 21:14:07 +03:00
Telegram documentation : https : / / core . telegram . org / bots / api #setchatstickerset
2022-03-07 14:10:44 +03:00
: param chat_id : Unique identifier for the target chat or username of the target supergroup ( in the format @supergroupusername )
2017-10-22 19:50:51 +03:00
: param sticker_set_name : Name of the sticker set to be set as the group sticker set
2022-03-06 21:14:07 +03:00
: return : API reply .
2017-10-22 19:50:51 +03:00
"""
result = apihelper . set_chat_sticker_set ( self . token , chat_id , sticker_set_name )
return result
2021-06-21 18:39:13 +03:00
def delete_chat_sticker_set ( self , chat_id : Union [ int , str ] ) - > bool :
2017-10-22 19:50:51 +03:00
"""
Use this method to delete a group sticker set from a supergroup . The bot must be an administrator in the chat
for this to work and must have the appropriate admin rights . Use the field can_set_sticker_set
optionally returned in getChat requests to check if the bot can use this method . Returns True on success .
2022-03-06 17:41:54 +03:00
2022-03-06 21:14:07 +03:00
Telegram documentation : https : / / core . telegram . org / bots / api #deletechatstickerset
2022-03-07 12:24:28 +03:00
: param chat_id : Unique identifier for the target chat or username of the target supergroup ( in the format @supergroupusername )
2022-03-06 21:14:07 +03:00
: return : API reply .
2017-10-22 19:50:51 +03:00
"""
result = apihelper . delete_chat_sticker_set ( self . token , chat_id )
return result
2021-06-21 18:39:13 +03:00
def get_chat_member ( self , chat_id : Union [ int , str ] , user_id : int ) - > types . ChatMember :
2016-06-07 14:44:30 +03:00
"""
Use this method to get information about a member of a chat . Returns a ChatMember object on success .
2022-03-06 17:41:54 +03:00
2022-03-06 21:14:07 +03:00
Telegram documentation : https : / / core . telegram . org / bots / api #getchatmember
2016-06-07 14:44:30 +03:00
: param chat_id :
: param user_id :
2022-03-06 21:14:07 +03:00
: return : API reply .
2016-06-07 14:44:30 +03:00
"""
2016-06-07 14:29:12 +03:00
result = apihelper . get_chat_member ( self . token , chat_id , user_id )
2016-06-07 14:00:44 +03:00
return types . ChatMember . de_json ( result )
2021-06-21 18:39:13 +03:00
def send_message (
self , chat_id : Union [ int , str ] , text : str ,
2021-12-31 14:05:40 +03:00
parse_mode : Optional [ str ] = None ,
entities : Optional [ List [ types . MessageEntity ] ] = None ,
2021-06-21 18:39:13 +03:00
disable_web_page_preview : Optional [ bool ] = None ,
2021-12-31 14:05:40 +03:00
disable_notification : Optional [ bool ] = None ,
protect_content : Optional [ bool ] = None ,
2021-06-21 18:49:03 +03:00
reply_to_message_id : Optional [ int ] = None ,
2021-12-31 14:05:40 +03:00
allow_sending_without_reply : Optional [ bool ] = None ,
2021-06-21 18:39:13 +03:00
reply_markup : Optional [ REPLY_MARKUP_TYPES ] = None ,
2021-12-31 14:05:40 +03:00
timeout : Optional [ int ] = None ) - > types . Message :
2015-06-28 12:27:25 +03:00
"""
Use this method to send text messages .
2015-07-25 21:59:36 +03:00
2020-12-09 01:41:07 +03:00
Warning : Do not send more than about 4000 characters each message , otherwise you ' ll risk an HTTP 414 error.
2021-06-21 18:39:13 +03:00
If you must send more than 4000 characters ,
use the ` split_string ` or ` smart_split ` function in util . py .
2015-07-25 21:59:36 +03:00
2022-03-06 21:14:07 +03:00
Telegram documentation : https : / / core . telegram . org / bots / api #sendmessage
2021-12-31 14:05:40 +03:00
: param chat_id : Unique identifier for the target chat or username of the target channel ( in the format @channelusername )
: param text : Text of the message to be sent
2022-01-02 13:58:15 +03:00
: param parse_mode : Send Markdown or HTML , if you want Telegram apps to show bold , italic , fixed - width text or inline URLs in your bot ' s message.
: param entities : List of special entities that appear in message text , which can be specified instead of parse_mode
2021-12-31 14:05:40 +03:00
: param disable_web_page_preview : Disables link previews for links in this message
: param disable_notification : Sends the message silently . Users will receive a notification with no sound .
2022-01-02 13:58:15 +03:00
: param protect_content : If True , the message content will be hidden for all users except for the target user
2021-12-31 14:05:40 +03:00
: param reply_to_message_id : If the message is a reply , ID of the original message
: param allow_sending_without_reply : Pass True , if the message should be sent even if the specified replied - to message is not found
: param reply_markup : Additional interface options . A JSON - serialized object for an inline keyboard , custom reply keyboard , instructions to remove reply keyboard or to force a reply from the user .
2020-04-24 18:19:30 +03:00
: param timeout :
2022-03-06 21:14:07 +03:00
: return : API reply .
2015-06-28 12:27:25 +03:00
"""
2020-12-09 01:41:07 +03:00
parse_mode = self . parse_mode if ( parse_mode is None ) else parse_mode
2020-07-04 21:07:42 +03:00
2015-07-03 02:42:47 +03:00
return types . Message . de_json (
2021-06-21 18:39:13 +03:00
apihelper . send_message (
self . token , chat_id , text , disable_web_page_preview , reply_to_message_id ,
reply_markup , parse_mode , disable_notification , timeout ,
2021-12-31 14:05:40 +03:00
entities , allow_sending_without_reply , protect_content = protect_content ) )
2015-06-26 17:16:11 +03:00
2021-06-21 18:39:13 +03:00
def forward_message (
self , chat_id : Union [ int , str ] , from_chat_id : Union [ int , str ] ,
2021-12-31 14:05:40 +03:00
message_id : int , disable_notification : Optional [ bool ] = None ,
protect_content : Optional [ bool ] = None ,
2021-06-21 18:39:13 +03:00
timeout : Optional [ int ] = None ) - > types . Message :
2015-06-26 17:35:52 +03:00
"""
2015-06-26 20:53:07 +03:00
Use this method to forward messages of any kind .
2022-03-06 17:41:54 +03:00
2022-03-06 21:14:07 +03:00
Telegram documentation : https : / / core . telegram . org / bots / api #forwardmessage
2016-02-27 06:17:35 +03:00
: param disable_notification :
2015-06-26 17:35:52 +03:00
: param chat_id : which chat to forward
: param from_chat_id : which chat message from
: param message_id : message id
2021-12-31 14:05:40 +03:00
: param protect_content : Protects the contents of the forwarded message from forwarding and saving
2020-08-25 18:18:51 +03:00
: param timeout :
2015-07-02 23:32:18 +03:00
: return : API reply .
2015-06-26 17:35:52 +03:00
"""
2016-02-27 06:17:35 +03:00
return types . Message . de_json (
2021-12-31 14:05:40 +03:00
apihelper . forward_message ( self . token , chat_id , from_chat_id , message_id , disable_notification , timeout , protect_content ) )
2015-06-26 20:53:07 +03:00
2021-06-21 18:39:13 +03:00
def copy_message (
self , chat_id : Union [ int , str ] ,
from_chat_id : Union [ int , str ] ,
message_id : int ,
caption : Optional [ str ] = None ,
parse_mode : Optional [ str ] = None ,
caption_entities : Optional [ List [ types . MessageEntity ] ] = None ,
disable_notification : Optional [ bool ] = None ,
2021-12-31 14:05:40 +03:00
protect_content : Optional [ bool ] = None ,
2021-06-21 18:39:13 +03:00
reply_to_message_id : Optional [ int ] = None ,
allow_sending_without_reply : Optional [ bool ] = None ,
reply_markup : Optional [ REPLY_MARKUP_TYPES ] = None ,
timeout : Optional [ int ] = None ) - > int :
2021-01-11 02:20:17 +03:00
"""
Use this method to copy messages of any kind .
2022-03-06 17:41:54 +03:00
2022-03-06 21:14:07 +03:00
Telegram documentation : https : / / core . telegram . org / bots / api #copymessage
2021-01-11 02:20:17 +03:00
: param chat_id : which chat to forward
: param from_chat_id : which chat message from
: param message_id : message id
2021-01-12 10:47:53 +03:00
: param caption :
: param parse_mode :
: param caption_entities :
: param disable_notification :
2021-12-31 14:05:40 +03:00
: param protect_content :
2021-01-12 10:47:53 +03:00
: param reply_to_message_id :
: param allow_sending_without_reply :
: param reply_markup :
2021-01-11 02:20:17 +03:00
: param timeout :
: return : API reply .
"""
2021-01-12 10:49:57 +03:00
return types . MessageID . de_json (
2021-01-11 02:20:17 +03:00
apihelper . copy_message ( self . token , chat_id , from_chat_id , message_id , caption , parse_mode , caption_entities ,
2021-01-19 01:27:39 +03:00
disable_notification , reply_to_message_id , allow_sending_without_reply , reply_markup ,
2021-12-31 14:05:40 +03:00
timeout , protect_content ) )
2021-01-11 02:20:17 +03:00
2021-06-21 18:39:13 +03:00
def delete_message ( self , chat_id : Union [ int , str ] , message_id : int ,
timeout : Optional [ int ] = None ) - > bool :
2017-05-07 17:37:03 +03:00
"""
2018-04-04 10:47:37 +03:00
Use this method to delete message . Returns True on success .
2022-03-06 17:41:54 +03:00
2022-03-06 21:14:07 +03:00
Telegram documentation : https : / / core . telegram . org / bots / api #deletemessage
2017-05-07 17:37:03 +03:00
: param chat_id : in which chat to delete
: param message_id : which message to delete
2020-08-25 18:18:51 +03:00
: param timeout :
2017-05-07 17:37:03 +03:00
: return : API reply .
"""
2020-07-21 01:20:01 +03:00
return apihelper . delete_message ( self . token , chat_id , message_id , timeout )
2017-05-07 17:37:03 +03:00
2020-05-16 17:34:56 +03:00
def send_dice (
2021-06-21 18:39:13 +03:00
self , chat_id : Union [ int , str ] ,
emoji : Optional [ str ] = None , disable_notification : Optional [ bool ] = None ,
reply_to_message_id : Optional [ int ] = None ,
reply_markup : Optional [ REPLY_MARKUP_TYPES ] = None ,
timeout : Optional [ int ] = None ,
2021-12-31 14:05:40 +03:00
allow_sending_without_reply : Optional [ bool ] = None ,
protect_content : Optional [ bool ] = None ) - > types . Message :
2020-04-15 08:10:05 +03:00
"""
Use this method to send dices .
2022-03-06 17:41:54 +03:00
2022-03-06 21:14:07 +03:00
Telegram documentation : https : / / core . telegram . org / bots / api #senddice
2020-04-15 08:10:05 +03:00
: param chat_id :
2020-04-27 08:30:05 +03:00
: param emoji :
2020-04-15 08:10:05 +03:00
: param disable_notification :
: param reply_to_message_id :
: param reply_markup :
2020-08-25 18:18:51 +03:00
: param timeout :
2021-06-21 18:39:13 +03:00
: param allow_sending_without_reply :
2021-12-31 14:05:40 +03:00
: param protect_content :
2020-04-15 08:10:05 +03:00
: return : Message
"""
return types . Message . de_json (
2020-05-16 17:34:56 +03:00
apihelper . send_dice (
self . token , chat_id , emoji , disable_notification , reply_to_message_id ,
2021-12-31 14:05:40 +03:00
reply_markup , timeout , allow_sending_without_reply , protect_content )
2020-04-15 08:10:05 +03:00
)
2021-06-21 18:39:13 +03:00
def send_photo (
self , chat_id : Union [ int , str ] , photo : Union [ Any , str ] ,
2021-12-31 14:05:40 +03:00
caption : Optional [ str ] = None , parse_mode : Optional [ str ] = None ,
2021-06-21 18:39:13 +03:00
caption_entities : Optional [ List [ types . MessageEntity ] ] = None ,
2021-12-31 14:05:40 +03:00
disable_notification : Optional [ bool ] = None ,
protect_content : Optional [ bool ] = None ,
reply_to_message_id : Optional [ int ] = None ,
allow_sending_without_reply : Optional [ bool ] = None ,
reply_markup : Optional [ REPLY_MARKUP_TYPES ] = None ,
timeout : Optional [ int ] = None , ) - > types . Message :
2015-06-26 21:14:45 +03:00
"""
2022-01-02 13:58:15 +03:00
Use this method to send photos . On success , the sent Message is returned .
2022-03-06 21:14:07 +03:00
Telegram documentation : https : / / core . telegram . org / bots / api #sendphoto
2022-03-06 17:41:54 +03:00
2015-06-26 21:14:45 +03:00
: param chat_id :
: param photo :
: param caption :
2021-06-21 18:39:13 +03:00
: param parse_mode :
2022-01-02 13:58:15 +03:00
: param caption_entities :
2021-06-21 18:39:13 +03:00
: param disable_notification :
2022-01-02 13:58:15 +03:00
: param protect_content :
2015-06-26 21:14:45 +03:00
: param reply_to_message_id :
2022-01-02 13:58:15 +03:00
: param allow_sending_without_reply :
2015-06-26 21:14:45 +03:00
: param reply_markup :
2020-08-25 18:18:51 +03:00
: param timeout :
2022-01-02 13:58:15 +03:00
: return : Message
2015-06-26 21:14:45 +03:00
"""
2020-12-09 01:41:07 +03:00
parse_mode = self . parse_mode if ( parse_mode is None ) else parse_mode
2020-07-04 21:07:42 +03:00
2015-07-03 02:42:47 +03:00
return types . Message . de_json (
2021-06-21 18:39:13 +03:00
apihelper . send_photo (
self . token , chat_id , photo , caption , reply_to_message_id , reply_markup ,
parse_mode , disable_notification , timeout , caption_entities ,
2021-12-31 14:05:40 +03:00
allow_sending_without_reply , protect_content ) )
2021-06-21 18:39:13 +03:00
2021-12-31 14:05:40 +03:00
# TODO: Rewrite this method like in API.
2021-06-21 18:39:13 +03:00
def send_audio (
self , chat_id : Union [ int , str ] , audio : Union [ Any , str ] ,
caption : Optional [ str ] = None , duration : Optional [ int ] = None ,
performer : Optional [ str ] = None , title : Optional [ str ] = None ,
reply_to_message_id : Optional [ int ] = None ,
reply_markup : Optional [ REPLY_MARKUP_TYPES ] = None ,
parse_mode : Optional [ str ] = None ,
disable_notification : Optional [ bool ] = None ,
timeout : Optional [ int ] = None ,
thumb : Optional [ Union [ Any , str ] ] = None ,
caption_entities : Optional [ List [ types . MessageEntity ] ] = None ,
2021-12-31 14:05:40 +03:00
allow_sending_without_reply : Optional [ bool ] = None ,
protect_content : Optional [ bool ] = None ) - > types . Message :
2015-06-26 21:14:45 +03:00
"""
2021-06-19 18:59:55 +03:00
Use this method to send audio files , if you want Telegram clients to display them in the music player .
Your audio must be in the . mp3 format .
2022-03-06 21:14:07 +03:00
Telegram documentation : https : / / core . telegram . org / bots / api #sendaudio
2022-03-06 17:41:54 +03:00
2022-03-19 11:49:36 +03:00
: param chat_id : Unique identifier for the message recipient
: param audio : Audio file to send .
2020-01-08 20:06:40 +03:00
: param caption :
2022-03-19 11:49:36 +03:00
: param duration : Duration of the audio in seconds
: param performer : Performer
: param title : Track name
: param reply_to_message_id : If the message is a reply , ID of the original message
2015-06-26 21:14:45 +03:00
: param reply_markup :
2022-03-19 11:49:36 +03:00
: param parse_mode :
2020-01-08 20:06:40 +03:00
: param disable_notification :
: param timeout :
2021-06-19 18:59:55 +03:00
: param thumb :
2021-06-21 18:39:13 +03:00
: param caption_entities :
: param allow_sending_without_reply :
2021-12-31 14:05:40 +03:00
: param protect_content :
2015-08-19 13:27:35 +03:00
: return : Message
2015-06-26 21:14:45 +03:00
"""
2020-12-09 01:41:07 +03:00
parse_mode = self . parse_mode if ( parse_mode is None ) else parse_mode
2015-07-03 02:42:47 +03:00
return types . Message . de_json (
2021-06-21 18:39:13 +03:00
apihelper . send_audio (
self . token , chat_id , audio , caption , duration , performer , title , reply_to_message_id ,
reply_markup , parse_mode , disable_notification , timeout , thumb ,
2021-12-31 14:05:40 +03:00
caption_entities , allow_sending_without_reply , protect_content ) )
2021-06-21 18:39:13 +03:00
2021-12-31 14:05:40 +03:00
# TODO: Rewrite this method like in API.
2021-06-21 18:39:13 +03:00
def send_voice (
self , chat_id : Union [ int , str ] , voice : Union [ Any , str ] ,
caption : Optional [ str ] = None , duration : Optional [ int ] = None ,
reply_to_message_id : Optional [ int ] = None ,
reply_markup : Optional [ REPLY_MARKUP_TYPES ] = None ,
parse_mode : Optional [ str ] = None ,
disable_notification : Optional [ bool ] = None ,
timeout : Optional [ int ] = None ,
caption_entities : Optional [ List [ types . MessageEntity ] ] = None ,
2021-12-31 14:05:40 +03:00
allow_sending_without_reply : Optional [ bool ] = None ,
protect_content : Optional [ bool ] = None ) - > types . Message :
2015-08-19 13:27:35 +03:00
"""
2021-06-19 18:59:55 +03:00
Use this method to send audio files , if you want Telegram clients to display the file
as a playable voice message .
2022-03-06 21:14:07 +03:00
Telegram documentation : https : / / core . telegram . org / bots / api #sendvoice
2022-03-06 17:41:54 +03:00
2022-03-06 21:14:07 +03:00
: param chat_id : Unique identifier for the message recipient .
2015-08-19 13:27:35 +03:00
: param voice :
2020-01-08 20:06:40 +03:00
: param caption :
2022-03-06 21:14:07 +03:00
: param duration : Duration of sent audio in seconds
2015-08-19 13:27:35 +03:00
: param reply_to_message_id :
: param reply_markup :
2022-03-07 12:24:28 +03:00
: param parse_mode :
2020-01-08 20:06:40 +03:00
: param disable_notification :
: param timeout :
2021-06-21 18:39:13 +03:00
: param caption_entities :
: param allow_sending_without_reply :
2021-12-31 14:05:40 +03:00
: param protect_content :
2015-08-19 13:27:35 +03:00
: return : Message
"""
2020-12-09 01:41:07 +03:00
parse_mode = self . parse_mode if ( parse_mode is None ) else parse_mode
2020-07-04 21:07:42 +03:00
2015-08-19 13:08:01 +03:00
return types . Message . de_json (
2021-06-21 18:39:13 +03:00
apihelper . send_voice (
self . token , chat_id , voice , caption , duration , reply_to_message_id , reply_markup ,
parse_mode , disable_notification , timeout , caption_entities ,
2021-12-31 14:05:40 +03:00
allow_sending_without_reply , protect_content ) )
2021-06-21 18:39:13 +03:00
2021-12-31 14:05:40 +03:00
# TODO: Rewrite this method like in API.
2021-06-21 18:39:13 +03:00
def send_document (
2021-12-25 16:23:26 +03:00
self , chat_id : Union [ int , str ] , document : Union [ Any , str ] ,
2021-06-21 18:39:13 +03:00
reply_to_message_id : Optional [ int ] = None ,
caption : Optional [ str ] = None ,
reply_markup : Optional [ REPLY_MARKUP_TYPES ] = None ,
parse_mode : Optional [ str ] = None ,
disable_notification : Optional [ bool ] = None ,
timeout : Optional [ int ] = None ,
thumb : Optional [ Union [ Any , str ] ] = None ,
caption_entities : Optional [ List [ types . MessageEntity ] ] = None ,
2021-06-27 11:38:45 +03:00
allow_sending_without_reply : Optional [ bool ] = None ,
2021-08-18 18:47:38 +03:00
visible_file_name : Optional [ str ] = None ,
2021-12-25 16:23:26 +03:00
disable_content_type_detection : Optional [ bool ] = None ,
2021-12-31 14:05:40 +03:00
data : Optional [ Union [ Any , str ] ] = None ,
protect_content : Optional [ bool ] = None ) - > types . Message :
2015-06-26 21:14:45 +03:00
"""
Use this method to send general files .
2022-03-06 21:14:07 +03:00
Telegram documentation : https : / / core . telegram . org / bots / api #senddocument
2022-03-06 17:41:54 +03:00
2021-08-18 18:47:38 +03:00
: param chat_id : Unique identifier for the target chat or username of the target channel ( in the format @channelusername )
2021-12-25 16:23:26 +03:00
: param document : ( document ) File to send . Pass a file_id as String to send a file that exists on the Telegram servers ( recommended ) , pass an HTTP URL as a String for Telegram to get a file from the Internet , or upload a new one using multipart / form - data
2021-08-18 18:47:38 +03:00
: param reply_to_message_id : If the message is a reply , ID of the original message
: param caption : Document caption ( may also be used when resending documents by file_id ) , 0 - 1024 characters after entities parsing
2015-06-26 21:14:45 +03:00
: param reply_markup :
2021-08-18 18:47:38 +03:00
: param parse_mode : Mode for parsing entities in the document caption
: param disable_notification : Sends the message silently . Users will receive a notification with no sound .
2020-01-08 20:06:40 +03:00
: param timeout :
2021-08-18 18:47:38 +03:00
: param thumb : InputFile or String : Thumbnail of the file sent ; can be ignored if thumbnail generation for the file is supported server - side . The thumbnail should be in JPEG format and less than 200 kB in size . A thumbnail ' s width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can ' t be reused and can be only uploaded as a new file , so you can pass “ attach : / / < file_attach_name > ” if the thumbnail was uploaded using multipart / form - data under < file_attach_name >
2021-06-21 18:39:13 +03:00
: param caption_entities :
: param allow_sending_without_reply :
2021-06-29 13:30:01 +03:00
: param visible_file_name : allows to define file name that will be visible in the Telegram instead of original file name
2021-08-18 18:47:38 +03:00
: param disable_content_type_detection : Disables automatic server - side content type detection for files uploaded using multipart / form - data
2021-12-25 16:23:26 +03:00
: param data : function typo miss compatibility : do not use it
2021-12-31 14:05:40 +03:00
: param protect_content :
2015-07-02 23:32:18 +03:00
: return : API reply .
2015-06-26 21:14:45 +03:00
"""
2020-12-09 01:41:07 +03:00
parse_mode = self . parse_mode if ( parse_mode is None ) else parse_mode
2021-12-25 16:23:26 +03:00
if data and not ( document ) :
# function typo miss compatibility
document = data
2020-07-04 21:07:42 +03:00
2021-01-11 02:20:17 +03:00
return types . Message . de_json (
2021-06-21 18:39:13 +03:00
apihelper . send_data (
2021-12-25 16:23:26 +03:00
self . token , chat_id , document , ' document ' ,
2021-08-18 18:47:38 +03:00
reply_to_message_id = reply_to_message_id , reply_markup = reply_markup , parse_mode = parse_mode ,
disable_notification = disable_notification , timeout = timeout , caption = caption , thumb = thumb ,
caption_entities = caption_entities , allow_sending_without_reply = allow_sending_without_reply ,
2022-01-10 14:38:28 +03:00
disable_content_type_detection = disable_content_type_detection , visible_file_name = visible_file_name ,
protect_content = protect_content ) )
2015-06-26 20:53:07 +03:00
2021-12-31 14:05:40 +03:00
# TODO: Rewrite this method like in API.
2020-05-16 17:34:56 +03:00
def send_sticker (
2022-01-10 14:38:28 +03:00
self , chat_id : Union [ int , str ] ,
sticker : Union [ Any , str ] ,
2021-06-21 18:39:13 +03:00
reply_to_message_id : Optional [ int ] = None ,
reply_markup : Optional [ REPLY_MARKUP_TYPES ] = None ,
disable_notification : Optional [ bool ] = None ,
timeout : Optional [ int ] = None ,
2021-12-31 14:05:40 +03:00
allow_sending_without_reply : Optional [ bool ] = None ,
2022-01-02 13:58:15 +03:00
protect_content : Optional [ bool ] = None ,
data : Union [ Any , str ] = None ) - > types . Message :
2015-06-26 21:14:45 +03:00
"""
Use this method to send . webp stickers .
2022-03-06 17:41:54 +03:00
2022-03-06 21:14:07 +03:00
Telegram documentation : https : / / core . telegram . org / bots / api #sendsticker
2015-06-26 21:14:45 +03:00
: param chat_id :
2022-01-10 14:38:28 +03:00
: param sticker :
2015-06-26 21:14:45 +03:00
: param data :
: param reply_to_message_id :
: param reply_markup :
2020-01-08 20:06:40 +03:00
: param disable_notification : to disable the notification
: param timeout : timeout
2021-06-21 18:39:13 +03:00
: param allow_sending_without_reply :
2021-12-31 14:05:40 +03:00
: param protect_content :
2022-01-02 13:58:15 +03:00
: param data : function typo miss compatibility : do not use it
2015-07-02 23:32:18 +03:00
: return : API reply .
2015-06-26 21:14:45 +03:00
"""
2022-01-02 13:58:15 +03:00
if data and not ( sticker ) :
# function typo miss compatibility
sticker = data
2015-07-03 02:42:47 +03:00
return types . Message . de_json (
2020-05-16 17:34:56 +03:00
apihelper . send_data (
2022-01-02 21:09:09 +03:00
self . token , chat_id , sticker , ' sticker ' ,
2021-06-21 18:39:13 +03:00
reply_to_message_id = reply_to_message_id , reply_markup = reply_markup ,
disable_notification = disable_notification , timeout = timeout ,
2022-01-10 14:38:28 +03:00
allow_sending_without_reply = allow_sending_without_reply ,
protect_content = protect_content ) )
2021-06-21 18:39:13 +03:00
def send_video (
2022-01-02 13:58:15 +03:00
self , chat_id : Union [ int , str ] , video : Union [ Any , str ] ,
2021-12-31 14:05:40 +03:00
duration : Optional [ int ] = None ,
width : Optional [ int ] = None ,
height : Optional [ int ] = None ,
thumb : Optional [ Union [ Any , str ] ] = None ,
2021-06-21 18:39:13 +03:00
caption : Optional [ str ] = None ,
parse_mode : Optional [ str ] = None ,
caption_entities : Optional [ List [ types . MessageEntity ] ] = None ,
2021-12-31 14:05:40 +03:00
supports_streaming : Optional [ bool ] = None ,
disable_notification : Optional [ bool ] = None ,
protect_content : Optional [ bool ] = None ,
reply_to_message_id : Optional [ int ] = None ,
allow_sending_without_reply : Optional [ bool ] = None ,
reply_markup : Optional [ REPLY_MARKUP_TYPES ] = None ,
2022-01-02 13:58:15 +03:00
timeout : Optional [ int ] = None ,
data : Optional [ Union [ Any , str ] ] = None ) - > types . Message :
2015-06-26 21:14:45 +03:00
"""
2022-01-02 13:58:15 +03:00
Use this method to send video files , Telegram clients support mp4 videos ( other formats may be sent as Document ) .
2022-03-06 17:41:54 +03:00
2022-03-06 21:14:07 +03:00
Telegram documentation : https : / / core . telegram . org / bots / api #sendvideo
2022-01-02 13:58:15 +03:00
: param chat_id : Unique identifier for the target chat or username of the target channel ( in the format @channelusername )
: param video : Video to send . You can either pass a file_id as String to resend a video that is already on the Telegram servers , or upload a new video file using multipart / form - data .
: param duration : Duration of sent video in seconds
: param width : Video width
: param height : Video height
: param thumb : Thumbnail of the file sent ; can be ignored if thumbnail generation for the file is supported server - side . The thumbnail should be in JPEG format and less than 200 kB in size . A thumbnail ' s width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can ' t be reused and can be only uploaded as a new file , so you can pass “ attach : / / < file_attach_name > ” if the thumbnail was uploaded using multipart / form - data under < file_attach_name > .
: param caption : Video caption ( may also be used when resending videos by file_id ) , 0 - 1024 characters after entities parsing
: param parse_mode : Mode for parsing entities in the video caption
2021-06-21 18:39:13 +03:00
: param caption_entities :
2022-01-02 13:58:15 +03:00
: param supports_streaming : Pass True , if the uploaded video is suitable for streaming
: param disable_notification : Sends the message silently . Users will receive a notification with no sound .
: param protect_content :
: param reply_to_message_id : If the message is a reply , ID of the original message
2021-06-21 18:39:13 +03:00
: param allow_sending_without_reply :
2022-01-02 13:58:15 +03:00
: param reply_markup :
: param timeout :
: param data : function typo miss compatibility : do not use it
2015-06-26 21:14:45 +03:00
"""
2020-12-09 01:41:07 +03:00
parse_mode = self . parse_mode if ( parse_mode is None ) else parse_mode
2022-01-02 13:58:15 +03:00
if data and not ( video ) :
# function typo miss compatibility
video = data
2020-07-04 21:07:42 +03:00
2015-07-03 02:42:47 +03:00
return types . Message . de_json (
2021-06-21 18:39:13 +03:00
apihelper . send_video (
2022-01-02 13:58:15 +03:00
self . token , chat_id , video , duration , caption , reply_to_message_id , reply_markup ,
2021-06-21 18:39:13 +03:00
parse_mode , supports_streaming , disable_notification , timeout , thumb , width , height ,
2021-12-31 14:05:40 +03:00
caption_entities , allow_sending_without_reply , protect_content ) )
2021-06-21 18:39:13 +03:00
def send_animation (
self , chat_id : Union [ int , str ] , animation : Union [ Any , str ] ,
duration : Optional [ int ] = None ,
2021-12-31 14:05:40 +03:00
width : Optional [ int ] = None ,
height : Optional [ int ] = None ,
thumb : Optional [ Union [ Any , str ] ] = None ,
2021-06-21 18:39:13 +03:00
caption : Optional [ str ] = None ,
parse_mode : Optional [ str ] = None ,
caption_entities : Optional [ List [ types . MessageEntity ] ] = None ,
2021-12-31 14:05:40 +03:00
disable_notification : Optional [ bool ] = None ,
protect_content : Optional [ bool ] = None ,
reply_to_message_id : Optional [ int ] = None ,
allow_sending_without_reply : Optional [ bool ] = None ,
reply_markup : Optional [ REPLY_MARKUP_TYPES ] = None ,
timeout : Optional [ int ] = None , ) - > types . Message :
2019-02-15 21:46:18 +03:00
"""
Use this method to send animation files ( GIF or H .264 / MPEG - 4 AVC video without sound ) .
2022-03-06 17:41:54 +03:00
2022-03-06 21:14:07 +03:00
Telegram documentation : https : / / core . telegram . org / bots / api #sendanimation
2019-02-15 21:46:18 +03:00
: param chat_id : Integer : Unique identifier for the message recipient — User or GroupChat id
2021-06-19 18:59:55 +03:00
: param animation : InputFile or String : Animation to send . You can either pass a file_id as String to resend an
animation that is already on the Telegram server
2019-02-15 21:46:18 +03:00
: param duration : Integer : Duration of sent video in seconds
2021-12-31 14:05:40 +03:00
: param width : Integer : Video width
: param height : Integer : Video height
: param thumb : InputFile or String : Thumbnail of the file sent
2019-02-15 21:46:18 +03:00
: param caption : String : Animation caption ( may also be used when resending animation by file_id ) .
: param parse_mode :
2022-01-10 14:38:28 +03:00
: param protect_content :
2019-02-15 21:46:18 +03:00
: param reply_to_message_id :
: param reply_markup :
2020-04-24 18:19:30 +03:00
: param disable_notification :
: param timeout :
2021-06-21 18:39:13 +03:00
: param caption_entities :
: param allow_sending_without_reply :
2019-02-15 21:46:18 +03:00
: return :
"""
2020-12-09 01:41:07 +03:00
parse_mode = self . parse_mode if ( parse_mode is None ) else parse_mode
2020-07-04 21:07:42 +03:00
2019-02-15 21:46:18 +03:00
return types . Message . de_json (
2021-06-21 18:39:13 +03:00
apihelper . send_animation (
self . token , chat_id , animation , duration , caption , reply_to_message_id ,
reply_markup , parse_mode , disable_notification , timeout , thumb ,
2021-12-31 14:05:40 +03:00
caption_entities , allow_sending_without_reply , protect_content , width , height ) )
2021-06-21 18:39:13 +03:00
2021-12-31 14:05:40 +03:00
# TODO: Rewrite this method like in API.
2021-06-21 18:39:13 +03:00
def send_video_note (
self , chat_id : Union [ int , str ] , data : Union [ Any , str ] ,
duration : Optional [ int ] = None ,
length : Optional [ int ] = None ,
reply_to_message_id : Optional [ int ] = None ,
reply_markup : Optional [ REPLY_MARKUP_TYPES ] = None ,
disable_notification : Optional [ bool ] = None ,
timeout : Optional [ int ] = None ,
thumb : Optional [ Union [ Any , str ] ] = None ,
2021-12-31 14:05:40 +03:00
allow_sending_without_reply : Optional [ bool ] = None ,
protect_content : Optional [ bool ] = None ) - > types . Message :
2017-05-19 17:19:15 +03:00
"""
2021-06-19 18:59:55 +03:00
As of v .4 .0 , Telegram clients support rounded square mp4 videos of up to 1 minute long . Use this method to send
video messages .
2022-03-06 21:14:07 +03:00
Telegram documentation : https : / / core . telegram . org / bots / api #sendvideonote
2022-03-06 17:41:54 +03:00
2017-05-19 17:19:15 +03:00
: param chat_id : Integer : Unique identifier for the message recipient — User or GroupChat id
2021-06-19 18:59:55 +03:00
: param data : InputFile or String : Video note to send . You can either pass a file_id as String to resend
a video that is already on the Telegram server
2017-05-19 17:19:15 +03:00
: param duration : Integer : Duration of sent video in seconds
: param length : Integer : Video width and height , Can ' t be None and should be in range of (0, 640)
: param reply_to_message_id :
: param reply_markup :
2020-01-08 20:06:40 +03:00
: param disable_notification :
: param timeout :
2020-08-21 17:38:54 +03:00
: param thumb : InputFile or String : Thumbnail of the file sent
2021-06-21 18:39:13 +03:00
: param allow_sending_without_reply :
2021-12-31 14:05:40 +03:00
: param protect_content :
2017-05-19 17:19:15 +03:00
: return :
"""
return types . Message . de_json (
2021-06-21 18:39:13 +03:00
apihelper . send_video_note (
self . token , chat_id , data , duration , length , reply_to_message_id , reply_markup ,
2021-12-31 14:05:40 +03:00
disable_notification , timeout , thumb , allow_sending_without_reply , protect_content ) )
2017-05-19 17:19:15 +03:00
2020-05-16 17:34:56 +03:00
def send_media_group (
2021-06-21 18:39:13 +03:00
self , chat_id : Union [ int , str ] ,
media : List [ Union [
types . InputMediaAudio , types . InputMediaDocument ,
types . InputMediaPhoto , types . InputMediaVideo ] ] ,
disable_notification : Optional [ bool ] = None ,
2021-12-31 14:05:40 +03:00
protect_content : Optional [ bool ] = None ,
2021-06-21 18:39:13 +03:00
reply_to_message_id : Optional [ int ] = None ,
timeout : Optional [ int ] = None ,
allow_sending_without_reply : Optional [ bool ] = None ) - > List [ types . Message ] :
2017-11-29 08:45:25 +03:00
"""
2022-03-06 17:41:54 +03:00
Send a group of photos or videos as an album . On success , an array of the sent Messages is returned .
2022-03-06 21:14:07 +03:00
Telegram documentation : https : / / core . telegram . org / bots / api #sendmediagroup
2017-11-29 08:45:25 +03:00
: param chat_id :
: param media :
: param disable_notification :
2021-12-31 14:05:40 +03:00
: param protect_content :
2017-11-29 08:45:25 +03:00
: param reply_to_message_id :
2020-08-25 18:18:51 +03:00
: param timeout :
2021-06-21 18:39:13 +03:00
: param allow_sending_without_reply :
2017-11-29 08:45:25 +03:00
: return :
"""
2020-05-16 17:34:56 +03:00
result = apihelper . send_media_group (
2021-06-21 18:39:13 +03:00
self . token , chat_id , media , disable_notification , reply_to_message_id , timeout ,
2021-12-31 14:05:40 +03:00
allow_sending_without_reply , protect_content )
2021-07-19 20:01:37 +03:00
return [ types . Message . de_json ( msg ) for msg in result ]
2017-11-29 08:45:25 +03:00
2021-12-31 14:05:40 +03:00
# TODO: Rewrite this method like in API.
2020-05-16 17:34:56 +03:00
def send_location (
2021-06-21 18:39:13 +03:00
self , chat_id : Union [ int , str ] ,
latitude : float , longitude : float ,
live_period : Optional [ int ] = None ,
reply_to_message_id : Optional [ int ] = None ,
reply_markup : Optional [ REPLY_MARKUP_TYPES ] = None ,
disable_notification : Optional [ bool ] = None ,
timeout : Optional [ int ] = None ,
horizontal_accuracy : Optional [ float ] = None ,
heading : Optional [ int ] = None ,
proximity_alert_radius : Optional [ int ] = None ,
2021-12-31 14:05:40 +03:00
allow_sending_without_reply : Optional [ bool ] = None ,
protect_content : Optional [ bool ] = None ) - > types . Message :
2015-06-28 12:27:25 +03:00
"""
Use this method to send point on the map .
2022-03-06 17:41:54 +03:00
2022-03-06 21:14:07 +03:00
Telegram documentation : https : / / core . telegram . org / bots / api #sendlocation
2015-06-28 12:27:25 +03:00
: param chat_id :
: param latitude :
: param longitude :
2021-06-21 18:39:13 +03:00
: param live_period :
2015-06-28 12:27:25 +03:00
: param reply_to_message_id :
: param reply_markup :
2020-01-08 20:06:40 +03:00
: param disable_notification :
2020-08-25 18:18:51 +03:00
: param timeout :
2021-06-21 18:39:13 +03:00
: param horizontal_accuracy :
: param heading :
: param proximity_alert_radius :
: param allow_sending_without_reply :
2021-12-31 14:05:40 +03:00
: param protect_content :
2015-07-02 23:32:18 +03:00
: return : API reply .
2015-06-28 12:27:25 +03:00
"""
2015-07-03 02:42:47 +03:00
return types . Message . de_json (
2020-05-16 17:34:56 +03:00
apihelper . send_location (
2021-06-21 18:39:13 +03:00
self . token , chat_id , latitude , longitude , live_period ,
reply_to_message_id , reply_markup , disable_notification , timeout ,
horizontal_accuracy , heading , proximity_alert_radius ,
2021-12-31 14:05:40 +03:00
allow_sending_without_reply , protect_content ) )
2021-06-21 18:39:13 +03:00
def edit_message_live_location (
self , latitude : float , longitude : float ,
chat_id : Optional [ Union [ int , str ] ] = None ,
message_id : Optional [ int ] = None ,
inline_message_id : Optional [ str ] = None ,
reply_markup : Optional [ REPLY_MARKUP_TYPES ] = None ,
timeout : Optional [ int ] = None ,
horizontal_accuracy : Optional [ float ] = None ,
heading : Optional [ int ] = None ,
proximity_alert_radius : Optional [ int ] = None ) - > types . Message :
2017-10-22 20:07:51 +03:00
"""
2022-03-06 17:41:54 +03:00
Use this method to edit live location .
2022-03-06 21:14:07 +03:00
Telegram documentation : https : / / core . telegram . org / bots / api #editmessagelivelocation
2017-10-22 20:07:51 +03:00
: param latitude :
: param longitude :
: param chat_id :
: param message_id :
: param reply_markup :
2020-08-25 18:18:51 +03:00
: param timeout :
2021-06-21 18:39:13 +03:00
: param inline_message_id :
: param horizontal_accuracy :
: param heading :
: param proximity_alert_radius :
2017-10-22 20:07:51 +03:00
: return :
"""
return types . Message . de_json (
2020-05-16 17:34:56 +03:00
apihelper . edit_message_live_location (
self . token , latitude , longitude , chat_id , message_id ,
2021-06-21 18:39:13 +03:00
inline_message_id , reply_markup , timeout ,
horizontal_accuracy , heading , proximity_alert_radius ) )
2017-10-22 20:07:51 +03:00
2020-05-16 17:34:56 +03:00
def stop_message_live_location (
2021-06-21 18:39:13 +03:00
self , chat_id : Optional [ Union [ int , str ] ] = None ,
message_id : Optional [ int ] = None ,
inline_message_id : Optional [ str ] = None ,
reply_markup : Optional [ REPLY_MARKUP_TYPES ] = None ,
timeout : Optional [ int ] = None ) - > types . Message :
2017-10-22 20:07:51 +03:00
"""
Use this method to stop updating a live location message sent by the bot
or via the bot ( for inline bots ) before live_period expires
2022-03-06 21:14:07 +03:00
Telegram documentation : https : / / core . telegram . org / bots / api #stopmessagelivelocation
2022-03-06 17:41:54 +03:00
2017-10-22 20:07:51 +03:00
: param chat_id :
: param message_id :
: param inline_message_id :
: param reply_markup :
2020-08-25 18:18:51 +03:00
: param timeout :
2017-10-22 20:07:51 +03:00
: return :
"""
return types . Message . de_json (
2020-05-16 17:34:56 +03:00
apihelper . stop_message_live_location (
self . token , chat_id , message_id , inline_message_id , reply_markup , timeout ) )
2017-10-22 20:07:51 +03:00
2021-12-31 14:05:40 +03:00
# TODO: Rewrite this method like in API.
2020-05-16 17:34:56 +03:00
def send_venue (
2021-06-21 18:39:13 +03:00
self , chat_id : Union [ int , str ] ,
latitude : float , longitude : float ,
title : str , address : str ,
foursquare_id : Optional [ str ] = None ,
foursquare_type : Optional [ str ] = None ,
disable_notification : Optional [ bool ] = None ,
reply_to_message_id : Optional [ int ] = None ,
reply_markup : Optional [ REPLY_MARKUP_TYPES ] = None ,
timeout : Optional [ int ] = None ,
allow_sending_without_reply : Optional [ bool ] = None ,
google_place_id : Optional [ str ] = None ,
2021-12-31 14:05:40 +03:00
google_place_type : Optional [ str ] = None ,
protect_content : Optional [ bool ] = None ) - > types . Message :
2016-04-14 09:48:26 +03:00
"""
Use this method to send information about a venue .
2022-03-06 17:41:54 +03:00
2022-03-06 21:14:07 +03:00
Telegram documentation : https : / / core . telegram . org / bots / api #sendvenue
2016-04-14 09:48:26 +03:00
: param chat_id : Integer or String : Unique identifier for the target chat or username of the target channel
: param latitude : Float : Latitude of the venue
: param longitude : Float : Longitude of the venue
: param title : String : Name of the venue
: param address : String : Address of the venue
: param foursquare_id : String : Foursquare identifier of the venue
2021-06-19 18:59:55 +03:00
: param foursquare_type : Foursquare type of the venue , if known . ( For example , “ arts_entertainment / default ” ,
“ arts_entertainment / aquarium ” or “ food / icecream ” . )
2016-04-14 09:48:26 +03:00
: param disable_notification :
: param reply_to_message_id :
: param reply_markup :
2020-08-25 18:18:51 +03:00
: param timeout :
2021-06-21 18:39:13 +03:00
: param allow_sending_without_reply :
: param google_place_id :
: param google_place_type :
2021-12-31 14:05:40 +03:00
: param protect_content :
2016-04-14 09:48:26 +03:00
: return :
"""
2016-04-14 08:55:28 +03:00
return types . Message . de_json (
2020-05-16 17:34:56 +03:00
apihelper . send_venue (
2020-08-25 18:18:51 +03:00
self . token , chat_id , latitude , longitude , title , address , foursquare_id , foursquare_type ,
2021-06-21 18:39:13 +03:00
disable_notification , reply_to_message_id , reply_markup , timeout ,
2021-12-31 14:05:40 +03:00
allow_sending_without_reply , google_place_id , google_place_type , protect_content ) )
2016-04-14 08:55:28 +03:00
2021-12-31 14:05:40 +03:00
# TODO: Rewrite this method like in API.
2020-05-16 17:34:56 +03:00
def send_contact (
2021-06-21 18:39:13 +03:00
self , chat_id : Union [ int , str ] , phone_number : str ,
first_name : str , last_name : Optional [ str ] = None ,
vcard : Optional [ str ] = None ,
disable_notification : Optional [ bool ] = None ,
reply_to_message_id : Optional [ int ] = None ,
reply_markup : Optional [ REPLY_MARKUP_TYPES ] = None ,
timeout : Optional [ int ] = None ,
2021-12-31 14:05:40 +03:00
allow_sending_without_reply : Optional [ bool ] = None ,
protect_content : Optional [ bool ] = None ) - > types . Message :
2022-03-06 21:14:07 +03:00
"""
Use this method to send phone contacts .
Telegram documentation : https : / / core . telegram . org / bots / api #sendcontact
: param chat_id : Integer or String : Unique identifier for the target chat or username of the target channel
: param phone_number : String : Contact ' s phone number
: param first_name : String : Contact ' s first name
: param last_name : String : Contact ' s last name
: param vcard : String : Additional data about the contact in the form of a vCard , 0 - 2048 bytes
: param disable_notification :
: param reply_to_message_id :
: param reply_markup :
: param timeout :
: param allow_sending_without_reply :
: param protect_content :
: return :
"""
2016-04-16 10:07:52 +03:00
return types . Message . de_json (
2020-05-16 17:34:56 +03:00
apihelper . send_contact (
2020-08-25 18:18:51 +03:00
self . token , chat_id , phone_number , first_name , last_name , vcard ,
2021-06-21 18:39:13 +03:00
disable_notification , reply_to_message_id , reply_markup , timeout ,
2021-12-31 14:05:40 +03:00
allow_sending_without_reply , protect_content ) )
2016-04-16 10:07:52 +03:00
2021-06-21 18:39:13 +03:00
def send_chat_action (
self , chat_id : Union [ int , str ] , action : str , timeout : Optional [ int ] = None ) - > bool :
2015-06-28 12:56:32 +03:00
"""
Use this method when you need to tell the user that something is happening on the bot ' s side.
The status is set for 5 seconds or less ( when a message arrives from your bot , Telegram clients clear
its typing status ) .
2022-03-06 17:41:54 +03:00
2022-03-06 21:14:07 +03:00
Telegram documentation : https : / / core . telegram . org / bots / api #sendchataction
2015-06-28 12:56:32 +03:00
: param chat_id :
2015-07-02 23:32:18 +03:00
: param action : One of the following strings : ' typing ' , ' upload_photo ' , ' record_video ' , ' upload_video ' ,
2021-06-19 18:59:55 +03:00
' record_audio ' , ' upload_audio ' , ' upload_document ' , ' find_location ' , ' record_video_note ' ,
' upload_video_note ' .
2020-08-25 18:18:51 +03:00
: param timeout :
2015-07-03 04:58:48 +03:00
: return : API reply . : type : boolean
2015-06-28 12:56:32 +03:00
"""
2020-05-16 17:34:56 +03:00
return apihelper . send_chat_action ( self . token , chat_id , action , timeout )
2022-03-07 12:24:28 +03:00
2021-06-21 18:39:13 +03:00
def kick_chat_member (
self , chat_id : Union [ int , str ] , user_id : int ,
until_date : Optional [ Union [ int , datetime ] ] = None ,
revoke_messages : Optional [ bool ] = None ) - > bool :
2016-04-14 09:48:26 +03:00
"""
2021-06-28 13:02:40 +03:00
This function is deprecated . Use ` ban_chat_member ` instead
2016-04-14 09:48:26 +03:00
"""
2021-06-28 12:59:21 +03:00
logger . info ( ' kick_chat_member is deprecated. Use ban_chat_member instead. ' )
return apihelper . ban_chat_member ( self . token , chat_id , user_id , until_date , revoke_messages )
2016-04-14 09:48:26 +03:00
2021-06-28 10:31:06 +03:00
def ban_chat_member (
self , chat_id : Union [ int , str ] , user_id : int ,
until_date : Optional [ Union [ int , datetime ] ] = None ,
revoke_messages : Optional [ bool ] = None ) - > bool :
"""
Use this method to ban a user in a group , a supergroup or a channel .
In the case of supergroups and channels , the user will not be able to return to the chat on their
own using invite links , etc . , unless unbanned first .
Returns True on success .
2022-03-06 17:41:54 +03:00
2022-03-06 21:14:07 +03:00
Telegram documentation : https : / / core . telegram . org / bots / api #banchatmember
2021-06-28 10:31:06 +03:00
: param chat_id : Int or string : Unique identifier for the target group or username of the target supergroup
: param user_id : Int : Unique identifier of the target user
: param until_date : Date when the user will be unbanned , unix time . If user is banned for more than 366 days or
less than 30 seconds from the current time they are considered to be banned forever
: param revoke_messages : Bool : Pass True to delete all messages from the chat for the user that is being removed .
If False , the user will be able to see messages in the group that were sent before the user was removed .
Always True for supergroups and channels .
: return : boolean
"""
return apihelper . ban_chat_member ( self . token , chat_id , user_id , until_date , revoke_messages )
2021-06-21 18:39:13 +03:00
def unban_chat_member (
self , chat_id : Union [ int , str ] , user_id : int ,
only_if_banned : Optional [ bool ] = False ) - > bool :
2020-01-08 20:06:40 +03:00
"""
2020-12-29 19:24:41 +03:00
Use this method to unban a previously kicked user in a supergroup or channel .
The user will not return to the group or channel automatically , but will be able to join via link , etc .
The bot must be an administrator for this to work . By default , this method guarantees that after the call
the user is not a member of the chat , but will be able to join it . So if the user is a member of the chat
they will also be removed from the chat . If you don ' t want this, use the parameter only_if_banned.
2022-03-06 21:14:07 +03:00
Telegram documentation : https : / / core . telegram . org / bots / api #unbanchatmember
2021-06-19 18:59:55 +03:00
: param chat_id : Unique identifier for the target group or username of the target supergroup or channel
( in the format @username )
2020-12-29 19:24:41 +03:00
: param user_id : Unique identifier of the target user
: param only_if_banned : Do nothing if the user is not banned
: return : True on success
2020-01-08 20:06:40 +03:00
"""
2020-11-18 02:22:52 +03:00
return apihelper . unban_chat_member ( self . token , chat_id , user_id , only_if_banned )
2016-04-14 09:48:26 +03:00
2020-05-16 17:34:56 +03:00
def restrict_chat_member (
2021-06-21 18:39:13 +03:00
self , chat_id : Union [ int , str ] , user_id : int ,
until_date : Optional [ Union [ int , datetime ] ] = None ,
can_send_messages : Optional [ bool ] = None ,
can_send_media_messages : Optional [ bool ] = None ,
can_send_polls : Optional [ bool ] = None ,
can_send_other_messages : Optional [ bool ] = None ,
can_add_web_page_previews : Optional [ bool ] = None ,
can_change_info : Optional [ bool ] = None ,
can_invite_users : Optional [ bool ] = None ,
can_pin_messages : Optional [ bool ] = None ) - > bool :
2017-06-30 19:47:09 +03:00
"""
Use this method to restrict a user in a supergroup .
The bot must be an administrator in the supergroup for this to work and must have
the appropriate admin rights . Pass True for all boolean parameters to lift restrictions from a user .
2020-12-29 19:24:41 +03:00
2022-03-06 21:14:07 +03:00
Telegram documentation : https : / / core . telegram . org / bots / api #restrictchatmember
2022-03-06 17:41:54 +03:00
: param chat_id : Int or String : Unique identifier for the target group or username of the target supergroup
2017-06-30 19:47:09 +03:00
or channel ( in the format @channelusername )
: param user_id : Int : Unique identifier of the target user
2017-06-30 20:16:51 +03:00
: param until_date : Date when restrictions will be lifted for the user , unix time .
If user is restricted for more than 366 days or less than 30 seconds from the current time ,
they are considered to be restricted forever
: param can_send_messages : Pass True , if the user can send text messages , contacts , locations and venues
2022-03-07 12:24:28 +03:00
: param can_send_media_messages : Pass True , if the user can send audios , documents , photos , videos , video notes
2017-06-30 20:16:51 +03:00
and voice notes , implies can_send_messages
2020-05-16 17:34:56 +03:00
: param can_send_polls : Pass True , if the user is allowed to send polls , implies can_send_messages
2022-03-07 12:24:28 +03:00
: param can_send_other_messages : Pass True , if the user can send animations , games , stickers and use inline bots , implies can_send_media_messages
2017-06-30 20:16:51 +03:00
: param can_add_web_page_previews : Pass True , if the user may add web page previews to their messages ,
implies can_send_media_messages
2021-06-19 18:59:55 +03:00
: param can_change_info : Pass True , if the user is allowed to change the chat title , photo and other settings .
Ignored in public supergroups
: param can_invite_users : Pass True , if the user is allowed to invite new users to the chat ,
implies can_invite_users
2020-05-16 17:34:56 +03:00
: param can_pin_messages : Pass True , if the user is allowed to pin messages . Ignored in public supergroups
2020-12-29 19:24:41 +03:00
: return : True on success
2017-06-30 19:47:09 +03:00
"""
2020-05-16 17:34:56 +03:00
return apihelper . restrict_chat_member (
self . token , chat_id , user_id , until_date ,
can_send_messages , can_send_media_messages ,
can_send_polls , can_send_other_messages ,
can_add_web_page_previews , can_change_info ,
can_invite_users , can_pin_messages )
2017-06-30 19:47:09 +03:00
2021-06-21 18:39:13 +03:00
def promote_chat_member (
self , chat_id : Union [ int , str ] , user_id : int ,
can_change_info : Optional [ bool ] = None ,
can_post_messages : Optional [ bool ] = None ,
can_edit_messages : Optional [ bool ] = None ,
can_delete_messages : Optional [ bool ] = None ,
can_invite_users : Optional [ bool ] = None ,
can_restrict_members : Optional [ bool ] = None ,
can_pin_messages : Optional [ bool ] = None ,
can_promote_members : Optional [ bool ] = None ,
is_anonymous : Optional [ bool ] = None ,
can_manage_chat : Optional [ bool ] = None ,
can_manage_voice_chats : Optional [ bool ] = None ) - > bool :
2017-06-30 19:47:09 +03:00
"""
Use this method to promote or demote a user in a supergroup or a channel . The bot must be an administrator
in the chat for this to work and must have the appropriate admin rights .
2020-12-29 19:24:41 +03:00
Pass False for all boolean parameters to demote a user .
2022-03-06 21:14:07 +03:00
Telegram documentation : https : / / core . telegram . org / bots / api #promotechatmember
2017-06-30 19:47:09 +03:00
: param chat_id : Unique identifier for the target chat or username of the target channel (
in the format @channelusername )
: param user_id : Int : Unique identifier of the target user
: param can_change_info : Bool : Pass True , if the administrator can change chat title , photo and other settings
: param can_post_messages : Bool : Pass True , if the administrator can create channel posts , channels only
: param can_edit_messages : Bool : Pass True , if the administrator can edit messages of other users , channels only
: param can_delete_messages : Bool : Pass True , if the administrator can delete messages of other users
: param can_invite_users : Bool : Pass True , if the administrator can invite new users to the chat
: param can_restrict_members : Bool : Pass True , if the administrator can restrict , ban or unban chat members
: param can_pin_messages : Bool : Pass True , if the administrator can pin messages , supergroups only
: param can_promote_members : Bool : Pass True , if the administrator can add new administrators with a subset
of his own privileges or demote administrators that he has promoted , directly or indirectly
( promoted by administrators that were appointed by him )
2021-06-21 18:39:13 +03:00
: param is_anonymous : Bool : Pass True , if the administrator ' s presence in the chat is hidden
: param can_manage_chat : Bool : Pass True , if the administrator can access the chat event log , chat statistics ,
message statistics in channels , see channel members ,
see anonymous administrators in supergroups and ignore slow mode .
Implied by any other administrator privilege
: param can_manage_voice_chats : Bool : Pass True , if the administrator can manage voice chats
For now , bots can use this privilege only for passing to other administrators .
2020-12-29 19:24:41 +03:00
: return : True on success .
2017-06-30 19:47:09 +03:00
"""
2021-06-21 18:39:13 +03:00
return apihelper . promote_chat_member (
self . token , chat_id , user_id , can_change_info , can_post_messages ,
can_edit_messages , can_delete_messages , can_invite_users ,
can_restrict_members , can_pin_messages , can_promote_members ,
is_anonymous , can_manage_chat , can_manage_voice_chats )
2017-06-30 19:47:09 +03:00
2021-06-21 18:39:13 +03:00
def set_chat_administrator_custom_title (
self , chat_id : Union [ int , str ] , user_id : int , custom_title : str ) - > bool :
2020-05-09 23:23:08 +03:00
"""
Use this method to set a custom title for an administrator
2020-12-29 19:24:41 +03:00
in a supergroup promoted by the bot .
2022-03-06 21:14:07 +03:00
Telegram documentation : https : / / core . telegram . org / bots / api #setchatadministratorcustomtitle
2020-05-09 23:23:08 +03:00
: param chat_id : Unique identifier for the target chat or username of the target supergroup
( in the format @supergroupusername )
: param user_id : Unique identifier of the target user
: param custom_title : New custom title for the administrator ;
0 - 16 characters , emoji are not allowed
2020-12-29 19:24:41 +03:00
: return : True on success .
2020-05-09 23:23:08 +03:00
"""
return apihelper . set_chat_administrator_custom_title ( self . token , chat_id , user_id , custom_title )
2021-12-07 20:17:51 +03:00
2021-12-08 12:00:39 +03:00
def ban_chat_sender_chat ( self , chat_id : Union [ int , str ] , sender_chat_id : Union [ int , str ] ) - > bool :
2021-12-07 20:17:51 +03:00
"""
Use this method to ban a channel chat in a supergroup or a channel .
The owner of the chat will not be able to send messages and join live
streams on behalf of the chat , unless it is unbanned first .
The bot must be an administrator in the supergroup or channel
for this to work and must have the appropriate administrator rights .
Returns True on success .
2022-03-06 21:14:07 +03:00
Telegram documentation : https : / / core . telegram . org / bots / api #banchatsenderchat
2021-12-07 20:17:51 +03:00
: param chat_id : Unique identifier for the target chat or username of the target channel ( in the format @channelusername )
: param sender_chat_id : Unique identifier of the target sender chat
: return : True on success .
"""
2021-12-08 12:00:39 +03:00
return apihelper . ban_chat_sender_chat ( self . token , chat_id , sender_chat_id )
2021-12-07 20:17:51 +03:00
def unban_chat_sender_chat ( self , chat_id : Union [ int , str ] , sender_chat_id : Union [ int , str ] ) - > bool :
"""
Use this method to unban a previously banned channel chat in a supergroup or channel .
The bot must be an administrator for this to work and must have the appropriate
administrator rights .
Returns True on success .
2022-03-06 21:14:07 +03:00
Telegram documentation : https : / / core . telegram . org / bots / api #unbanchatsenderchat
2021-12-07 20:17:51 +03:00
: params :
: param chat_id : Unique identifier for the target chat or username of the target channel ( in the format @channelusername )
: param sender_chat_id : Unique identifier of the target sender chat
: return : True on success .
"""
return apihelper . unban_chat_sender_chat ( self . token , chat_id , sender_chat_id )
2021-06-21 18:39:13 +03:00
def set_chat_permissions (
self , chat_id : Union [ int , str ] , permissions : types . ChatPermissions ) - > bool :
2020-05-11 16:38:09 +03:00
"""
Use this method to set default chat permissions for all members .
2020-12-29 19:24:41 +03:00
The bot must be an administrator in the group or a supergroup for this to work
and must have the can_restrict_members admin rights .
2022-03-06 21:14:07 +03:00
Telegram documentation : https : / / core . telegram . org / bots / api #setchatpermissions
2020-05-11 16:38:09 +03:00
: param chat_id : Unique identifier for the target chat or username of the target supergroup
( in the format @supergroupusername )
: param permissions : New default chat permissions
2020-12-29 19:24:41 +03:00
: return : True on success
2020-05-11 16:38:09 +03:00
"""
return apihelper . set_chat_permissions ( self . token , chat_id , permissions )
2021-06-21 18:39:13 +03:00
def create_chat_invite_link (
2021-11-05 21:22:03 +03:00
self , chat_id : Union [ int , str ] ,
name : Optional [ str ] = None ,
2021-06-21 18:39:13 +03:00
expire_date : Optional [ Union [ int , datetime ] ] = None ,
2021-11-05 21:22:03 +03:00
member_limit : Optional [ int ] = None ,
creates_join_request : Optional [ bool ] = None ) - > types . ChatInviteLink :
2021-05-19 02:24:07 +03:00
"""
Use this method to create an additional invite link for a chat .
The bot must be an administrator in the chat for this to work and must have the appropriate admin rights .
2022-03-06 21:14:07 +03:00
Telegram documentation : https : / / core . telegram . org / bots / api #createchatinvitelink
2021-05-19 02:24:07 +03:00
: param chat_id : Id : Unique identifier for the target chat or username of the target channel
( in the format @channelusername )
2021-11-08 18:51:42 +03:00
: param name : Invite link name ; 0 - 32 characters
2021-08-18 18:52:09 +03:00
: param expire_date : Point in time ( Unix timestamp ) when the link will expire
: param member_limit : Maximum number of users that can be members of the chat simultaneously
2021-11-08 18:51:42 +03:00
: param creates_join_request : True , if users joining the chat via the link need to be approved by chat administrators . If True , member_limit can ' t be specified
2021-05-19 02:24:07 +03:00
: return :
"""
2021-06-17 21:28:53 +03:00
return types . ChatInviteLink . de_json (
2021-11-05 21:22:03 +03:00
apihelper . create_chat_invite_link ( self . token , chat_id , name , expire_date , member_limit , creates_join_request )
2021-06-17 21:28:53 +03:00
)
2021-05-19 02:24:07 +03:00
2021-06-21 18:39:13 +03:00
def edit_chat_invite_link (
2021-11-08 18:51:42 +03:00
self , chat_id : Union [ int , str ] ,
invite_link : Optional [ str ] = None ,
name : Optional [ str ] = None ,
expire_date : Optional [ Union [ int , datetime ] ] = None ,
member_limit : Optional [ int ] = None ,
2021-11-05 21:22:03 +03:00
creates_join_request : Optional [ bool ] = None ) - > types . ChatInviteLink :
2021-05-19 02:24:07 +03:00
"""
Use this method to edit a non - primary invite link created by the bot .
The bot must be an administrator in the chat for this to work and must have the appropriate admin rights .
2022-03-06 21:14:07 +03:00
Telegram documentation : https : / / core . telegram . org / bots / api #editchatinvitelink
2021-05-19 02:24:07 +03:00
: param chat_id : Id : Unique identifier for the target chat or username of the target channel
( in the format @channelusername )
2021-11-08 18:51:42 +03:00
: param name : Invite link name ; 0 - 32 characters
2021-08-18 18:52:09 +03:00
: param invite_link : The invite link to edit
: param expire_date : Point in time ( Unix timestamp ) when the link will expire
: param member_limit : Maximum number of users that can be members of the chat simultaneously
2021-11-08 18:51:42 +03:00
: param creates_join_request : True , if users joining the chat via the link need to be approved by chat administrators . If True , member_limit can ' t be specified
2021-05-19 02:24:07 +03:00
: return :
"""
2021-06-17 21:28:53 +03:00
return types . ChatInviteLink . de_json (
2021-11-05 21:22:03 +03:00
apihelper . edit_chat_invite_link ( self . token , chat_id , name , invite_link , expire_date , member_limit , creates_join_request )
2021-06-17 21:28:53 +03:00
)
2021-05-19 02:24:07 +03:00
2021-06-21 18:39:13 +03:00
def revoke_chat_invite_link (
self , chat_id : Union [ int , str ] , invite_link : str ) - > types . ChatInviteLink :
2021-05-19 02:24:07 +03:00
"""
Use this method to revoke an invite link created by the bot .
Note : If the primary link is revoked , a new link is automatically generated The bot must be an administrator
2022-03-07 12:24:28 +03:00
in the chat for this to work and must have the appropriate admin rights .
2021-05-19 02:24:07 +03:00
2022-03-06 21:14:07 +03:00
Telegram documentation : https : / / core . telegram . org / bots / api #revokechatinvitelink
2021-05-19 02:24:07 +03:00
: param chat_id : Id : Unique identifier for the target chat or username of the target channel
( in the format @channelusername )
2021-08-18 18:52:09 +03:00
: param invite_link : The invite link to revoke
2021-05-19 02:24:07 +03:00
: return :
"""
2021-06-17 21:28:53 +03:00
return types . ChatInviteLink . de_json (
apihelper . revoke_chat_invite_link ( self . token , chat_id , invite_link )
)
2021-05-19 02:24:07 +03:00
2021-06-21 18:39:13 +03:00
def export_chat_invite_link ( self , chat_id : Union [ int , str ] ) - > str :
2017-06-30 19:47:09 +03:00
"""
Use this method to export an invite link to a supergroup or a channel . The bot must be an administrator
in the chat for this to work and must have the appropriate admin rights .
2020-12-29 19:24:41 +03:00
2022-03-06 21:14:07 +03:00
Telegram documentation : https : / / core . telegram . org / bots / api #exportchatinvitelink
2017-06-30 19:47:09 +03:00
: param chat_id : Id : Unique identifier for the target chat or username of the target channel
( in the format @channelusername )
2020-12-29 19:24:41 +03:00
: return : exported invite link as String on success .
2017-06-30 19:47:09 +03:00
"""
return apihelper . export_chat_invite_link ( self . token , chat_id )
2021-11-06 10:15:28 +03:00
def approve_chat_join_request ( self , chat_id : Union [ str , int ] , user_id : Union [ int , str ] ) - > bool :
"""
Use this method to approve a chat join request .
The bot must be an administrator in the chat for this to work and must have
the can_invite_users administrator right . Returns True on success .
2022-03-06 21:14:07 +03:00
Telegram documentation : https : / / core . telegram . org / bots / api #approvechatjoinrequest
2021-11-06 10:15:28 +03:00
: param chat_id : Unique identifier for the target chat or username of the target supergroup
( in the format @supergroupusername )
: param user_id : Unique identifier of the target user
: return : True on success .
"""
return apihelper . approve_chat_join_request ( self . token , chat_id , user_id )
def decline_chat_join_request ( self , chat_id : Union [ str , int ] , user_id : Union [ int , str ] ) - > bool :
"""
Use this method to decline a chat join request .
The bot must be an administrator in the chat for this to work and must have
the can_invite_users administrator right . Returns True on success .
2022-03-06 21:14:07 +03:00
Telegram documentation : https : / / core . telegram . org / bots / api #declinechatjoinrequest
2021-11-06 10:15:28 +03:00
: param chat_id : Unique identifier for the target chat or username of the target supergroup
( in the format @supergroupusername )
: param user_id : Unique identifier of the target user
: return : True on success .
"""
return apihelper . decline_chat_join_request ( self . token , chat_id , user_id )
2021-06-21 18:39:13 +03:00
def set_chat_photo ( self , chat_id : Union [ int , str ] , photo : Any ) - > bool :
2017-06-30 19:47:09 +03:00
"""
Use this method to set a new profile photo for the chat . Photos can ' t be changed for private chats.
The bot must be an administrator in the chat for this to work and must have the appropriate admin rights .
Returns True on success .
Note : In regular groups ( non - supergroups ) , this method will only work if the ‘ All Members Are Admins ’
2022-03-07 12:24:28 +03:00
setting is off in the target group .
2022-03-06 17:41:54 +03:00
2022-03-06 21:14:07 +03:00
Telegram documentation : https : / / core . telegram . org / bots / api #setchatphoto
2017-06-30 19:47:09 +03:00
: param chat_id : Int or Str : Unique identifier for the target chat or username of the target channel
( in the format @channelusername )
: param photo : InputFile : New chat photo , uploaded using multipart / form - data
: return :
"""
return apihelper . set_chat_photo ( self . token , chat_id , photo )
2021-06-21 18:39:13 +03:00
def delete_chat_photo ( self , chat_id : Union [ int , str ] ) - > bool :
2017-06-30 19:47:09 +03:00
"""
Use this method to delete a chat photo . Photos can ' t be changed for private chats.
The bot must be an administrator in the chat for this to work and must have the appropriate admin rights .
Returns True on success .
2022-03-07 12:24:28 +03:00
Note : In regular groups ( non - supergroups ) , this method will only work if the ‘ All Members Are Admins ’ setting is off in the target group .
2022-03-06 17:41:54 +03:00
2022-03-06 21:14:07 +03:00
Telegram documentation : https : / / core . telegram . org / bots / api #deletechatphoto
2017-06-30 19:47:09 +03:00
: param chat_id : Int or Str : Unique identifier for the target chat or username of the target channel
( in the format @channelusername )
"""
return apihelper . delete_chat_photo ( self . token , chat_id )
2021-06-21 18:39:13 +03:00
2022-01-21 21:50:33 +03:00
def get_my_commands ( self , scope : Optional [ types . BotCommandScope ] = None ,
language_code : Optional [ str ] = None ) - > List [ types . BotCommand ] :
2021-06-28 10:31:06 +03:00
"""
Use this method to get the current list of the bot ' s commands.
2021-06-21 18:39:13 +03:00
Returns List of BotCommand on success .
2022-03-06 17:41:54 +03:00
2022-03-06 21:14:07 +03:00
Telegram documentation : https : / / core . telegram . org / bots / api #getmycommands
2021-06-28 10:31:06 +03:00
: param scope : The scope of users for which the commands are relevant .
Defaults to BotCommandScopeDefault .
: param language_code : A two - letter ISO 639 - 1 language code . If empty ,
commands will be applied to all users from the given scope ,
for whose language there are no dedicated commands
2021-06-21 18:39:13 +03:00
"""
2021-06-26 14:36:14 +03:00
result = apihelper . get_my_commands ( self . token , scope , language_code )
2021-06-21 18:39:13 +03:00
return [ types . BotCommand . de_json ( cmd ) for cmd in result ]
2017-06-30 19:47:09 +03:00
2021-06-28 10:31:06 +03:00
def set_my_commands ( self , commands : List [ types . BotCommand ] ,
scope : Optional [ types . BotCommandScope ] = None ,
language_code : Optional [ str ] = None ) - > bool :
2020-05-08 21:06:39 +03:00
"""
Use this method to change the list of the bot ' s commands.
2022-03-06 17:41:54 +03:00
2022-03-06 21:14:07 +03:00
Telegram documentation : https : / / core . telegram . org / bots / api #setmycommands
2021-06-21 18:39:13 +03:00
: param commands : List of BotCommand . At most 100 commands can be specified .
2021-06-28 10:31:06 +03:00
: param scope : The scope of users for which the commands are relevant .
Defaults to BotCommandScopeDefault .
: param language_code : A two - letter ISO 639 - 1 language code . If empty ,
commands will be applied to all users from the given scope ,
for whose language there are no dedicated commands
2021-06-26 14:36:14 +03:00
: return :
"""
return apihelper . set_my_commands ( self . token , commands , scope , language_code )
2021-06-28 10:31:06 +03:00
def delete_my_commands ( self , scope : Optional [ types . BotCommandScope ] = None ,
2022-01-10 16:49:49 +03:00
language_code : Optional [ str ] = None ) - > bool :
2021-06-26 14:36:14 +03:00
"""
2021-06-28 10:31:06 +03:00
Use this method to delete the list of the bot ' s commands for the given scope and user language.
After deletion , higher level commands will be shown to affected users .
Returns True on success .
2022-03-06 21:14:07 +03:00
Telegram documentation : https : / / core . telegram . org / bots / api #deletemycommands
2022-03-06 17:41:54 +03:00
2021-06-28 10:31:06 +03:00
: param scope : The scope of users for which the commands are relevant .
Defaults to BotCommandScopeDefault .
: param language_code : A two - letter ISO 639 - 1 language code . If empty ,
commands will be applied to all users from the given scope ,
for whose language there are no dedicated commands
2020-05-08 21:06:39 +03:00
"""
2021-06-26 14:36:14 +03:00
return apihelper . delete_my_commands ( self . token , scope , language_code )
2020-05-08 21:06:39 +03:00
2021-06-21 18:39:13 +03:00
def set_chat_title ( self , chat_id : Union [ int , str ] , title : str ) - > bool :
2017-06-30 19:47:09 +03:00
"""
Use this method to change the title of a chat . Titles can ' t be changed for private chats.
The bot must be an administrator in the chat for this to work and must have the appropriate admin rights .
Returns True on success .
Note : In regular groups ( non - supergroups ) , this method will only work if the ‘ All Members Are Admins ’
2022-03-07 12:24:28 +03:00
setting is off in the target group .
2022-03-06 17:41:54 +03:00
2022-03-06 21:14:07 +03:00
Telegram documentation : https : / / core . telegram . org / bots / api #setchattitle
2017-06-30 19:47:09 +03:00
: param chat_id : Int or Str : Unique identifier for the target chat or username of the target channel
( in the format @channelusername )
: param title : New chat title , 1 - 255 characters
: return :
"""
return apihelper . set_chat_title ( self . token , chat_id , title )
2021-06-21 18:39:13 +03:00
def set_chat_description ( self , chat_id : Union [ int , str ] , description : Optional [ str ] = None ) - > bool :
2017-06-30 19:47:09 +03:00
"""
Use this method to change the description of a supergroup or a channel .
The bot must be an administrator in the chat for this to work and must have the appropriate admin rights .
2020-12-29 19:24:41 +03:00
2022-03-06 21:14:07 +03:00
Telegram documentation : https : / / core . telegram . org / bots / api #setchatdescription
2017-06-30 19:47:09 +03:00
: param chat_id : Int or Str : Unique identifier for the target chat or username of the target channel
( in the format @channelusername )
: param description : Str : New chat description , 0 - 255 characters
2020-12-29 19:24:41 +03:00
: return : True on success .
2017-06-30 19:47:09 +03:00
"""
return apihelper . set_chat_description ( self . token , chat_id , description )
2021-06-21 18:39:13 +03:00
def pin_chat_message (
self , chat_id : Union [ int , str ] , message_id : int ,
disable_notification : Optional [ bool ] = False ) - > bool :
2017-06-30 19:47:09 +03:00
"""
Use this method to pin a message in a supergroup .
The bot must be an administrator in the chat for this to work and must have the appropriate admin rights .
Returns True on success .
2022-03-06 17:41:54 +03:00
2022-03-06 21:14:07 +03:00
Telegram documentation : https : / / core . telegram . org / bots / api #pinchatmessage
2017-06-30 19:47:09 +03:00
: param chat_id : Int or Str : Unique identifier for the target chat or username of the target channel
( in the format @channelusername )
: param message_id : Int : Identifier of a message to pin
: param disable_notification : Bool : Pass True , if it is not necessary to send a notification
to all group members about the new pinned message
: return :
"""
return apihelper . pin_chat_message ( self . token , chat_id , message_id , disable_notification )
2021-06-21 18:39:13 +03:00
def unpin_chat_message ( self , chat_id : Union [ int , str ] , message_id : Optional [ int ] = None ) - > bool :
2017-06-30 19:47:09 +03:00
"""
2020-11-29 14:47:53 +03:00
Use this method to unpin specific pinned message in a supergroup chat .
2017-06-30 19:47:09 +03:00
The bot must be an administrator in the chat for this to work and must have the appropriate admin rights .
Returns True on success .
2022-03-06 17:41:54 +03:00
2022-03-06 21:14:07 +03:00
Telegram documentation : https : / / core . telegram . org / bots / api #unpinchatmessage
2017-06-30 19:47:09 +03:00
: param chat_id : Int or Str : Unique identifier for the target chat or username of the target channel
( in the format @channelusername )
2020-11-29 14:47:53 +03:00
: param message_id : Int : Identifier of a message to unpin
2017-06-30 19:47:09 +03:00
: return :
"""
2020-11-29 15:21:59 +03:00
return apihelper . unpin_chat_message ( self . token , chat_id , message_id )
2017-06-30 19:47:09 +03:00
2021-06-21 18:39:13 +03:00
def unpin_all_chat_messages ( self , chat_id : Union [ int , str ] ) - > bool :
2020-11-29 14:47:53 +03:00
"""
Use this method to unpin a all pinned messages in a supergroup chat .
The bot must be an administrator in the chat for this to work and must have the appropriate admin rights .
Returns True on success .
2022-03-06 17:41:54 +03:00
2022-03-06 21:14:07 +03:00
Telegram documentation : https : / / core . telegram . org / bots / api #unpinallchatmessages
2020-11-29 14:47:53 +03:00
: param chat_id : Int or Str : Unique identifier for the target chat or username of the target channel
( in the format @channelusername )
: return :
"""
2020-11-29 15:21:59 +03:00
return apihelper . unpin_all_chat_messages ( self . token , chat_id )
2020-11-29 14:47:53 +03:00
2021-06-21 18:39:13 +03:00
def edit_message_text (
self , text : str ,
chat_id : Optional [ Union [ int , str ] ] = None ,
message_id : Optional [ int ] = None ,
inline_message_id : Optional [ str ] = None ,
parse_mode : Optional [ str ] = None ,
2021-08-18 18:47:38 +03:00
entities : Optional [ List [ types . MessageEntity ] ] = None ,
disable_web_page_preview : Optional [ bool ] = None ,
2021-06-21 18:39:13 +03:00
reply_markup : Optional [ REPLY_MARKUP_TYPES ] = None ) - > Union [ types . Message , bool ] :
2020-01-08 20:17:25 +03:00
"""
2020-01-08 20:06:40 +03:00
Use this method to edit text and game messages .
2022-03-06 17:41:54 +03:00
2022-03-06 21:14:07 +03:00
Telegram documentation : https : / / core . telegram . org / bots / api #editmessagetext
2020-01-08 20:06:40 +03:00
: param text :
: param chat_id :
: param message_id :
: param inline_message_id :
: param parse_mode :
2021-08-18 18:47:38 +03:00
: param entities :
2020-01-08 20:06:40 +03:00
: param disable_web_page_preview :
: param reply_markup :
: return :
"""
2020-12-09 01:41:07 +03:00
parse_mode = self . parse_mode if ( parse_mode is None ) else parse_mode
2020-07-04 21:07:42 +03:00
2016-04-17 05:24:37 +03:00
result = apihelper . edit_message_text ( self . token , text , chat_id , message_id , inline_message_id , parse_mode ,
2021-08-18 18:47:38 +03:00
entities , disable_web_page_preview , reply_markup )
2016-06-07 14:29:12 +03:00
if type ( result ) == bool : # if edit inline message return is bool not Message.
2016-04-17 05:24:37 +03:00
return result
return types . Message . de_json ( result )
2016-04-14 10:03:07 +03:00
2021-06-21 18:39:13 +03:00
def edit_message_media (
self , media : Any , chat_id : Optional [ Union [ int , str ] ] = None ,
message_id : Optional [ int ] = None ,
inline_message_id : Optional [ str ] = None ,
reply_markup : Optional [ REPLY_MARKUP_TYPES ] = None ) - > Union [ types . Message , bool ] :
2020-01-08 20:17:25 +03:00
"""
2021-06-19 18:59:55 +03:00
Use this method to edit animation , audio , document , photo , or video messages .
If a message is a part of a message album , then it can be edited only to a photo or a video .
Otherwise , message type can be changed arbitrarily . When inline message is edited , new file can ' t be uploaded.
Use previously uploaded file via its file_id or specify a URL .
2022-03-06 17:41:54 +03:00
2022-03-06 21:14:07 +03:00
Telegram documentation : https : / / core . telegram . org / bots / api #editmessagemedia
2020-01-08 20:06:40 +03:00
: param media :
: param chat_id :
: param message_id :
: param inline_message_id :
: param reply_markup :
: return :
"""
2018-08-09 19:10:01 +03:00
result = apihelper . edit_message_media ( self . token , media , chat_id , message_id , inline_message_id , reply_markup )
if type ( result ) == bool : # if edit inline message return is bool not Message.
return result
return types . Message . de_json ( result )
2021-06-21 18:39:13 +03:00
def edit_message_reply_markup (
self , chat_id : Optional [ Union [ int , str ] ] = None ,
message_id : Optional [ int ] = None ,
inline_message_id : Optional [ str ] = None ,
reply_markup : Optional [ REPLY_MARKUP_TYPES ] = None ) - > Union [ types . Message , bool ] :
2020-01-08 20:17:25 +03:00
"""
2020-01-08 20:06:40 +03:00
Use this method to edit only the reply markup of messages .
2022-03-06 17:41:54 +03:00
2022-03-06 21:14:07 +03:00
Telegram documentation : https : / / core . telegram . org / bots / api #editmessagereplymarkup
2020-01-08 20:06:40 +03:00
: param chat_id :
: param message_id :
: param inline_message_id :
: param reply_markup :
: return :
"""
2016-08-29 15:50:27 +03:00
result = apihelper . edit_message_reply_markup ( self . token , chat_id , message_id , inline_message_id , reply_markup )
if type ( result ) == bool :
return result
return types . Message . de_json ( result )
2016-04-14 10:17:53 +03:00
2020-05-16 17:34:56 +03:00
def send_game (
2021-06-21 18:39:13 +03:00
self , chat_id : Union [ int , str ] , game_short_name : str ,
disable_notification : Optional [ bool ] = None ,
reply_to_message_id : Optional [ int ] = None ,
reply_markup : Optional [ REPLY_MARKUP_TYPES ] = None ,
timeout : Optional [ int ] = None ,
2021-12-31 14:05:40 +03:00
allow_sending_without_reply : Optional [ bool ] = None ,
protect_content : Optional [ bool ] = None ) - > types . Message :
2020-01-08 20:17:25 +03:00
"""
2022-03-06 21:14:07 +03:00
Used to send the game .
Telegram documentation : https : / / core . telegram . org / bots / api #sendgame
2022-03-06 17:41:54 +03:00
2020-01-08 20:06:40 +03:00
: param chat_id :
: param game_short_name :
: param disable_notification :
: param reply_to_message_id :
: param reply_markup :
2020-08-25 18:18:51 +03:00
: param timeout :
2021-06-21 18:39:13 +03:00
: param allow_sending_without_reply :
2021-12-31 14:05:40 +03:00
: param protect_content :
2020-01-08 20:06:40 +03:00
: return :
"""
2020-05-16 17:34:56 +03:00
result = apihelper . send_game (
self . token , chat_id , game_short_name , disable_notification ,
2021-06-21 18:39:13 +03:00
reply_to_message_id , reply_markup , timeout ,
2021-12-31 14:05:40 +03:00
allow_sending_without_reply , protect_content )
2016-10-08 15:36:48 +03:00
return types . Message . de_json ( result )
2021-06-21 18:39:13 +03:00
def set_game_score (
self , user_id : Union [ int , str ] , score : int ,
force : Optional [ bool ] = None ,
chat_id : Optional [ Union [ int , str ] ] = None ,
message_id : Optional [ int ] = None ,
inline_message_id : Optional [ str ] = None ,
disable_edit_message : Optional [ bool ] = None ) - > Union [ types . Message , bool ] :
2020-01-08 20:17:25 +03:00
"""
2022-03-06 17:41:54 +03:00
Sets the value of points in the game to a specific user .
2022-03-06 21:14:07 +03:00
Telegram documentation : https : / / core . telegram . org / bots / api #setgamecore
2020-01-08 20:06:40 +03:00
: param user_id :
: param score :
: param force :
: param chat_id :
: param message_id :
: param inline_message_id :
2021-06-01 06:39:09 +03:00
: param disable_edit_message :
2020-01-08 20:06:40 +03:00
: return :
"""
2021-06-19 18:59:55 +03:00
result = apihelper . set_game_score ( self . token , user_id , score , force , disable_edit_message , chat_id ,
message_id , inline_message_id )
2016-10-29 16:22:46 +03:00
if type ( result ) == bool :
return result
return types . Message . de_json ( result )
2021-06-21 18:39:13 +03:00
def get_game_high_scores (
self , user_id : int , chat_id : Optional [ Union [ int , str ] ] = None ,
message_id : Optional [ int ] = None ,
inline_message_id : Optional [ str ] = None ) - > List [ types . GameHighScore ] :
2020-01-08 20:17:25 +03:00
"""
2022-03-06 21:14:07 +03:00
Gets top points and game play .
Telegram documentation : https : / / core . telegram . org / bots / api #getgamehighscores
2022-03-06 17:41:54 +03:00
2020-01-08 20:06:40 +03:00
: param user_id :
: param chat_id :
: param message_id :
: param inline_message_id :
: return :
"""
2016-10-29 16:22:46 +03:00
result = apihelper . get_game_high_scores ( self . token , user_id , chat_id , message_id , inline_message_id )
2021-07-19 20:01:37 +03:00
return [ types . GameHighScore . de_json ( r ) for r in result ]
2016-10-29 16:22:46 +03:00
2021-12-31 14:05:40 +03:00
# TODO: rewrite this method like in API
2021-06-21 18:39:13 +03:00
def send_invoice (
self , chat_id : Union [ int , str ] , title : str , description : str ,
invoice_payload : str , provider_token : str , currency : str ,
prices : List [ types . LabeledPrice ] , start_parameter : Optional [ str ] = None ,
photo_url : Optional [ str ] = None , photo_size : Optional [ int ] = None ,
photo_width : Optional [ int ] = None , photo_height : Optional [ int ] = None ,
need_name : Optional [ bool ] = None , need_phone_number : Optional [ bool ] = None ,
need_email : Optional [ bool ] = None , need_shipping_address : Optional [ bool ] = None ,
send_phone_number_to_provider : Optional [ bool ] = None ,
send_email_to_provider : Optional [ bool ] = None ,
is_flexible : Optional [ bool ] = None ,
disable_notification : Optional [ bool ] = None ,
reply_to_message_id : Optional [ int ] = None ,
reply_markup : Optional [ REPLY_MARKUP_TYPES ] = None ,
provider_data : Optional [ str ] = None ,
timeout : Optional [ int ] = None ,
2021-07-15 08:56:04 +03:00
allow_sending_without_reply : Optional [ bool ] = None ,
2021-07-15 09:27:07 +03:00
max_tip_amount : Optional [ int ] = None ,
2021-12-31 14:05:40 +03:00
suggested_tip_amounts : Optional [ List [ int ] ] = None ,
protect_content : Optional [ bool ] = None ) - > types . Message :
2020-01-08 20:17:25 +03:00
"""
2022-03-06 17:41:54 +03:00
Sends invoice .
2022-03-06 21:14:07 +03:00
Telegram documentation : https : / / core . telegram . org / bots / api #sendinvoice
2020-07-21 01:20:01 +03:00
: param chat_id : Unique identifier for the target private chat
: param title : Product name
: param description : Product description
2021-06-19 18:59:55 +03:00
: param invoice_payload : Bot - defined invoice payload , 1 - 128 bytes . This will not be displayed to the user ,
use for your internal processes .
2020-07-21 01:20:01 +03:00
: param provider_token : Payments provider token , obtained via @Botfather
2021-06-19 18:59:55 +03:00
: param currency : Three - letter ISO 4217 currency code ,
see https : / / core . telegram . org / bots / payments #supported-currencies
: param prices : Price breakdown , a list of components
( e . g . product price , tax , discount , delivery cost , delivery tax , bonus , etc . )
: param start_parameter : Unique deep - linking parameter that can be used to generate this invoice
when used as a start parameter
: param photo_url : URL of the product photo for the invoice . Can be a photo of the goods
or a marketing image for a service . People like it better when they see what they are paying for .
2020-07-21 01:20:01 +03:00
: param photo_size : Photo size
: param photo_width : Photo width
: param photo_height : Photo height
: param need_name : Pass True , if you require the user ' s full name to complete the order
: param need_phone_number : Pass True , if you require the user ' s phone number to complete the order
: param need_email : Pass True , if you require the user ' s email to complete the order
: param need_shipping_address : Pass True , if you require the user ' s shipping address to complete the order
: param is_flexible : Pass True , if the final price depends on the shipping method
: param send_phone_number_to_provider : Pass True , if user ' s phone number should be sent to provider
: param send_email_to_provider : Pass True , if user ' s email address should be sent to provider
: param disable_notification : Sends the message silently . Users will receive a notification with no sound .
: param reply_to_message_id : If the message is a reply , ID of the original message
2021-06-19 18:59:55 +03:00
: param reply_markup : A JSON - serialized object for an inline keyboard . If empty ,
one ' Pay total price ' button will be shown . If not empty , the first button must be a Pay button
: param provider_data : A JSON - serialized data about the invoice , which will be shared with the payment provider .
A detailed description of required fields should be provided by the payment provider .
2020-08-25 18:18:51 +03:00
: param timeout :
2021-06-21 18:39:13 +03:00
: param allow_sending_without_reply :
2021-07-15 08:56:04 +03:00
: param max_tip_amount : The maximum accepted amount for tips in the smallest units of the currency
: param suggested_tip_amounts : A JSON - serialized array of suggested amounts of tips in the smallest
units of the currency . At most 4 suggested tip amounts can be specified . The suggested tip
amounts must be positive , passed in a strictly increased order and must not exceed max_tip_amount .
2021-12-31 14:05:40 +03:00
: param protect_content :
2020-01-08 20:06:40 +03:00
: return :
"""
2020-05-16 17:34:56 +03:00
result = apihelper . send_invoice (
self . token , chat_id , title , description , invoice_payload , provider_token ,
currency , prices , start_parameter , photo_url , photo_size , photo_width ,
photo_height , need_name , need_phone_number , need_email , need_shipping_address ,
2020-07-21 01:20:01 +03:00
send_phone_number_to_provider , send_email_to_provider , is_flexible , disable_notification ,
2021-07-15 08:56:04 +03:00
reply_to_message_id , reply_markup , provider_data , timeout , allow_sending_without_reply ,
2021-12-31 14:05:40 +03:00
max_tip_amount , suggested_tip_amounts , protect_content )
2017-05-25 05:56:58 +03:00
return types . Message . de_json ( result )
2021-08-18 18:52:09 +03:00
# noinspection PyShadowingBuiltins
2021-12-31 14:05:40 +03:00
# TODO: rewrite this method like in API
2020-05-02 13:09:52 +03:00
def send_poll (
2021-06-21 18:39:13 +03:00
self , chat_id : Union [ int , str ] , question : str , options : List [ str ] ,
is_anonymous : Optional [ bool ] = None , type : Optional [ str ] = None ,
allows_multiple_answers : Optional [ bool ] = None ,
correct_option_id : Optional [ int ] = None ,
explanation : Optional [ str ] = None ,
explanation_parse_mode : Optional [ str ] = None ,
open_period : Optional [ int ] = None ,
close_date : Optional [ Union [ int , datetime ] ] = None ,
is_closed : Optional [ bool ] = None ,
2021-08-18 19:36:48 +03:00
disable_notification : Optional [ bool ] = False ,
2021-06-21 18:39:13 +03:00
reply_to_message_id : Optional [ int ] = None ,
reply_markup : Optional [ REPLY_MARKUP_TYPES ] = None ,
allow_sending_without_reply : Optional [ bool ] = None ,
timeout : Optional [ int ] = None ,
2021-12-31 14:05:40 +03:00
explanation_entities : Optional [ List [ types . MessageEntity ] ] = None ,
protect_content : Optional [ bool ] = None ) - > types . Message :
2020-05-02 13:09:52 +03:00
"""
2022-03-06 17:41:54 +03:00
Sends a poll .
2022-03-06 21:14:07 +03:00
Telegram documentation : https : / / core . telegram . org / bots / api #sendpoll
2020-01-08 20:06:40 +03:00
: param chat_id :
2020-05-02 13:09:52 +03:00
: param question :
2020-05-02 13:27:39 +03:00
: param options : array of str with answers
2020-05-02 13:09:52 +03:00
: param is_anonymous :
: param type :
: param allows_multiple_answers :
: param correct_option_id :
: param explanation :
: param explanation_parse_mode :
: param open_period :
: param close_date :
: param is_closed :
2021-08-18 19:36:48 +03:00
: param disable_notification :
2020-05-02 13:09:52 +03:00
: param reply_to_message_id :
2021-06-21 18:39:13 +03:00
: param allow_sending_without_reply :
2020-01-08 20:06:40 +03:00
: param reply_markup :
2020-08-25 18:18:51 +03:00
: param timeout :
2021-06-21 18:39:13 +03:00
: param explanation_entities :
2021-12-31 14:05:40 +03:00
: param protect_content :
2020-01-08 20:06:40 +03:00
: return :
"""
2020-05-02 13:09:52 +03:00
if isinstance ( question , types . Poll ) :
2020-12-24 19:55:24 +03:00
raise RuntimeError ( " The send_poll signature was changed, please see send_poll function details. " )
2020-05-02 13:09:52 +03:00
return types . Message . de_json (
apihelper . send_poll (
self . token , chat_id ,
question , options ,
is_anonymous , type , allows_multiple_answers , correct_option_id ,
explanation , explanation_parse_mode , open_period , close_date , is_closed ,
2021-08-18 19:36:48 +03:00
disable_notification , reply_to_message_id , allow_sending_without_reply ,
2021-12-31 14:05:40 +03:00
reply_markup , timeout , explanation_entities , protect_content ) )
2019-06-06 21:47:08 +03:00
2021-06-21 18:39:13 +03:00
def stop_poll (
self , chat_id : Union [ int , str ] , message_id : int ,
reply_markup : Optional [ REPLY_MARKUP_TYPES ] = None ) - > types . Poll :
2020-01-08 20:17:25 +03:00
"""
2022-03-06 17:41:54 +03:00
Stops a poll .
2022-03-06 21:14:07 +03:00
Telegram documentation : https : / / core . telegram . org / bots / api #stoppoll
2020-01-08 20:06:40 +03:00
: param chat_id :
: param message_id :
2020-08-25 18:18:51 +03:00
: param reply_markup :
2020-01-08 20:06:40 +03:00
: return :
"""
2020-08-25 18:18:51 +03:00
return types . Poll . de_json ( apihelper . stop_poll ( self . token , chat_id , message_id , reply_markup ) )
2019-06-06 21:47:08 +03:00
2021-06-21 18:39:13 +03:00
def answer_shipping_query (
self , shipping_query_id : str , ok : bool ,
shipping_options : Optional [ List [ types . ShippingOption ] ] = None ,
error_message : Optional [ str ] = None ) - > bool :
2020-01-08 20:17:25 +03:00
"""
2022-03-06 17:41:54 +03:00
Asks for an answer to a shipping question .
2022-03-06 21:14:07 +03:00
Telegram documentation : https : / / core . telegram . org / bots / api #answershippingquery
2020-01-08 20:06:40 +03:00
: param shipping_query_id :
: param ok :
: param shipping_options :
: param error_message :
: return :
"""
2017-06-02 11:07:35 +03:00
return apihelper . answer_shipping_query ( self . token , shipping_query_id , ok , shipping_options , error_message )
2017-05-25 05:56:58 +03:00
2021-06-21 18:39:13 +03:00
def answer_pre_checkout_query (
self , pre_checkout_query_id : int , ok : bool ,
error_message : Optional [ str ] = None ) - > bool :
2020-01-08 20:17:25 +03:00
"""
2022-03-06 17:41:54 +03:00
Response to a request for pre - inspection .
2022-03-06 21:14:07 +03:00
Telegram documentation : https : / / core . telegram . org / bots / api #answerprecheckoutquery
2020-01-08 20:17:25 +03:00
: param pre_checkout_query_id :
: param ok :
: param error_message :
: return :
2021-06-19 18:59:55 +03:00
"""
2017-05-25 05:56:58 +03:00
return apihelper . answer_pre_checkout_query ( self . token , pre_checkout_query_id , ok , error_message )
2021-06-21 18:39:13 +03:00
def edit_message_caption (
self , caption : str , chat_id : Optional [ Union [ int , str ] ] = None ,
message_id : Optional [ int ] = None ,
inline_message_id : Optional [ str ] = None ,
2021-07-28 21:10:15 +03:00
parse_mode : Optional [ str ] = None ,
2021-07-28 21:06:31 +03:00
caption_entities : Optional [ List [ types . MessageEntity ] ] = None ,
2021-06-21 18:39:13 +03:00
reply_markup : Optional [ REPLY_MARKUP_TYPES ] = None ) - > Union [ types . Message , bool ] :
2020-01-08 20:17:25 +03:00
"""
2022-03-06 17:41:54 +03:00
Use this method to edit captions of messages .
2022-03-06 21:14:07 +03:00
Telegram documentation : https : / / core . telegram . org / bots / api #editmessagecaption
2020-01-08 20:06:40 +03:00
: param caption :
: param chat_id :
: param message_id :
: param inline_message_id :
: param parse_mode :
2021-08-18 18:47:38 +03:00
: param caption_entities :
2020-01-08 20:06:40 +03:00
: param reply_markup :
: return :
"""
2020-12-09 01:41:07 +03:00
parse_mode = self . parse_mode if ( parse_mode is None ) else parse_mode
2020-08-21 17:36:08 +03:00
2016-10-08 15:36:48 +03:00
result = apihelper . edit_message_caption ( self . token , caption , chat_id , message_id , inline_message_id ,
2021-07-30 17:15:37 +03:00
parse_mode , caption_entities , reply_markup )
2016-08-29 15:50:27 +03:00
if type ( result ) == bool :
2016-08-29 15:21:56 +03:00
return result
2016-08-29 15:50:27 +03:00
return types . Message . de_json ( result )
2016-04-14 10:17:53 +03:00
2021-06-21 18:39:13 +03:00
def reply_to ( self , message : types . Message , text : str , * * kwargs ) - > types . Message :
2015-07-24 14:44:01 +03:00
"""
Convenience function for ` send_message ( message . chat . id , text , reply_to_message_id = message . message_id , * * kwargs ) `
2022-03-06 17:41:54 +03:00
2021-06-19 18:59:55 +03:00
: param message :
2020-01-08 20:06:40 +03:00
: param text :
: param kwargs :
: return :
2015-07-24 14:44:01 +03:00
"""
2015-07-03 00:38:11 +03:00
return self . send_message ( message . chat . id , text , reply_to_message_id = message . message_id , * * kwargs )
2021-06-21 18:39:13 +03:00
def answer_inline_query (
self , inline_query_id : str ,
results : List [ Any ] ,
cache_time : Optional [ int ] = None ,
is_personal : Optional [ bool ] = None ,
next_offset : Optional [ str ] = None ,
switch_pm_text : Optional [ str ] = None ,
switch_pm_parameter : Optional [ str ] = None ) - > bool :
2016-01-06 09:31:21 +03:00
"""
Use this method to send answers to an inline query . On success , True is returned .
No more than 50 results per query are allowed .
2022-03-06 17:41:54 +03:00
2022-03-06 21:14:07 +03:00
Telegram documentation : https : / / core . telegram . org / bots / api #answerinlinequery
2016-01-06 09:31:21 +03:00
: param inline_query_id : Unique identifier for the answered query
: param results : Array of results for the inline query
2021-06-19 18:59:55 +03:00
: param cache_time : The maximum amount of time in seconds that the result of the inline query
may be cached on the server .
: param is_personal : Pass True , if results may be cached on the server side only for
the user that sent the query .
: param next_offset : Pass the offset that a client should send in the next query with the same text
to receive more results .
2016-04-14 10:32:08 +03:00
: param switch_pm_parameter : If passed , clients will display a button with specified text that switches the user
2021-06-19 18:59:55 +03:00
to a private chat with the bot and sends the bot a start message with the parameter switch_pm_parameter
2016-04-14 10:32:08 +03:00
: param switch_pm_text : Parameter for the start message sent to the bot when user presses the switch button
2016-01-06 09:31:21 +03:00
: return : True means success .
"""
2016-04-14 10:32:08 +03:00
return apihelper . answer_inline_query ( self . token , inline_query_id , results , cache_time , is_personal , next_offset ,
switch_pm_text , switch_pm_parameter )
2016-01-05 09:07:47 +03:00
2021-06-21 18:39:13 +03:00
def answer_callback_query (
2021-07-10 22:03:31 +03:00
self , callback_query_id : int ,
2021-06-21 18:39:13 +03:00
text : Optional [ str ] = None , show_alert : Optional [ bool ] = None ,
url : Optional [ str ] = None , cache_time : Optional [ int ] = None ) - > bool :
2016-04-16 09:53:41 +03:00
"""
Use this method to send answers to callback queries sent from inline keyboards . The answer will be displayed to
the user as a notification at the top of the chat screen or as an alert .
2022-03-06 17:41:54 +03:00
2022-03-06 21:14:07 +03:00
Telegram documentation : https : / / core . telegram . org / bots / api #answercallbackquery
2016-04-16 09:53:41 +03:00
: param callback_query_id :
: param text :
: param show_alert :
2020-01-08 20:06:40 +03:00
: param url :
: param cache_time :
2016-04-16 09:53:41 +03:00
: return :
"""
2016-12-03 08:38:30 +03:00
return apihelper . answer_callback_query ( self . token , callback_query_id , text , show_alert , url , cache_time )
2016-04-16 09:53:41 +03:00
2021-06-21 18:39:13 +03:00
def set_sticker_set_thumb (
self , name : str , user_id : int , thumb : Union [ Any , str ] = None ) :
"""
Use this method to set the thumbnail of a sticker set .
Animated thumbnails can be set for animated sticker sets only . Returns True on success .
2022-03-06 17:41:54 +03:00
2022-03-06 21:14:07 +03:00
Telegram documentation : https : / / core . telegram . org / bots / api #setstickersetthumb
2022-03-06 17:41:54 +03:00
: param name : Sticker set name
: param user_id : User identifier
: param thumb :
2021-06-21 18:39:13 +03:00
"""
return apihelper . set_sticker_set_thumb ( self . token , name , user_id , thumb )
def get_sticker_set ( self , name : str ) - > types . StickerSet :
2017-08-06 09:25:25 +03:00
"""
Use this method to get a sticker set . On success , a StickerSet object is returned .
2022-03-06 17:41:54 +03:00
2022-03-06 21:14:07 +03:00
Telegram documentation : https : / / core . telegram . org / bots / api #getstickerset
2017-08-06 09:25:25 +03:00
: param name :
: return :
"""
result = apihelper . get_sticker_set ( self . token , name )
return types . StickerSet . de_json ( result )
2021-06-21 18:39:13 +03:00
def upload_sticker_file ( self , user_id : int , png_sticker : Union [ Any , str ] ) - > types . File :
2017-08-06 09:25:25 +03:00
"""
Use this method to upload a . png file with a sticker for later use in createNewStickerSet and addStickerToSet
methods ( can be used multiple times ) . Returns the uploaded File on success .
2022-03-06 17:41:54 +03:00
2022-03-06 21:14:07 +03:00
Telegram documentation : https : / / core . telegram . org / bots / api #uploadstickerfile
2017-08-06 09:25:25 +03:00
: param user_id :
: param png_sticker :
: return :
"""
result = apihelper . upload_sticker_file ( self . token , user_id , png_sticker )
return types . File . de_json ( result )
2021-06-21 18:39:13 +03:00
def create_new_sticker_set (
self , user_id : int , name : str , title : str ,
emojis : str ,
2022-02-01 13:47:42 +03:00
png_sticker : Union [ Any , str ] = None ,
tgs_sticker : Union [ Any , str ] = None ,
webm_sticker : Union [ Any , str ] = None ,
2021-06-21 20:59:39 +03:00
contains_masks : Optional [ bool ] = None ,
mask_position : Optional [ types . MaskPosition ] = None ) - > bool :
"""
Use this method to create new sticker set owned by a user .
The bot will be able to edit the created sticker set .
Returns True on success .
2022-03-06 17:41:54 +03:00
2022-03-06 21:14:07 +03:00
Telegram documentation : https : / / core . telegram . org / bots / api #createnewstickerset
2021-06-21 20:59:39 +03:00
: param user_id :
: param name :
: param title :
: param emojis :
2021-06-22 16:57:34 +03:00
: param png_sticker :
: param tgs_sticker :
2022-02-01 13:47:42 +03:00
: param webm_sticker :
2021-06-21 20:59:39 +03:00
: param contains_masks :
: param mask_position :
: return :
"""
return apihelper . create_new_sticker_set (
2021-06-22 16:57:34 +03:00
self . token , user_id , name , title , emojis , png_sticker , tgs_sticker ,
2022-02-01 13:47:42 +03:00
contains_masks , mask_position , webm_sticker )
2021-06-21 20:59:39 +03:00
2021-06-22 16:57:34 +03:00
def add_sticker_to_set (
self , user_id : int , name : str , emojis : str ,
png_sticker : Optional [ Union [ Any , str ] ] = None ,
tgs_sticker : Optional [ Union [ Any , str ] ] = None ,
2022-02-01 13:47:42 +03:00
webm_sticker : Optional [ Union [ Any , str ] ] = None ,
2021-06-22 16:57:34 +03:00
mask_position : Optional [ types . MaskPosition ] = None ) - > bool :
2021-06-21 20:59:39 +03:00
"""
2021-06-22 16:57:34 +03:00
Use this method to add a new sticker to a set created by the bot .
It ' s required to pass `png_sticker` or `tgs_sticker`.
Returns True on success .
2022-03-06 17:41:54 +03:00
2022-03-06 21:14:07 +03:00
Telegram documentation : https : / / core . telegram . org / bots / api #addstickertoset
2021-06-21 20:59:39 +03:00
: param user_id :
: param name :
: param emojis :
2021-06-22 16:57:34 +03:00
: param png_sticker : Required if ` tgs_sticker ` is None
: param tgs_sticker : Required if ` png_sticker ` is None
2022-02-19 21:39:52 +03:00
: param webm_sticker :
2021-06-21 20:59:39 +03:00
: param mask_position :
: return :
"""
return apihelper . add_sticker_to_set (
2022-02-01 13:47:42 +03:00
self . token , user_id , name , emojis , png_sticker , tgs_sticker , mask_position , webm_sticker )
2021-06-21 20:59:39 +03:00
2021-06-21 18:39:13 +03:00
def set_sticker_position_in_set ( self , sticker : str , position : int ) - > bool :
2017-08-06 09:25:25 +03:00
"""
Use this method to move a sticker in a set created by the bot to a specific position . Returns True on success .
2022-03-06 17:41:54 +03:00
2022-03-06 21:14:07 +03:00
Telegram documentation : https : / / core . telegram . org / bots / api #setstickerpositioninset
2017-08-06 09:25:25 +03:00
: param sticker :
: param position :
: return :
"""
return apihelper . set_sticker_position_in_set ( self . token , sticker , position )
2021-06-21 18:39:13 +03:00
def delete_sticker_from_set ( self , sticker : str ) - > bool :
2017-08-06 09:25:25 +03:00
"""
Use this method to delete a sticker from a set created by the bot . Returns True on success .
2022-03-06 17:41:54 +03:00
2022-03-06 21:14:07 +03:00
Telegram documentation : https : / / core . telegram . org / bots / api #deletestickerfromset
2017-08-06 09:25:25 +03:00
: param sticker :
: return :
"""
return apihelper . delete_sticker_from_set ( self . token , sticker )
2021-06-21 18:39:13 +03:00
def register_for_reply (
self , message : types . Message , callback : Callable , * args , * * kwargs ) - > None :
2015-07-24 14:44:01 +03:00
"""
Registers a callback function to be notified when a reply to ` message ` arrives .
2018-05-27 17:01:07 +03:00
Warning : In case ` callback ` as lambda function , saving reply handlers will not work .
2015-07-24 14:44:01 +03:00
: param message : The message for which we are awaiting a reply .
: param callback : The callback function to be called when a reply arrives . Must accept one ` message `
parameter , which will contain the replied message .
"""
2018-04-12 13:45:32 +03:00
message_id = message . message_id
self . register_for_reply_by_message_id ( message_id , callback , * args , * * kwargs )
2015-07-24 14:44:01 +03:00
2021-06-21 18:39:13 +03:00
def register_for_reply_by_message_id (
self , message_id : int , callback : Callable , * args , * * kwargs ) - > None :
2018-04-12 13:45:32 +03:00
"""
Registers a callback function to be notified when a reply to ` message ` arrives .
2015-07-24 14:44:01 +03:00
2018-05-27 17:01:07 +03:00
Warning : In case ` callback ` as lambda function , saving reply handlers will not work .
2015-07-24 14:44:01 +03:00
2018-05-27 17:02:04 +03:00
: param message_id : The id of the message for which we are awaiting a reply .
2018-04-12 13:45:32 +03:00
: param callback : The callback function to be called when a reply arrives . Must accept one ` message `
parameter , which will contain the replied message .
"""
2020-04-12 20:41:32 +03:00
self . reply_backend . register_handler ( message_id , Handler ( callback , * args , * * kwargs ) )
2015-07-24 14:44:01 +03:00
2021-06-17 21:28:53 +03:00
def _notify_reply_handlers ( self , new_messages ) - > None :
2020-01-08 20:06:40 +03:00
"""
Notify handlers of the answers
2022-03-06 17:41:54 +03:00
2020-01-08 20:06:40 +03:00
: param new_messages :
: return :
"""
2018-04-12 13:45:32 +03:00
for message in new_messages :
if hasattr ( message , " reply_to_message " ) and message . reply_to_message is not None :
2020-04-12 20:41:32 +03:00
handlers = self . reply_backend . get_handlers ( message . reply_to_message . message_id )
2020-08-24 16:02:35 +03:00
if handlers :
for handler in handlers :
self . _exec_task ( handler [ " callback " ] , message , * handler [ " args " ] , * * handler [ " kwargs " ] )
2018-04-12 13:45:32 +03:00
2021-06-21 18:39:13 +03:00
def register_next_step_handler (
self , message : types . Message , callback : Callable , * args , * * kwargs ) - > None :
2015-07-30 06:02:08 +03:00
"""
Registers a callback function to be notified when new message arrives after ` message ` .
2018-05-27 17:01:07 +03:00
Warning : In case ` callback ` as lambda function , saving next step handlers will not work .
2018-04-12 13:45:32 +03:00
: param message : The message for which we want to handle new message in the same chat .
2015-07-30 06:02:08 +03:00
: param callback : The callback function which next new message arrives .
2018-04-12 13:45:32 +03:00
: param args : Args to pass in callback func
: param kwargs : Args to pass in callback func
2015-07-30 06:02:08 +03:00
"""
chat_id = message . chat . id
2018-04-12 13:45:32 +03:00
self . register_next_step_handler_by_chat_id ( chat_id , callback , * args , * * kwargs )
2022-03-06 16:39:41 +03:00
def setup_middleware ( self , middleware : BaseMiddleware ) :
"""
Register middleware
2022-03-06 17:41:54 +03:00
2022-03-06 16:39:41 +03:00
: param middleware : Subclass of ` telebot . handler_backends . BaseMiddleware `
: return : None
"""
if not self . use_class_middlewares :
logger . warning ( ' Middleware is not enabled. Pass use_class_middlewares=True to enable it. ' )
return
self . middlewares . append ( middleware )
2022-01-24 16:15:04 +03:00
def set_state ( self , user_id : int , state : Union [ int , str ] , chat_id : int = None ) - > None :
2021-09-25 15:12:32 +03:00
"""
Sets a new state of a user .
2022-03-06 17:41:54 +03:00
2022-01-24 22:38:35 +03:00
: param user_id :
2021-09-25 15:12:32 +03:00
: param state : new state . can be string or integer .
2022-01-24 22:38:35 +03:00
: param chat_id :
2021-09-25 15:12:32 +03:00
"""
2022-01-24 16:15:04 +03:00
if chat_id is None :
chat_id = user_id
self . current_states . set_state ( chat_id , user_id , state )
2021-09-25 15:12:32 +03:00
2022-01-24 16:15:04 +03:00
def reset_data ( self , user_id : int , chat_id : int = None ) :
"""
Reset data for a user in chat .
2022-03-06 17:41:54 +03:00
2022-01-24 16:15:04 +03:00
: param user_id :
: param chat_id :
"""
if chat_id is None :
chat_id = user_id
2022-01-24 22:38:35 +03:00
2022-01-24 16:15:04 +03:00
self . current_states . reset_data ( chat_id , user_id )
def delete_state ( self , user_id : int , chat_id : int = None ) - > None :
2021-09-25 15:12:32 +03:00
"""
Delete the current state of a user .
2022-03-06 17:41:54 +03:00
2022-01-24 22:38:35 +03:00
: param user_id :
2021-09-25 15:12:32 +03:00
: param chat_id :
: return :
"""
2022-01-24 16:15:04 +03:00
if chat_id is None :
chat_id = user_id
self . current_states . delete_state ( chat_id , user_id )
2021-09-25 15:12:32 +03:00
2022-01-24 16:15:04 +03:00
def retrieve_data ( self , user_id : int , chat_id : int = None ) - > Optional [ Union [ int , str ] ] :
if chat_id is None :
chat_id = user_id
return self . current_states . get_interactive_data ( chat_id , user_id )
2021-10-01 13:56:54 +03:00
2022-01-24 16:15:04 +03:00
def get_state ( self , user_id : int , chat_id : int = None ) - > Optional [ Union [ int , str ] ] :
2021-09-25 15:12:32 +03:00
"""
Get current state of a user .
2022-03-06 17:41:54 +03:00
2022-01-24 22:38:35 +03:00
: param user_id :
2021-09-25 15:12:32 +03:00
: param chat_id :
: return : state of a user
"""
2022-01-24 16:15:04 +03:00
if chat_id is None :
chat_id = user_id
return self . current_states . get_state ( chat_id , user_id )
2021-09-25 15:12:32 +03:00
2022-01-24 16:15:04 +03:00
def add_data ( self , user_id : int , chat_id : int = None , * * kwargs ) :
2021-10-01 13:56:54 +03:00
"""
Add data to states .
2022-03-06 17:41:54 +03:00
2022-01-24 22:38:35 +03:00
: param user_id :
2021-10-01 13:56:54 +03:00
: param chat_id :
"""
2022-01-24 16:15:04 +03:00
if chat_id is None :
chat_id = user_id
2021-10-01 13:56:54 +03:00
for key , value in kwargs . items ( ) :
2022-01-24 16:15:04 +03:00
self . current_states . set_data ( chat_id , user_id , key , value )
2021-10-01 13:56:54 +03:00
2021-06-21 18:39:13 +03:00
def register_next_step_handler_by_chat_id (
self , chat_id : Union [ int , str ] , callback : Callable , * args , * * kwargs ) - > None :
2018-04-12 13:45:32 +03:00
"""
Registers a callback function to be notified when new message arrives after ` message ` .
2018-05-27 17:01:07 +03:00
Warning : In case ` callback ` as lambda function , saving next step handlers will not work .
2018-04-12 13:45:32 +03:00
: param chat_id : The chat for which we want to handle new message .
: param callback : The callback function which next new message arrives .
: param args : Args to pass in callback func
: param kwargs : Args to pass in callback func
"""
2020-04-12 20:41:32 +03:00
self . next_step_backend . register_handler ( chat_id , Handler ( callback , * args , * * kwargs ) )
2017-11-29 08:53:39 +03:00
2021-06-21 18:39:13 +03:00
def clear_step_handler ( self , message : types . Message ) - > None :
2017-08-21 13:10:47 +03:00
"""
Clears all callback functions registered by register_next_step_handler ( ) .
: param message : The message for which we want to handle new message after that in same chat .
"""
chat_id = message . chat . id
2018-04-12 13:45:32 +03:00
self . clear_step_handler_by_chat_id ( chat_id )
2015-07-30 06:02:08 +03:00
2021-06-21 18:39:13 +03:00
def clear_step_handler_by_chat_id ( self , chat_id : Union [ int , str ] ) - > None :
2018-04-12 13:45:32 +03:00
"""
Clears all callback functions registered by register_next_step_handler ( ) .
: param chat_id : The chat for which we want to clear next step handlers
"""
2020-04-12 20:41:32 +03:00
self . next_step_backend . clear_handlers ( chat_id )
2018-05-20 23:40:25 +03:00
2021-06-21 18:39:13 +03:00
def clear_reply_handlers ( self , message : types . Message ) - > None :
2018-04-12 13:45:32 +03:00
"""
Clears all callback functions registered by register_for_reply ( ) and register_for_reply_by_message_id ( ) .
2018-05-19 00:42:06 +03:00
: param message : The message for which we want to clear reply handlers
2018-04-12 13:45:32 +03:00
"""
message_id = message . message_id
self . clear_reply_handlers_by_message_id ( message_id )
2021-06-21 18:39:13 +03:00
def clear_reply_handlers_by_message_id ( self , message_id : int ) - > None :
2018-04-12 13:45:32 +03:00
"""
Clears all callback functions registered by register_for_reply ( ) and register_for_reply_by_message_id ( ) .
: param message_id : The message id for which we want to clear reply handlers
"""
2020-04-12 20:41:32 +03:00
self . reply_backend . clear_handlers ( message_id )
2018-05-20 23:40:25 +03:00
2018-04-12 13:45:32 +03:00
def _notify_next_handlers ( self , new_messages ) :
2020-01-08 20:06:40 +03:00
"""
Description : TBD
2022-03-06 17:41:54 +03:00
2020-01-08 20:06:40 +03:00
: param new_messages :
: return :
"""
2020-04-12 20:41:32 +03:00
for i , message in enumerate ( new_messages ) :
need_pop = False
handlers = self . next_step_backend . get_handlers ( message . chat . id )
2020-08-24 16:02:35 +03:00
if handlers :
for handler in handlers :
need_pop = True
self . _exec_task ( handler [ " callback " ] , message , * handler [ " args " ] , * * handler [ " kwargs " ] )
2020-04-12 20:41:32 +03:00
if need_pop :
2022-01-24 22:38:35 +03:00
# removing message that was detected with next_step_handler
new_messages . pop ( i )
2021-09-25 15:12:32 +03:00
2018-04-12 13:45:32 +03:00
@staticmethod
2022-01-24 16:15:04 +03:00
def _build_handler_dict ( handler , pass_bot = False , * * filters ) :
2020-01-08 20:17:25 +03:00
"""
Builds a dictionary for a handler
2022-03-06 17:41:54 +03:00
2020-01-08 20:17:25 +03:00
: param handler :
2020-01-08 20:06:40 +03:00
: param filters :
: return :
"""
2016-06-13 14:15:15 +03:00
return {
' function ' : handler ,
2022-01-24 16:15:04 +03:00
' pass_bot ' : pass_bot ,
2021-09-11 17:02:40 +03:00
' filters ' : { ftype : fvalue for ftype , fvalue in filters . items ( ) if fvalue is not None }
# Remove None values, they are skipped in _test_filter anyway
#'filters': filters
2016-06-13 14:15:15 +03:00
}
2020-04-08 21:13:19 +03:00
def middleware_handler ( self , update_types = None ) :
"""
Middleware handler decorator .
This decorator can be used to decorate functions that must be handled as middlewares before entering any other
message handlers
But , be careful and check type of the update inside the handler if more than one update_type is given
Example :
2022-03-07 14:10:44 +03:00
. . code - block : : python3
2020-04-08 21:13:19 +03:00
2022-03-07 14:10:44 +03:00
bot = TeleBot ( ' TOKEN ' )
2020-04-08 21:13:19 +03:00
2022-03-07 14:10:44 +03:00
# Print post message text before entering to any post_channel handlers
@bot.middleware_handler ( update_types = [ ' channel_post ' , ' edited_channel_post ' ] )
def print_channel_post_text ( bot_instance , channel_post ) :
print ( channel_post . text )
# Print update id before entering to any handlers
@bot.middleware_handler ( )
def print_channel_post_text ( bot_instance , update ) :
print ( update . update_id )
2020-04-08 21:13:19 +03:00
: param update_types : Optional list of update types that can be passed into the middleware handler .
"""
def decorator ( handler ) :
self . add_middleware_handler ( handler , update_types )
return handler
return decorator
def add_middleware_handler ( self , handler , update_types = None ) :
"""
2022-03-19 11:49:36 +03:00
Add middleware handler .
2020-04-08 21:13:19 +03:00
: param handler :
: param update_types :
: return :
"""
2020-12-24 19:55:24 +03:00
if not apihelper . ENABLE_MIDDLEWARE :
2022-01-24 16:15:04 +03:00
raise RuntimeError ( " Middleware is not enabled. Use apihelper.ENABLE_MIDDLEWARE before initialising TeleBot. " )
2020-12-24 19:55:24 +03:00
2020-04-08 21:13:19 +03:00
if update_types :
for update_type in update_types :
self . typed_middleware_handlers [ update_type ] . append ( handler )
else :
self . default_middleware_handlers . append ( handler )
2022-01-24 16:15:04 +03:00
# function register_middleware_handler
def register_middleware_handler ( self , callback , update_types = None ) :
"""
Middleware handler decorator .
This function will create a decorator that can be used to decorate functions that must be handled as middlewares before entering any other
message handlers
But , be careful and check type of the update inside the handler if more than one update_type is given
Example :
bot = TeleBot ( ' TOKEN ' )
bot . register_middleware_handler ( print_channel_post_text , update_types = [ ' channel_post ' , ' edited_channel_post ' ] )
2022-01-24 22:38:35 +03:00
: param callback :
2022-01-24 16:15:04 +03:00
: param update_types : Optional list of update types that can be passed into the middleware handler .
"""
self . add_middleware_handler ( callback , update_types )
2022-02-19 21:39:02 +03:00
@staticmethod
def check_commands_input ( commands , method_name ) :
2022-02-16 16:05:54 +03:00
if not isinstance ( commands , list ) or not all ( isinstance ( item , str ) for item in commands ) :
logger . error ( f " { method_name } : Commands filter should be list of strings (commands), unknown type supplied to the ' commands ' filter list. Not able to use the supplied type. " )
2022-02-19 21:39:02 +03:00
@staticmethod
def check_regexp_input ( regexp , method_name ) :
2022-02-16 16:05:54 +03:00
if not isinstance ( regexp , str ) :
2022-02-19 21:39:02 +03:00
logger . error ( f " { method_name } : Regexp filter should be string. Not able to use the supplied type. " )
2022-02-16 16:05:54 +03:00
2021-10-01 14:08:01 +03:00
def message_handler ( self , commands = None , regexp = None , func = None , content_types = None , chat_types = None , * * kwargs ) :
2015-07-02 04:38:31 +03:00
"""
Message handler decorator .
This decorator can be used to decorate functions that must handle certain types of messages .
All message handlers are tested in the order they were added .
Example :
2022-03-07 14:10:44 +03:00
2022-03-07 12:24:28 +03:00
. . code - block : : python
bot = TeleBot ( ' TOKEN ' )
# Handles all messages which text matches regexp.
@bot.message_handler ( regexp = ' someregexp ' )
def command_help ( message ) :
bot . send_message ( message . chat . id , ' Did someone call for help? ' )
# Handles messages in private chat
@bot.message_handler ( chat_types = [ ' private ' ] ) # You can add more chat types
def command_help ( message ) :
bot . send_message ( message . chat . id , ' Private chat detected, sir! ' )
# Handle all sent documents of type 'text/plain'.
@bot.message_handler ( func = lambda message : message . document . mime_type == ' text/plain ' ,
content_types = [ ' document ' ] )
def command_handle_document ( message ) :
bot . send_message ( message . chat . id , ' Document received, sir! ' )
# Handle all other messages.
@bot.message_handler ( func = lambda message : True , content_types = [ ' audio ' , ' photo ' , ' voice ' , ' video ' , ' document ' ,
' text ' , ' location ' , ' contact ' , ' sticker ' ] )
def default_command ( message ) :
bot . send_message ( message . chat . id , " This is the default command handler. " )
2015-07-02 04:38:31 +03:00
2020-04-24 18:19:30 +03:00
: param commands : Optional list of strings ( commands to handle ) .
2015-07-02 04:38:31 +03:00
: param regexp : Optional regular expression .
2021-06-19 18:59:55 +03:00
: param func : Optional lambda function . The lambda receives the message to test as the first parameter .
It must return True if the command should handle the message .
2021-05-11 23:26:22 +03:00
: param content_types : Supported message content types . Must be a list . Defaults to [ ' text ' ] .
2021-09-10 18:42:43 +03:00
: param chat_types : list of chat types
2015-07-02 04:38:31 +03:00
"""
2020-01-08 20:06:40 +03:00
if content_types is None :
content_types = [ " text " ]
2022-02-16 16:05:54 +03:00
method_name = " message_handler "
if commands is not None :
2022-02-19 21:39:02 +03:00
self . check_commands_input ( commands , method_name )
if isinstance ( commands , str ) :
commands = [ commands ]
2022-02-16 16:05:54 +03:00
if regexp is not None :
2022-02-19 21:39:02 +03:00
self . check_regexp_input ( regexp , method_name )
2021-09-11 19:26:55 +03:00
if isinstance ( content_types , str ) :
logger . warning ( " message_handler: ' content_types ' filter should be List of strings (content types), not string. " )
content_types = [ content_types ]
2016-02-20 13:58:16 +03:00
def decorator ( handler ) :
2016-06-13 14:15:15 +03:00
handler_dict = self . _build_handler_dict ( handler ,
2021-09-11 17:02:40 +03:00
chat_types = chat_types ,
2021-05-11 23:26:22 +03:00
content_types = content_types ,
2016-06-13 14:15:15 +03:00
commands = commands ,
regexp = regexp ,
func = func ,
2016-06-13 16:47:15 +03:00
* * kwargs )
2016-06-13 14:15:15 +03:00
self . add_message_handler ( handler_dict )
return handler
2016-02-20 13:58:16 +03:00
2016-06-13 14:15:15 +03:00
return decorator
2016-02-20 13:58:16 +03:00
2016-06-13 14:15:15 +03:00
def add_message_handler ( self , handler_dict ) :
2020-01-08 20:17:25 +03:00
"""
2020-01-08 20:06:40 +03:00
Adds a message handler
2022-03-06 17:41:54 +03:00
Note that you should use register_message_handler to add message_handler to the bot .
2020-01-08 20:06:40 +03:00
: param handler_dict :
: return :
"""
2016-02-20 13:58:16 +03:00
self . message_handlers . append ( handler_dict )
2022-01-24 16:15:04 +03:00
def register_message_handler ( self , callback , content_types = None , commands = None , regexp = None , func = None , chat_types = None , pass_bot = False , * * kwargs ) :
2021-08-16 21:41:27 +03:00
"""
Registers message handler .
2022-03-06 17:41:54 +03:00
2021-08-16 21:41:27 +03:00
: param callback : function to be called
: param content_types : list of content_types
: param commands : list of commands
: param regexp :
: param func :
2021-09-10 18:42:43 +03:00
: param chat_types : True for private chat
2022-01-24 16:15:04 +03:00
: param pass_bot : Pass TeleBot to handler .
2021-08-16 21:41:27 +03:00
: return : decorated function
"""
2022-02-16 16:05:54 +03:00
method_name = " register_message_handler "
if commands is not None :
2022-02-19 21:39:02 +03:00
self . check_commands_input ( commands , method_name )
if isinstance ( commands , str ) :
commands = [ commands ]
2022-02-16 16:05:54 +03:00
if regexp is not None :
2022-02-19 21:39:02 +03:00
self . check_regexp_input ( regexp , method_name )
2021-09-11 19:26:55 +03:00
if isinstance ( content_types , str ) :
logger . warning ( " register_message_handler: ' content_types ' filter should be List of strings (content types), not string. " )
content_types = [ content_types ]
2022-03-07 11:30:39 +03:00
2021-08-16 21:41:27 +03:00
handler_dict = self . _build_handler_dict ( callback ,
2021-09-11 17:02:40 +03:00
chat_types = chat_types ,
2021-08-19 23:36:37 +03:00
content_types = content_types ,
commands = commands ,
regexp = regexp ,
func = func ,
2022-01-24 16:15:04 +03:00
pass_bot = pass_bot ,
2021-08-19 23:36:37 +03:00
* * kwargs )
2021-08-16 21:41:27 +03:00
self . add_message_handler ( handler_dict )
2021-09-11 17:02:40 +03:00
2021-09-10 18:42:43 +03:00
def edited_message_handler ( self , commands = None , regexp = None , func = None , content_types = None , chat_types = None , * * kwargs ) :
2020-01-08 20:06:40 +03:00
"""
Edit message handler decorator
2022-03-06 17:41:54 +03:00
2020-01-08 20:06:40 +03:00
: param commands :
: param regexp :
: param func :
: param content_types :
2021-09-10 18:42:43 +03:00
: param chat_types : list of chat types
2020-01-08 20:06:40 +03:00
: param kwargs :
: return :
"""
if content_types is None :
content_types = [ " text " ]
2022-02-16 16:05:54 +03:00
method_name = " edited_message_handler "
if commands is not None :
2022-02-19 21:39:02 +03:00
self . check_commands_input ( commands , method_name )
if isinstance ( commands , str ) :
commands = [ commands ]
2022-02-16 16:05:54 +03:00
if regexp is not None :
2022-02-19 21:39:02 +03:00
self . check_regexp_input ( regexp , method_name )
2021-09-11 19:26:55 +03:00
if isinstance ( content_types , str ) :
logger . warning ( " edited_message_handler: ' content_types ' filter should be List of strings (content types), not string. " )
content_types = [ content_types ]
2016-06-07 14:29:12 +03:00
def decorator ( handler ) :
2016-06-13 14:15:15 +03:00
handler_dict = self . _build_handler_dict ( handler ,
2021-09-11 17:02:40 +03:00
chat_types = chat_types ,
content_types = content_types ,
2016-06-13 14:15:15 +03:00
commands = commands ,
regexp = regexp ,
func = func ,
2016-06-13 16:47:15 +03:00
* * kwargs )
2016-06-13 14:15:15 +03:00
self . add_edited_message_handler ( handler_dict )
2016-06-07 14:29:12 +03:00
return handler
return decorator
2016-06-13 14:15:15 +03:00
def add_edited_message_handler ( self , handler_dict ) :
2020-01-08 20:06:40 +03:00
"""
Adds the edit message handler
2022-03-06 17:41:54 +03:00
Note that you should use register_edited_message_handler to add edited_message_handler to the bot .
2022-03-19 11:49:36 +03:00
2020-01-08 20:06:40 +03:00
: param handler_dict :
: return :
"""
2016-06-07 14:29:12 +03:00
self . edited_message_handlers . append ( handler_dict )
2022-01-24 16:15:04 +03:00
def register_edited_message_handler ( self , callback , content_types = None , commands = None , regexp = None , func = None , chat_types = None , pass_bot = False , * * kwargs ) :
2021-08-16 21:41:27 +03:00
"""
Registers edited message handler .
2022-03-06 17:41:54 +03:00
2021-08-16 21:41:27 +03:00
: param callback : function to be called
: param content_types : list of content_types
: param commands : list of commands
: param regexp :
: param func :
2021-09-10 18:42:43 +03:00
: param chat_types : True for private chat
2022-01-24 16:15:04 +03:00
: param pass_bot : Pass TeleBot to handler .
2021-08-16 21:41:27 +03:00
: return : decorated function
"""
2022-02-16 16:05:54 +03:00
method_name = " register_edited_message_handler "
if commands is not None :
2022-02-19 21:39:02 +03:00
self . check_commands_input ( commands , method_name )
if isinstance ( commands , str ) :
commands = [ commands ]
2022-02-16 16:05:54 +03:00
if regexp is not None :
2022-02-19 21:39:02 +03:00
self . check_regexp_input ( regexp , method_name )
2021-09-11 19:26:55 +03:00
if isinstance ( content_types , str ) :
logger . warning ( " register_edited_message_handler: ' content_types ' filter should be List of strings (content types), not string. " )
content_types = [ content_types ]
2021-08-16 21:41:27 +03:00
handler_dict = self . _build_handler_dict ( callback ,
2021-09-11 17:02:40 +03:00
chat_types = chat_types ,
2021-08-19 23:36:37 +03:00
content_types = content_types ,
commands = commands ,
regexp = regexp ,
func = func ,
2022-01-24 16:15:04 +03:00
pass_bot = pass_bot ,
2021-08-19 23:36:37 +03:00
* * kwargs )
2021-08-16 21:41:27 +03:00
self . add_edited_message_handler ( handler_dict )
2021-09-11 17:02:40 +03:00
2021-09-25 15:12:32 +03:00
2021-07-28 21:10:15 +03:00
def channel_post_handler ( self , commands = None , regexp = None , func = None , content_types = None , * * kwargs ) :
2020-01-08 20:06:40 +03:00
"""
Channel post handler decorator
2022-03-06 17:41:54 +03:00
2020-01-08 20:06:40 +03:00
: param commands :
: param regexp :
: param func :
: param content_types :
: param kwargs :
: return :
"""
if content_types is None :
content_types = [ " text " ]
2022-02-16 16:05:54 +03:00
method_name = " channel_post_handler "
if commands is not None :
2022-02-19 21:39:02 +03:00
self . check_commands_input ( commands , method_name )
if isinstance ( commands , str ) :
commands = [ commands ]
2022-02-16 16:05:54 +03:00
if regexp is not None :
2022-02-19 21:39:02 +03:00
self . check_regexp_input ( regexp , method_name )
2021-09-11 19:26:55 +03:00
if isinstance ( content_types , str ) :
logger . warning ( " channel_post_handler: ' content_types ' filter should be List of strings (content types), not string. " )
content_types = [ content_types ]
2016-12-03 08:28:22 +03:00
def decorator ( handler ) :
handler_dict = self . _build_handler_dict ( handler ,
2021-09-11 17:02:40 +03:00
content_types = content_types ,
2016-12-03 08:28:22 +03:00
commands = commands ,
regexp = regexp ,
func = func ,
* * kwargs )
self . add_channel_post_handler ( handler_dict )
return handler
return decorator
def add_channel_post_handler ( self , handler_dict ) :
2020-01-08 20:06:40 +03:00
"""
Adds channel post handler
2022-03-06 17:41:54 +03:00
Note that you should use register_channel_post_handler to add channel_post_handler to the bot .
2020-01-08 20:06:40 +03:00
: param handler_dict :
: return :
"""
2016-12-03 08:28:22 +03:00
self . channel_post_handlers . append ( handler_dict )
2021-08-16 21:41:27 +03:00
2022-01-24 16:15:04 +03:00
def register_channel_post_handler ( self , callback , content_types = None , commands = None , regexp = None , func = None , pass_bot = False , * * kwargs ) :
2021-08-16 21:41:27 +03:00
"""
Registers channel post message handler .
2022-03-06 17:41:54 +03:00
2021-08-16 21:41:27 +03:00
: param callback : function to be called
: param content_types : list of content_types
: param commands : list of commands
: param regexp :
: param func :
2022-01-24 16:15:04 +03:00
: param pass_bot : Pass TeleBot to handler .
2021-08-16 21:41:27 +03:00
: return : decorated function
"""
2022-02-16 16:05:54 +03:00
method_name = " register_channel_post_handler "
if commands is not None :
2022-02-19 21:39:02 +03:00
self . check_commands_input ( commands , method_name )
if isinstance ( commands , str ) :
commands = [ commands ]
2022-02-16 16:05:54 +03:00
if regexp is not None :
2022-02-19 21:39:02 +03:00
self . check_regexp_input ( regexp , method_name )
2021-09-11 19:26:55 +03:00
if isinstance ( content_types , str ) :
logger . warning ( " register_channel_post_handler: ' content_types ' filter should be List of strings (content types), not string. " )
content_types = [ content_types ]
2021-08-16 21:41:27 +03:00
handler_dict = self . _build_handler_dict ( callback ,
2021-08-19 23:36:37 +03:00
content_types = content_types ,
commands = commands ,
regexp = regexp ,
func = func ,
2022-01-24 16:15:04 +03:00
pass_bot = pass_bot ,
2021-08-19 23:36:37 +03:00
* * kwargs )
2021-08-16 21:41:27 +03:00
self . add_channel_post_handler ( handler_dict )
2021-09-11 17:02:40 +03:00
2021-07-28 21:10:15 +03:00
def edited_channel_post_handler ( self , commands = None , regexp = None , func = None , content_types = None , * * kwargs ) :
2020-01-08 20:06:40 +03:00
"""
Edit channel post handler decorator
2022-03-06 17:41:54 +03:00
2020-01-08 20:06:40 +03:00
: param commands :
: param regexp :
: param func :
: param content_types :
: param kwargs :
: return :
"""
if content_types is None :
content_types = [ " text " ]
2022-02-16 16:05:54 +03:00
method_name = " edited_channel_post_handler "
if commands is not None :
2022-02-19 21:39:02 +03:00
self . check_commands_input ( commands , method_name )
if isinstance ( commands , str ) :
commands = [ commands ]
2022-02-16 16:05:54 +03:00
if regexp is not None :
2022-02-19 21:39:02 +03:00
self . check_regexp_input ( regexp , method_name )
2021-09-11 19:26:55 +03:00
if isinstance ( content_types , str ) :
logger . warning ( " edited_channel_post_handler: ' content_types ' filter should be List of strings (content types), not string. " )
content_types = [ content_types ]
2016-12-03 08:28:22 +03:00
def decorator ( handler ) :
handler_dict = self . _build_handler_dict ( handler ,
2021-09-11 17:02:40 +03:00
content_types = content_types ,
2016-12-03 08:28:22 +03:00
commands = commands ,
regexp = regexp ,
func = func ,
* * kwargs )
2017-03-04 16:30:07 +03:00
self . add_edited_channel_post_handler ( handler_dict )
2016-12-03 08:28:22 +03:00
return handler
return decorator
def add_edited_channel_post_handler ( self , handler_dict ) :
2020-01-08 20:06:40 +03:00
"""
Adds the edit channel post handler
2022-03-06 17:41:54 +03:00
Note that you should use register_edited_channel_post_handler to add edited_channel_post_handler to the bot .
2020-01-08 20:06:40 +03:00
: param handler_dict :
: return :
"""
2016-12-03 08:28:22 +03:00
self . edited_channel_post_handlers . append ( handler_dict )
2022-01-24 16:15:04 +03:00
def register_edited_channel_post_handler ( self , callback , content_types = None , commands = None , regexp = None , func = None , pass_bot = False , * * kwargs ) :
2021-08-16 21:41:27 +03:00
"""
Registers edited channel post message handler .
2022-03-06 21:14:07 +03:00
2021-08-16 21:41:27 +03:00
: param callback : function to be called
: param content_types : list of content_types
: param commands : list of commands
: param regexp :
: param func :
2022-01-24 16:15:04 +03:00
: param pass_bot : Pass TeleBot to handler .
2021-08-16 21:41:27 +03:00
: return : decorated function
"""
2022-02-16 16:05:54 +03:00
method_name = " register_edited_channel_post_handler "
if commands is not None :
2022-02-19 21:39:02 +03:00
self . check_commands_input ( commands , method_name )
if isinstance ( commands , str ) :
commands = [ commands ]
2022-02-16 16:05:54 +03:00
if regexp is not None :
2022-02-19 21:39:02 +03:00
self . check_regexp_input ( regexp , method_name )
2021-09-11 19:26:55 +03:00
if isinstance ( content_types , str ) :
logger . warning ( " register_edited_channel_post_handler: ' content_types ' filter should be List of strings (content types), not string. " )
content_types = [ content_types ]
2021-08-16 21:41:27 +03:00
handler_dict = self . _build_handler_dict ( callback ,
2021-08-19 23:36:37 +03:00
content_types = content_types ,
commands = commands ,
regexp = regexp ,
func = func ,
2022-01-24 16:15:04 +03:00
pass_bot = pass_bot ,
2021-08-19 23:36:37 +03:00
* * kwargs )
2021-08-16 21:41:27 +03:00
self . add_edited_channel_post_handler ( handler_dict )
2016-06-16 11:49:51 +03:00
def inline_handler ( self , func , * * kwargs ) :
2020-01-08 20:06:40 +03:00
"""
Inline call handler decorator
2022-03-06 17:41:54 +03:00
2020-01-08 20:06:40 +03:00
: param func :
: param kwargs :
: return :
"""
2016-02-20 13:58:16 +03:00
def decorator ( handler ) :
2016-06-16 11:49:51 +03:00
handler_dict = self . _build_handler_dict ( handler , func = func , * * kwargs )
2016-06-13 14:24:27 +03:00
self . add_inline_handler ( handler_dict )
2016-02-20 13:58:16 +03:00
return handler
2016-01-04 18:10:32 +03:00
return decorator
2016-06-13 14:24:27 +03:00
def add_inline_handler ( self , handler_dict ) :
2020-01-08 20:06:40 +03:00
"""
Adds inline call handler
2022-03-06 17:41:54 +03:00
Note that you should use register_inline_handler to add inline_handler to the bot .
2020-01-08 20:06:40 +03:00
: param handler_dict :
: return :
"""
2016-02-20 13:58:16 +03:00
self . inline_handlers . append ( handler_dict )
2022-01-24 16:15:04 +03:00
def register_inline_handler ( self , callback , func , pass_bot = False , * * kwargs ) :
2021-08-16 21:41:27 +03:00
"""
Registers inline handler .
2022-03-06 17:41:54 +03:00
2021-08-16 21:41:27 +03:00
: param callback : function to be called
: param func :
2022-01-24 16:15:04 +03:00
: param pass_bot : Pass TeleBot to handler .
2021-08-16 21:41:27 +03:00
: return : decorated function
"""
2022-01-24 16:15:04 +03:00
handler_dict = self . _build_handler_dict ( callback , func = func , pass_bot = pass_bot , * * kwargs )
2021-08-16 21:41:27 +03:00
self . add_inline_handler ( handler_dict )
2016-06-16 11:49:51 +03:00
def chosen_inline_handler ( self , func , * * kwargs ) :
2020-01-08 20:06:40 +03:00
"""
Description : TBD
2022-03-06 17:41:54 +03:00
2020-01-08 20:06:40 +03:00
: param func :
: param kwargs :
: return :
"""
2016-02-20 13:58:16 +03:00
def decorator ( handler ) :
2016-06-16 11:49:51 +03:00
handler_dict = self . _build_handler_dict ( handler , func = func , * * kwargs )
2016-06-13 14:24:27 +03:00
self . add_chosen_inline_handler ( handler_dict )
2016-02-20 13:58:16 +03:00
return handler
2016-01-05 08:18:32 +03:00
return decorator
2016-06-13 14:24:27 +03:00
def add_chosen_inline_handler ( self , handler_dict ) :
2020-01-08 20:06:40 +03:00
"""
Description : TBD
2022-03-06 17:41:54 +03:00
Note that you should use register_chosen_inline_handler to add chosen_inline_handler to the bot .
2020-01-08 20:06:40 +03:00
: param handler_dict :
: return :
"""
2016-02-20 13:58:16 +03:00
self . chosen_inline_handlers . append ( handler_dict )
2022-01-24 16:15:04 +03:00
def register_chosen_inline_handler ( self , callback , func , pass_bot = False , * * kwargs ) :
2021-08-16 21:41:27 +03:00
"""
Registers chosen inline handler .
2022-03-19 11:49:36 +03:00
2021-08-16 21:41:27 +03:00
: param callback : function to be called
: param func :
2022-01-24 16:15:04 +03:00
: param pass_bot : Pass TeleBot to handler .
2021-08-16 21:41:27 +03:00
: return : decorated function
"""
2022-01-24 16:15:04 +03:00
handler_dict = self . _build_handler_dict ( callback , func = func , pass_bot = pass_bot , * * kwargs )
2021-08-16 21:41:27 +03:00
self . add_chosen_inline_handler ( handler_dict )
2016-06-16 11:49:51 +03:00
def callback_query_handler ( self , func , * * kwargs ) :
2020-01-08 20:06:40 +03:00
"""
Callback request handler decorator
2022-03-06 17:41:54 +03:00
2020-01-08 20:06:40 +03:00
: param func :
: param kwargs :
: return :
"""
2016-04-16 09:18:19 +03:00
def decorator ( handler ) :
2016-06-16 11:49:51 +03:00
handler_dict = self . _build_handler_dict ( handler , func = func , * * kwargs )
2016-06-13 14:24:27 +03:00
self . add_callback_query_handler ( handler_dict )
2016-09-28 14:41:36 +03:00
return handler
2016-04-16 09:18:19 +03:00
return decorator
2016-06-13 14:24:27 +03:00
def add_callback_query_handler ( self , handler_dict ) :
2020-01-08 20:06:40 +03:00
"""
Adds a callback request handler
2022-03-06 17:41:54 +03:00
Note that you should use register_callback_query_handler to add callback_query_handler to the bot .
2020-01-08 20:06:40 +03:00
: param handler_dict :
: return :
"""
2016-04-16 09:18:19 +03:00
self . callback_query_handlers . append ( handler_dict )
2022-01-24 16:15:04 +03:00
def register_callback_query_handler ( self , callback , func , pass_bot = False , * * kwargs ) :
2021-08-16 21:41:27 +03:00
"""
2022-03-06 17:41:54 +03:00
Registers callback query handler .
2021-08-16 21:41:27 +03:00
: param callback : function to be called
: param func :
2022-01-24 16:15:04 +03:00
: param pass_bot : Pass TeleBot to handler .
2021-08-16 21:41:27 +03:00
: return : decorated function
"""
2022-01-24 16:15:04 +03:00
handler_dict = self . _build_handler_dict ( callback , func = func , pass_bot = pass_bot , * * kwargs )
2021-08-16 21:41:27 +03:00
self . add_callback_query_handler ( handler_dict )
2017-05-25 06:22:40 +03:00
def shipping_query_handler ( self , func , * * kwargs ) :
2020-01-08 20:06:40 +03:00
"""
Shipping request handler
2022-03-06 17:41:54 +03:00
2020-01-08 20:06:40 +03:00
: param func :
: param kwargs :
: return :
"""
2017-05-25 06:22:40 +03:00
def decorator ( handler ) :
handler_dict = self . _build_handler_dict ( handler , func = func , * * kwargs )
self . add_shipping_query_handler ( handler_dict )
return handler
return decorator
def add_shipping_query_handler ( self , handler_dict ) :
2020-01-08 20:06:40 +03:00
"""
2022-03-06 17:41:54 +03:00
Adds a shipping request handler .
Note that you should use register_shipping_query_handler to add shipping_query_handler to the bot .
2020-01-08 20:06:40 +03:00
: param handler_dict :
: return :
"""
2017-05-25 06:22:40 +03:00
self . shipping_query_handlers . append ( handler_dict )
2022-01-24 16:15:04 +03:00
def register_shipping_query_handler ( self , callback , func , pass_bot = False , * * kwargs ) :
2021-08-16 21:41:27 +03:00
"""
Registers shipping query handler .
2022-03-06 17:41:54 +03:00
2021-08-16 21:41:27 +03:00
: param callback : function to be called
: param func :
2022-01-24 16:15:04 +03:00
: param pass_bot : Pass TeleBot to handler .
2021-08-16 21:41:27 +03:00
: return : decorated function
"""
2022-01-24 16:15:04 +03:00
handler_dict = self . _build_handler_dict ( callback , func = func , pass_bot = pass_bot , * * kwargs )
2021-08-16 21:41:27 +03:00
self . add_shipping_query_handler ( handler_dict )
2017-05-25 06:22:40 +03:00
def pre_checkout_query_handler ( self , func , * * kwargs ) :
2020-01-08 20:06:40 +03:00
"""
Pre - checkout request handler
2022-03-06 17:41:54 +03:00
2020-01-08 20:06:40 +03:00
: param func :
: param kwargs :
: return :
"""
2017-05-25 06:22:40 +03:00
def decorator ( handler ) :
handler_dict = self . _build_handler_dict ( handler , func = func , * * kwargs )
2017-05-25 06:45:44 +03:00
self . add_pre_checkout_query_handler ( handler_dict )
2017-05-25 06:22:40 +03:00
return handler
return decorator
2017-05-25 06:23:37 +03:00
def add_pre_checkout_query_handler ( self , handler_dict ) :
2020-01-08 20:06:40 +03:00
"""
Adds a pre - checkout request handler
2022-03-06 17:41:54 +03:00
Note that you should use register_pre_checkout_query_handler to add pre_checkout_query_handler to the bot .
2020-01-08 20:06:40 +03:00
: param handler_dict :
: return :
"""
2017-05-25 06:22:40 +03:00
self . pre_checkout_query_handlers . append ( handler_dict )
2021-08-16 21:41:27 +03:00
2022-01-24 16:15:04 +03:00
def register_pre_checkout_query_handler ( self , callback , func , pass_bot = False , * * kwargs ) :
2021-08-16 21:41:27 +03:00
"""
Registers pre - checkout request handler .
2022-03-06 17:41:54 +03:00
2021-08-16 21:41:27 +03:00
: param callback : function to be called
: param func :
2022-01-24 16:15:04 +03:00
: param pass_bot : Pass TeleBot to handler .
2021-08-16 21:41:27 +03:00
: return : decorated function
"""
2022-01-24 16:15:04 +03:00
handler_dict = self . _build_handler_dict ( callback , func = func , pass_bot = pass_bot , * * kwargs )
2021-08-16 21:41:27 +03:00
self . add_pre_checkout_query_handler ( handler_dict )
2017-05-25 06:22:40 +03:00
2020-03-09 13:25:54 +03:00
def poll_handler ( self , func , * * kwargs ) :
"""
Poll request handler
2022-03-06 17:41:54 +03:00
2020-03-09 13:25:54 +03:00
: param func :
: param kwargs :
: return :
"""
def decorator ( handler ) :
handler_dict = self . _build_handler_dict ( handler , func = func , * * kwargs )
self . add_poll_handler ( handler_dict )
return handler
return decorator
def add_poll_handler ( self , handler_dict ) :
"""
Adds a poll request handler
2022-03-06 17:41:54 +03:00
Note that you should use register_poll_handler to add poll_handler to the bot .
2020-03-09 13:25:54 +03:00
: param handler_dict :
: return :
"""
self . poll_handlers . append ( handler_dict )
2022-01-24 16:15:04 +03:00
def register_poll_handler ( self , callback , func , pass_bot = False , * * kwargs ) :
2021-08-16 21:41:27 +03:00
"""
Registers poll handler .
2022-03-06 17:41:54 +03:00
2021-08-16 21:41:27 +03:00
: param callback : function to be called
: param func :
2022-01-24 16:15:04 +03:00
: param pass_bot : Pass TeleBot to handler .
2021-08-16 21:41:27 +03:00
: return : decorated function
"""
2022-01-24 16:15:04 +03:00
handler_dict = self . _build_handler_dict ( callback , func = func , pass_bot = pass_bot , * * kwargs )
2021-08-16 21:41:27 +03:00
self . add_poll_handler ( handler_dict )
2020-05-12 03:09:34 +03:00
def poll_answer_handler ( self , func = None , * * kwargs ) :
"""
Poll_answer request handler
2022-03-06 17:41:54 +03:00
2020-05-12 03:09:34 +03:00
: param func :
: param kwargs :
: return :
"""
def decorator ( handler ) :
handler_dict = self . _build_handler_dict ( handler , func = func , * * kwargs )
self . add_poll_answer_handler ( handler_dict )
return handler
return decorator
def add_poll_answer_handler ( self , handler_dict ) :
"""
2022-03-06 17:41:54 +03:00
Adds a poll_answer request handler .
Note that you should use register_poll_answer_handler to add poll_answer_handler to the bot .
2020-05-12 03:09:34 +03:00
: param handler_dict :
: return :
"""
self . poll_answer_handlers . append ( handler_dict )
2021-08-16 21:41:27 +03:00
2022-01-24 16:15:04 +03:00
def register_poll_answer_handler ( self , callback , func , pass_bot = False , * * kwargs ) :
2021-08-16 21:41:27 +03:00
"""
Registers poll answer handler .
2022-03-06 17:41:54 +03:00
2021-08-16 21:41:27 +03:00
: param callback : function to be called
: param func :
2022-01-24 16:15:04 +03:00
: param pass_bot : Pass TeleBot to handler .
2021-08-16 21:41:27 +03:00
: return : decorated function
"""
2022-01-24 16:15:04 +03:00
handler_dict = self . _build_handler_dict ( callback , func = func , pass_bot = pass_bot , * * kwargs )
2021-08-16 21:41:27 +03:00
self . add_poll_answer_handler ( handler_dict )
2021-06-23 17:10:48 +03:00
def my_chat_member_handler ( self , func = None , * * kwargs ) :
"""
2022-03-06 17:41:54 +03:00
my_chat_member handler .
2021-06-23 17:10:48 +03:00
: param func :
: param kwargs :
: return :
"""
def decorator ( handler ) :
handler_dict = self . _build_handler_dict ( handler , func = func , * * kwargs )
self . add_my_chat_member_handler ( handler_dict )
return handler
return decorator
def add_my_chat_member_handler ( self , handler_dict ) :
"""
2022-03-06 17:41:54 +03:00
Adds a my_chat_member handler .
Note that you should use register_my_chat_member_handler to add my_chat_member_handler to the bot .
2021-06-23 17:10:48 +03:00
: param handler_dict :
: return :
"""
self . my_chat_member_handlers . append ( handler_dict )
2022-01-24 16:15:04 +03:00
def register_my_chat_member_handler ( self , callback , func = None , pass_bot = False , * * kwargs ) :
2021-08-16 21:41:27 +03:00
"""
Registers my chat member handler .
2022-03-06 17:41:54 +03:00
2021-08-16 21:41:27 +03:00
: param callback : function to be called
: param func :
2022-01-24 16:15:04 +03:00
: param pass_bot : Pass TeleBot to handler .
2021-08-16 21:41:27 +03:00
: return : decorated function
"""
2022-01-24 16:15:04 +03:00
handler_dict = self . _build_handler_dict ( callback , func = func , pass_bot = pass_bot , * * kwargs )
2021-08-16 21:41:27 +03:00
self . add_my_chat_member_handler ( handler_dict )
2021-06-23 17:10:48 +03:00
def chat_member_handler ( self , func = None , * * kwargs ) :
"""
2022-03-06 17:41:54 +03:00
chat_member handler .
2021-06-23 17:10:48 +03:00
: param func :
: param kwargs :
: return :
"""
def decorator ( handler ) :
handler_dict = self . _build_handler_dict ( handler , func = func , * * kwargs )
self . add_chat_member_handler ( handler_dict )
return handler
return decorator
def add_chat_member_handler ( self , handler_dict ) :
"""
2022-03-06 17:41:54 +03:00
Adds a chat_member handler .
Note that you should use register_chat_member_handler to add chat_member_handler to the bot .
2021-06-23 17:10:48 +03:00
: param handler_dict :
: return :
"""
self . chat_member_handlers . append ( handler_dict )
2022-01-24 16:15:04 +03:00
def register_chat_member_handler ( self , callback , func = None , pass_bot = False , * * kwargs ) :
2021-08-16 21:41:27 +03:00
"""
Registers chat member handler .
2022-03-06 17:41:54 +03:00
2021-08-16 21:41:27 +03:00
: param callback : function to be called
: param func :
2022-01-24 16:15:04 +03:00
: param pass_bot : Pass TeleBot to handler .
2021-08-16 21:41:27 +03:00
: return : decorated function
"""
2022-01-24 16:15:04 +03:00
handler_dict = self . _build_handler_dict ( callback , func = func , pass_bot = pass_bot , * * kwargs )
2021-08-16 21:41:27 +03:00
self . add_chat_member_handler ( handler_dict )
2020-05-12 03:09:34 +03:00
2021-11-05 21:22:03 +03:00
def chat_join_request_handler ( self , func = None , * * kwargs ) :
"""
chat_join_request handler
2022-03-06 17:41:54 +03:00
2021-11-05 21:22:03 +03:00
: param func :
: param kwargs :
: return :
"""
def decorator ( handler ) :
handler_dict = self . _build_handler_dict ( handler , func = func , * * kwargs )
self . add_chat_join_request_handler ( handler_dict )
return handler
return decorator
def add_chat_join_request_handler ( self , handler_dict ) :
"""
2022-03-06 17:41:54 +03:00
Adds a chat_join_request handler .
Note that you should use register_chat_join_request_handler to add chat_join_request_handler to the bot .
2021-11-05 21:22:03 +03:00
: param handler_dict :
: return :
"""
self . chat_join_request_handlers . append ( handler_dict )
2022-01-24 16:15:04 +03:00
def register_chat_join_request_handler ( self , callback , func = None , pass_bot = False , * * kwargs ) :
2021-11-05 21:22:03 +03:00
"""
Registers chat join request handler .
2022-03-19 11:49:36 +03:00
2021-11-05 21:22:03 +03:00
: param callback : function to be called
: param func :
2022-01-24 16:15:04 +03:00
: param pass_bot : Pass TeleBot to handler .
2021-11-05 21:22:03 +03:00
: return : decorated function
"""
2022-01-24 16:15:04 +03:00
handler_dict = self . _build_handler_dict ( callback , func = func , pass_bot = pass_bot , * * kwargs )
2021-11-05 21:22:03 +03:00
self . add_chat_join_request_handler ( handler_dict )
2016-06-13 16:47:15 +03:00
def _test_message_handler ( self , message_handler , message ) :
2020-01-08 20:17:25 +03:00
"""
2020-01-08 20:06:40 +03:00
Test message handler
2022-03-06 17:41:54 +03:00
2020-01-08 20:06:40 +03:00
: param message_handler :
: param message :
: return :
"""
2020-08-24 16:02:35 +03:00
for message_filter , filter_value in message_handler [ ' filters ' ] . items ( ) :
2016-06-13 16:47:15 +03:00
if filter_value is None :
continue
2020-04-24 18:19:30 +03:00
if not self . _test_filter ( message_filter , filter_value , message ) :
2015-09-08 11:44:31 +03:00
return False
2016-06-13 16:47:15 +03:00
2015-09-08 11:44:31 +03:00
return True
2022-03-06 17:41:54 +03:00
def add_custom_filter ( self , custom_filter : Union [ SimpleCustomFilter , AdvancedCustomFilter ] ) :
2021-09-11 19:47:59 +03:00
"""
Create custom filter .
2022-03-06 17:41:54 +03:00
2022-03-19 11:49:36 +03:00
: param custom_filter : Class with check ( message ) method .
2022-03-06 17:41:54 +03:00
: param custom_filter : Custom filter class with key .
2021-09-11 21:10:21 +03:00
"""
2021-09-11 19:47:59 +03:00
self . custom_filters [ custom_filter . key ] = custom_filter
def _test_filter ( self , message_filter , filter_value , message ) :
2020-01-08 20:17:25 +03:00
"""
Test filters
2022-03-06 17:41:54 +03:00
2021-08-19 22:46:12 +03:00
: param message_filter : Filter type passed in handler
: param filter_value : Filter value passed in handler
: param message : Message to test
: return : True if filter conforms
"""
if message_filter == ' content_types ' :
return message . content_type in filter_value
elif message_filter == ' regexp ' :
return message . content_type == ' text ' and re . search ( filter_value , message . text , re . IGNORECASE )
elif message_filter == ' commands ' :
return message . content_type == ' text ' and util . extract_command ( message . text ) in filter_value
2021-09-10 18:42:43 +03:00
elif message_filter == ' chat_types ' :
return message . chat . type in filter_value
2021-08-19 22:46:12 +03:00
elif message_filter == ' func ' :
return filter_value ( message )
2021-09-11 21:10:21 +03:00
elif self . custom_filters and message_filter in self . custom_filters :
2021-09-11 21:02:56 +03:00
return self . _check_filter ( message_filter , filter_value , message )
2021-09-11 21:10:21 +03:00
else :
return False
2021-09-11 21:02:56 +03:00
def _check_filter ( self , message_filter , filter_value , message ) :
2021-09-11 21:10:21 +03:00
filter_check = self . custom_filters . get ( message_filter )
if not filter_check :
return False
2021-09-12 19:36:23 +03:00
elif isinstance ( filter_check , SimpleCustomFilter ) :
2021-09-11 21:10:21 +03:00
return filter_value == filter_check . check ( message )
2021-09-12 19:36:23 +03:00
elif isinstance ( filter_check , AdvancedCustomFilter ) :
2021-09-11 21:49:51 +03:00
return filter_check . check ( message , filter_value )
2021-08-19 22:46:12 +03:00
else :
2021-09-11 21:10:21 +03:00
logger . error ( " Custom filter: wrong type. Should be SimpleCustomFilter or AdvancedCustomFilter. " )
2021-08-19 22:46:12 +03:00
return False
2015-07-02 04:38:31 +03:00
2022-03-06 16:39:41 +03:00
# middleware check-up method
def _check_middleware ( self , update_type ) :
"""
Check middleware
2022-03-06 17:41:54 +03:00
2022-03-06 16:39:41 +03:00
: param message :
: return :
"""
2022-03-06 17:52:42 +03:00
middlewares = None
if self . middlewares :
middlewares = [ i for i in self . middlewares if update_type in i . update_types ]
2022-03-06 16:39:41 +03:00
return middlewares
def _run_middlewares_and_handler ( self , message , handlers , middlewares , * args , * * kwargs ) :
2022-03-06 17:41:54 +03:00
"""
This class is made to run handler and middleware in queue .
2022-03-06 16:39:41 +03:00
: param handler : handler that should be executed .
: param middleware : middleware that should be executed .
: return :
"""
data = { }
params = [ ]
handler_error = None
skip_handler = False
if middlewares :
for middleware in middlewares :
result = middleware . pre_process ( message , data )
# We will break this loop if CancelUpdate is returned
# Also, we will not run other middlewares
if isinstance ( result , CancelUpdate ) :
return
elif isinstance ( result , SkipHandler ) and skip_handler is False :
skip_handler = True
try :
if handlers and not skip_handler :
for handler in handlers :
process_handler = self . _test_message_handler ( handler , message )
if not process_handler : continue
else :
for i in inspect . signature ( handler [ ' function ' ] ) . parameters :
params . append ( i )
if len ( params ) == 1 :
handler [ ' function ' ] ( message )
elif len ( params ) == 2 :
if handler . get ( ' pass_bot ' ) is True :
handler [ ' function ' ] ( message , self )
elif handler . get ( ' pass_bot ' ) is False :
handler [ ' function ' ] ( message , data )
elif len ( params ) == 3 :
if params [ 2 ] == ' bot ' and handler . get ( ' pass_bot ' ) is True :
handler [ ' function ' ] ( message , data , self )
2022-04-15 22:13:14 +03:00
elif not handler . get ( ' pass_bot ' ) :
raise RuntimeError ( ' Your handler accepts 3 parameters but pass_bot is False. Please re-check your handler. ' )
2022-03-06 16:39:41 +03:00
else :
handler [ ' function ' ] ( message , self , data )
except Exception as e :
handler_error = e
if not middlewares :
if self . exception_handler :
return self . exception_handler . handle ( e )
logging . error ( str ( e ) )
return
if middlewares :
for middleware in middlewares :
middleware . post_process ( message , data , handler_error )
def _notify_command_handlers ( self , handlers , new_messages , update_type ) :
2020-01-08 20:06:40 +03:00
"""
2022-03-06 17:41:54 +03:00
Notifies command handlers .
2020-01-08 20:06:40 +03:00
: param handlers :
: param new_messages :
: return :
"""
2022-03-06 16:39:41 +03:00
if len ( handlers ) == 0 and not self . use_class_middlewares :
2020-08-24 16:02:35 +03:00
return
2022-03-06 16:39:41 +03:00
2015-07-02 04:38:31 +03:00
for message in new_messages :
2022-03-07 19:40:39 +03:00
if self . use_class_middlewares :
middleware = self . _check_middleware ( update_type )
2022-03-06 16:39:41 +03:00
self . _exec_task ( self . _run_middlewares_and_handler , message , handlers = handlers , middlewares = middleware )
return
2022-03-07 19:40:39 +03:00
else :
for message_handler in handlers :
if self . _test_message_handler ( message_handler , message ) :
self . _exec_task ( message_handler [ ' function ' ] , message , pass_bot = message_handler [ ' pass_bot ' ] , task_type = ' handler ' )
break