def test_with_pattern(self, inline_query): handler = InlineQueryHandler(self.callback_basic, pattern='(?P<begin>.*)est(?P<end>.*)') assert handler.check_update(inline_query) inline_query.inline_query.query = 'nothing here' assert not handler.check_update(inline_query)
def test_basic(self, dp, inline_query): handler = InlineQueryHandler(self.callback_basic) dp.add_handler(handler) assert handler.check_update(inline_query) dp.process_update(inline_query) assert self.test_flag
def init_handlers(dispatcher): logging.info("Инициализация обработчиков inline кдавиатуры") dispatcher.add_handler(InlineQueryHandler(inline_handler))
def register(dispatcher: Dispatcher) -> None: dispatcher.add_handler(InlineQueryHandler(inline_query))
def main(*, use_proxy=False): request_kwargs = None request_kwargs = {'proxy_url': proxy} if use_proxy else None updater = Updater(token=BOT_TOKEN, use_context=True, request_kwargs=request_kwargs) dispatcher = updater.dispatcher j_queue = updater.job_queue start_handler = CommandHandler('start', start_bot) inline_caps_handler = InlineQueryHandler(inline_caps) dog_handler = CallbackQueryHandler(dog, pattern="dog-image") help_handler = CommandHandler('help', help_bot) music_handler = CommandHandler('music', list_all_files) main_menu_handler = CallbackQueryHandler(main_menu, pattern='main-menu') music_menu_handler = CallbackQueryHandler(music_menu, pattern='music-menu') corona_menu_handler = CallbackQueryHandler(corona_menu, pattern="corona-menu") weather_menu_handler = CallbackQueryHandler(weather_options_menu, pattern='weather-options-menu') set_timer_handler = CommandHandler('timer', set_timer) unknown_handler = MessageHandler(Filters.command, unknown) echo_back_handler = MessageHandler(Filters.text, echo_back) dispatcher.add_handler(start_handler) dispatcher.add_handler(inline_caps_handler) dispatcher.add_handler(help_handler) dispatcher.add_handler(dog_handler) dispatcher.add_handler(music_handler) dispatcher.add_handler(main_menu_handler) dispatcher.add_handler(music_menu_handler) dispatcher.add_handler( CallbackQueryHandler(list_all_files, pattern='list-all-files')) dispatcher.add_handler( CallbackQueryHandler(music_list, pattern='music-list')) dispatcher.add_handler( CallbackQueryHandler(callback_file_select, pattern='^music-[0-9]+$')) dispatcher.add_handler( CallbackQueryHandler(next_music_page, pattern="next-page")) dispatcher.add_handler( CallbackQueryHandler(prev_music_page, pattern="prev-page")) dispatcher.add_handler(corona_menu_handler) dispatcher.add_handler( CallbackQueryHandler(callback_country_select, pattern='^corona-[a-zA-Z]+$')) dispatcher.add_handler( CallbackQueryHandler(update_corona_data, pattern='update-corona-data')) dispatcher.add_handler(weather_menu_handler) dispatcher.add_handler( CallbackQueryHandler(current_weather_menu, pattern='option-current-weather')) dispatcher.add_handler( CallbackQueryHandler(next_days_weather_menu, pattern='option-next-days')) dispatcher.add_handler( CallbackQueryHandler(city_current_weather_select, pattern='^current-weather-[a-zA-Z ]+$')) dispatcher.add_handler( CallbackQueryHandler(city_next_days_weather_select, pattern='^next-days-weather-[a-zA-Z ]+$')) dispatcher.add_handler( MessageHandler(Filters.regex('youtu.be|youtube.com'), youtube_link_handle)) dispatcher.add_handler( CallbackQueryHandler(download_audio, pattern='download-audio')) dispatcher.add_handler( CallbackQueryHandler(download_video, pattern='download-video')) dispatcher.add_handler( CallbackQueryHandler(youtube_download_help, pattern='youtube-dl-help')) dispatcher.add_handler(set_timer_handler) dispatcher.add_handler(unknown_handler) dispatcher.add_handler(echo_back_handler) j_minute = j_queue.run_repeating(callback_welcome, interval=30, first=0) j_minute.enabled = False run(updater)
seen_add = seen.add return [x for x in seq if not (x in seen or seen_add(x))] def chosen_result_handler(bot, update): parts = shlex.split(update.chosen_inline_result.query) query_id = update.chosen_inline_result.result_id options = [ Option(id=query_id + hash(part)[:32], title=part) for part in deduplicate(parts[1:]) ] poll = Poll(id=query_id, title=parts[0], creator_id=update.chosen_inline_result.from_user.id, options=options) db_session.add(poll) db_session.commit() if __name__ == "__main__": updater = Updater(token=TG_TOKEN) dispatcher = updater.dispatcher dispatcher.add_handler(InlineQueryHandler(inline_handler)) dispatcher.add_handler(CallbackQueryHandler(button_handler)) dispatcher.add_handler(ChosenInlineResultHandler(chosen_result_handler)) dispatcher.add_error_handler( lambda bot, update, error: logging.error(error)) updater.start_polling()
def test_other_update_types(self, false_update): handler = InlineQueryHandler(self.callback_basic) assert not handler.check_update(false_update)
title="Usage: <movie> | <tv> | <anime>", description="Example: <movie> Avengers endgame", message_text=st.INLINE_DESC, thumb_url="https://telegra.ph/file/47a7fb822017512f0ee65.jpg", reply_markup=InlineKeyboardMarkup( [ [ InlineKeyboardButton( text="Movies", switch_inline_query_current_chat="<movie> ", ), InlineKeyboardButton( text="TVshows", switch_inline_query_current_chat="<tv> ", ), InlineKeyboardButton( text="Anime", switch_inline_query_current_chat="<anime> ", ), ] ] ), ) ) update.inline_query.answer(results[:50], cache_time=10) INLINE_HANDLER = InlineQueryHandler(inlinequery) dp.add_handler(INLINE_HANDLER)
def add_update_handlers(dp): dp.add_handler(CommandHandler("start", text.start)) dp.add_handler(CommandHandler("about", text.about)) dp.add_handler(InlineQueryHandler(inlinequery)) return dp
token = yaml.load(f)['test'] except KeyError: with open('settings.yml') as f: token = yaml.load(f)['test'] with open('adik', 'rb') as f: adik_photo = BytesIO(f.read()) adik_cd = 0.0 updater = Updater(token=token) dispatcher = updater.dispatcher start_handler = CommandHandler('start', start) adik_handler = MessageHandler(Filters.text, adik) cats_handler = CommandHandler(['котик', 'кот', 'cat', 'ket'], cat, pass_args=True) dogs_handler = CommandHandler( ['пёсик', 'пёсель', 'песик', 'песель', 'пёс', 'пес', 'dog', 'doggo'], dog, pass_args=True) inline_cats_handler = InlineQueryHandler(inline_cats) dispatcher.add_handler(start_handler) dispatcher.add_handler(adik_handler) dispatcher.add_handler(cats_handler) dispatcher.add_handler(dogs_handler) dispatcher.add_handler(inline_cats_handler) updater.start_polling()
def main(): t_bot = telegram.Bot(token=constants.EXTREPYTHON_BOT_TOKEN) print(t_bot.get_me()) updater = Updater(token=constants.EXTREPYTHON_BOT_TOKEN) dispatcher = updater.dispatcher logging.basicConfig( format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO) awesome_filter = AwesomeFilter() #commands handlers start_command_handler = CommandHandler('start', commands.start) chat_id_handler = CommandHandler('chatId', commands.chat_id) inline_keyboard_handler = CommandHandler('keyboard', commands.inline_keyboard) timer_handler = CommandHandler('set', commands.set_timer, pass_args=True, pass_job_queue=True, pass_chat_data=True) unset_timer_handler = CommandHandler('unset', commands.unset, pass_chat_data=True) homer_handler = CommandHandler('homer', commands.homer) python_handler = CommandHandler('python', commands.python) emoji_handler = CommandHandler('emoji', commands.emoji, pass_args=True) caps_handler = CommandHandler('caps', commands.caps, pass_args=True) unknown_handler = MessageHandler(Filters.command, utils.unknown) #messages handlers awesome_handler = MessageHandler(awesome_filter, messages.awesome_callback) echo_handler = MessageHandler(Filters.text, messages.echo) callback_query_handler = CallbackQueryHandler(callback_queries.button) #echo_all_handler = MessageHandler(Filters.all, messages.echo_all, edited_updates=True) #inline query handlers inline_caps_handler = InlineQueryHandler(inline_queries.inline_query) #add commands handlers dispatcher.add_handler(start_command_handler) dispatcher.add_handler(chat_id_handler) dispatcher.add_handler(inline_keyboard_handler) dispatcher.add_handler(timer_handler) dispatcher.add_handler(unset_timer_handler) dispatcher.add_handler(python_handler) dispatcher.add_handler(emoji_handler) dispatcher.add_handler(homer_handler) #add messages handlers dispatcher.add_handler(awesome_handler) dispatcher.add_handler(echo_handler) dispatcher.add_handler(caps_handler) dispatcher.add_handler(callback_query_handler) dispatcher.add_handler(unknown_handler) #dispatcher.add_handler(echo_all_handler) #add inline queries handlers dispatcher.add_handler(inline_caps_handler) updater.start_polling()
def main(updater): dispatcher = updater.dispatcher dbFuncs.initDB() newcomm = CommandHandler('new', new, Filters.private) startcomm = CommandHandler('start', start, Filters.private, pass_args=True, pass_job_queue=True) cancelcomm = CommandHandler('cancel', cancel, Filters.private, pass_user_data=True) sendcomm = CommandHandler( 'send', sendAll, Filters.private & Filters.chat(chat_id=[114951690])) helpcomm = CommandHandler('help', help, Filters.private) backupcomm = CommandHandler('backup', backup, Filters.private) settingscomm = CommandHandler('settings', settings, Filters.private) pushinlinecall = CallbackQueryHandler(pushInline, pattern=r"^" + patterns[0], pass_job_queue=True) pushadmincall = CallbackQueryHandler(pushSettings, pattern=r"^" + patterns[1], pass_job_queue=True) settingsmaincall = CallbackQueryHandler(settings_main, pattern=r"^" + patterns[2]) settingslangcall = CallbackQueryHandler(settings_language, pattern=r"^" + patterns[3]) setnamemess = MessageHandler(Filters.text & Filters.private, setName) blankcodemess = MessageHandler(Filters.private & Filters.regex(r'^\/.*'), blankCode) editmessagemess = MessageHandler(Filters.private & Filters.text & Filters.update.edited_message, editMessage, pass_job_queue=True) rcvreplymess = MessageHandler(Filters.private & Filters.text & Filters.reply & (~Filters.update.edited_message), rcvReply, pass_job_queue=True) rcvmessagemess = MessageHandler( Filters.private & Filters.text & (~Filters.update.edited_message), rcvMessage) newlistconv = ConversationHandler(entry_points=[newcomm, startcomm], states={SETNAME: [setnamemess]}, fallbacks=[cancelcomm], persistent=True, name="newlist") listhandlerconv = ConversationHandler( entry_points=[pushinlinecall], states={SETTINGS: [pushadmincall]}, fallbacks=[pushinlinecall, cancelcomm], persistent=True, name="listhandler", per_message=True) settingshandlerconv = ConversationHandler(entry_points=[settingsmaincall], states={ SETTINGS: [settingsmaincall], LANGUAGE: [settingslangcall] }, fallbacks=[cancelcomm], persistent=True, name="settingshandler", per_message=True) dispatcher.add_handler(newlistconv) dispatcher.add_handler(listhandlerconv) dispatcher.add_handler(settingshandlerconv) dispatcher.add_handler(pushinlinecall) dispatcher.add_handler(pushadmincall) dispatcher.add_handler(sendcomm) dispatcher.add_handler(helpcomm) dispatcher.add_handler(backupcomm) dispatcher.add_handler(settingscomm) dispatcher.add_handler(InlineQueryHandler(inlineQuery)) dispatcher.add_handler(ChosenInlineResultHandler(chosenQuery)) dispatcher.add_handler(blankcodemess) dispatcher.add_handler(editmessagemess) dispatcher.add_handler(rcvreplymess) dispatcher.add_handler(rcvmessagemess) dispatcher.add_handler(CallbackQueryHandler(fixButtons)) dispatcher.add_error_handler(contextCallback) updater.start_polling() updater.idle()
def unknown(update, context): context.bot.send_message(chat_id=update.effective_chat.id, text="Sorry, I didn't understand that command.") #unknown_handler = MessageHandler(Filters.command, unknown) #dispatcher.add_handler(unknown_handler) def inline(update, context): query = update.inline_query.query if not query: return results = list() answer = check_alternative(query) results.append( InlineQueryResultArticle( id="חלופה", title=f'החלופה העברית ל{query} היא: {answer}', input_message_content=InputTextMessageContent(answer) ) ) context.bot.answer_inline_query(update.inline_query.id, results) inline_handler = InlineQueryHandler(inline) dispatcher.add_handler(inline_handler) updater.start_polling() updater.idle() print("end")
def setup( # pylint: disable=R0913,R0914,R0915 dispatcher: Dispatcher, admin: Union[int, str], oc_url: str, oc_username: str, oc_password: str, oc_path: str, ad_url: str, ad_url_active: str, ad_username: str, ad_password: str, yourls_url: str, yourls_signature: str, ) -> None: """ * Adds handlers. Convenience method to avoid doing that all in the main script. * Sets the bot commands and makes sure ``dispatcher.bot_data`` is set up correctly. * Registers a :class:`telegram.ext.TypeHandler` that makes sure that conversations are not interrupted * Sets up statistics Args: dispatcher: The :class:`telegram.ext.Dispatcher`. admin: The admins chat id. oc_url: URL of the OwnCloud Instance. oc_username: Username for the OwnCloud Instance. oc_password: Password of the OwnCloud Instance. oc_path: Remote path on the OwnCloud Instance. ad_url: URL of the AkaDressen file. ad_url_active: URL of the AkaDressen file containing only the active members. ad_username: Username for the AkaDressen. ad_password: Password for the AkaDressen. yourls_url: URL of the YOURLS instance. yourls_signature: Signature for the YOURLS instance. """ def check_conversation_status(update: Update, context: CallbackContext) -> None: """ Checks if the user is currently in a conversation. If they are and the corresponding conversation does *not* handle the incoming update, the user will get a corresponding message and the update will be discarded. Args: update: The update. context: The context as provided by the :class:`telegram.ext.Dispatcher`. """ if not update.effective_user: return conversation = context.user_data.get(CONVERSATION_KEY, None) if not conversation: return conversation_check = not bool( conversations[conversation].check_update(update)) # Make sure that the callback queries for vcard requests are not processed if update.callback_query: contact_request_check = bool( re.match(inline.REQUEST_CONTACT_PATTERN, update.callback_query.data)) highscore_check = 'highscore' in update.callback_query.data else: contact_request_check = False highscore_check = False if conversation_check or contact_request_check or highscore_check: text = interrupt_replies[conversation] if update.callback_query: update.callback_query.answer(text=text, show_alert=True) elif update.effective_message: update.effective_message.reply_text(text) raise DispatcherHandlerStop() def clear_conversation_status(update: Update, context: CallbackContext) -> None: """ Clears the conversation status of a user in case of an error. Just to be sure. Args: update: The update. context: The context as provided by the :class:`telegram.ext.Dispatcher`. """ if update.effective_user: context.user_data.pop(CONVERSATION_KEY) # ------------------------------------------------------------------------------------------- # # Set up statistics set_dispatcher(dispatcher) # Count total number of updates register_stats(SimpleStats('stats', lambda u: bool(u.effective_user)), admin_id=int(admin)) # Count number of started games register_stats( SimpleStats( 'game_stats', lambda u: bool(u.message) and Filters.text('/spiel_starten')(u)), admin_id=int(admin), ) # Count number of requested contacts register_stats( admin_id=int(admin), stats=SimpleStats( 'contact_stats', lambda u: bool(u.callback_query and 'contact_request' in u. callback_query.data), ), ) # Handlers # Prepare conversations game_handler = game.GAME_HANDLER editing_conversation = editing.build_editing_handler(int(admin)) canceling_conversation = cancel_membership.CANCEL_MEMBERSHIP_HANDLER banning_conversation = ban.build_banning_handler(int(admin)) conversations: Dict[str, ConversationHandler] = { game.CONVERSATION_VALUE: game_handler, editing.CONVERSATION_VALUE: editing_conversation, cancel_membership.CONVERSATION_VALUE: canceling_conversation, ban.CONVERSATION_VALUE: banning_conversation, } interrupt_replies: Dict[str, str] = { game.CONVERSATION_VALUE: game.CONVERSATION_INTERRUPT_TEXT, editing.CONVERSATION_VALUE: editing.CONVERSATION_INTERRUPT_TEXT, cancel_membership.CONVERSATION_VALUE: cancel_membership.CONVERSATION_INTERRUPT_TEXT, ban.CONVERSATION_VALUE: ban.CONVERSATION_INTERRUPT_TEXT, } # Registration status dispatcher.add_handler(TypeHandler(Update, registration.check_registration_status), group=-2) # Conversation Interruption behaviour dispatcher.add_handler(TypeHandler(Update, check_conversation_status), group=-1) # Game Conversation # Must be first so that the fallback can catch unrelated messages dispatcher.add_handler(game_handler) # Registration process # We need the filter here in order to not catch /start with deep linking parameter used for # inline help dispatcher.add_handler( CommandHandler('start', registration.start, filters=Filters.text('/start'))) dispatcher.add_handler( CallbackQueryHandler(registration.request_registration, pattern=REGISTRATION_PATTERN, run_async=True)) dispatcher.add_handler(registration.ACCEPT_REGISTRATION_HANDLER) dispatcher.add_handler(registration.DENY_REGISTRATION_HANDLER) # Edit user data dispatcher.add_handler(editing_conversation) # Cancel membership dispatcher.add_handler(canceling_conversation) # Banning members dispatcher.add_handler(banning_conversation) # Simple commands dispatcher.add_handler( CommandHandler(['hilfe', 'help'], commands.help_message)) dispatcher.add_handler(CommandHandler('daten_anzeigen', commands.show_data)) dispatcher.add_handler( CommandHandler('kontakt_abrufen', commands.start_inline)) dispatcher.add_handler( CommandHandler('start', commands.start_inline, filters=Filters.text(f'/start {INLINE_HELP}'))) # Inline Mode dispatcher.add_handler(InlineQueryHandler(inline.search_users)) dispatcher.add_handler(inline.SEND_VCARD_HANDLER) # Highscores dispatcher.add_handler( CommandHandler('highscore', highscore.show_highscore)) dispatcher.add_handler(highscore.HIGHSCORE_HANDLER) # Set commands dispatcher.bot.set_my_commands(BOT_COMMANDS) # Admin stuff dispatcher.add_handler( CommandHandler('rebuild', bot.admin.rebuild_orchestra, filters=Filters.user(int(admin)))) # Error Handler dispatcher.add_error_handler(error.handle_error) dispatcher.add_error_handler(clear_conversation_status) # Schedule jobs check_user_status.schedule_daily_job(dispatcher) backup.PATH = oc_path backup.URL = oc_url backup.USERNAME = oc_username backup.PASSWORD = oc_password backup.schedule_daily_job(dispatcher) # Set up AkaDressen credentials Member.set_akadressen_credentials(ad_url, ad_url_active, ad_username, ad_password) # Set up bot_data bot_data = dispatcher.bot_data if not bot_data.get(ORCHESTRA_KEY): bot_data[ORCHESTRA_KEY] = Orchestra() else: # We rebuild the orchestra on start up to make sure code changes are applied old_orchestra = bot_data.pop(ORCHESTRA_KEY) new_orchestra = old_orchestra.copy() bot_data[ORCHESTRA_KEY] = new_orchestra if not bot_data.get(PENDING_REGISTRATIONS_KEY): bot_data[PENDING_REGISTRATIONS_KEY] = dict() if not bot_data.get(DENIED_USERS_KEY): bot_data[DENIED_USERS_KEY] = list() bot_data[ADMIN_KEY] = int(admin) yourls_client = YOURLSClient(yourls_url, signature=yourls_signature, nonce_life=True) bot_data[YOURLS_KEY] = yourls_client # Clear conversation key user_data = dispatcher.user_data for user_id in user_data: user_data[user_id].pop(CONVERSATION_KEY, None)
if not update.chosen_inline_result.result_id.endswith('photo'): return sender_id = update.chosen_inline_result.from_user.id receiver, message_id, chat_id, file_id = to_be_whispers[str(sender_id)] receiver = receiver.lower() insert_whisper(sender_id, receiver, message_id, chat_id) del to_be_whispers[str(sender_id)] del temp[str(sender_id).lower()] def error(bot, update, error): logging.warning('Update "%s" caused error "%s"' % (update, error)) updater = Updater(token) dp = updater.dispatcher dp.add_handler(InlineQueryHandler(inline_query)) dp.add_handler(CommandHandler('start', start, pass_args=True)) dp.add_handler(CommandHandler('cancel', cancel)) dp.add_handler(ChosenInlineResultHandler(chosen)) dp.add_handler(MessageHandler(Filters.photo, photo)) dp.add_error_handler(error) # 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 add_update_handlers(dispatcher): dispatcher.add_handler(CommandHandler("start", text.start)) dispatcher.add_handler(CommandHandler("about", text.about)) dispatcher.add_handler(InlineQueryHandler(handle_inline_query)) return dispatcher
def set_up_inline_handler(updater): inline_query_handler = InlineQueryHandler(answer_inline_query) updater.dispatcher.add_handler(inline_query_handler)
updater.dispatcher.add_handler( MessageHandler(Filters.text('➕ Add category'), noavailable)) updater.dispatcher.add_handler( MessageHandler(Filters.text('🗑 Remove category'), noavailable)) updater.dispatcher.add_handler( MessageHandler(Filters.text('📦 New product'), noavailable)) updater.dispatcher.add_handler( MessageHandler(Filters.text('🗑 Delete product'), noavailable)) updater.dispatcher.add_handler( MessageHandler(Filters.text('👋 Welcome text'), welcometext)) updater.dispatcher.add_handler(MessageHandler(Filters.text('🛒 Cart'), cart)) updater.dispatcher.add_handler(MessageHandler(Filters.text('📦 Orders'), order)) updater.dispatcher.add_handler(MessageHandler(Filters.text('👥 Users'), user)) updater.dispatcher.add_handler( InlineQueryHandler(catalogquery, pattern='🍕 pizza')) updater.dispatcher.add_handler(CallbackQueryHandler(addcard, pattern='addcard')) updater.dispatcher.add_handler(CallbackQueryHandler(cancel, pattern='cancel')) updater.dispatcher.add_handler(CallbackQueryHandler(accept, pattern='accept')) updater.dispatcher.add_handler(CallbackQueryHandler(clear, pattern='clear')) updater.dispatcher.add_handler( CallbackQueryHandler(plaseorder, pattern='plaseorder')) updater.dispatcher.add_handler( CallbackQueryHandler(addaddress, pattern='addaddress')) updater.dispatcher.add_handler( CallbackQueryHandler(addresses, pattern='addresses')) updater.start_polling() updater.idle()
SEARCH_URL = 'https://www.etymonline.com/search?q=' from telegram import InlineQueryResultArticle, InputTextMessageContent def inline_etym(bot,update): query = update.inline_query.query result = [] text = first_result_return(query) result.append(InlineQueryResultArticle( id=query, title=query, input_message_content=InputTextMessageContent(query + ': \n' + text))) bot.answer_inline_query(update.inline_query.id, result) inline_etym_handler = InlineQueryHandler(inline_etym) dispatcher.add_handler(inline_etym_handler) updater.start_polling() ''' functions from https://github.com/tetrismegistus/etym ''' def soup_search(search_term): # post request to search URL, return beautiful soup parsed object url = SEARCH_URL + search_term response = requests.get(url) return BeautifulSoup(response.text, 'html.parser') def first_result_return(word): #print("{}\n".format(search_page.find("div", class_="searchList__pageCount--2jQdB").get_text()))
) sets.dispatcher.add_handler( CommandHandler("translator", menu) ) sets.dispatcher.add_handler( CommandHandler("info", menu) ) sets.dispatcher.add_handler( MessageHandler(Filters.audio | Filters.text, menu) ) sets.dispatcher.add_handler( InlineQueryHandler(search) ) sets.dispatcher.add_handler( CallbackQueryHandler(download) ) sets.start_polling() else: exit() print("Bot started") while True: sleep(1) path = os.statvfs("/")
def add_update_handlers(dp): browse_handler = ConversationHandler( entry_points=[ CommandHandler('artist', browse.search_artist, pass_args=True, allow_edited=True), CommandHandler('song', browse.search_song, pass_args=True, allow_edited=True), CommandHandler('album', browse.search_album, pass_args=True, allow_edited=True), CommandHandler('search', browse.search_all, pass_args=True, allow_edited=True), CommandHandler('new', browse.new), CommandHandler('top', browse.top), CommandHandler('trending', browse.trending), RegexHandler(r'^/(dev)_(\d+)(@.+)?$', browse.derived, pass_groups=True), RegexHandler(r'^/(rel)_(\d+)(@.+)?$', browse.related, pass_groups=True), RegexHandler(r'^/(albys)_(\d+)(@.+)?$', browse.albums_by_song, pass_groups=True), CallbackQueryHandler(browse.artist, pattern=r'^(arlist)\|(.*)\|(.*)$', pass_groups=True) ], states={ BrowseState.page: [ MessageHandler(Filters.text, browse.edited, allow_edited=True, pass_update_queue=True) ], BrowseState.input: [MessageHandler(Filters.text, browse.search_input, allow_edited=True)], BrowseState.input_song: [MessageHandler(Filters.text, browse.search_input_song, allow_edited=True)], BrowseState.input_artist: [MessageHandler(Filters.text, browse.search_input_artist, allow_edited=True)], BrowseState.input_album: [MessageHandler(Filters.text, browse.search_input_album, allow_edited=True)] }, fallbacks=[CommandHandler('cancel', cancel)], allow_reentry=True ) # Was inside BrowseState.page state, but we always want paging buttons to work.. even in semi old messages browse_page_handler = CallbackQueryHandler(browse.next_page, pattern=r'^(page)\|(.+)\|(.+)$', pass_groups=True) start_handler = CommandHandler('start', text.start, pass_args=True, pass_update_queue=True) help_handler = CommandHandler('help', text.send_help) inline_handler = CommandHandler('inline', text.inline) about_handler = CommandHandler('about', text.about) privacy_handler = CommandHandler('privacy', text.privacy) kill_handler = CommandHandler('kill', text.kill) settings_handler = CommandHandler('settings', settings.start) # TODO: Handle edited_message in these too? (would be nice for eg. /artist pinocchio) song_handler = RegexHandler(r'^/(?:info|s)_(\d+)(@.+)?$', info.song, pass_groups=True) artist_handler = RegexHandler(r'^/(?:ar)_(\d+)(@.+)?$', info.artist, pass_groups=True) album_handler = RegexHandler(r'^/(?:al)_(\d+)(@.+)?$', info.album, pass_groups=True) song_by_pv_handler = MessageHandler(Filters.entity(MessageEntity.URL), info.song_by_pv) lyrics_handler = CallbackQueryHandler(info.lyrics, pattern=r'^(?:ly)\|([^\|]*)\|?([^\|]*)?$', pass_groups=True) pv_handler = CallbackQueryHandler(info.pv, pattern=r'^(?:pv)\|([^\|]*)\|?([^\|]*)?$', pass_groups=True) album_list_handler = CallbackQueryHandler(info.album_list, pattern=r'^(?:allist)\|(.*)$', pass_groups=True) forwarded_handler = MessageHandler(forwarded_filter, info.forwarded, pass_update_queue=True) set_handler = CallbackQueryHandler(settings.delegate, pattern='^(?:set)\|([^\|]*)\|?([^\|]*)?$', pass_groups=True, pass_job_queue=True) # Remove the spinning loading icon from buttons cancel_callback_query_handler = CallbackQueryHandler(cancel_callback_query) song_direct_handler = InlineQueryHandler(inline.song_direct, pattern=r'^!(?:s)#(\d+)$', pass_groups=True) song_search_handler = InlineQueryHandler(inline.song_search, pattern=r'^\!(?:s) ?(.*)$', pass_groups=True) album_direct_handler = InlineQueryHandler(inline.album_direct, pattern=r'^!(?:al)#(\d+)$', pass_groups=True) album_search_handler = InlineQueryHandler(inline.album_search, pattern=r'^\!(?:al) ?(.*)$', pass_groups=True) artist_direct_handler = InlineQueryHandler(inline.artist_direct, pattern=r'^!(?:ar?)#(\d+)$', pass_groups=True) artist_search_handler = InlineQueryHandler(inline.artist_search, pattern=r'^\!(?:ar?) ?(.*)$', pass_groups=True) inline_leftover_handler = InlineQueryHandler(inline.delegate) # All who didn't match above regex cancel_handler = CommandHandler('cancel', text.cancel) unknown_command_handler = MessageHandler(Filters.command, text.unknown) # Add handlers to dispatcher dp.add_handler(forwarded_handler) # Has to be here otherwise BrowseState.page handler will eat it dp.add_handler(song_by_pv_handler) # Same deal here dp.add_handler(browse_handler) dp.add_handler(browse_page_handler) dp.add_handler(start_handler) dp.add_handler(help_handler) dp.add_handler(inline_handler) dp.add_handler(about_handler) dp.add_handler(privacy_handler) dp.add_handler(kill_handler) dp.add_handler(settings_handler) dp.add_handler(song_handler) dp.add_handler(artist_handler) dp.add_handler(album_handler) dp.add_handler(lyrics_handler) dp.add_handler(pv_handler) dp.add_handler(album_list_handler) dp.add_handler(set_handler) dp.add_handler(cancel_callback_query_handler) dp.add_handler(song_direct_handler) dp.add_handler(artist_direct_handler) dp.add_handler(album_direct_handler) dp.add_handler(song_search_handler) dp.add_handler(album_search_handler) # Has to be before artist since the 'r' in 'ar' is optional there dp.add_handler(artist_search_handler) dp.add_handler(inline_leftover_handler) dp.add_handler(cancel_handler) dp.add_handler(unknown_command_handler) return dp
def test_context(self, cdp, inline_query): handler = InlineQueryHandler(self.callback_context) cdp.add_handler(handler) cdp.process_update(inline_query) assert self.test_flag
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters, CallbackQueryHandler, InlineQueryHandler updater = Updater(TOKEN, use_context=True) dispatcher = updater.dispatcher dispatcher.add_handler(CommandHandler("start", CMD.start)) dispatcher.add_handler(CommandHandler("help", CMD.help)) dispatcher.add_handler(CommandHandler("swap", CMD.swap)) dispatcher.add_handler(CommandHandler("src", CMD.src_query)) dispatcher.add_handler(CommandHandler("dest", CMD.dest_query)) dispatcher.add_handler(CommandHandler("langs", CMD.selected_languages)) dispatcher.add_handler(CommandHandler("fav", CMD.favorites_setting_query)) dispatcher.add_handler(CommandHandler("cancel", CMD.cancel)) dispatcher.add_handler(CommandHandler("contact", CMD.contact)) dispatcher.add_handler(MessageHandler(Filters.command, CMD.unrecognized)) dispatcher.add_handler( MessageHandler(Filters.text & ~Filters.command & ~Filters.via_bot(BOT_ID), CMD.translate)) dispatcher.add_handler( MessageHandler(Filters.document.category("text"), CMD.translate_file)) dispatcher.add_handler(CallbackQueryHandler(CMD.query_handle)) dispatcher.add_handler(InlineQueryHandler(Inline.query)) dispatcher.add_error_handler(CMD.error_callback) updater.start_polling() updater.idle()
text=str(r.text) + " 🔞", reply_to_message_id=update.message.message_id) else: context.bot.send_message( chat_id=update.effective_chat.id, text=str(r.text) + " ✅", reply_to_message_id=update.message.message_id) else: context.bot.send_message(chat_id=update.effective_chat.id, text="请回复一条带有图片的消息", reply_to_message_id=update.message.message_id) msg_hanlder = MessageHandler(~Filters.command, msg) result_hanlder = ChosenInlineResultHandler(onsend) inline_caps_handler = InlineQueryHandler(inline_caps) dispatcher = updater.dispatcher dispatcher.add_handler(CallbackQueryHandler(query2, pattern=r"^challenge\|")) dispatcher.add_handler(CallbackQueryHandler(checkin, pattern=r"^checkin")) dispatcher.add_handler(msg_hanlder) dispatcher.add_handler(result_hanlder) dispatcher.add_handler(inline_caps_handler) dispatcher.add_handler(CallbackQueryHandler(query)) dispatcher.add_handler(CommandHandler('check', check)) dispatcher.add_handler(CommandHandler('lick', lick)) dispatcher.add_handler(CommandHandler('start', start)) dispatcher.add_handler(CommandHandler('acc', acc)) dispatcher.add_handler(CommandHandler('top', top)) dispatcher.add_handler(CommandHandler('topweek', topweek)) dispatcher.add_handler(CommandHandler('topmonth', topmonth)) dispatcher.add_handler(CommandHandler('topyear', topyear))
def go(self) -> None: # TODO: длинный метод logging.basicConfig( format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO) logger = logging.getLogger(__name__) # Create the Updater and pass it your bot's token. updater = Updater(self.__token) # Get the dispatcher to register handlers dispatcher = updater.dispatcher MAIN_MENU_STATE, SHOW_CARD_STATE, SELECT_TAG_STATE, ADD_CARD_TEXT_STATE, ADD_CARD_TAG_STATE, ADD_CARD_AUTHOR_STATE, ADD_CARD_COUNTRY_STATE, CARD_SAVED_STATE = range( 8) # текст кнопки "выбрать все колоды" ALL_TAGS_TAG = "! Все !" # TODO: избавиться от этих переменных (риски ошибок при нескольких сеансах) self.__last_selected_tag = None self.__card_text = None self.__card_tag = None self.__card_author = None self.__card_country = None self.__last_card = None def main_menu_state_handler(update: Update, context: CallbackContext) -> int: logger.info("Главное меню") text = 'Привет. Я карточных дел мастер. Выбери, что мы с тобой будем делать' reply_keyboard = [['Вытянуть карточку'], ['Добавить карточку'], ['Список всех карточек']] keyboard_markup = ReplyKeyboardMarkup(reply_keyboard, one_time_keyboard=True) update.message.reply_text(text, reply_markup=keyboard_markup) return MAIN_MENU_STATE def select_tag_state_handler(update: Update, context: CallbackContext) -> int: text = 'Выбери колоду или "Все", если хочешь смешать все колоды' logger.info("Выбрать колоду") tags = self.__card_service.get_all_tags() tags = [ALL_TAGS_TAG] + tags reply_keyboard = [[tag] for tag in tags] keyboard_markup = ReplyKeyboardMarkup(reply_keyboard, one_time_keyboard=True) update.message.reply_text( text, reply_markup=keyboard_markup, reply_to_message_id=update.message.message_id) return SELECT_TAG_STATE def show_card_state_handler(update: Update, context: CallbackContext) -> int: if self.__last_card != None: card = self.__last_card self.__last_selected_tag = card.tag logger.info('Просмотр последней добавленной карты') else: user_data = context.user_data selected_tag = self.__last_selected_tag if update.message.text == 'Вытащить еще одну карту' else update.message.text self.__last_selected_tag = selected_tag logger.info('Выбрана колода "%s"', selected_tag) tag = None if selected_tag == ALL_TAGS_TAG else selected_tag card = self.__card_service.get_random_card(tag) def get_markdownV2_card_message_text(card: Card): result = '' author_text = f'{card.author} ' if card.author else '' country_text = f'{card.country} ' if card.country else '' title_text = author_text + country_text result += f'* {title_text} *\n\n' if title_text else '' # result+= card.text.replace('.', r'\.') result += re.escape(card.text) return result def get_plaintext_card_message_text(card: Card): result = '' author_text = f'{card.author} ' if card.author else '' country_text = f'{card.country} ' if card.country else '' title_text = author_text + country_text result += f'{title_text}\n\n' if title_text else '' result += card.text return result reply_text = get_plaintext_card_message_text(card) reply_keyboard = [["Вытащить еще одну карту"], ["Выбрать колоду"], ["Вернуться в главное меню"]] markup = ReplyKeyboardMarkup(reply_keyboard, one_time_keyboard=True) update.message.reply_text( reply_text, reply_markup=markup, reply_to_message_id=update.message.message_id) # update.message.reply_text(reply_text, reply_markup=markup, parse_mode='MarkdownV2', reply_to_message_id=update.message.message_id) logger.info('Показана цитата "%s"', card.text) return SHOW_CARD_STATE def add_card_text_state_handler(update: Update, context: CallbackContext) -> int: text = 'Введите текст цитаты (можно несколько строк)' logger.info("Ввод цитаты") self.__last_card = None # update.message.reply_text(text, reply_markup=ReplyKeyboardRemove(), reply_to_message_id=update.message.message_id) update.message.reply_text(text, reply_markup=ReplyKeyboardRemove()) return ADD_CARD_TEXT_STATE def add_card_tag_state_handler(update: Update, context: CallbackContext) -> int: self.__card_text = update.message.text text = 'Введите название колоды или выбирите из списка' logger.info("Ввод названия колоды") tags = self.__card_service.get_all_tags() reply_keyboard = [[tag] for tag in tags] keyboard_markup = ReplyKeyboardMarkup(reply_keyboard, one_time_keyboard=True) update.message.reply_text( text, reply_markup=keyboard_markup, reply_to_message_id=update.message.message_id) return ADD_CARD_TAG_STATE def add_card_author_state_handler(update: Update, context: CallbackContext) -> int: self.__card_tag = update.message.text text = 'Введите автора цитаты' logger.info("Ввод автора цитаты") update.message.reply_text( text, reply_markup=ReplyKeyboardRemove(), reply_to_message_id=update.message.message_id) return ADD_CARD_AUTHOR_STATE def add_card_country_state_handler(update: Update, context: CallbackContext) -> int: self.__card_author = update.message.text text = 'Введите страну (если хотите)' logger.info("Ввод страны цитаты") reply_keyboard = [['Пропустить этот шаг']] keyboard_markup = ReplyKeyboardMarkup(reply_keyboard, one_time_keyboard=True) update.message.reply_text( text, reply_markup=keyboard_markup, reply_to_message_id=update.message.message_id) return ADD_CARD_COUNTRY_STATE def card_saved_state_handler(update: Update, context: CallbackContext) -> int: self.__card_country = '' if update.message.text == "Пропустить этот шаг" else update.message.text card = Card(self.__card_text, self.__card_tag, self.__card_author, self.__card_country) card_id = self.__card_service.save_new_card(card) card.id = card_id self.__last_card = card self.__card_text, self.__card_tag, self.__card_author, self.__card_country = None, None, None, None text = 'Цитата сохранена' logger.info("Цитата сохранена") reply_keyboard = [['Посмотреть карточку сохраненной цитаты'], ['Вернуться в главное меню']] keyboard_markup = ReplyKeyboardMarkup(reply_keyboard, one_time_keyboard=True) update.message.reply_text(text, reply_markup=keyboard_markup) # update.message.reply_text(text, reply_markup=markup, reply_to_message_id=update.message.message_id) return CARD_SAVED_STATE def cancel(update: Update, context: CallbackContext) -> int: logger.info("Отмена") text = 'Bye! I hope we can talk again some day.' update.message.reply_text( text, reply_markup=ReplyKeyboardRemove(), reply_to_message_id=update.message.message_id) return ConversationHandler.END conv_handler = ConversationHandler( entry_points=[CommandHandler('start', main_menu_state_handler)], states={ MAIN_MENU_STATE: [ MessageHandler(Filters.regex('^.*Вытянуть карточку.*$'), select_tag_state_handler), MessageHandler(Filters.regex('^.*Добавить карточку.*$'), add_card_text_state_handler), # MessageHandler(Filters.regex('^.*Список всех карточек.*$'), get_all_card_state_handler) ], SELECT_TAG_STATE: [ MessageHandler(Filters.text, show_card_state_handler), CommandHandler('cancel', cancel) ], SHOW_CARD_STATE: [ MessageHandler( Filters.regex('^.*Вытащить еще одну карту.*$'), show_card_state_handler), MessageHandler(Filters.regex('^.*Выбрать колоду.*$'), select_tag_state_handler), MessageHandler( Filters.regex('^.*Вернуться в главное меню.*$'), main_menu_state_handler), CommandHandler('cancel', cancel) ], ADD_CARD_TEXT_STATE: [ MessageHandler(Filters.text, add_card_tag_state_handler), CommandHandler('cancel', cancel) ], ADD_CARD_TAG_STATE: [ MessageHandler(Filters.text, add_card_author_state_handler), CommandHandler('cancel', cancel) ], ADD_CARD_AUTHOR_STATE: [ MessageHandler(Filters.text, add_card_country_state_handler), CommandHandler('cancel', cancel) ], ADD_CARD_COUNTRY_STATE: [ MessageHandler(Filters.text, card_saved_state_handler), CommandHandler('cancel', cancel) ], CARD_SAVED_STATE: [ MessageHandler( Filters.regex( '^.*Посмотреть карточку сохраненной цитаты.*$'), show_card_state_handler), MessageHandler( Filters.regex('^.*Вернуться в главное меню.*$'), main_menu_state_handler), MessageHandler(Filters.text, card_saved_state_handler), CommandHandler('cancel', cancel) ], }, fallbacks=[CommandHandler('cancel', cancel)], ) dispatcher.add_handler(conv_handler) def inlinequery(update: Update, context: CallbackContext) -> None: """Handle the inline query.""" query = update.inline_query.query logger.info('Inline query "%s"', query) all_tags = self.__card_service.get_all_tags() + [None] def get_inline_query_result_for_tag(tag): card = self.__card_service.get_random_card(tag) title = ALL_TAGS_TAG if tag == None else tag return InlineQueryResultArticle( id=uuid4(), title=title, input_message_content=InputTextMessageContent(card.text)) results = [ get_inline_query_result_for_tag(tag) for tag in all_tags ] update.inline_query.answer(results) dispatcher.add_handler(InlineQueryHandler(inlinequery)) # запускаем бота updater.start_polling() # бесконечная работа бота updater.idle()
summary_handler = CommandHandler('summarise', summarise) dispatcher.add_handler(summary_handler) support_handler = CommandHandler('supportedSites', supported_sites) dispatcher.add_handler(support_handler) # creating resonses for inline mode from telegram import InlineQueryResultArticle, InputTextMessageContent def inline_summarise(update, context): query = update.inline_query.query # not working. somehow can't recognize links if not query: return else: # summary = es.main(query) results = [] results.append( InlineQueryResultArticle( id = query, title = 'Summarise', input_message_content = InputTextMessageContent(query) ) ) context.bot.answer_inline_query(update.inline_query.id, results) from telegram.ext import InlineQueryHandler inline_summarise_handler = InlineQueryHandler(inline_summarise) dispatcher.add_handler(inline_summarise_handler) # start the bot updater.start_polling()
try: print("1): Free") print("2): Strict") #ans = input("Choose: ") while (1 == 1): for a in comandss: sets.dispatcher.add_handler(CommandHandler(a, menu)) sets.dispatcher.add_handler( MessageHandler( Filters.audio | Filters.text | Filters.voice | Filters.photo, menu)) sets.dispatcher.add_handler(InlineQueryHandler(search)) sets.dispatcher.add_handler(CallbackQueryHandler(download)) sets.start_polling() else: raise KeyboardInterrupt print("Bot started") while True: sleep(1) path = os.statvfs("/") free_space = path.f_bavail * path.f_frsize if (del1 <= del2 and is_audio == 0) or free_space <= limit:
text=__("{name1} didn't bluff! Giving 6 cards to {name2}", multi=game.translate) .format(name1=player.prev.user.first_name, name2=player.user.first_name)) try: player.draw() except DeckEmptyError: send_async(bot, player.game.chat.id, text=__("There are no more cards in the deck.", multi=game.translate)) game.turn() # Add all handlers to the dispatcher and run the bot dispatcher.add_handler(InlineQueryHandler(reply_to_query)) dispatcher.add_handler(ChosenInlineResultHandler(process_result)) dispatcher.add_handler(CallbackQueryHandler(select_game)) dispatcher.add_handler(CommandHandler('start', start_game, pass_args=True)) dispatcher.add_handler(CommandHandler('new', new_game)) dispatcher.add_handler(CommandHandler('join', join_game)) dispatcher.add_handler(CommandHandler('leave', leave_game)) dispatcher.add_handler(CommandHandler('open', open_game)) dispatcher.add_handler(CommandHandler('close', close_game)) dispatcher.add_handler(CommandHandler('enable_translations', enable_translations)) dispatcher.add_handler(CommandHandler('disable_translations', disable_translations)) dispatcher.add_handler(CommandHandler('skip', skip_player)) dispatcher.add_handler(CommandHandler('notify_me', notify_me)) simple_commands.register()
main_states = [ MSH(Filters.regex('^🌈 Подписаться на 21_Daily_Tips 🌈$'), to_story), MSH(Filters.regex('^🤷♂️ 21_FAQ 🤷$'), to_faq), MSH(Filters.regex('^🔮 Всякое 🔮$'), to_misc), MSH(Filters.regex('^📲 Свяжись с нами! 📲$'), inlinequery, pass_user_data=True), MSH(Filters.regex('^🕸🔗📱$'), to_links) ] return_states = [ MSH(Filters.regex('^👈🏿$'), rewind), MSH(Filters.regex('^🤙🏿$'), to_links) ] inliner = [InlineQueryHandler(inlinequery)] conv_handler = ConversationHandler( entry_points=[ CMH('start', start), MSH(Filters.all, rewind), ], states={ MAIN: main_states, STORY: main_states.__add__(return_states), FAQ: main_states.__add__(inliner), MISC: main_states.__add__(return_states), CONTACT: main_states.__add__(return_states), }, fallbacks=[MSH(Filters.all, help)], )
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(InlineQueryHandler(inlinequery)) updater.dispatcher.add_handler(CommandHandler('search_books', search_books)) updater.dispatcher.add_handler( CallbackQueryHandler(search_books, pattern='search_books')) updater.dispatcher.add_handler( MessageHandler(Filters.text, callback=search_books)) if os.environ.get("HEROKU"): updater.start_webhook(listen="0.0.0.0", port=PORT, url_path=TELEGRAM_BOT_TOKEN) updater.bot.set_webhook(f"{APP_URL}/{TELEGRAM_BOT_TOKEN}") else: updater.start_polling()
def main(): print(token) # Create the EventHandler and pass it your bot's token. updater = Updater(token, workers=10) # Get the dispatcher to register handlers dp = updater.dispatcher inline_caps_handler = InlineQueryHandler(inline_caps) # This is how we add handlers for Telegram messages dp.addHandler(inline_caps_handler) dp.addHandler(CommandHandler(CommandsKeys.start, start)) dp.addHandler(CommandHandler(CommandsKeys.check_in, check_in)) dp.addHandler(CommandHandler(CommandsKeys.check_out, check_out)) dp.addHandler(CommandHandler(CommandsKeys.man, man)) dp.addHandler(CommandHandler(CommandsKeys.check_remove, check_remove)) dp.addHandler(CommandHandler(CommandsKeys.cheked_time, checked_time)) dp.addHandler(CommandHandler(CommandsKeys.esc, esc)) [dp.addHandler(CommandHandler(x, man)) for x in CommandsKeys.man_pool] # Message handlers only receive updates that don't contain commands # dp.addHandler(MessageHandler([filters.TEXT], message)) # Regex handlers will receive all updates on which their regex matches, # but we have to add it in a separate group, since in one group, # only one handler will be executed # dp.addHandler(RegexHandler('.*', any_message), group='log') # String handlers work pretty much the same. Note that we have to tell # the handler to pass the args or update_queue parameter # dp.addHandler(StringCommandHandler('reply', cli_reply, pass_args=True)) dp.addHandler( StringRegexHandler(r'/.*', cli_noncommand, pass_update_queue=True)) # All TelegramErrors are caught for you and delivered to the error # handler(s). Other types of Errors are not caught. dp.addErrorHandler(error) # Start the Bot and store the update Queue, so we can insert updates update_queue = updater.start_polling(timeout=10) ''' # Alternatively, run with webhook: update_queue = updater.start_webhook('0.0.0.0', 443, url_path=token, cert='cert.pem', key='key.key', webhook_url='https://example.com/%s' % token) # Or, if SSL is handled by a reverse proxy, the webhook URL is already set # and the reverse proxy is configured to deliver directly to port 6000: update_queue = updater.start_webhook('0.0.0.0', 6000) ''' # Start CLI-Loop while True: try: text = raw_input() except NameError: text = input() # Gracefully stop the event handler if text == 'stop': updater.stop() break # else, put the text into the update queue to be handled by our # handlers elif len(text) > 0: update_queue.put(text)
config = configparser.ConfigParser() config.read('config.ini') TOKEN = config['auth']['telegram_token'] def inline_article(bot, update): query = update.inline_query.query if not query or len(query) < 3: return data = get_all(query) results = list() for card in data: results.append( InlineQueryResultArticle( id=card['id'], title=card['name'], input_message_content=InputTextMessageContent(card['png']), ) ) bot.answer_inline_query(update.inline_query.id, results) updater = Updater(token=TOKEN) dispatcher = updater.dispatcher inline_article_handler = InlineQueryHandler(inline_article) dispatcher.add_handler(inline_article_handler) updater.start_polling()