Python telegram.ext.MessageHandler() Examples
The following are 30
code examples of telegram.ext.MessageHandler().
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: Server.py From CineMonster with Apache License 2.0 | 7 votes |
def __init__(self): self.config_instance = self.config_init() updater = Updater(self.config_instance.TELEGRAM_BOT_KEY) dp = updater.dispatcher logging.basicConfig( format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', filename=self.config_instance.LOG_FILE ) dp.add_handler(MessageHandler( [Filters.text], self.command_check_resps)) dp.add_handler(CommandHandler("start", self.command_start)) dp.add_handler(CommandHandler( "roll", self.command_roll, pass_args=True)) dp.add_handler(CommandHandler("leaderboard", self.command_leaderboard)) dp.add_error_handler(self.error) jq = updater.job_queue jq.put(self.update_all_timers, 1) self.logger.info("Started... ") updater.start_polling() updater.idle()
Example #3
Source File: telegram.py From platypush with MIT License | 7 votes |
def run(self): # noinspection PyPackageRequirements from telegram.ext import MessageHandler, Filters super().run() telegram = self._plugin.get_telegram() dispatcher = telegram.dispatcher dispatcher.add_handler(MessageHandler(Filters.group, self._group_hook())) dispatcher.add_handler(MessageHandler(Filters.text, self._msg_hook(TextMessageEvent))) dispatcher.add_handler(MessageHandler(Filters.photo, self._msg_hook(PhotoMessageEvent))) dispatcher.add_handler(MessageHandler(Filters.video, self._msg_hook(VideoMessageEvent))) dispatcher.add_handler(MessageHandler(Filters.contact, self._msg_hook(ContactMessageEvent))) dispatcher.add_handler(MessageHandler(Filters.location, self._msg_hook(LocationMessageEvent))) dispatcher.add_handler(MessageHandler(Filters.document, self._msg_hook(DocumentMessageEvent))) dispatcher.add_handler(MessageHandler(Filters.command, self._command_hook())) self.logger.info('Initialized Telegram backend') telegram.start_polling() # vim:sw=4:ts=4:et:
Example #4
Source File: bot.py From gdrivemirror_bot with GNU General Public License v3.0 | 6 votes |
def main(): updater = Updater(token=TOKEN, workers = 8) dispatcher = updater.dispatcher start_cmd = CommandHandler("start" , start) help_cmd = CommandHandler("help" , help) donate_cmd = CommandHandler("donate" , donate) dispatcher.add_handler(start_cmd) dispatcher.add_handler(help_cmd) dispatcher.add_handler(donate_cmd) if ADMIN_MODULE: extras.add_extra_commands(dispatcher) else: print("ADMIN_MODULE not found. (Won't effect the bot though.)") start_handler = MessageHandler((Filters.all) , start_bot) dispatcher.add_handler(start_handler) updater.start_polling()
Example #5
Source File: telegram_main.py From convai-bot-1337 with GNU General Public License v3.0 | 6 votes |
def __init__(self, token): self._bot = telegram.Bot(token) self._updater = Updater(bot=self._bot) dp = self._updater.dispatcher dp.add_handler(CommandHandler("start", self._start_cmd)) dp.add_handler(CommandHandler("reset", self._reset_cmd)) dp.add_handler(CommandHandler("stop", self._reset_cmd)) dp.add_handler(CommandHandler("help", self._help_cmd)) dp.add_handler(CommandHandler("text", self._text_cmd)) dp.add_handler(CommandHandler("evaluation_start", self._evaluation_start_cmd)) dp.add_handler(CommandHandler("evaluation_end", self._evaluation_end_cmd)) dp.add_handler(MessageHandler(Filters.text, self._echo_cmd)) dp.add_handler(CallbackQueryHandler(self._eval_keyboard)) dp.add_error_handler(self._error) self._users_fsm = {} self._users = {} self._text_and_qas = load_text_and_qas('data/squad-25-qas.json') self._text_ind = 0 self._evaluation = {} self._eval_suggestions = None
Example #6
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 #7
Source File: telegrambot.py From django-telegrambot with BSD 3-Clause "New" or "Revised" License | 6 votes |
def main(): logger.info("Loading handlers for telegram bot") # Default dispatcher (this is related to the first bot in settings.TELEGRAM_BOT_TOKENS) dp = DjangoTelegramBot.dispatcher # To get Dispatcher related to a specific bot # dp = DjangoTelegramBot.getDispatcher('BOT_n_token') #get by bot token # dp = DjangoTelegramBot.getDispatcher('BOT_n_username') #get by bot username # on different commands - answer in Telegram dp.add_handler(CommandHandler("start", start)) dp.add_handler(CommandHandler("help", help)) dp.add_handler(CommandHandler("startgroup", startgroup)) dp.add_handler(CommandHandler("me", me)) dp.add_handler(CommandHandler("chat", chat)) dp.add_handler(MessageHandler(Filters.forwarded , forwarded)) # 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)
Example #8
Source File: telegrambot.py From django-telegrambot with BSD 3-Clause "New" or "Revised" License | 6 votes |
def main(): logger.info("Loading handlers for telegram bot") # Default dispatcher (this is related to the first bot in settings.TELEGRAM_BOT_TOKENS) dp = DjangoTelegramBot.dispatcher # To get Dispatcher related to a specific bot # dp = DjangoTelegramBot.getDispatcher('BOT_n_token') #get by bot token # dp = DjangoTelegramBot.getDispatcher('BOT_n_username') #get by bot username # on different commands - answer in Telegram 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) # log all errors dp.addErrorHandler(error)
Example #9
Source File: towel_mode.py From vldc-bot with MIT License | 6 votes |
def add_towel_mode(upd: Updater, handlers_group: int): logger.info("registering towel-mode handlers") dp = upd.dispatcher # catch all new users and drop the towel dp.add_handler(MessageHandler(Filters.status_update.new_chat_members, catch_new_user), handlers_group) # check for reply or remove messages dp.add_handler(MessageHandler( Filters.group & ~Filters.status_update, catch_reply), handlers_group ) # "i am a bot button" dp.add_handler(CallbackQueryHandler(i_am_a_bot_btn), handlers_group) # ban quarantine users, if time is gone upd.job_queue.run_repeating(ban_user, interval=60, first=60, context={ "chat_id": get_config()["GROUP_CHAT_ID"] })
Example #10
Source File: start.py From server_monitor_bot with MIT License | 6 votes |
def main(): logging_location = log_location + log_name logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level= logging.INFO, filename= logging_location) logging.info("Bot server started") print(token_val) try: if token_val == "": raise ValueError("Not found") command_filter = CommandFilter() updater = Updater(token= token_val, use_context= True) dispatcher = updater.dispatcher start_handler = CommandHandler('start',start) command_message_handler = MessageHandler(command_filter, exec_command) dispatcher.add_handler(start_handler) dispatcher.add_handler(command_message_handler) logging.info("Successfully initialized handlers") except ValueError as ex: print('It seems your token is empty!') return except Exception as e: logging.warning("Error intializing handlers") logging.error(str(e)) updater.start_polling()
Example #11
Source File: maintenance.py From NanoWalletBot with BSD 3-Clause "New" or "Revised" License | 6 votes |
def main(): # Create the EventHandler and pass it your bot's token. if (proxy_url is None): updater = Updater(api_key, workers=64) else: updater = Updater(token=api_key, workers=64, request_kwargs={'proxy_url': proxy_url, 'urllib3_proxy_kwargs': {'username': proxy_user, 'password': proxy_pass}}) # Get the dispatcher to register handlers dp = updater.dispatcher # on noncommand i.e message - return not found dp.add_handler(MessageHandler(Filters.command, maintenance)) dp.add_handler(MessageHandler(Filters.text, maintenance)) # log all errors dp.add_error_handler(error) # Start the Bot #updater.start_polling() updater.start_webhook(listen='127.0.0.1', port=int(listen_port), url_path=api_key) updater.bot.setWebhook('https://{0}/{1}'.format(domain, api_key)) # Run the bot until the you presses Ctrl-C or the process receives SIGINT, # SIGTERM or SIGABRT. This should be used most of the time, since # start_polling() is non-blocking and will stop the bot gracefully. updater.idle()
Example #12
Source File: bot.py From ConvAI-baseline with Apache License 2.0 | 6 votes |
def __init__(self): self.history = {} self.updater = Updater(TOKEN) self.name = str(self).split(' ')[-1][:-1] self.dp = self.updater.dispatcher self.dp.add_handler(CommandHandler("start", start)) self.dp.add_handler(CommandHandler("help", help)) self.dp.add_handler(MessageHandler([Filters.text], echo)) self.dp.add_error_handler(error) self.stories = StoriesHandler() logger.info('I\'m alive!')
Example #13
Source File: bot.py From TranscriberBot with GNU General Public License v3.0 | 6 votes |
def __register_handlers(self): functional.apply_fn( self.message_handlers.items(), lambda h: self.__add_handler(MessageHandler( h[0], lambda b, u, **kwargs: self.__pre__hook(h[1], b, u, **kwargs))) ) functional.apply_fn( self.command_handlers.items(), lambda h: self.__add_handler(ChannelCommandHandler( h[0], lambda b, u, **kwargs: self.__pre__hook(h[1][0], b, u, **kwargs), filters=h[1][1])) ) functional.apply_fn( self.callback_handlers.items(), lambda h: self.__add_handler(CallbackQueryHandler(h[1])) ) # Decorators for adding callbacks
Example #14
Source File: daysandbox_bot.py From daysandbox_bot with MIT License | 6 votes |
def register_handlers(dispatcher, mode): assert mode in ('production', 'test') dispatcher.add_handler(MessageHandler( Filters.status_update.new_chat_members, handle_new_chat_members )) dispatcher.add_handler(CommandHandler( ['start', 'help'], handle_start_help )) dispatcher.add_handler(CommandHandler('stat', handle_stat)) dispatcher.add_handler(CommandHandler( ['daysandbox_set', 'daysandbox_get'], handle_set_get )) dispatcher.add_handler(RegexHandler( r'^/setlogformat ', handle_setlogformat, channel_post_updates=True )) dispatcher.add_handler(CommandHandler('setlog', handle_setlog)) dispatcher.add_handler(CommandHandler('unsetlog', handle_unsetlog)) dispatcher.add_handler(MessageHandler( Filters.all, partial(handle_any_message, mode), edited_updates=True ))
Example #15
Source File: admin.py From superCodingBot with MIT License | 6 votes |
def __init__(self, mount_point, admin_list, fallback): self.admin_list = admin_list self.mount_point = mount_point self.utility = Utility(mount_point) self.conv_handler1 = ConversationHandler( entry_points=[CommandHandler('broadcast', self.broadcast)], allow_reentry=True, states={ BDC: [MessageHandler(Filters.text, self.broadcast_message)] }, fallbacks=[fallback] ) self.conv_handler2 = ConversationHandler( entry_points=[CommandHandler('senddb', self.getDb)], allow_reentry=True, states={ DB: [MessageHandler(Filters.document, self.db)] }, fallbacks=[fallback] ) # START OF ADMIN CONVERSATION HANDLER TO BROADCAST MESSAGE
Example #16
Source File: register.py From superCodingBot with MIT License | 6 votes |
def __init__(self, mount_point, fallback): self.mount_point = mount_point self.conv_handler = ConversationHandler( entry_points=[CommandHandler('register', self.register)], allow_reentry=True, states={ NAME: [MessageHandler(Filters.text, self.name, pass_user_data=True)], JUDGE: [CallbackQueryHandler(self.judge, pass_user_data=True, pattern=r'\w*reg1\b')], HANDLE: [MessageHandler(Filters.text, self.handle, pass_user_data=True)] }, fallbacks=[fallback] )
Example #17
Source File: telegram_fbchat_facade.py From steely with GNU General Public License v3.0 | 6 votes |
def listen(self): def innerOnMessage(bot, update): try: print(update.message) thread_id = update.effective_chat.id thread_type = _telegram_chat_to_fbchat_thread_type( update.effective_chat) self.thread[thread_id].append(update.effective_message) self.onMessage(author_id=update.effective_user.id, message=update.effective_message.text, thread_id=thread_id, thread_type=thread_type) except Exception as e: log(e) self.dispatcher.add_handler(MessageHandler(filters=Filters.all, callback=innerOnMessage)) self.updater.start_polling() self.updater.idle()
Example #18
Source File: bot.py From welcomebot with GNU General Public License v2.0 | 6 votes |
def main(): # Create the Updater and pass it your bot's token. updater = Updater(TOKEN, workers=10, use_context=True) # Get the dispatcher to register handlers dp = updater.dispatcher dp.add_handler(CommandHandler("start", help)) dp.add_handler(CommandHandler("help", help)) dp.add_handler(CommandHandler("welcome", set_welcome)) dp.add_handler(CommandHandler("goodbye", set_goodbye)) dp.add_handler(CommandHandler("disable_goodbye", disable_goodbye)) dp.add_handler(CommandHandler("lock", lock)) dp.add_handler(CommandHandler("unlock", unlock)) dp.add_handler(CommandHandler("quiet", quiet)) dp.add_handler(CommandHandler("unquiet", unquiet)) dp.add_handler(MessageHandler(Filters.status_update, empty_message)) dp.add_error_handler(error) updater.start_polling(timeout=30, clean=True) updater.idle()
Example #19
Source File: compiler.py From superCodingBot with MIT License | 6 votes |
def __init__(self, api_key, fallback): self.compiler = HackerRankAPI(api_key=api_key) self.conv_handler = ConversationHandler( entry_points=[CommandHandler('compiler', self.compilers)], allow_reentry=True, states={ LANG: [CallbackQueryHandler(self.lang, pass_user_data=True, pattern=r'\w*comp1\b')], CODE: [CallbackQueryHandler(self.code, pass_user_data=True, pattern=r'\w*so1\b')], DECODE: [MessageHandler(Filters.text, self.decode, pass_user_data=True)], TESTCASES: [MessageHandler(Filters.text, self.testcases, pass_user_data=True)], OTHER: [MessageHandler(Filters.text, self.other, pass_user_data=True)], FILE: [MessageHandler(Filters.document, self.filer, pass_user_data=True)], FILETEST: [MessageHandler(Filters.document, self.filetest, pass_user_data=True)] }, fallbacks=[fallback] )
Example #20
Source File: smile_mode.py From vldc-bot with MIT License | 5 votes |
def add_smile_mode(upd: Updater, handlers_group: int): """ Set up all handler for SmileMode """ logger.info("registering smile-mode handlers") dp = upd.dispatcher dp.add_handler(MessageHandler(~Filters.sticker & ~Filters.animation, smile), handlers_group)
Example #21
Source File: bot.py From Awesome-Python-Scripts with MIT License | 5 votes |
def main(): """Start the bot.""" # Create the EventHandler and pass it your bot's token. TOKEN = os.environ['TOKEN'] updater = Updater(TOKEN) # Get the dispatcher to register handlers dp = updater.dispatcher # on different commands - answer in Telegram dp.add_handler(CommandHandler("start", start)) dp.add_handler(CommandHandler("help", help)) dp.add_handler(CommandHandler("get", get)) dp.add_handler(CommandHandler("ls", ls)) dp.add_handler(CommandHandler("put", put)) dp.add_handler(CommandHandler("mkdir", mkdir)) #admin functionalities dp.add_handler(CommandHandler("adduser", add_user)) dp.add_handler(CommandHandler("showuser", show_user)) dp.add_handler(CommandHandler("removeUser", remove_user)) dp.add_handler(CommandHandler("remove", remove)) dp.add_handler(CommandHandler("rmdir", rmdir)) # on noncommand i.e message - echo the message on Telegram dp.add_handler(MessageHandler(Filters.document, echo)) # log all errors dp.add_error_handler(error) # Start the Bot updater.start_polling() # Run the bot until you press Ctrl-C or the process receives SIGINT, # SIGTERM or SIGABRT. This should be used most of the time, since # start_polling() is non-blocking and will stop the bot gracefully. updater.idle()
Example #22
Source File: main.py From simple-forwarder-bot with MIT License | 5 votes |
def main(): global dispatcher, updater, Token, Blacklist, admin load_config() updater = Updater(Token) dispatcher = updater.dispatcher fwd_text_handler = MessageHandler(Filters.all & (~Filters.command), read_text_message) ban_user_handler = CommandHandler('ban', ban_user) unban_user_handler = CommandHandler('unban', unban_user) callback_query_handler = CallbackQueryHandler(answer_session) dispatcher.add_handler(callback_query_handler) dispatcher.add_handler(fwd_text_handler) dispatcher.add_handler(ban_user_handler) dispatcher.add_handler(unban_user_handler) updater.start_polling()
Example #23
Source File: bot.py From music-bot with GNU General Public License v3.0 | 5 votes |
def main(): u = Updater('YOUR-TOKEN') dp = u.dispatcher dp.add_handler(CommandHandler("start", start)) dp.add_handler(MessageHandler(Filters.text, music)) u.start_polling() u.idle()
Example #24
Source File: __main__.py From Marie-2.0-English with GNU General Public License v3.0 | 5 votes |
def main(): test_handler = CommandHandler("test", test) start_handler = CommandHandler("start", start, pass_args=True) help_handler = CommandHandler("help", get_help) help_callback_handler = CallbackQueryHandler(help_button, pattern=r"help_") settings_handler = CommandHandler("settings", get_settings) settings_callback_handler = CallbackQueryHandler(settings_button, pattern=r"stngs_") donate_handler = CommandHandler("donate", donate) migrate_handler = MessageHandler(Filters.status_update.migrate, migrate_chats) # dispatcher.add_handler(test_handler) dispatcher.add_handler(start_handler) dispatcher.add_handler(help_handler) dispatcher.add_handler(settings_handler) dispatcher.add_handler(help_callback_handler) dispatcher.add_handler(settings_callback_handler) dispatcher.add_handler(migrate_handler) dispatcher.add_handler(donate_handler) # dispatcher.add_error_handler(error_callback) if WEBHOOK: LOGGER.info("Using webhooks.") updater.start_webhook(listen="0.0.0.0", port=PORT, url_path=TOKEN) if CERT_PATH: updater.bot.set_webhook(url=URL + TOKEN, certificate=open(CERT_PATH, 'rb')) else: updater.bot.set_webhook(url=URL + TOKEN) else: LOGGER.info("Using long polling.") updater.start_polling(timeout=15, read_latency=4) updater.idle()
Example #25
Source File: taghints.py From rules-bot with GNU Affero General Public License v3.0 | 5 votes |
def register(dispatcher): dispatcher.add_handler(MessageHandler(Filters.regex(rf'{"|".join(HINTS.keys())}.*'), hint_handler)) dispatcher.add_handler(CommandHandler(('hints', 'listhints'), list_available_hints))
Example #26
Source File: echobot2.py From bale-bot-samples with Apache License 2.0 | 5 votes |
def main(): """Start the bot.""" # Create the Updater and pass it your bot's token. # Make sure to set use_context=True to use the new context based callbacks # Post version 12 this will no longer be necessary updater = Updater(token="TOKEN", base_url="https://tapi.bale.ai/") # Get the dispatcher to register handlers dp = updater.dispatcher # on different commands - answer in Telegram 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) # Start the Bot updater.start_polling(poll_interval=2) # Run the bot until you press Ctrl-C or the process receives SIGINT, # SIGTERM or SIGABRT. This should be used most of the time, since # start_polling() is non-blocking and will stop the bot gracefully. updater.idle()
Example #27
Source File: telegram.py From macaw with MIT License | 5 votes |
def __init__(self, params): """ A Telegram bot interface for Macaw. Args: params(dict): A dict of parameters. The params 'logger' and 'bot_token' are mandatory. """ super().__init__(params) self.logger = self.params['logger'] self.MAX_MSG_LEN = 1000 # maximum number of characters in each response message. self.MAX_OPTION_LEN = 30 # maximum number of characters in each clickable option text. # Starting the bot by creating the Updater. # Make sure to set use_context=True to use the new context based callbacks # If you don't have a bot_token, add 'botfather' to your personal Telegram account and follow the instructions # to get a token for your bot. self.updater = Updater(self.params['bot_token'], use_context=True) self.dp = self.updater.dispatcher # Telegram command handlers (e.g., /start) self.dp.add_handler(CommandHandler('start', self.start)) self.dp.add_handler(CommandHandler('help', self.help)) # Telegram message handlers self.dp.add_handler(MessageHandler(Filters.text, self.request_handler)) self.dp.add_handler(MessageHandler(Filters.voice, self.voice_request_handler)) self.dp.add_handler(CallbackQueryHandler(self.button_click_handler)) # logging all errors self.dp.add_error_handler(self.error)
Example #28
Source File: fools.py From vldc-bot with MIT License | 5 votes |
def add_fools_mode(upd: Updater, handlers_group: int): logger.info("registering fools handlers") dp = upd.dispatcher dp.add_handler(MessageHandler(Filters.group & ~ Filters.status_update, mesaĝa_traduko), handlers_group)
Example #29
Source File: uwu.py From vldc-bot with MIT License | 5 votes |
def add_uwu(upd: Updater, handlers_group: int): logger.info("register uwu handlers") dp = upd.dispatcher dp.add_handler(MessageHandler(uwu_filter, uwu), handlers_group)
Example #30
Source File: bot.py From Telegram-bot-Google-Drive with MIT License | 5 votes |
def main(): updater = Updater(token=config.TOKEN,use_context=True) dispatcher = updater.dispatcher updater.dispatcher.add_handler(CommandHandler('start', start)) dispatcher.add_handler(MessageHandler(Filters.document,file_handler)) updater.start_polling()