我们从Python开源项目中,提取了以下12个代码示例,用于说明如何使用telegram.ext.Dispatcher()。
def stop(self): """ Stops the polling/webhook thread, the dispatcher and the job queue """ self.job_queue.stop() with self.__lock: if self.running or self.dispatcher.has_running_threads: self.logger.debug('Stopping Updater and Dispatcher...') self.running = False self._stop_httpd() self._stop_dispatcher() self._join_threads() # Stop the Request instance only if it was created by the Updater if self._request: self._request.stop()
def setup(webhook_url=None): """If webhook_url is not passed, run with long-polling.""" logging.basicConfig(level=logging.WARNING) if webhook_url: bot = Bot(TOKEN) update_queue = Queue() dp = Dispatcher(bot, update_queue) else: updater = Updater(TOKEN) bot = updater.bot dp = updater.dispatcher dp.add_handler(MessageHandler([], example_handler)) # Remove this line # Add your handlers here if webhook_url: bot.set_webhook(webhook_url=webhook_url) thread = Thread(target=dp.start, name='dispatcher') thread.start() return update_queue, bot else: bot.set_webhook() # Delete webhook updater.start_polling() updater.idle()
def bot_hook(): """Entry point for the Telegram connection.""" bot = telegram.Bot(botdata['BotToken']) dispatcher = Dispatcher(bot, None, workers=0) dispatcher.add_handler(CommandHandler('Abfahrten', abfahrten, pass_args=True)) dispatcher.add_handler(CommandHandler('abfahrten', abfahrten, pass_args=True)) dispatcher.add_handler(CommandHandler('Abfahrt', abfahrten, pass_args=True)) dispatcher.add_handler(CommandHandler('abfahrt', abfahrten, pass_args=True)) dispatcher.add_handler(CommandHandler('A', abfahrten, pass_args=True)) dispatcher.add_handler(CommandHandler('a', abfahrten, pass_args=True)) dispatcher.add_handler(CommandHandler('Hilfe', hilfe)) dispatcher.add_handler(CommandHandler('hilfe', hilfe)) dispatcher.add_handler(CommandHandler('help', hilfe)) dispatcher.add_handler(MessageHandler(Filters.location, nearest_stations)) update = telegram.update.Update.de_json(request.json, bot) dispatcher.process_update(update) return 'OK'
def stop(self): """Stops the polling/webhook thread, the dispatcher and the job queue.""" self.job_queue.stop() with self.__lock: if self.running or self.dispatcher.has_running_threads: self.logger.debug('Stopping Updater and Dispatcher...') self.running = False self._stop_httpd() self._stop_dispatcher() self._join_threads() # Stop the Request instance only if it was created by the Updater if self._request: self._request.stop()
def test_init(self): """ Test init function of admincommands class """ with patch("ownbot.admincommands.UserManager"): dispatcher = Mock(spec=Dispatcher) AdminCommands(dispatcher) self.assertTrue(dispatcher.add_handler.called)
def _stop_dispatcher(self): self.logger.debug('Requesting Dispatcher to stop...') self.dispatcher.stop()
def setup(): '''GAE DISPATCHER SETUP''' global dispatcher # Note that update_queue is setted to None and # 0 workers are allowed on Google app Engine (If not-->Problems with multithreading) dispatcher = Dispatcher(bot=bot, update_queue=None, workers=0) # ---Register handlers here--- dispatcher.add_handler(CommandHandler("start", start)) dispatcher.add_handler(CommandHandler("help", help)) dispatcher.add_handler(MessageHandler([Filters.text], echo)) dispatcher.add_error_handler(error) return dispatcher
def __init__(self, token=None, base_url=None, workers=4, bot=None, user_sig_handler=None, request_kwargs=None): if (token is None) and (bot is None): raise ValueError('`token` or `bot` must be passed') if (token is not None) and (bot is not None): raise ValueError('`token` and `bot` are mutually exclusive') if bot is not None: self.bot = bot else: # we need a connection pool the size of: # * for each of the workers # * 1 for Dispatcher # * 1 for polling Updater (even if webhook is used, we can spare a connection) # * 1 for JobQueue # * 1 for main thread if request_kwargs is None: request_kwargs = {} if 'con_pool_size' not in request_kwargs: request_kwargs['con_pool_size'] = workers + 4 self._request = Request(**request_kwargs) self.bot = Bot(token, base_url, request=self._request) self.user_sig_handler = user_sig_handler self.update_queue = Queue() self.job_queue = JobQueue(self.bot) self.__exception_event = Event() self.dispatcher = Dispatcher( self.bot, self.update_queue, job_queue=self.job_queue, workers=workers, exception_event=self.__exception_event) self.last_update_id = 0 self.logger = logging.getLogger(__name__) self.running = False self.is_idle = False self.httpd = None self.__lock = Lock() self.__threads = [] """:type: list[Thread]"""
def _start_polling(self, poll_interval, timeout, read_latency, bootstrap_retries, clean, allowed_updates): """ Thread target of thread 'updater'. Runs in background, pulls updates from Telegram and inserts them in the update queue of the Dispatcher. """ cur_interval = poll_interval self.logger.debug('Updater thread started') self._bootstrap(bootstrap_retries, clean=clean, webhook_url='', allowed_updates=None) while self.running: try: updates = self.bot.getUpdates( self.last_update_id, timeout=timeout, read_latency=read_latency, allowed_updates=allowed_updates) except RetryAfter as e: self.logger.info(str(e)) cur_interval = 0.5 + e.retry_after except TelegramError as te: self.logger.error("Error while getting Updates: {0}".format(te)) # Put the error into the update queue and let the Dispatcher # broadcast it self.update_queue.put(te) cur_interval = self._increase_poll_interval(cur_interval) else: if not self.running: if len(updates) > 0: self.logger.debug('Updates ignored and will be pulled ' 'again on restart.') break if updates: for update in updates: self.update_queue.put(update) self.last_update_id = updates[-1].update_id + 1 cur_interval = poll_interval sleep(cur_interval)
def __init__(self, token=None, base_url=None, workers=4, bot=None, user_sig_handler=None, request_kwargs=None): if (token is None) and (bot is None): raise ValueError('`token` or `bot` must be passed') if (token is not None) and (bot is not None): raise ValueError('`token` and `bot` are mutually exclusive') self.logger = logging.getLogger(__name__) con_pool_size = workers + 4 if bot is not None: self.bot = bot if bot.request.con_pool_size < con_pool_size: self.logger.warning( 'Connection pool of Request object is smaller than optimal value (%s)', con_pool_size) else: # we need a connection pool the size of: # * for each of the workers # * 1 for Dispatcher # * 1 for polling Updater (even if webhook is used, we can spare a connection) # * 1 for JobQueue # * 1 for main thread if request_kwargs is None: request_kwargs = {} if 'con_pool_size' not in request_kwargs: request_kwargs['con_pool_size'] = con_pool_size self._request = Request(**request_kwargs) self.bot = Bot(token, base_url, request=self._request) self.user_sig_handler = user_sig_handler self.update_queue = Queue() self.job_queue = JobQueue(self.bot) self.__exception_event = Event() self.dispatcher = Dispatcher( self.bot, self.update_queue, job_queue=self.job_queue, workers=workers, exception_event=self.__exception_event) self.last_update_id = 0 self.running = False self.is_idle = False self.httpd = None self.__lock = Lock() self.__threads = []
def _start_polling(self, poll_interval, timeout, read_latency, bootstrap_retries, clean, allowed_updates): # """ # Thread target of thread 'updater'. Runs in background, pulls # updates from Telegram and inserts them in the update queue of the # Dispatcher. # """ cur_interval = poll_interval self.logger.debug('Updater thread started') self._bootstrap(bootstrap_retries, clean=clean, webhook_url='', allowed_updates=None) while self.running: try: updates = self.bot.get_updates( self.last_update_id, timeout=timeout, read_latency=read_latency, allowed_updates=allowed_updates) except RetryAfter as e: self.logger.info(str(e)) cur_interval = 0.5 + e.retry_after except TelegramError as te: self.logger.error("Error while getting Updates: {0}".format(te)) # Put the error into the update queue and let the Dispatcher # broadcast it self.update_queue.put(te) cur_interval = self._increase_poll_interval(cur_interval) else: if not self.running: if len(updates) > 0: self.logger.debug('Updates ignored and will be pulled ' 'again on restart.') break if updates: for update in updates: self.update_queue.put(update) self.last_update_id = updates[-1].update_id + 1 cur_interval = poll_interval sleep(cur_interval)