def main(): logging.info('covid19india_bot started') _initStateCodes('statecodes.json') updater = Updater(token=_readToken(_tokenFile), use_context=True) updater.dispatcher.add_handler(CommandHandler('start', start)) updater.dispatcher.add_handler(CommandHandler('help', help)) updater.dispatcher.add_handler(CommandHandler('covid19india', covid19india)) updater.dispatcher.add_handler(CommandHandler('statecodes', statecodes)) updater.dispatcher.add_handler(CommandHandler('mohfw', mohfw)) updater.dispatcher.add_handler(CommandHandler('comparemohfw', comparemohfw)) updater.dispatcher.add_handler(CommandHandler('ndma', ndma)) updater.dispatcher.add_handler(CommandHandler('comparendma', comparendma)) updater.dispatcher.add_handler(CommandHandler('recon', recon)) updater.dispatcher.add_handler(CommandHandler('advanced', advanced)) updater.dispatcher.add_handler(CommandHandler('request', request)) updater.dispatcher.add_handler(MessageHandler(Filters.regex('#request') | \ Filters.regex('#resources'), \ request)) updater.start_polling() updater.idle()
def main(): updater = Updater(TOKEN, use_context=True) #get the dispatcher to register handler dispatcher = updater.dispatcher dispatcher.add_handler(CommandHandler("start", start)) dispatcher.add_handler(MessageHandler(Filters.regex('^💼 Wallets$'),save_wallet)) dispatcher.add_handler(MessageHandler(Filters.regex('^🎁 Bonus$'),bonus)) my_conversation_handler = ConversationHandler(entry_points=[CallbackQueryHandler(button_wall, pattern='^' + str(TITLE) + '$')],states={TITLE: [MessageHandler(Filters.text & ~Filters.command, get_title)]},fallbacks=[CommandHandler("caaancel",cancel)]) #------Second Conversation my_conversation_handlor = ConversationHandler(entry_points=[MessageHandler(Filters.regex('^☎️ Help$'),supp)],states={TYPING: [MessageHandler(Filters.text,typ)]},fallbacks=[CommandHandler("caaancel",cancel)]) dispatcher.add_handler(my_conversation_handler) dispatcher.add_handler(my_conversation_handlor) dispatcher.add_handler(MessageHandler(Filters.text,joined)) updater.start_webhook(listen="0.0.0.0", port=int(PORT), url_path=TOKEN) updater.bot.setWebhook('https://working-bot-python.herokuapp.com/' + TOKEN) print('Running... [Press Ctrl+C to stop]') updater.idle() update.stop()
def __init__(self, channel: 'TelegramChannel'): self.channel: 'TelegramChannel' = channel self.bot = channel.bot_manager self.msg_storage: Dict[Tuple[int, int], ETMCommandMsgStorage] = dict() self.bot.dispatcher.add_handler( CommandHandler("extra", self.extra_listing)) self.bot.dispatcher.add_handler( MessageHandler( Filters.regex(r"^/h_(?P<id>[0-9]+)_(?P<command>[a-z0-9_-]+)"), self.extra_usage)) self.bot.dispatcher.add_handler( MessageHandler( Filters.regex(r"^/(?P<id>[0-9]+)_(?P<command>[a-z0-9_-]+)"), self.extra_call)) self.command_conv = ConversationHandler( entry_points=[], states={ Flags.COMMAND_PENDING: [CallbackQueryHandler(self.command_exec)] }, fallbacks=[CallbackQueryHandler(self.bot.session_expired)], per_message=True, per_chat=True, per_user=False) self.bot.dispatcher.add_handler(self.command_conv) self.modules_list: List[Any[EFBChannel, EFBMiddleware]] = [] for i in sorted(coordinator.slaves.keys()): self.modules_list.append(coordinator.slaves[i]) self.modules_list.extend(coordinator.middlewares)
def decorator(func): arg: Any if not BotMemory.updater: create_bot() if issubclass(cls, MessageHandler) and isinstance(command, str): filters = kwargs.pop("filters", None) arg = Filters.regex(command) if filters: arg = arg & filters if not allow_updates: arg = arg & ~Filters.update.edited_message else: arg = command or func.__name__ if not allow_updates and not issubclass(cls, MessageHandler): filters = kwargs.pop("filters", None) if filters: filters = filters & ~Filters.update.edited_message else: filters = ~Filters.update.edited_message kwargs["filters"] = filters BotMemory.updater.dispatcher.add_handler(cls(arg, func, **kwargs)) return func
def _add_handlers(self): self.dp.add_handler( CommandHandler( "start", self._start_chat_handler_secure, Filters.regex(self.secure_key) ) ) self.dp.add_handler(CommandHandler("start", self._start_chat_handler)) super()._add_handlers()
def add_handlers(self): start_handler = CommandHandler('start', self.start) self.dispatcher.add_handler(start_handler) admin_list_users_handler = MessageHandler(Filters.regex('^LIST$'), self.admin_list_users) self.dispatcher.add_handler(admin_list_users_handler) admin_add_user_handler = MessageHandler(Filters.regex('^ADD \d+$'), self.admin_add_user) self.dispatcher.add_handler(admin_add_user_handler) admin_delete_user_handler = MessageHandler(Filters.regex('^DEL \d+$'), self.admin_delete_user) self.dispatcher.add_handler(admin_delete_user_handler) admin_sendtoall_handler = MessageHandler(Filters.regex('^SENDTOALL'), self.admin_sendtoall) self.dispatcher.add_handler(admin_sendtoall_handler) mainmenu_handler = MessageHandler(Filters.regex('^main menu$'), self.start) self.dispatcher.add_handler(mainmenu_handler) openconnect_handler = MessageHandler(Filters.regex('^openconnect$'), self.openconnect) self.dispatcher.add_handler(openconnect_handler) mtproto_handler = MessageHandler(Filters.regex('^mtproto$'), self.mtproto) self.dispatcher.add_handler(mtproto_handler) openconnect_show_data_handler = \ MessageHandler(Filters.regex('^show openconnect data$'), self.openconnect_show_data) self.dispatcher.add_handler(openconnect_show_data_handler) openconnect_add_data_handler = \ MessageHandler(Filters.regex('^add openconnect data$'), self.openconnect_add_data) self.dispatcher.add_handler(openconnect_add_data_handler) user_input_handler = MessageHandler(Filters.regex('.*'), self.user_input) self.dispatcher.add_handler(user_input_handler)
def main() -> None: updater = Updater(token=config.TOKEN, use_context=True) dispatcher = updater.dispatcher down_handler = ConversationHandler( entry_points=[CommandHandler('download', download)], states = { TYPE: [MessageHandler(Filters.regex('^('+'|'.join([i for i in config.ALLOWED_TYPES])+')$'), type)], MAGNET: [MessageHandler(Filters.regex('^magnet*'), magnet)], CONFIRM: [MessageHandler(Filters.regex('^OK$'), confirm)], }, fallbacks=[CommandHandler('cancel', cancel),], ) dispatcher.add_handler(down_handler) dispatcher.add_handler(CommandHandler('start', start)) dispatcher.add_handler(CommandHandler('status', status)) dispatcher.add_handler(CommandHandler('clear', clear)) dispatcher.add_handler(CommandHandler('help', help)) dispatcher.add_handler(MessageHandler(Filters.command, unknown)) updater.start_polling() updater.idle()
def start(): random.seed() logging.basicConfig( level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s') updater = Updater(token=config.BOT_TOKEN) dispatcher = updater.dispatcher dispatcher.add_handler( MessageHandler(Filters.regex("(?i).*да[^\w]*$"), message_handler)) updater.start_polling()
def add_roll(upd: Updater, handlers_group: int): logger.info("registering roll handlers") dp = upd.dispatcher dp.add_handler(MessageHandler(Filters.dice, roll), handlers_group) dp.add_handler( MessageHandler(Filters.regex(MEME_REGEX), roll, run_async=True), handlers_group ) dp.add_handler( CommandHandler( "gdpr_me", satisfy_GDPR, filters=Filters.chat(username=get_group_chat_id().strip("@")), run_async=True, ), handlers_group, ) dp.add_handler( CommandHandler( "hussars", show_hussars, filters=~Filters.chat(username=get_group_chat_id().strip("@")) | admin_filter, run_async=True, ), handlers_group, ) dp.add_handler( CommandHandler( "htop", show_active_hussars, filters=admin_filter & Filters.chat(username=get_group_chat_id().strip("@")), run_async=True, ), handlers_group, ) dp.add_handler( CommandHandler( "wipe_hussars", wipe_hussars, filters=admin_filter & Filters.chat(username=get_group_chat_id().strip("@")), run_async=True, ), handlers_group, )
def _init_updater(api_token): # Create the Updater and pass it your bot's token. updater = Updater(api_token, use_context=True) updater.dispatcher.add_handler( CommandHandler('start', _start_command_handler)) updater.dispatcher.add_handler( CommandHandler('help', _help_command_handler)) updater.dispatcher.add_handler( MessageHandler(Filters.regex(TODO_LIST_START_REGEX), _todo_list_message_handler)) updater.dispatcher.add_handler( CallbackQueryHandler(_keyboard_click_handler)) updater.dispatcher.add_error_handler(_error_handler) return updater
def main(): logger = Logger('finance_telebot.log', os.getenv('DEBUG') == 'true') logger.info('Starting Finance Bot') token = os.getenv('TELEGRAM_BOT_TOKEN') updater = Updater(token=os.getenv('TELEGRAM_BOT_TOKEN'), use_context=True) dispatcher = updater.dispatcher _init_commands(dispatcher, logger) _init_callbacks(dispatcher, logger) dispatcher.add_handler( MessageHandler(Filters.regex(r'^(\d+)$'), number_handler)) dispatcher.add_handler(MessageHandler(Filters.text, text_handler)) # register_dispatcher(dispatcher) # jq = updater.job_queue # jq.run_repeating(command.job_save_mem, 3 * 3600, 3600) run(updater, token) updater.idle() logger.info('Stopping Finance Bot') updater.stop()
def init(): global tg_updater global tg_dispatcher timer_thread = threading.Thread(target=main_loop) timer_thread.start() cmd_thread = threading.Thread(target=cmd_loop) cmd_thread.start() start_handler = CommandHandler('start', start) tg_dispatcher.add_handler(start_handler) help_handler = CommandHandler('help', printHelp) tg_dispatcher.add_handler(help_handler) stop_handler = CommandHandler('stop', stopNotice) tg_dispatcher.add_handler(stop_handler) resume_handler = CommandHandler('resume', resumeNotice) tg_dispatcher.add_handler(resume_handler) inm_handler = CommandHandler('114514', RedTeaOnly) tg_dispatcher.add_handler(inm_handler) set_timezone_handler = ConversationHandler( entry_points=[CommandHandler('settimezone', set_timezone)], states={ SETTING_TZ: [MessageHandler(Filters.regex('^[+-][0-9]{1,2}:00.*'), set_timezone_done), MessageHandler(~Filters.command, set_timezone_wrong_format)], SETTING_TZ_RETRY: [MessageHandler(~Filters.command, set_timezone)] }, fallbacks=[CommandHandler('cancel', cancel_set_timezone)] ) tg_dispatcher.add_handler(set_timezone_handler) tg_updater.start_polling() #tg_updater.idle() pass
return ConversationHandler.END def unrecognized(update: Update, _context: CallbackContext): '''Guide the user if they are unsure of what to write.''' update.message.reply_text( 'I don\'t see numbers here 👀\n\n' 'You can specify the amount of copies with a single number.\n' 'Examples:\n' ' • <code>1</code>\n' ' • <code>10</code>\n', parse_mode=ParseMode.HTML, ) copies_handler = ConversationHandler( entry_points=[ CallbackQueryHandler(update_copies, pattern='[0-9a-f]+:copies') ], states={ State.UPDATE: [ MessageHandler(Filters.regex(number_ptn), process_input), CallbackQueryHandler(increment, pattern='[0-9a-f]+:copies:inc'), CallbackQueryHandler(decrement, pattern='[0-9a-f]+:copies:dec'), CallbackQueryHandler(end_conversation, pattern='[0-9a-f]+:copies:back'), ], }, fallbacks=[MessageHandler(Filters.text, unrecognized)], )
""" message to handle any "Option [0-9]" Regrex. """ update.message.reply_text("For Future Implementations...") # sending the reply message with the selected option #update.message.reply_text("You just clicked on '%s'" % update.message.text) pass updater.dispatcher.add_handler(CommandHandler("start", start)) updater.dispatcher.add_handler(CommandHandler("remove", remove)) updater.dispatcher.add_handler(CommandHandler("help", help)) updater.dispatcher.add_handler(CommandHandler("getstatus", getstatus)) updater.dispatcher.add_handler(CommandHandler("execquery", execquery)) updater.dispatcher.add_handler( MessageHandler(Filters.regex(r"TD Specific"), TDSpecific)) updater.dispatcher.add_handler( MessageHandler(Filters.regex(r"TD Adhoc"), TDAdhoc)) updater.dispatcher.add_handler( MessageHandler(Filters.regex(r"TD Extract"), TDExtract)) updater.dispatcher.add_handler( MessageHandler(Filters.regex(r"<<<<>>>>"), TDExtras)) updater.dispatcher.add_handler( MessageHandler(Filters.regex(r"J01_STEP"), TDSpecificSheet)) updater.dispatcher.add_handler( MessageHandler(Filters.regex(r"J01_UPDXL"), TDSpecificUpdExcel)) print( 'TD RegressionBot Started..... Please Check with Murali Before Closing This....' )
full_message += f"{user.full_name}: {round(user.current_score/user.num_responses,2) if user.num_responses else 0}, {banned_str}\n" context.bot.send_message(chat_id=update.message.chat_id, text=full_message) def get_group_id(update, context): update.message.reply_text(f"Group ID: {update.message.chat.id}") """ start - start counting lols getgroupid - get the current group's id getscores - get the list of current scores getaverages - get the list of average scores """ dispatcher.add_handler(CommandHandler("start", start)) dispatcher.add_handler(CommandHandler("getgroupid", get_group_id)) dispatcher.add_handler(CommandHandler("getscores", get_scores)) dispatcher.add_handler(CommandHandler("getscores", get_averages)) lol_handler = MessageHandler(filters=(Filters.reply & Filters.regex(GENERAL_LOL_REGEX)), callback=on_lol_message) dispatcher.add_handler(lol_handler) updater.start_polling() logging.info("Polling...") updater.idle() dump_thread_stop.set() dump_thread.join() dump_dictionary(id_to_userdata, USERDATA_FILE)
request = requests.get(url, headers=headers) soup = BeautifulSoup(request.text, 'html.parser') title = soup.select(css_selector) for i in title: if stopper == 'yes' and i == title[-1]: break # print(i.get_text()) if 'href' in str(i): s2=re.sub(':.*$','',str(i.get_text())) s+=f'''{s2} {re.findall('href="([^"]+)', str(i))[0]} ''' update.message.reply_text(f'{s}') updater = Updater(token, use_context=True) start_command = CommandHandler('start', start_handler) updater.dispatcher.add_handler(start_command) updater.dispatcher.add_handler(MessageHandler(Filters.regex(texts['btn1pg1']), page2)) updater.dispatcher.add_handler(MessageHandler(Filters.regex(texts['btn2pg1']), page2)) updater.dispatcher.add_handler(MessageHandler(Filters.regex(texts['btn1pg2']), searchpage)) updater.dispatcher.add_handler(MessageHandler(Filters.regex(texts['btn2pg2']), page3)) updater.dispatcher.add_handler(MessageHandler(Filters.regex(texts['btn1pg3']), searchpage)) updater.dispatcher.add_handler(MessageHandler(Filters.regex(texts['btn2pg3']), searchpage)) updater.dispatcher.add_handler(MessageHandler(Filters.regex(texts['return']), start_handler)) updater.dispatcher.add_handler(MessageHandler(Filters.regex('^([0-9]+)$'), newresult)) updater.dispatcher.add_handler(MessageHandler(Filters.text, noresult)) updater.start_polling() updater.idle()
def main(): updater = Updater(token, use_context=True) updater.dispatcher.add_handler(CommandHandler("start", start_handler)) updater.dispatcher.add_handler( MessageHandler(Filters.regex("قیمت طلا و سکه"), sekke_gold)) updater.dispatcher.add_handler( MessageHandler(Filters.regex("نرخ ارز"), arz)) updater.dispatcher.add_handler( MessageHandler(Filters.regex("ارزهای دیجیتال"), crypto)) updater.dispatcher.add_handler( MessageHandler(Filters.regex("تبدیل ارز"), exchange)) updater.dispatcher.add_handler( MessageHandler(Filters.regex("بازگشت"), return_handler)) updater.dispatcher.add_handler( MessageHandler(Filters.regex("سکه بهار آزادی"), bahar)) updater.dispatcher.add_handler( MessageHandler(Filters.regex("سکه امامی"), emami)) updater.dispatcher.add_handler( MessageHandler(Filters.regex("نیم سکه"), nim)) updater.dispatcher.add_handler( MessageHandler(Filters.regex("ربع سکه"), rob)) updater.dispatcher.add_handler( MessageHandler(Filters.regex("طلای ۱۸ عیار"), gold_18)) updater.dispatcher.add_handler( MessageHandler(Filters.regex("طلای ۲۴ عیار"), gold_24)) updater.dispatcher.add_handler( MessageHandler(Filters.regex("دلار آمریکا"), dollar_usa)) updater.dispatcher.add_handler(MessageHandler(Filters.regex("یورو"), euro)) updater.dispatcher.add_handler( MessageHandler(Filters.regex("پوند انگلیس"), pond)) updater.dispatcher.add_handler( MessageHandler(Filters.regex("فرانک سوئیس"), frank)) updater.dispatcher.add_handler( MessageHandler(Filters.regex("درهم امارات"), derham)) updater.dispatcher.add_handler( MessageHandler(Filters.regex("لیر ترکیه"), lir)) updater.dispatcher.add_handler( MessageHandler(Filters.regex("یوان چین"), youan)) updater.dispatcher.add_handler( MessageHandler(Filters.regex("ین ژاپن"), yen)) updater.dispatcher.add_handler( MessageHandler(Filters.regex("دلار کانادا"), dollar_canada)) updater.dispatcher.add_handler( MessageHandler(Filters.regex("بورس"), stock_price)) updater.dispatcher.add_handler( MessageHandler(Filters.regex("بیتکوین"), bitcoin)) updater.dispatcher.add_handler( MessageHandler(Filters.regex("اتریوم"), etherium)) updater.dispatcher.add_handler(MessageHandler(Filters.regex("تتر"), tether)) updater.dispatcher.add_handler(MessageHandler(Filters.regex("دش"), dash)) updater.dispatcher.add_handler(MessageHandler(Filters.regex("ریپل"), riple)) updater.dispatcher.add_handler( MessageHandler(Filters.regex("لایتکوین"), litecoin)) updater.dispatcher.add_handler( MessageHandler(Filters.regex("\d دلار به ریال"), dollar_to_rial)) updater.dispatcher.add_handler( MessageHandler(Filters.regex("\d ریال به دلار"), rial_to_dollar)) updater.start_polling() updater.idle()
updater.dispatcher.add_handler(CommandHandler('start', start_handler)) updater.dispatcher.add_handler(CommandHandler('authorize', authorize)) updater.dispatcher.add_handler( CallbackQueryHandler(check_auth, pattern='check_auth')) updater.dispatcher.add_handler(CommandHandler('shelves', shelves)) updater.dispatcher.add_handler(CallbackQueryHandler(shelves, pattern='shelves')) updater.dispatcher.add_handler(CommandHandler('books', books)) updater.dispatcher.add_handler(CallbackQueryHandler(books, pattern='books_')) updater.dispatcher.add_handler( MessageHandler(Filters.regex(r'^/book_\d*$'), book)) updater.dispatcher.add_handler( CallbackQueryHandler(add_to_shelf, pattern='add_to_shelf')) updater.dispatcher.add_handler( CallbackQueryHandler(add_to_shelf, pattern='rm_from_shelf')) updater.dispatcher.add_handler( CallbackQueryHandler(inlinebook, pattern='inlinebook')) updater.dispatcher.add_handler(CommandHandler('logout', logout)) updater.dispatcher.add_handler(InlineQueryHandler(inlinequery)) updater.dispatcher.add_handler(CommandHandler('search_books', search_books))
from telegram.ext.filters import Filters, BaseFilter import command import message import voice ### Создание обектов хенделеров ### # Комманды start_handler = CommandHandler('start', command.start) send_user_name_handler = CommandHandler('my_name', command.send_user_name) send_user_photo_handler = CommandHandler('my_photo', command.send_user_photo) send_qr_code_handler = CommandHandler('qr_code', command.send_qr_code) # Сообщения send_rand_chance_handler = MessageHandler(Filters.regex(r'\?'), message.send_rand_chance) # Голосовые сообщения send_text_from_voice_handler = MessageHandler(Filters.voice, voice.send_text_from_voice) ### ### ### ### ### ### ### ### ### ### # Список всех хендеров, не забудьте изменить после доавления нового handlers_list = [ # Комманды start_handler, send_user_name_handler, send_user_photo_handler,
""" method to handle /remove command to remove the keyboard and return back to text reply """ # making a reply markup to remove keyboard # documentation: https://python-telegram-bot.readthedocs.io/en/stable/telegram.replykeyboardremove.html reply_markup = ReplyKeyboardRemove() # sending the reply so as to remove the keyboard update.message.reply_text(text="I'm back.", reply_markup=reply_markup) pass def echo(update: Update, context: CallbackContext): """ message to handle any "Option [0-9]" Regrex. """ # sending the reply message with the selected option update.message.reply_text("You just clicked on '%s'" % update.message.text) pass updater.dispatcher.add_handler(CommandHandler("start", start)) updater.dispatcher.add_handler(CommandHandler("remove", remove)) # adding the message handler with filter to handle the Option [0-9] regex input # documentation for MessageHandler: https://python-telegram-bot.readthedocs.io/en/stable/telegram.ext.messagehandler.html # documentation for Filter: https://python-telegram-bot.readthedocs.io/en/stable/telegram.ext.filters.html#telegram.ext.filters.Filters updater.dispatcher.add_handler( MessageHandler(Filters.regex(r"Option [0-9]"), echo)) updater.start_polling()
def handler() -> MessageHandler: return MessageHandler(Filters.regex(config.CMD_MIN_MAX), cmd)
def handler() -> MessageHandler: return MessageHandler(Filters.regex(config.CMD_OPTIMIZE), cmd)
def __init__(self, token: str, redis: str = "redis://127.0.0.1:6379/0", superadmin: int = None, bosses_file: str = None, bosses_expiration: int = 12, gyms_file: str = None, gyms_expiration: int = 12, debug_folder: str = None): # Init and test redis connection self._redis = StrictRedis.from_url(url=redis, charset="utf-8", decode_responses=False) _LOGGER.info("Try to connect to Redis...") try: self._redis.ping() except exceptions.ConnectionError: _LOGGER.critical("Unable to connect to Redis") sys.exit() _LOGGER.info("Successfully connected to Redis") # Save superadmin self._superadmin = int(superadmin) if superadmin is not None else None # Add superadmin to the admins db if self._superadmin is not None: self._redis.set(redis_keys.SUPERADMIN, self._superadmin) self._redis.sadd(redis_keys.ADMIN, self._superadmin) # Save debug folder self._debug_folder = debug_folder if self._debug_folder is not None: self._debug_folder = os.path.abspath(debug_folder) ScreenshotRaid.debug = True _LOGGER.info("\"{}\" was set as debug folder".format( self._debug_folder)) # Init the bot self._bot = Bot(token) # Init updater self._updater = Updater(bot=self._bot, use_context=True) # Get the id of the bot self._id = self._bot.get_me().id # Set the handler functions # Set the handler for screens self._updater.dispatcher.add_handler( MessageHandler(Filters.photo, self._handler_screenshot)) # Set the handler to set the hangout self._updater.dispatcher.add_handler( MessageHandler( Filters.reply & Filters.regex(r"^\s*[0-2]?[0-9][:.,][0-5]?[0-9]\s*$"), self._handler_set_hangout)) # Set the handler for the buttons self._updater.dispatcher.add_handler( CallbackQueryHandler(self._handler_buttons)) # Set the handler for the pinned message notify self._updater.dispatcher.add_handler( MessageHandler(Filters.status_update.pinned_message, self._handler_event_pinned)) # Set the handler to set the boss self._updater.dispatcher.add_handler( MessageHandler(Filters.reply & Filters.regex(r"^\s*[a-zA-Z]+\s*$"), self._handler_set_boss)) # Set the handler for scan command self._updater.dispatcher.add_handler( CommandHandler("scan", self._handler_command_scan)) # Set the handler for enablechat command self._updater.dispatcher.add_handler( CommandHandler("enablechat", self._handler_command_enablechat)) # Set the handler for disablechat command self._updater.dispatcher.add_handler( CommandHandler("disablechat", self._handler_command_disablechat)) # Set the handler for enablescan command self._updater.dispatcher.add_handler( CommandHandler("enablescan", self._handler_command_enablescan)) # Set the handler for disablescan command self._updater.dispatcher.add_handler( CommandHandler("disablescan", self._handler_command_disablescan)) # Set the handler for addadmin command self._updater.dispatcher.add_handler( CommandHandler("addadmin", self._handler_command_addadmin, Filters.reply)) # Set the handler for removeadmin command self._updater.dispatcher.add_handler( CommandHandler("removeadmin", self._handler_command_removeadmin, Filters.reply)) # Set the handler for the errors self._updater.dispatcher.add_error_handler(self._handler_error) # Creates background scheduler for update the db self._scheduler = BackgroundScheduler(daemon=True) # Creates job to update bosses list if bosses_file is not None: bosses.load_from(bosses_file) self._scheduler.add_job(lambda: bosses.load_from(bosses_file), 'interval', hours=int(bosses_expiration)) # Creates job to update gyms list if gyms_file is not None: gyms.load_from(gyms_file) self._scheduler.add_job(lambda: gyms.load_from(gyms_file), 'interval', hours=int(gyms_expiration)) # Starts the scheduler self._scheduler.start() _LOGGER.info("Bot ready")
class UserWithoutEmailFilter(BaseFilter): def filter(self, message: Message): user = get_user_instance(message.from_user, message.chat_id) return user.email is None class NonConfirmedUserFilter(BaseFilter): def filter(self, message: Message): user = get_user_instance(message.from_user, message.chat_id) return user.email is not None and user.is_confirmed is False updater = Updater(token=env('BOT_TOKEN')) dispatcher = updater.dispatcher dispatcher.add_handler(CommandHandler('start', start)) dispatcher.add_handler(CommandHandler('reset', reset_email)) dispatcher.add_handler(MessageHandler(UserWithoutEmailFilter() & Filters.text & Filters.regex('@'), send_confirmation)) # looks like email, so send confirmation to it dispatcher.add_handler(MessageHandler(NonConfirmedUserFilter() & Filters.text & Filters.regex('Resend confirmation email'), resend)) # resend confirmation email dispatcher.add_handler(MessageHandler(NonConfirmedUserFilter() & Filters.text & Filters.regex('Change email'), reset_email)) # change email dispatcher.add_handler(MessageHandler(NonConfirmedUserFilter() & Filters.text & Filters.regex(r'\w{8}\-\w{4}\-\w{4}\-\w{4}\-\w{12}'), confirm_email)) # confirm email dispatcher.add_handler(MessageHandler(UserWithoutEmailFilter(), prompt_for_setting_email)) dispatcher.add_handler(MessageHandler(NonConfirmedUserFilter(), prompt_for_confirm)) dispatcher.add_handler(MessageHandler(ConfirmedUserFilter() & Filters.text, send_text_message)) dispatcher.add_handler(MessageHandler(ConfirmedUserFilter() & Filters.photo, send_photo)) dispatcher.add_handler(MessageHandler(ConfirmedUserFilter() & Filters.voice, send_voice)) if __name__ == '__main__': create_tables() updater.start_polling()
def endWerWas(update, context): """ Sendet die Information, welcher User welche Bestellung abgegeben hat. :param update: Update-Objekt mit Info um welchen Chat es sich handelt :param context: Context-Objekt mit zusätzlichen Chat-Infos """ id = getChatId(update) message = _manager.werWas(id) sendMessage(update, message) if __name__ == "__main__": """ Führt je nach Chatupdates die jeweiligen Funktionen aus. """ updater = Updater(TOKEN, use_context=True) updater.dispatcher.add_handler(CommandHandler('capricapri', startOrder)) updater.dispatcher.add_handler( MessageHandler(Filters.regex(r'Nr'), bestellung)) updater.dispatcher.add_handler( MessageHandler(Filters.regex(r'lösche'), wasLoeschen)) updater.dispatcher.add_handler(CommandHandler('Ende', end)) updater.dispatcher.add_handler(CommandHandler('WerWas', endWerWas)) updater.start_polling() updater.idle()
from telegram.ext import MessageHandler, ConversationHandler from telegram.ext.filters import Filters import re def cancel(update, context): context.bot.send_message( chat_id=update.effective_chat.id, text="Stopping") return ConversationHandler.END pattern = re.compile("cancel|stop|abort") handler = MessageHandler(Filters.regex(pattern), cancel)
user = user_crud.get_or_create(update.effective_user.id) update.message.reply_text(f'We are talking about {user.current_topic!r}') log.debug(f'User {update.effective_user.first_name!r} got current topic.') def download_nltk_resources(): nltk.download('punkt') nltk.download('wordnet') updater = Updater(TOKEN) conv_handler = ConversationHandler( entry_points=[ CommandHandler('change_topic', start_change_topic), MessageHandler(Filters.regex(ButtonPattern.CHANGE.value), start_change_topic) ], states={ CHANGE_TOPIC: [ CommandHandler('cancel', cancel), MessageHandler(Filters.regex(ButtonPattern.CANCEL.value), cancel), MessageHandler(Filters.text, change_topic), ] }, fallbacks=[ CommandHandler('cancel', cancel), MessageHandler(Filters.regex(ButtonPattern.CANCEL.value), cancel), ]) updater.dispatcher.add_handler(CommandHandler('hello', hello))
'''Guide the user if they are unsure of what to write.''' update.message.reply_text( 'I don\'t see pages here 👀\n\n' 'You can either write individual pages or ranges.\n' 'Examples:\n' ' • <code>1</code>\n' ' • <code>2-24</code>\n' ' • <code>1, 3-6, 8</code>', parse_mode=ParseMode.HTML, ) pages_handler = ConversationHandler( entry_points=[CallbackQueryHandler(update_pages, pattern='[0-9a-f]+:pages$')], states={ State.ADD: [ MessageHandler(Filters.regex(page_range_ptn), process_addition), CallbackQueryHandler(switch_to_remove, pattern='[0-9a-f]+:pages:remove$'), CallbackQueryHandler(add_all, pattern='[0-9a-f]+:pages:add_all'), CallbackQueryHandler(end_conversation, pattern='[0-9a-f]+:pages:back'), ], State.REMOVE: [ MessageHandler(Filters.regex(page_range_ptn), process_removal), CallbackQueryHandler(switch_to_add, pattern='[0-9a-f]+:pages:add$'), CallbackQueryHandler(remove_all, pattern='[0-9a-f]+:pages:remove_all'), CallbackQueryHandler(end_conversation, pattern='[0-9a-f]+:pages:back'), ], }, fallbacks=[MessageHandler(Filters.text, unrecognized)], )
class NonConfirmedUserFilter(BaseFilter): def filter(self, message: Message): user = get_user_instance(message.from_user, message.chat_id) return user.email is not None and user.is_confirmed is False updater = Updater(token=env('BOT_TOKEN')) dispatcher = updater.dispatcher dispatcher.add_handler(CommandHandler('start', start)) dispatcher.add_handler(CommandHandler('reset', reset_email)) dispatcher.add_handler( MessageHandler( UserWithoutEmailFilter() & Filters.text & Filters.regex('@'), send_confirmation)) # looks like email, so send confirmation to it dispatcher.add_handler( MessageHandler( NonConfirmedUserFilter() & Filters.text & Filters.regex('Resend confirmation email'), resend)) # resend confirmation email dispatcher.add_handler( MessageHandler( NonConfirmedUserFilter() & Filters.text & Filters.regex('Change email'), reset_email)) # change email dispatcher.add_handler( MessageHandler( NonConfirmedUserFilter() & Filters.text & Filters.regex('\w{8}\-\w{4}\-\w{4}\-\w{4}\-\w{12}'), confirm_email)) # confirm email
logger.info("User %s canceled the conversation.", user.first_name) update.message.reply_text( '¿Te vas pronto? Puedes volver a iniciar esta conversación con /start. Si tuviste algun problema con el bot, no dudes en contactar a @Dyotson ' '(Max Militzer) para arreglarlo', reply_markup=ReplyKeyboardRemove()) return ConversationHandler.END def send_to_json(context): thread = Thread(target=write_json, args=(context.user_data, )) thread.start() conv_handler = ConversationHandler( entry_points=[CommandHandler('start', start)], states={ GENDER: [MessageHandler(Filters.regex('^(El|Ella|Elle)$'), gender)], PHOTO: [ MessageHandler(Filters.photo, photo), CommandHandler('skip', skip_photo) ], LOCATION: [ MessageHandler(Filters.text, location), CommandHandler('skip', skip_location), ], BIO: [MessageHandler(Filters.text & ~Filters.command, bio)], }, fallbacks=[CommandHandler('cancel', cancel)], )