Python telegram.ext.Dispatcher() Examples
The following are 12
code examples of telegram.ext.Dispatcher().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
telegram.ext
, or try the search function
.
Example #1
Source File: herokubotcp.py From ptb-heroku-skeleton with MIT License | 8 votes |
def __init__(self, TOKEN, NAME): super(BotComm, self).__init__() self.TOKEN = TOKEN self.NAME=NAME self.bot = telegram.Bot(self.TOKEN) try: self.bot.setWebhook("https://{}.herokuapp.com/{}".format(self.NAME, self.TOKEN)) except: raise RuntimeError("Failed to set the webhook") self.update_queue = Queue() self.dp = Dispatcher(self.bot, self.update_queue) self.dp.add_handler(CommandHandler("start", self._start)) self.dp.add_handler(MessageHandler(Filters.text, self._echo)) self.dp.add_error_handler(self._error)
Example #2
Source File: bot.py From python-telegram-bot-openshift with GNU General Public License v3.0 | 6 votes |
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()
Example #3
Source File: web_util.py From daysandbox_bot with MIT License | 5 votes |
def setup_web_app(app, mode='production'): logging.basicConfig(level=logging.DEBUG) bot = init_bot_with_mode(mode) update_queue = Queue() dispatcher = Dispatcher(bot, update_queue, workers=32) #dispatcher = Dispatcher(bot, None, workers=0) register_handlers(dispatcher, mode) thread = Thread(target=dispatcher.start, name='dispatcher') thread.start() secret_key = str(uuid.uuid4()) @app.route('/%s/' % secret_key, method='POST') def page(): if request.headers.get('content-type') == 'application/json': json_string = request.body.read().decode('utf-8') update = Update.de_json(json.loads(json_string), bot) dispatcher.process_update(update) return '' else: abort(403) config = json.load(open('var/config.json')) key = 'test_webhook_url' if mode == 'test' else 'webhook_url' url = config[key] % {'secret_key': secret_key} logging.debug('Webhook has been set to %s' % url) bot.set_webhook(url=url)
Example #4
Source File: updater.py From telegram-robot-rss with Mozilla Public License 2.0 | 5 votes |
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()
Example #5
Source File: app.py From python-telegram-bot-openshift3 with GNU General Public License v3.0 | 5 votes |
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(CommandHandler("start", start)) dp.add_handler(CommandHandler("help", help)) # on noncommand i.e message - echo the message on Telegram dp.add_handler(MessageHandler(Filters.text, echo)) # log all errors dp.add_error_handler(error) # 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()
Example #6
Source File: pr.py From vldc-bot with MIT License | 5 votes |
def add_pr(upd: Updater, handlers_group: int): logger.info("registering PR handler") dp: Dispatcher = upd.dispatcher dp.add_handler(CommandHandler("pr", _pr), handlers_group)
Example #7
Source File: at_least_70k.py From vldc-bot with MIT License | 5 votes |
def add_70k(upd: Updater, handlers_group: int): logger.info("registering 70k handler") dp: Dispatcher = upd.dispatcher dp.add_handler(CommandHandler("70k", _70k), handlers_group)
Example #8
Source File: message_handler.py From python-telegram-bot-GAE with GNU General Public License v3.0 | 5 votes |
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
Example #9
Source File: app.py From superCodingBot with MIT License | 4 votes |
def setup(self, webhook_url=None): """If webhook_url is not passed, run with long-polling.""" logging.basicConfig(level=logging.WARNING) if webhook_url: self.bot = Bot(self.bot_token) update_queue = Queue() dp = Dispatcher(self.bot, update_queue) else: updater = Updater(self.bot_token) self.bot = updater.bot dp = updater.dispatcher dp.add_handler(CommandHandler('help', self.help)) dp.add_handler(CommandHandler('start', self.start)) dp.add_handler(CommandHandler('ongoing', self.competitions.ongoing)) dp.add_handler(CommandHandler('givememydb', self.admin.givememydb)) dp.add_handler(CommandHandler('getcfjson', self.admin.getcfjson)) dp.add_handler(CommandHandler('adminhandle', self.admin.adminhandle)) dp.add_handler(CommandHandler('adminud', self.adminupdate)) dp.add_handler(CommandHandler('adminuq', self.admqupd)) dp.add_handler(self.cf.conv_handler10) dp.add_handler(self.cc.conv_handler) dp.add_handler(self.competitions.conv_handler) dp.add_handler(self.competitions.conv_handler1) dp.add_handler(self.register.conv_handler) dp.add_handler(self.compiler.conv_handler) dp.add_handler(self.unregister.conv_handler) dp.add_handler(self.ques_of_the_day.conv_handler) dp.add_handler(self.ques_of_the_day.conv_handler1) dp.add_handler(self.ranklist.conv_handler) dp.add_handler(self.update.conv_handler) dp.add_handler(self.geeks_for_geeks.conv_handler) dp.add_handler(self.admin.conv_handler1) dp.add_handler(self.admin.conv_handler2) dp.add_handler(self.conv_handler) # log all errors dp.add_error_handler(self.error_handler) if webhook_url: self.bot.set_webhook(webhook_url=webhook_url) thread = Thread(target=dp.start, name='dispatcher') thread.start() return update_queue, self.bot else: self.bot.set_webhook() # Delete webhook updater.start_polling() updater.idle()
Example #10
Source File: updater.py From telegram-robot-rss with Mozilla Public License 2.0 | 4 votes |
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 = []
Example #11
Source File: updater.py From telegram-robot-rss with Mozilla Public License 2.0 | 4 votes |
def _start_polling(self, poll_interval, timeout, read_latency, bootstrap_retries, clean, allowed_updates): # pragma: no cover # """ # 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)
Example #12
Source File: updater.py From telegram-robot-rss with Mozilla Public License 2.0 | 4 votes |
def _stop_dispatcher(self): self.logger.debug('Requesting Dispatcher to stop...') self.dispatcher.stop()