def run_get_updates(token: str, handlers: List[Callable]) -> None: proxy_params = get_socks_proxy_params() persistence = PicklePersistence(os.environ['PERSISTENCE_DATA_FILE']) if proxy_params is not None: LOGGER.warning(f"Using SOCKS5 proxy:\n{proxy_params}") updater = Updater(token, request_kwargs=proxy_params, use_context=True, persistence=persistence) dp = updater.dispatcher for handler in handlers: dp.add_handler(handler) dp.add_error_handler(log_error) updater.start_polling() updater.idle()
def main(): pers = PicklePersistence("persistence") defaults = Defaults(parse_mode="HTML", disable_notification=True) updater = Updater("BOTTOKEN", defaults=defaults, persistence=pers) dp = updater.dispatcher dp.add_handler( MessageHandler(Filters.update.channel_post & Filters.chat(CHANNEL_ID), new_post)) dp.add_handler( MessageHandler( Filters.update.edited_channel_post & Filters.chat(CHANNEL_ID), edited_post)) dp.add_handler( MessageHandler( Filters.status_update.pinned_message & Filters.chat(GROUP_ID), del_msg)) if "messages" not in dp.bot_data: dp.bot_data = {"messages": {}} updater.start_polling() updater.idle()
def main(): my_persistence = PicklePersistence(filename='my_pickle', single_file=False, store_chat_data=False) updater = Updater(TOKEN, persistence=my_persistence) updater.dispatcher.add_handler(certificate_conversation_handler) updater.dispatcher.add_handler(command_handler) updater.dispatcher.add_error_handler(error_handler) # updater.start_polling() # updater.idle() updater.start_webhook(port=PORT, url_path=TOKEN, webhook_url=BASE_URL + TOKEN) updater.idle()
def main(): pp = PicklePersistence(filename='users_states') updater = Updater(token, persistence=pp, use_context=True) dp = updater.dispatcher conv_handler = ConversationHandler( entry_points=[CommandHandler('start', start)], states={ MENU: [ CallbackQueryHandler(catalog, pattern='^catalog$'), CallbackQueryHandler(purchases, pattern='^purchases$'), CallbackQueryHandler(warranty, pattern='^warranty$') ], LOOKING_KEYS: [CallbackQueryHandler(start_over, pattern='^back$')], CHOOSING: [ CallbackQueryHandler(start_over, pattern='^back$'), CallbackQueryHandler(product, pattern='') ], LOOKING: [ CallbackQueryHandler(catalog, pattern='^back$'), CallbackQueryHandler(buy, pattern='^buy$') ], BUY: [ CallbackQueryHandler(product, pattern='^back$'), CallbackQueryHandler(check, pattern='') ], CHECK: [ CallbackQueryHandler(product, pattern='^back$'), CallbackQueryHandler(check, pattern=''), ] }, fallbacks=[], name="seller_bot", persistent=True, ) dp.add_handler(conv_handler) dp.add_error_handler(error) updater.start_polling() updater.idle()
def main(): logger.info("Starting Bot.") # request object for bot request = Request(con_pool_size=8) bot = Bot(token=bot_token, request=request) persistence = PicklePersistence(filename='bot_data.pickle') # create the EventHandler and pass it the bot's instance updater = Updater(bot=bot, use_context=True, persistence=persistence) # jobs job_queue = updater.job_queue job_queue.run_repeating(callback=check_shinies, interval=60, first=0) # get the dispatcher to register handlers dp = updater.dispatcher # /start handler dp.add_handler(CommandHandler(callback=start, command='start')) dp.add_handler(CallbackQueryHandler(callback=start, pattern='^overview')) dp.add_handler( CallbackQueryHandler(callback=list_shinies, pattern='^list_shinies')) dp.add_handler( CallbackQueryHandler(callback=select_source, pattern='^select_source')) dp.add_handler( CallbackQueryHandler(callback=delete_message, pattern='^delete_message$')) # error handler 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()
def test_with_handler(self, bot, update, pickle_persistence, good_pickle_files): u = Updater(bot=bot, persistence=pickle_persistence, use_context=True) dp = u.dispatcher def first(update, context): if not context.user_data == {}: pytest.fail() if not context.chat_data == {}: pytest.fail() context.user_data['test1'] = 'test2' context.chat_data['test3'] = 'test4' def second(update, context): if not context.user_data['test1'] == 'test2': pytest.fail() if not context.chat_data['test3'] == 'test4': pytest.fail() h1 = MessageHandler(None, first, pass_user_data=True, pass_chat_data=True) h2 = MessageHandler(None, second, pass_user_data=True, pass_chat_data=True) dp.add_handler(h1) dp.process_update(update) del (dp) del (u) del (pickle_persistence) pickle_persistence_2 = PicklePersistence(filename='pickletest', store_user_data=True, store_chat_data=True, singe_file=False, on_flush=False) u = Updater(bot=bot, persistence=pickle_persistence_2) dp = u.dispatcher dp.add_handler(h2) dp.process_update(update)
def main(): pp = PicklePersistence(filename='notionbot') updater = Updater(BOT_TOKEN, persistence=pp, use_context=True) dp = updater.dispatcher convhandler = ConversationHandler( entry_points=[ CommandHandler('start', start), CommandHandler('setclient', get_notion_api_key), CommandHandler('setpage', askpage), ], states={ TYPING_NOTION_API_KEY: [MessageHandler(Filters.text, setclient)], TYPING_NOTION_PAGE_ADDRESS: [MessageHandler(Filters.text, setpage)], }, fallbacks=[CommandHandler('done', done)], name='my_conversation', persistent=True) dp.add_handler(convhandler) help_handler = CommandHandler('help', help_msg) dp.add_handler(help_handler) check_client_handler = CommandHandler('check_client', check_client) dp.add_handler(check_client_handler) checkpage_handler = CommandHandler('checkpage', checkpage) dp.add_handler(checkpage_handler) send_text_to_notion_handler = MessageHandler(Filters.text, send_text_to_notion) dp.add_handler(send_text_to_notion_handler) dp.add_error_handler(error) updater.start_polling() updater.idle()
def run(): os.makedirs(cfg.DATA_DIR_NAME, exist_ok=True) storage = PicklePersistence( filename=os.path.join(cfg.DATA_DIR_NAME, cfg.TG_STORAGE_NAME)) updater = Updater(creds.TG_BOT_TOKEN, persistence=storage) dispatcher = updater.dispatcher updater.bot.set_my_commands(Cmd.BOT_COMMANDS_LIST) # handle Bitrix OAuth keys update here in job queue bot_data = dispatcher.bot_data if cfg.BOT_ACCESS_TOKEN_PERSISTENT_KEY not in bot_data: bot_data[ cfg. BOT_ACCESS_TOKEN_PERSISTENT_KEY] = creds.BITRIX_APP_ACCESS_TOKEN bot_data[ cfg. BOT_REFRESH_TOKEN_PERSISTENT_KEY] = creds.BITRIX_APP_REFRESH_TOKEN jq = updater.job_queue global JOB_QUEUE JOB_QUEUE = jq # refresh oauth jq.run_repeating(bitrix_oauth_update_job, interval=cfg.BITRIX_OAUTH_UPDATE_INTERVAL, first=1) # start festive statistics jobs FestiveStats.jq_add_festive_stats(jq) dispatcher.add_handler(FestiveApprovement.FESTIVE_CV_HANDLER) dispatcher.add_handler(FestiveApprovement.FESTIVE_REAPPROVE_HANDLER) dispatcher.add_handler(cv_handler) for fb in cv_handler.fallbacks: dispatcher.add_handler(fb) dispatcher.add_error_handler(error_handler) updater.start_polling(allowed_updates=Update.ALL_TYPES) updater.idle()
def startBot(): botPersistent = PicklePersistence(filename='sav.almcn') updater = Updater(token=TELEGRAM_API, persistence=botPersistent, use_context=True) dispatcher = updater.dispatcher dispatcher.add_handler(start_handler) #The start handler is given to the bot dispatcher.add_handler(about_handler) #The about handler is given to the bot dispatcher.add_handler(text_handler) #The text handler is given to the bot dispatcher.add_handler(everything_handler, group = 1) #The default handler is given to the bot if(ISPRODUCTION): updater.start_webhook(listen="0.0.0.0", port=PORT, url_path=TELEGRAM_API) webhook = "https://{}.herokuapp.com/{}".format(APPNAME, TELEGRAM_API) updater.bot.set_webhook(webhook) #starts the bot if it is hosted on Heroku else: updater.start_polling() #Starts the bot printTime("The bot is up! :)") updater.idle() #Makes sure the bot stops when the ctrl+c signal is sent printTime("The bot stopped :C")
def main(): my_persistence = PicklePersistence(filename="users") updater = Updater("",persistence=my_persistence,use_context=True) dp = updater.dispatcher jobs = updater.job_queue # jobs.run_repeating( check_logic,interval=36000,first=0) jobs.run_repeating( check_logic,interval=3600,first=0) # jobs.run_once( check_logic,when=datetime.datetime.now(datetime.timezone.utc)) dp.add_handler(MessageHandler(Filters.status_update.new_chat_members,kick_member)) dp.add_error_handler(error) updater.start_polling() updater.idle()
def main(): my_persistence = PicklePersistence(filename='my_pickle', single_file=False, store_chat_data=False) updater = Updater(TOKEN, persistence=my_persistence) updater.dispatcher.add_handler(command_handler) updater.dispatcher.add_handler(registration_conversation_handler) updater.dispatcher.add_handler(message_handler) updater.dispatcher.add_handler(callback_query_handler) # ...and the error handler updater.dispatcher.add_error_handler(error_handler) # updater.start_polling() # updater.idle() updater.start_webhook(port=PORT, url_path=TOKEN, webhook_url=URL + TOKEN, ip_address=SERVER_IP) updater.idle()
def __init__(self, token, *args, **kwargs): persistence_file = os.path.join(settings.MEDIA_ROOT, 'bot_persistence_file') persistence = PicklePersistence(filename=persistence_file) super(BotUpdater, self).__init__( token, persistence=persistence, use_context=True, *args, **kwargs) self.set_commands() self.reply_manager = TelegramReplyTemplate dp = self.dispatcher conv_handler = ConversationHandler( entry_points=[CommandHandler('start', self.start)], states={ self.MAIN_MENU: self.get_time_management_handlers(), self.AUTH: self.get_auth_handlers(), self.STARTING: self.get_starting_shift_handlers(), self.ABSENCE: self.get_absence_handlers(), self.PROFILE: self.get_profile_handlers(), self.STATS_PAGE: self.get_stats_handers(), self.EVENTS_PAGE: self.get_event_handlers(), self.TASKS_PAGE: self.get_tasks_handlers(), self.NEWS_PAGE: self.get_news_handlers(), self.ACTIONS_PAGE: self.get_actions_handlers(), self.EVENT_CREATE: self.get_event_creation_handlers(), self.TASK_CREATE: self.get_task_creation_handlers(), self.NEWS_CREATE: self.get_news_creation_handlers(), }, fallbacks=[ CommandHandler('start', self.start) ], persistent=True, name='main_conversation' ) dp.add_handler(conv_handler) dp.add_handler(CallbackQueryHandler(self.event_accepted, pattern='^event_will_come_(-?[0-9]+)$'),) dp.add_handler(CallbackQueryHandler(self.event_rejected, pattern='^event_will_not_come_(-?[0-9]+)$'),) dp.add_handler(CallbackQueryHandler(self.task_done, pattern='^task_done_(-?[0-9]+)$'),) dp.add_handler(MessageHandler(Filters.text, self.undefined_cmd_msg))
def __init__(self): ### Get working directory self.path = os.path.dirname(os.path.realpath(__file__)) ### Get configuration data config = {} try: config = json.load(open(os.path.join(self.path, "config.json"))) except: logger.critical("File Not found: config.json") exit() self.token = config["telegram"]["token"] self.chat_id = config["telegram"]["chat_id"] # Initialize Telegram bot pp = PicklePersistence(filename="mexico") updater = Updater(self.token, persistence=pp, use_context=True) dp = updater.dispatcher option_handler = ConversationHandler( entry_points=[CommandHandler("start", self.start)], states={ THROW: [ MessageHandler(Filters.regex("^(Throw)$"), self.throw), ], }, fallbacks=[MessageHandler(Filters.regex("^restart$"), self.start)], name="mexico", persistent=True) dp.add_handler(option_handler) # log all errors dp.add_error_handler(self.error) # Start the Bot updater.start_polling() updater.idle()
def main(): pp = PicklePersistence(filename='vhfbeaconbot') updater = Updater(TELEGRAMTOKEN, persistence=pp, use_context=True) # Get the dispatcher to register handlers dp = updater.dispatcher # CALLSIGN, LOCATION, CONFIRM, REPORT, BEACON, RST, CONFIRMREPORT conv_handler = ConversationHandler( persistent=True, name='cv_persistent', entry_points=[CommandHandler('start', start)], states={ CALLSIGN: [MessageHandler(Filters.text, callsign)], LOCATION: [MessageHandler(Filters.location, location)], CONFIRM: [MessageHandler(Filters.regex('^(Yes|No)$'), confirm)], REPORT: [ MessageHandler(Filters.text, report), CommandHandler('report', start_beacon_report) ], BEACON: [MessageHandler(Filters.text, report_beacon)], RST: [MessageHandler(Filters.text, report_rst)], CONFIRMREPORT: [MessageHandler(Filters.regex('^(Yes|No)$'), confirm_report)], }, fallbacks=[ CommandHandler('cancel', cancel), CommandHandler('start', start), CommandHandler('reset', reset) ]) dp.add_handler(conv_handler) # log all errors dp.add_error_handler(error) # Start the Bot updater.start_polling() updater.idle()
def main(): """ Init telegram bot, attach handlers and wait for incoming requests. """ # Init telegram bot bot = Updater(TELEGRAM_BOT_TOKEN, persistence=PicklePersistence(filename=session_data_path), use_context=True) dispatcher = bot.dispatcher setup_existing_user(dispatcher=dispatcher) setup_sentry_jobs(dispatcher=dispatcher) dispatcher.add_handler(CommandHandler('start', start, run_async=True)) dispatcher.add_handler(CommandHandler('cancel', cancel, run_async=True)) dispatcher.add_handler(CallbackQueryHandler(dispatch_query, run_async=True)) dispatcher.add_handler( MessageHandler(Filters.text, plain_input, run_async=True)) # Start the bot bot.start_polling() logger.info(BOT_STARTUP_MSG) logger.info(f""" ========================================================================== ========================================================================== Debug: {DEBUG} Telegram bot token: {"SET" if TELEGRAM_BOT_TOKEN else "MISSING!"} Slack webhook: {SLACK_WEBHOOK} LCD endpoint: {LCD_ENDPOINT} Sentry nodes: {SENTRY_NODES} Node IP: {NODE_IP} ========================================================================== ========================================================================== """) # 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. bot.idle()
def main(): my_persistence = PicklePersistence(filename='pickle_promo') q = mq.MessageQueue(all_burst_limit=28, all_time_limit_ms=3000) updater = Updater(bot=MQBot(token=PROMO_BOT_TKN, mqueue=q, request=Request(con_pool_size=10)), use_context=True, persistence=my_persistence) j = updater.job_queue j.run_daily(time=datetime.time(datetime(12, 2, 1)), callback=del_expired_list, context=None) dispatcher = updater.dispatcher for hndlr in handlers_to_add: dispatcher.add_handler(hndlr) load_db_to_bot(context=dispatcher) # Exceptional Case # # dispatcher.add_handler(MessageHandler(Filters.text, exceptional)) updater.bot.set_my_commands([ BotCommand('start', 'start the bot'), BotCommand('remove', 'remove a channel'), BotCommand('shared', '#shared of current promo'), BotCommand('unshared', '#unshared of current promo'), BotCommand('configure', 'get the grpid'), BotCommand('cancel', 'stop current operation') ]) if SERVER_IP_ADDR: updater.start_webhook(listen='127.0.0.1', port=PORT_NUM, url_path=PROMO_BOT_TKN.split(':')[-1], allowed_updates=['message', 'callback_query']) updater.bot.set_webhook(url=WEBHOOK_URL, certificate=open(NAME_OF_PEM_FILE, 'rb')) else: updater.start_polling() updater.idle()
def main(): import json with open('config.json') as fp: config = json.load(fp) persistence = PicklePersistence(filename='conversationbot') updater = Updater(config["API_TOKEN"], use_context=True, persistence=persistence) dp = updater.dispatcher # Add Handlers dp.add_handler( CommandHandler("tweets", handle_tweet_request, pass_args=True)) dp.add_handler(CommandHandler("start", start)) dp.add_handler(MessageHandler(Filters.photo, handle_photo)) dp.add_handler(MessageHandler(Filters.text, handle_text)) login_handler = ConversationHandler( entry_points=[CommandHandler('start', start)], states={ MENU: [ #MessageHandler(Filters.regex('^(Oxygen)$'), handle_menu), MessageHandler(Filters.photo, handle_photo), #MessageHandler(Filters.regex('^(Oxygen Bed)$'), handle_menu), #MessageHandler(Filters.regex('^(Medicine)$'), handle_menu), #MessageHandler(Filters.regex('^(Plasma)$'), handle_menu), #MessageHandler(Filters.regex('^(Ambulance)$'), handle_menu) ], GET_LOCATION: [MessageHandler(Filters.text, fetch_info)], }, fallbacks=[MessageHandler(Filters.regex('.*'), exit_convo)]) #dp.add_handler(login_handler) # log all errors dp.add_error_handler(error) updater.start_polling() updater.idle()
def main(): defaults = Defaults(disable_web_page_preview=True) pp = PicklePersistence(filename='chat_data_states', store_user_data=False, store_bot_data=False) updater = Updater(BOT_TOKEN, use_context=True, persistence=pp, defaults=defaults) dp = updater.dispatcher print('f') dp.add_handler(CommandHandler("start", send_start)) dp.add_handler(CommandHandler("help", send_help)) dp.add_handler(CommandHandler(["count", "ct", "c"], send_count)) dp.add_handler(CommandHandler(["stats", "getstats"], send_stats)) updater.start_polling() updater.idle()
def __init__(self, token, admin, device): # Admin contains the ID of the user that can allow other users to print self.admin = admin # Device is the CUPS printer name from `lpstat -e` self.device = device # Using a pickle in ./ to persist the allowlist self.persistence = PicklePersistence(filename='data.pickle') # Setting up python-telegram-bot self.updater = Updater( token=token, use_context=True, persistence=self.persistence) # Registering command handlers self.dispatcher = self.updater.dispatcher self.dispatcher.add_handler(CommandHandler('start', self.cmd_start)) self.dispatcher.add_handler(CommandHandler('add', self.cmd_add)) self.dispatcher.add_handler(CommandHandler('deny', self.cmd_deny)) # This message handler will only trigger on PDF files self.dispatcher.add_handler(MessageHandler( Filters.document.pdf, self.on_message))
def main(): defaults = Defaults(disable_web_page_preview=True) pp = PicklePersistence(filename='chat_data_states', store_user_data=False, store_bot_data=False) updater = Updater(BOT_TOKEN, use_context=True, persistence=pp, defaults=defaults) dp = updater.dispatcher restart_jobs(dp) dp.add_handler(CommandHandler("start", send_start)) dp.add_handler(CommandHandler("help", send_help)) dp.add_handler( CommandHandler(["monitoron", "mon", "getupdates", "startupdates"], send_monitor_on)) dp.add_handler( CommandHandler(["monitoroff", "moff", "stopupdates"], send_monitor_off)) dp.add_handler( CommandHandler(["monitorstatus", "mstatus", "status"], send_monitor_status)) dp.add_handler(CommandHandler(["sethome", "set"], send_set_home)) dp.add_handler(CommandHandler("home", send_home)) dp.add_handler(CommandHandler("here", send_here)) dp.add_handler(CommandHandler(["search", "find", "city"], send_search)) dp.add_handler(MessageHandler(Filters.location, location_sent)) dp.add_handler(MessageHandler(Filters.regex(r'Cancel'), location_canceled)) # dp.add_handler(MessageHandler(Filters.text, print_id)) updater.start_polling() updater.idle()
def main(): pp = PicklePersistence(filename='conversationbot') updater = Updater("1004568616:AAED-QoeDoFZQy_c5rEW2COcoQPzoBgxff4", persistence=pp, use_context=True) dp = updater.dispatcher conv_handler = ConversationHandler( entry_points=[CommandHandler('start', start)], states={ CHOOSING: [ MessageHandler(Filters.regex('^(Name|Age|Hobby)$'), regular_choice), MessageHandler(Filters.regex('^Something else$'), custom_choice), ], TYPING_CHOICE: [ MessageHandler(Filters.text, regular_choice), ], TYPING_REPLY: [ MessageHandler(Filters.text, received_information), ], }, fallbacks=[MessageHandler(Filters.regex('^Done$'), done)], name="my_conversation", persistent=True) dp.add_handler(conv_handler) show_data_handler = CommandHandler('show_data', show_data) dp.add_handler(show_data_handler) dp.add_error_handler(error) updater.start_polling() updater.idle()
def main(): updater = Updater( TELEGRAM_BOT_TOKEN, persistence=PicklePersistence("drive_data"), use_context=True, ) dispatcher = updater.dispatcher dispatcher.add_handler(CommandHandler("help", help_text)) dispatcher.add_handler(CommandHandler("create_doc", create_doc)) dispatcher.add_handler(CommandHandler("list_docs", list_docs_to_retrieve)) dispatcher.add_handler( CallbackQueryHandler( retrieve_doc, pattern=rf"^{GET_DOC} \S.+", pass_chat_data=True ) ) dispatcher.add_handler(CommandHandler("delete_doc", list_docs_for_deletion)) dispatcher.add_handler( CallbackQueryHandler( delete_doc, pattern=rf"^{DELETE_DOC} \S.+", pass_chat_data=True ) ) dispatcher.add_handler(CommandHandler("update_doc", list_docs_to_update)) dispatcher.add_handler( CallbackQueryHandler( update_doc, pattern=rf"^{UPDATE_DOC} \S.+", pass_chat_data=True ) ) dispatcher.add_handler(CommandHandler("update_content", update_content)) dispatcher.add_handler(InlineQueryHandler(update_inline)) updater.start_polling() updater.idle()
def main(): bot_persistence = PicklePersistence(filename='persistence') updater = Updater(token=BotToken, persistence=bot_persistence, use_context=True) dispatcher = updater.dispatcher # if(isNewer()): # for BotAuthorizedId in getBotAuthorizedIDs(): # updater.bot.sendMessage(chat_id=BotAuthorizedId, text=bot_messages['VERCHANGE_MESSAGE']) latestNews = getlatestNews() for news in latestNews: for BotAuthorizedId in getBotAuthorizedIDs(): updater.bot.sendMessage(chat_id=BotAuthorizedId, text=news) dispatcher.add_handler(CommandHandler('start', start)) dispatcher.add_handler(CommandHandler('uptime', uptime)) dispatcher.add_handler(CommandHandler('ver', version)) dispatcher.add_handler(CommandHandler('help', help)) dispatcher.add_handler(CommandHandler('anno', hypothesis)) dispatcher.add_handler(CommandHandler('importFC', importFlashCards)) dispatcher.add_handler(CommandHandler('tsr', tsrRetired)) dispatcher.add_handler(CommandHandler('srs', TimeSpacedRepetition)) # dispatcher.add_handler(CommandHandler('getMD', generateMD)) dispatcher.add_handler(CommandHandler('getMM', generateMinmapHTML)) dispatcher.add_handler(MessageHandler(Filters.text, addEntry)) dispatcher.add_handler(MessageHandler(Filters.photo, image_handler)) dispatcher.add_handler(CallbackQueryHandler(ShowAnswer,pattern=btns['SHOW_ANSWER'])) dispatcher.add_handler(CallbackQueryHandler(AnswerHandler,pattern="ansrfdbk")) dispatcher.add_handler(CallbackQueryHandler(Skip,pattern=btns['SKIP'])) dispatcher.add_handler(CallbackQueryHandler(Cancel,pattern=btns['CANCEL'])) updater.start_polling() updater.idle()
def main() -> None: """Setup and run ONGAbot""" context_types = ContextTypes(bot_data=BotData, user_data=UserData) persistence = PicklePersistence(filename=os.getenv("DB_PATH", "ongabot.db"), context_types=context_types) updater = Updater( os.getenv("API_TOKEN"), persistence=persistence, use_context=True, context_types=context_types, ) # Register handlers dispatcher = updater.dispatcher dispatcher.add_handler(StartCommandHandler()) dispatcher.add_handler(HelpCommandHandler()) dispatcher.add_handler(OngaCommandHandler()) dispatcher.add_handler(NewEventCommandHandler()) dispatcher.add_handler(CancelEventCommandHandler()) dispatcher.add_handler(EventPollHandler()) dispatcher.add_handler(EventPollAnswerHandler()) dispatcher.add_handler(ScheduleCommandHandler()) dispatcher.add_handler(DeScheduleCommandHandler()) dispatcher.add_error_handler(error) bot_data: BotData = persistence.bot_data bot_data.schedule_all_event_jobs(updater.job_queue, create_event_callback) # Start the bot updater.start_polling() # Block 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()
def main(): start_sevabit_update_thread() print("Starting bot") # Create the Updater and pass it your bot's token. global pp, updater pp = PicklePersistence(filename=PERSISTENCE_FILENAME, store_user_data=True, store_chat_data=False, on_flush=True) updater = Updater(TELEGRAM_TOKEN, persistence=pp, user_sig_handler=stop_sevabit_thread) # Get the dispatcher to register handlers dp = updater.dispatcher updater.dispatcher.add_handler( CommandHandler('start', start, pass_user_data=True)) updater.dispatcher.add_handler( CommandHandler('help', help, pass_user_data=True)) updater.dispatcher.add_handler( CallbackQueryHandler(dispatch_query, pass_user_data=True)) updater.dispatcher.add_handler( MessageHandler(Filters.text, service_node_input, pass_user_data=True)) # log all errors dp.add_error_handler(error) # Start the Bot updater.start_polling() print("Bot started") # 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()
def main(): """Setup and run ONGAbot""" API_TOKEN = os.getenv("API_TOKEN") DB_PATH = os.getenv("DB_PATH", "ongabot.db") pp = PicklePersistence(filename=DB_PATH) updater = Updater(API_TOKEN, persistence=pp, use_context=True) # Get the dispatcher to register handlers dp = updater.dispatcher dp.add_handler(StartCommandHandler()) dp.add_handler(HelpCommandHandler()) dp.add_handler(OngaCommandHandler()) dp.add_handler(NewEventCommandHandler()) dp.add_handler(EventPollHandler()) dp.add_error_handler(error) # Start the Bot updater.start_polling() # Block 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()
def main() -> None: """Run the bot.""" # We use persistence to demonstrate how buttons can still work after the bot was restarted persistence = PicklePersistence(filepath="arbitrarycallbackdatabot") # Create the Application and pass it your bot's token. application = ( Application.builder() .token("TOKEN") .persistence(persistence) .arbitrary_callback_data(True) .build() ) application.add_handler(CommandHandler("start", start)) application.add_handler(CommandHandler("help", help_command)) application.add_handler(CommandHandler("clear", clear)) application.add_handler( CallbackQueryHandler(handle_invalid_button, pattern=InvalidCallbackData) ) application.add_handler(CallbackQueryHandler(list_button)) # Run the bot until the user presses Ctrl-C application.run_polling()
def persistence_object(config_enabled=True, file_path='persistence/data.pickle'): if not config_enabled: return logger.info('unpickling persistence: %s', file_path) try: # try to load the file try: with open(file_path, "rb") as f: pickle.load(f) except FileNotFoundError: pass except (UnpicklingError, EOFError): logger.warning( 'deserialization failed: removing persistence file and trying again' ) os.remove(file_path) return PicklePersistence(filename=file_path, store_chat_data=False, store_bot_data=False)
def main(): # 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 pp = PicklePersistence(filename='lunch') updater = Updater("1104322131:AAGPE5A8Mwo8CUKejxYmGHOPw4U8on7M83g", use_context=True, persistence=pp) updater.dispatcher.add_handler(CommandHandler('open', open_command)) updater.dispatcher.add_handler(CommandHandler('reset', open_command)) updater.dispatcher.add_handler(CommandHandler('order', order)) updater.dispatcher.add_handler(CallbackQueryHandler(button)) updater.dispatcher.add_handler(CommandHandler('cancel', cancel_command)) #updater.dispatcher.add_handler(CommandHandler('close', close_command)) updater.dispatcher.add_handler(CommandHandler('summary', summary_command)) updater.dispatcher.add_handler(CommandHandler('bill', money_command)) updater.dispatcher.add_handler(CommandHandler('help', help_command)) # Start the Bot updater.start_polling() # Run the bot until the user presses Ctrl-C or the process receives SIGINT, # SIGTERM or SIGABRT updater.idle()
def main(): bot_persistence = PicklePersistence(filename='persistence') updater = Updater(token=BotToken, persistence=bot_persistence, use_context=True) dispatcher = updater.dispatcher if (isNewer()): for BotAuthorizedId in getBotAuthorizedIDs(): updater.bot.sendMessage(chat_id=BotAuthorizedId, text=bot_messages['VERCHANGE_MESSAGE']) dispatcher.add_handler(CommandHandler('start', start)) dispatcher.add_handler(CommandHandler('uptime', uptime)) dispatcher.add_handler(CommandHandler('ver', version)) dispatcher.add_handler(CommandHandler('help', help)) dispatcher.add_handler(CommandHandler('anno', hypothesis)) dispatcher.add_handler(MessageHandler(Filters.text, addEntry)) dispatcher.add_handler(MessageHandler(Filters.photo, image_handler)) updater.start_polling() updater.idle()