def test_perChatMessageWithoutChat(self): handler = ConversationHandler( entry_points=[CommandHandler('start', self.start_end)], states={}, fallbacks=[]) user = User(first_name="Misses Test", id=123) cbq = CallbackQuery(0, user, None, None) update = Update(0, callback_query=cbq) handler.check_update(update)
def test_all_update_types(self, dp, bot, user1): handler = ConversationHandler(entry_points=[CommandHandler('start', self.start_end)], states={}, fallbacks=[]) message = Message(0, user1, None, self.group, text='ignore', bot=bot) callback_query = CallbackQuery(0, user1, None, message=message, data='data', bot=bot) chosen_inline_result = ChosenInlineResult(0, user1, 'query', bot=bot) inline_query = InlineQuery(0, user1, 'query', 0, bot=bot) pre_checkout_query = PreCheckoutQuery(0, user1, 'USD', 100, [], bot=bot) shipping_query = ShippingQuery(0, user1, [], None, bot=bot) assert not handler.check_update(Update(0, callback_query=callback_query)) assert not handler.check_update(Update(0, chosen_inline_result=chosen_inline_result)) assert not handler.check_update(Update(0, inline_query=inline_query)) assert not handler.check_update(Update(0, message=message)) assert not handler.check_update(Update(0, pre_checkout_query=pre_checkout_query)) assert not handler.check_update(Update(0, shipping_query=shipping_query))
config_handler = ConversationHandler( entry_points=[CommandHandler('config', config)], states={ CHOOSING: [ CallbackQueryHandler(ask_profile_pic, pattern="^changepic$"), CallbackQueryHandler(ask_change_name, pattern="^changename$"), CallbackQueryHandler(ask_change_timezone, pattern="^changetimezone$"), CallbackQueryHandler(ask_change_gender, pattern="^changegender$"), CallbackQueryHandler(ask_change_schedule, pattern="^changeschedule"), CallbackQueryHandler(ask_change_language, pattern="^changelanguage$"), CallbackQueryHandler(view_profile, pattern="^viewprofile$"), CallbackQueryHandler(ask_delete_user, pattern="^deleteuser$"), ], PROCESS_GENDER: [ CallbackQueryHandler(process_gender, pattern="^(Male|Female|Other)$") ], PROCESS_PROFILE_PIC: [MessageHandler(Filters.photo, process_profile_pic)], PROCESS_NAME: [ MessageHandler(~is_answering_filter & ~Filters.command, process_name) ], PROCESS_LANGUAGE: [CallbackQueryHandler(process_language, pattern='^(ES|GB)$')], PROCESS_DELETE_USER: [CallbackQueryHandler(process_delete_user, pattern="^deleteuser$")], PROCESS_SCHEDULE: [ MessageHandler(Filters.regex('^([0-1]?[0-9]|2[0-3]):[0-5][0-9]$'), process_change_schedule), MessageHandler(~Filters.regex('^([0-1]?[0-9]|2[0-3]):[0-5][0-9]$'), process_wrong_schedule) ], PROCESS_TIMEZONE: [ MessageHandler(Filters.location, process_change_timezone), CallbackQueryHandler(default_timezone, pattern="^default-timezone$") ] }, fallbacks=[ CallbackQueryHandler(back, pattern="^back$"), CallbackQueryHandler(_exit, pattern="^exit$") ], name="configurator")
] 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)], ) bot.add_handler(conv_handler) #Errors bot.add_error_handler(error) #˜˜˜˜˜˜ Gogogo ˜˜˜˜˜˜# bot_core.start_polling() bot_core.idle()
from token_api import token_api logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO) WAITING_FOR_TEST, WAITING_FOR_TEXT, WAITING_FOR_LABEL = range(3) updater = Updater(token_api()) test_handler = ConversationHandler( entry_points=[CommandHandler('test', test_bayes)], states={ WAITING_FOR_TEST: [MessageHandler(Filters.text, test_bayes__text)] }, fallbacks=[CommandHandler('start', start)] ) train_handler = ConversationHandler( entry_points=[CommandHandler('train', train_bayes)], states={ WAITING_FOR_TEXT: [MessageHandler(Filters.text, train_bayes__text)], WAITING_FOR_LABEL: [CallbackQueryHandler(train_bayes__label)] }, fallbacks=[CommandHandler('start', start)] ) updater.dispatcher.add_handler(CommandHandler('start', start))
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()
def add_conversation(self, conversation): """ This method adds a conversation flow Parameters ---------- conversation : Conversation object The conversation that will be added """ if isinstance(conversation, Conversation): entry_points = [] for entry_point in conversation.get_entry_points(): handler = None if entry_point[0]: handler = CommandHandler(entry_point[0], entry_point[1], pass_user_data=entry_point[3]) else: handler = MessageHandler(entry_point[2], entry_point[1], pass_user_data=entry_point[3]) entry_points.append(handler) states = {} states_commands = conversation.get_states() for state in states_commands: states[state] = [] for command in states_commands[state]: if command[0]: states[state].append( CommandHandler(command[0], command[1], pass_user_data=command[3])) else: states[state].append( MessageHandler(command[2], command[1], pass_user_data=command[3])) fallbacks = [] for fallback in conversation.get_fallbacks(): handler = None if fallback[0]: handler = CommandHandler(fallback[0], fallback[1], pass_user_data=fallback[3]) else: handler = MessageHandler(fallback[2], fallback[1], pass_user_data=fallback[3]) fallbacks.append(handler) self.dp.add_handler( ConversationHandler(entry_points=entry_points, states=states, fallbacks=fallbacks)) else: raise NotAConversation( "Must pass Conversation object, not {}".format( type(conversation)))
bot.send_photo(update.message.chat_id, img, caption=random.choice(captions), parse_mode=ParseMode.MARKDOWN, reply_markup=ReplyKeyboardRemove()) return ConversationHandler.END def meme_fallback(update, context): bot = context.bot msg = "Joe!" bot.send_message(chat_id=update.message.chat_id, text=msg, parse_mode=ParseMode.MARKDOWN, reply_to_message_id=update.message.message_id, reply_markup=ReplyKeyboardRemove()) return ConversationHandler.END reddit_conv = ConversationHandler( entry_points=[CommandHandler("meme", meme)], states={ CHOICE: [MessageHandler(redditpage_filter, get_memes)], }, fallbacks=[CommandHandler("exit", meme_fallback)], name="Memeversatie", )
def test_channel_message_without_chat(self, bot): handler = ConversationHandler(entry_points=[CommandHandler('start', self.start_end)], states={}, fallbacks=[]) message = Message(0, None, None, Chat(0, Chat.CHANNEL, 'Misses Test'), bot=bot) update = Update(0, message=message) assert not handler.check_update(update)
item = crud.get_item_for_user_card(db=db, telegram_id=telegram_id, card_name=card_name, question=question) print_question_and_answer(update, item) return waiting_select_question_endpoint(update, context, card_questions_list) else: update.message.reply_text( f"Вопроса '{user_answer}' в карточке {card_name} нет!") return waiting_select_question_endpoint(update, context, card_questions_list) conv_handler = ConversationHandler( entry_points=[CommandHandler('view', start_view)], states={ WAITING_SELECT_CARD: [ MessageHandler( Filters.text & ~(Filters.command | Filters.regex('^Выход$')), select_card) ], WAITING_SELECT_QUESTION: [ MessageHandler( Filters.text & ~(Filters.command | Filters.regex('^Выход$')), select_question) ], }, fallbacks=[MessageHandler(Filters.regex('^Выход$'), done)], )
def add_stock_plugin(dispatcher): # 股票-快速简报打印器 def fast_list_all_mine(update, context): try: stocks = sql_funcs.sql_select_all_mine(update.effective_user.id) if stocks is None: user = update.effective_user.name + ":\n" text = user + "数据库中没有您的自选信息" warning("股票模块-快速打印简报方法:" + text) context.bot.send_message(chat_id=update.effective_chat.id, text=text) else: text = "" for i in stocks: try: session = requests.session() session.get("https://xueqiu.com/k?q=" + i[1], headers=header) res = session.get( "https://stock.xueqiu.com/v5/stock/batch/quote.json?symbol=" + i[1], headers=header) json_str = res.json() # 股票名 name = json_str['data']['items'][0]['quote']['name'] # 数据时间 dt = json_str['data']['items'][0]['quote']['time'] if dt is not None: time_local = time.localtime(dt / 1000) dt = time.strftime("%Y-%m-%d %H:%M:%S", time_local) # 交易状态 status = json_str['data']['items'][0]['market'][ 'status'] # 现价 current = json_str['data']['items'][0]['quote'][ 'current'] # 昨收 end_price = json_str['data']['items'][0]['quote'][ 'last_close'] # 跌涨数 cost = 0 if current is not None and end_price is not None: cost = current - end_price # 跌涨率% rate = 0 if cost is not None and end_price is not None and cost != 0: rate = cost / end_price cost = float(format(cost, ".2f")) if cost > 0: cost = "+" + str(cost) rate = float(format(rate * 100, ".2f")) if rate > 0: rate = "+" + str(rate) text += "%s" % dt text += "(%s)\n" % status text += "%s " % name text += "(%s)\n" % i[1] text += "现价:%s " % current text += "(%s " % cost text += ",%s%%)\n\n" % rate except Exception as e: user = update.effective_user.name + ":\n" text = user + "服务器错误,错误原因:" + str(e) error("股票模块-快速打印简报方法:" + text) context.bot.send_message( chat_id=update.effective_chat.id, text=text) return info("股票模块-快速打印简报方法:成功获取用户" + update.effective_user.name + "的" + str(len(stocks)) + "条股票数据") user = update.effective_user.name + ":\n" context.bot.send_message(chat_id=update.effective_chat.id, text=user + text) except: error("股票模块-快速打印简报方法异常") handler = CommandHandler('stock_mine', fast_list_all_mine) dispatcher.add_handler(handler) # 股票-功能选择器 def stock_input(update: Update, _: CallbackContext) -> int: try: keyboard = [[ InlineKeyboardButton("自选", callback_data='自选'), InlineKeyboardButton("搜索", callback_data='搜索'), ]] reply_markup = InlineKeyboardMarkup(keyboard) user = update.effective_user.name + ":\n" info("股票模块-方法选择器:" + update.effective_user.name + "开始了股票功能") update.message.reply_text( user + '请选择方法', reply_markup=reply_markup, ) except: error("股票模块-方法选择器异常") return STOCK_FUNC # 股票-自选功能选择器 def stock_func(update: Update, _: CallbackContext) -> int: try: query = update.callback_query query.answer() query.delete_message() if query.data == "自选": info("股票模块-功能选择器:" + update.effective_user.name + "选择了自选功能") keyboard = [[ InlineKeyboardButton("添加自选", callback_data='添加自选'), InlineKeyboardButton("删除自选", callback_data='删除自选'), ], [InlineKeyboardButton("查看自选", callback_data='查看自选')], [ InlineKeyboardButton("列出全部自选", callback_data='列出全部自选') ]] reply_markup = InlineKeyboardMarkup(keyboard) user = update.effective_user.name + ":\n" query.bot.send_message( chat_id=update.effective_chat.id, text=user + "请选择功能", reply_markup=reply_markup, ) return STOCK_MINE elif query.data == "搜索": user = update.effective_user.name + ":\n" info("股票模块-功能选择器:" + update.effective_user.name + "选择了搜索功能") query.bot.send_message(chat_id=update.effective_chat.id, text=user + "请输入搜索词") return STOCK_SEARCH except: error("股票模块-自选功能选择器异常") return ConversationHandler.END # 股票-自选股查看器 def stock_list_mine(update: Update): try: query = update.callback_query user_id = update.effective_user.id stocks = sql_funcs.sql_select_all_mine(user_id) if stocks is None: user = update.effective_user.name + ":\n" warning("股票模块-自选功能-股票选择器:" + update.effective_user.name + ":数据库中无自选股") query.bot.send_message(chat_id=update.effective_chat.id, text=user + "数据库内没有您的自选数据") return False else: keyboard = [] for i in stocks: describe = i[0] + "(股票代码" + i[1] + ")" keyboard.append( [InlineKeyboardButton(describe, callback_data=i[1])]) reply_markup = InlineKeyboardMarkup(keyboard) user = update.effective_user.name + ":\n" query.bot.send_message( chat_id=update.effective_chat.id, text=user + "请选择股票", reply_markup=reply_markup, ) return True except: error("股票模块-自选模块-股票选择器异常") return False # 股票-股票信息打印函数 def display_stock(code, update: Update): query = update.callback_query try: session = requests.session() session.get("https://xueqiu.com/k?q=" + code, headers=header) res = session.get( "https://stock.xueqiu.com/v5/stock/batch/quote.json?symbol=" + code, headers=header) json_str = res.json() # 地区 region = json_str['data']['items'][0]['market']['region'] # 交易状态 status = json_str['data']['items'][0]['market']['status'] # 时区 time_zone = json_str['data']['items'][0]['market']['time_zone'] # 交易市场 exchange = json_str['data']['items'][0]['quote']['exchange'] # 货币种类 currency = json_str['data']['items'][0]['quote']['currency'] # 股票名 name = json_str['data']['items'][0]['quote']['name'] # 数据时间 dt = json_str['data']['items'][0]['quote']['time'] if dt is not None: time_local = time.localtime(dt / 1000) dt = time.strftime("%Y-%m-%d %H:%M:%S", time_local) # 现价 current = json_str['data']['items'][0]['quote']['current'] # 今开 start_price = json_str['data']['items'][0]['quote']['open'] # 昨收 end_price = json_str['data']['items'][0]['quote']['last_close'] # 跌涨数 cost = 0 if current is not None and end_price is not None: cost = current - end_price # 跌涨率% rate = 0 if cost is not None and end_price is not None and cost != 0: rate = cost / end_price cost = float(format(cost, ".2f")) if cost > 0: cost = "+" + str(cost) rate = float(format(rate * 100, ".2f")) if rate > 0: rate = "+" + str(rate) # 最高 high = json_str['data']['items'][0]['quote']['high'] # 最低 low = json_str['data']['items'][0]['quote']['low'] # 成交量(万手) deal = json_str['data']['items'][0]['quote']['volume'] if deal is not None: deal = format(float(format(deal / 10000, ".2f")), ",") # 成交额(万元) amount = json_str['data']['items'][0]['quote']['amount'] if amount is not None: amount = format(int(format(amount / 10000, ".0f")), ",") # 换手 turnover_rate = json_str['data']['items'][0]['quote'][ 'turnover_rate'] # 振幅 amplitude = json_str['data']['items'][0]['quote']['amplitude'] # 市值(万元) total_price = json_str['data']['items'][0]['quote'][ 'market_capital'] if total_price is not None: total_price = format(int(format(total_price / 10000, ".0f")), ",") # 总股本(万元) total_shares = json_str['data']['items'][0]['quote'][ 'total_shares'] if total_price is not None: total_shares = format(int(format(total_shares / 10000, ".0f")), ",") text = "股票名称:%s\n" % name text += "股票代码:%s\n" % code text += "地区:%s\n" % region text += "时区:%s\n" % time_zone text += "交易市场:%s\n" % exchange text += "货币种类:%s\n" % currency text += "交易状态:%s\n" % status text += "数据时间(当地):%s\n" % dt text += "现价:%s\n" % current text += "今开:%s\n" % start_price text += "昨收:%s\n" % end_price text += "跌涨:%s\n" % cost text += "跌涨率:%s%%\n" % rate text += "最高:%s\n" % high text += "最低:%s\n" % low text += "成交量:%s万手\n" % deal text += "成交额:%s万\n" % amount text += "换手:%s%%\n" % turnover_rate text += "振幅:%s%%\n" % amplitude text += "市值:%s万\n" % total_price text += "总股本:%s万" % total_shares user = update.effective_user.name + ":\n" info("股票模块-自选股-自选股具体信息:用户" + update.effective_user.name + "打印了一条股票具体信息,股票代码:" + code) query.bot.send_message(chat_id=update.effective_chat.id, text=user + text) except Exception as e: user = update.effective_user.name + ":\n" text = user + "服务器错误,错误原因:" + str(e) error("股票模块-自选股-自选股具体信息:" + text) query.bot.send_message(chat_id=update.effective_chat.id, text=text) # 股票-自选功能选择器 def stock_mine(update: Update, _: CallbackContext) -> int: try: query = update.callback_query query.answer() query.delete_message() if query.data == "添加自选": user = update.effective_user.name + ":\n" info("股票模块-自选股功能-自选股功能选择处理器:用户" + update.effective_user.name + "选择添加一条自选") query.bot.send_message(chat_id=update.effective_chat.id, text=user + "请输入搜索词") return STOCK_ADD_MINE elif query.data == "删除自选": info("股票模块-自选股功能-自选股功能选择处理器:用户" + update.effective_user.name + "选择删除一条自选") if not stock_list_mine(update): return ConversationHandler.END else: return STOCK_DELETE_MINE elif query.data == "查看自选": info("股票模块-自选股功能-自选股功能选择处理器:用户" + update.effective_user.name + "选择查看全部自选") if not stock_list_mine(update): return ConversationHandler.END else: return STOCK_SELECT elif query.data == "列出全部自选": info("股票模块-自选股功能-自选股功能选择处理器:用户" + update.effective_user.name + "选择列出全部自选简报") stocks = sql_funcs.sql_select_all_mine( update.effective_user.id) if stocks is None: user = update.effective_user.name + ":\n" query.bot.send_message(chat_id=update.effective_chat.id, text=user + "数据库中没有您的自选信息") else: stocks = sql_funcs.sql_select_all_mine( update.effective_user.id) if stocks is None: user = update.effective_user.name + ":\n" query.bot.send_message( chat_id=update.effective_chat.id, text=user + "数据库中没有您的自选信息") else: text = "" for i in stocks: try: session = requests.session() session.get("https://xueqiu.com/k?q=" + i[1], headers=header) res = session.get( "https://stock.xueqiu.com/v5/stock/batch/quote.json?symbol=" + i[1], headers=header) json_str = res.json() # 股票名 name = json_str['data']['items'][0]['quote'][ 'name'] # 数据时间 dt = json_str['data']['items'][0]['quote'][ 'time'] if dt is not None: time_local = time.localtime(dt / 1000) dt = time.strftime("%Y-%m-%d %H:%M:%S", time_local) # 交易状态 status = json_str['data']['items'][0][ 'market']['status'] # 现价 current = json_str['data']['items'][0][ 'quote']['current'] # 昨收 end_price = json_str['data']['items'][0][ 'quote']['last_close'] # 跌涨数 cost = 0 if current is not None and end_price is not None: cost = current - end_price # 跌涨率% rate = 0 if cost is not None and end_price is not None and cost != 0: rate = cost / end_price cost = float(format(cost, ".2f")) if cost > 0: cost = "+" + str(cost) rate = float(format(rate * 100, ".2f")) if rate > 0: rate = "+" + str(rate) text += "%s" % dt text += "(%s)\n" % status text += "%s " % name text += "(%s)\n" % i[1] text += "现价:%s " % current text += "(%s " % cost text += ",%s%%)\n\n" % rate except Exception as e: user = update.effective_user.name + ":\n" query.bot.send_message( chat_id=update.effective_chat.id, text=user + "服务器错误,错误原因:" + str(e)) return ConversationHandler.END user = update.effective_user.name + ":\n" query.bot.send_message( chat_id=update.effective_chat.id, text=user + text) return ConversationHandler.END except: error("股票模块-自选股功能-自选股功能选择处理器异常") return ConversationHandler.END # 股票-股票查找器 def search_func(update: Update): try: key = update.message.text session = requests.session() session.get("https://xueqiu.com/k?q=" + key, headers=header) res = session.get( "https://xueqiu.com/query/v1/search/web/stock.json?q=" + key, headers=header) json_str = res.json() res = json_str['list'] flag = 0 keyboard = [] for i in res: flag += 1 if flag > 5: break describe = i['name'] + "(股票代码" + i['code'] + ")" keyboard.append( [InlineKeyboardButton(describe, callback_data=i['code'])]) if json_str['count'] == 0: user = update.effective_user.name + ":\n" update.message.reply_text(text=user + "无搜索结果") return ConversationHandler.END text = "获取到的结果共%s个\n请选择一个进行查看\n" % json_str['count'] if json_str['count'] > 5: text += "搜索结果过多,仅显示前五条结果" reply_markup = InlineKeyboardMarkup(keyboard) user = update.effective_user.name + ":\n" update.message.reply_text( text=user + text, reply_markup=reply_markup, ) except Exception as e: user = update.effective_user.name + ":\n" update.message.reply_text(text=user + "服务器错误,错误原因:" + str(e)) # 股票-自选股添加选择器 def add_mine(update: Update, _: CallbackContext) -> int: info("用户" + update.effective_user.name + "选择了添加自选") search_func(update) return STOCK_DO_ADD_MINE # 股票-自选股添加器 def do_add_mine(update: Update, _: CallbackContext) -> None: query = update.callback_query query.answer() query.delete_message() code = query.data info("用户" + update.effective_user.name + "添加了一条自选,代码为:" + code) user_id = update.effective_user.id session = requests.session() session.get("https://xueqiu.com/k?q=" + code, headers=header) res = session.get( "https://stock.xueqiu.com/v5/stock/batch/quote.json?symbol=" + code, headers=header) json_str = res.json() name = json_str['data']['items'][0]['quote']['name'] if sql_funcs.sql_insert_mine(user_id, code, name): user = update.effective_user.name + ":\n" info("用户" + update.effective_user.name + "添加了一条自选成功,代码为:" + code) query.bot.send_message(chat_id=update.effective_chat.id, text=user + "添加成功") else: user = update.effective_user.name + ":\n" warning("用户" + update.effective_user.name + "添加自选失败,代码为:" + code) query.bot.send_message( chat_id=update.effective_chat.id, text=user + "添加失败,您可能已经添加该股票或您已经达到自选添加上限。(上限为%s)" % max_mine_stock) return ConversationHandler.END # 股票-自选股删除器 def do_delete_mine(update: Update, _: CallbackContext) -> None: query = update.callback_query query.answer() query.delete_message() code = query.data info("用户" + update.effective_user.name + "删除了一条自选,代码为:" + code) user_id = update.effective_user.id if sql_funcs.sql_delete_mine(user_id, code): user = update.effective_user.name + ":\n" info("用户" + update.effective_user.name + "删除了一条自选成功,代码为:" + code) query.bot.send_message(chat_id=update.effective_chat.id, text=user + "删除成功") else: user = update.effective_user.name + ":\n" info("用户" + update.effective_user.name + "删除了一条自选失败,代码为:" + code) query.bot.send_message(chat_id=update.effective_chat.id, text=user + "删除失败") return ConversationHandler.END # 股票-搜索功能 def stock_search(update: Update, _: CallbackContext) -> int: search_func(update) return STOCK_SELECT # 股票-查看搜索结果股票信息 def stock_select(update: Update, _: CallbackContext) -> int: query = update.callback_query query.answer() query.delete_message() code = query.data display_stock(code, update) return ConversationHandler.END conv_handler = ConversationHandler( entry_points=[CommandHandler('stock', stock_input)], states={ STOCK_FUNC: [CallbackQueryHandler(stock_func, pattern='^(自选|搜索)$')], STOCK_SEARCH: [MessageHandler(Filters.text, stock_search)], STOCK_MINE: [CallbackQueryHandler(stock_mine)], STOCK_SELECT: [CallbackQueryHandler(stock_select)], STOCK_ADD_MINE: [MessageHandler(Filters.text, add_mine)], STOCK_DO_ADD_MINE: [CallbackQueryHandler(do_add_mine)], STOCK_DELETE_MINE: [CallbackQueryHandler(do_delete_mine)] }, fallbacks=[CommandHandler('cancel', cancel)], ) dispatcher.add_handler(conv_handler)
def setup(): # Create the Updater and pass it your bot's token. updater = driversakhabot.updater # Get the dispatcher to register handlers dp = updater.dispatcher # Add conversation handler with the states CHOOSING, TYPING_CHOICE and TYPING_REPLY conv_handler = ConversationHandler( entry_points=[CommandHandler('start', main_menu)], states={ GETMOBILE: [ MessageHandler(Filters.text, done, pass_user_data=True), MessageHandler(Filters.contact, set_mobile, pass_user_data=True), ], MENU_CHOICE: [ RegexHandler( '^(' + check_in_text + '|' + check_out_text + ')$', # open_duty_slip, location_update_menu, pass_user_data=True), RegexHandler('^(' + open_duty_slip_text + ')$', get_duty_slips, pass_user_data=True), ], TYPING_CHOICE: [ MessageHandler(Filters.text, received_location_information, pass_user_data=True), MessageHandler(Filters.location, received_location_information, pass_user_data=True), MessageHandler(Filters.contact, received_location_information, pass_user_data=True), ], DUTYSLIP_FORM: [ MessageHandler(Filters.text, received_dutyslip_information, pass_user_data=True), RegexHandler('^(' + cash_text + ')$', received_dutyslip_information, pass_user_data=True), RegexHandler('^(' + credit_text + ')$', received_dutyslip_information, pass_user_data=True), MessageHandler(Filters.location, received_dutyslip_information, pass_user_data=True), ], DUTYSLIP_CHOICE: [ RegexHandler('^(ID: [a-z,0-9,\s]+)', open_duty_slip, pass_user_data=True), RegexHandler('^(' + cancel_text + ')$', cancel, pass_user_data=True), ], DUTYSLIP_MENU: [ RegexHandler('^(' + start_duty_text + ')$', start_duty, pass_user_data=True), RegexHandler('^(' + cancel_text + ')$', cancel, pass_user_data=True), ], DUTYSLIP_OPEN: [ RegexHandler('^(' + stop_duty_text + ')$', stop_duty, pass_user_data=True), RegexHandler('^(' + submit_text + ')$', submit_duty, pass_user_data=True), RegexHandler('^(' + cancel_text + ')$', cancel, pass_user_data=True), ], LOCATION_CHOICE: [ RegexHandler('^(' + add_handoff_text + '|' + add_vehicle_text + ')$', handoff_vehicle, pass_user_data=True), RegexHandler('^(' + send_location_text + ')$', get_location, pass_user_data=True), RegexHandler('^(' + submit_text + ')$', submit_location_update, pass_user_data=True), RegexHandler('^(' + cancel_text + ')$', cancel, pass_user_data=True), ], }, fallbacks=[RegexHandler('^[dD]one$', done, pass_user_data=True)]) dp.add_handler(conv_handler) # log all errors dp.add_error_handler(error)
def error(update, context): """Log Errors caused by Updates.""" logger.warning('Update "%s" caused error "%s"', update, context.error) conv_handler = ConversationHandler( entry_points=[CommandHandler('start', start)], states={ LOCATION: [ CommandHandler('start', start), MessageHandler(Filters.location, location) ], PHOTO: [CommandHandler('start', start), MessageHandler(Filters.photo, photo)], LENGTH: [CommandHandler('start', start), MessageHandler(Filters.text, length)], TIME: [CommandHandler('start', start), MessageHandler(Filters.text, time)], CONFIRMATION: [ MessageHandler(Filters.regex('^Confirm$'), confirmation), MessageHandler(Filters.regex('^Restart$'), start) ] }, fallbacks=[CommandHandler('cancel', cancel)]) dispatcher.add_handler(conv_handler) # Add error handlers updater.start_polling() updater.idle()
def main(): updater = Updater(config.token) # Get the dispatcher to register handlers dp = updater.dispatcher # Базовые команды dp.add_handler(CommandHandler("start", start.start)) dp.add_handler(CommandHandler("help", help.help)) # Просмотр dp.add_handler(CommandHandler("list", list.all)) #dp.add_handler(CommandHandler("view", view.all_items)) # so many messages dp.add_handler(RegexHandler('^\/view(\d+).*', view.item, pass_groups=True)) # Подписка dp.add_handler(CommandHandler("subscribe", subscription.activate)) dp.add_handler(CommandHandler("unsubscribe", subscription.deactivate)) # Добавление dp.add_handler( ConversationHandler( entry_points=[CommandHandler('add', add.add, pass_user_data=True)], states={ add.NAME: [MessageHandler(Filters.text, add.name)], add.DESCRIPTION: [MessageHandler(Filters.text, add.description)], add.PHOTO: [ MessageHandler(Filters.photo, add.photo), CommandHandler('skip', add.skip_photo) ], add.PUBLISH: [ CommandHandler('publish', add.publish, pass_user_data=True), ], }, fallbacks=[ CommandHandler(u'cancel', add.cancel, pass_user_data=True) ])) # Редактирование dp.add_handler(CommandHandler("edit", edit.list_items)) edit_handler = ConversationHandler( entry_points=[ RegexHandler('^/edit(\d+).*', edit.edit, pass_groups=True, pass_user_data=True) ], states={ edit.NAME: [ MessageHandler(Filters.text, edit.name, pass_user_data=True), CommandHandler('skip', edit.skip_name, pass_user_data=True) ], edit.DESCRIPTION: [ MessageHandler(Filters.text, edit.description, pass_user_data=True), CommandHandler('skip', edit.skip_description, pass_user_data=True) ], edit.PHOTO: [ MessageHandler(Filters.photo, edit.photo, pass_user_data=True), CommandHandler('skip', edit.skip_photo, pass_user_data=True) ], edit.PUBLISH: [ CommandHandler('save', edit.publish, pass_user_data=True), ], }, fallbacks=[CommandHandler('cancel', edit.cancel, pass_user_data=True)]) dp.add_handler(edit_handler) # Удаление dp.add_handler(CommandHandler("delete", delete.list_items)) dp.add_handler( RegexHandler(u'^\/delete(\d+).*', delete.delete_item, pass_groups=True)) # Другое dp.add_handler( RegexHandler(u'.*(\s|\W|^)(С|с)т(и|і)л{1,2}(и|і)(\s|\W|$).*', jokes.stilli)) dp.add_handler(CommandHandler("support", support.support)) # log all errors dp.add_error_handler(error) # Start the Bot updater.start_polling() # Block until the you presses Ctrl-C or the process receives SIGINT, # SIGTERM or SIGABRT. This should be used most of the time, since # start_polling() is non-blocking and will stop the bot gracefully. updater.idle()
def main(): updater = Updater(token='1361442277:AAGvchKc35aElkOd9NPFIBJGCO3s8XzpjQI', use_context=True) dispatcher = updater.dispatcher start_handler = CommandHandler('start', start) help_handler = CommandHandler('help', help) get_all_handler = CommandHandler('getAll', get_all) add_conv_handler = ConversationHandler( entry_points=[CommandHandler('addTask', add_task)], states={ NAME: [MessageHandler(Filters.text & (~Filters.command), name)], DESCRIPTION: [MessageHandler(Filters.text & (~Filters.command), description)], DATE: [MessageHandler(Filters.text & (~Filters.command), date)], TIME: [MessageHandler(Filters.text & (~Filters.command), time)] }, fallbacks=[CommandHandler('cancel', cancel)]) update_conv_handler = ConversationHandler( entry_points=[CommandHandler('editTask', update_task)], states={ UPDATE_GET: [MessageHandler(Filters.text & (~Filters.command), update_get)], UPDATE_DESCRIPTION: [ MessageHandler(Filters.text & (~Filters.command), update_description), CommandHandler('skip', skip_description) ], UPDATE_DATE: [ MessageHandler(Filters.text & (~Filters.command), update_date), CommandHandler('skip', skip_date) ], UPDATE_TIME: [ MessageHandler(Filters.text & (~Filters.command), update_time), CommandHandler('skip', skip_time) ] }, fallbacks=[CommandHandler('cancel', cancel_update)]) delete_conv_handler = ConversationHandler( entry_points=[CommandHandler('delTask', del_task)], states={ DELETE_GET: [MessageHandler(Filters.text & (~Filters.command), delete_get)] }, fallbacks=[CommandHandler('cancel', cancel_delete)]) done_conv_handler = ConversationHandler( entry_points=[CommandHandler('doneTask', done_task)], states={ DONE_GET: [MessageHandler(Filters.text & (~Filters.command), done_get)] }, fallbacks=[CommandHandler('cancel', cancel_done)]) unknown_command_handler = MessageHandler(Filters.command, unknown) dispatcher.add_handler(get_all_handler) dispatcher.add_handler(help_handler) dispatcher.add_handler(start_handler) dispatcher.add_handler(add_conv_handler) dispatcher.add_handler(update_conv_handler) dispatcher.add_handler(delete_conv_handler) dispatcher.add_handler(done_conv_handler) dispatcher.add_handler(unknown_command_handler) j = updater.job_queue checking_job = j.run_repeating(check_db, interval=600, first=0) updater.start_polling() updater.idle()
def save(update, context): context.bot.send_message(chat_id=update.effective_chat.id, text=saving, parse_mode='MarkdownV2') start_handler = CommandHandler('start', start) save_handler = CommandHandler('how', save) dispatcher.add_handler(start_handler) dispatcher.add_handler(save_handler) dispatcher.add_handler( ConversationHandler( entry_points=[CommandHandler('download', download.get_song)], states={ download.SONG: [MessageHandler(Filters.text, download.download)] }, fallbacks=[], )) dispatcher.add_handler( ConversationHandler( entry_points=[CommandHandler('playlist', playlist.get_playlist)], states={ playlist.PLAYLIST: [MessageHandler(Filters.text, playlist.playlist)] }, fallbacks=[], )) updater.start_polling()
def main(): global db global uHandler global valid global lang # Intialisation botToken = 'INSERT BOT TOKEN HERE' updater = Updater(botToken, use_context=True) botLang = open("lang.yml", 'r') lang = yaml.load(botLang, Loader=yaml.SafeLoader) uHandler = UserHandler(lang) dp = updater.dispatcher db = Database() valid = Validator() # CONVERSATION PART 1: User Conversation Handler uConvo = ConversationHandler( # First collection: Entry to conversation entry_points = [CommandHandler('setup', setup)], # Second collection: Handlers for conversation states = { UTOPIC: [MessageHandler(Filters.text, userTopic),], UGENDER: [MessageHandler(Filters.text, userGender),], UAGE: [MessageHandler(Filters.text, userAge),], UREPLIES: [MessageHandler(Filters.text, userReplies),], UREMOVE: [MessageHandler(Filters.text, userRemove),] }, # Third Collection: Exit the conversation fallbacks = [MessageHandler(Filters.regex('^Done$'), uDone)] ) # CONVERSATION PART 2: User Partner Conversation Handler pConvo = ConversationHandler( # First collection: Entry to conversation entry_points = [CommandHandler('criteria', partnerSetup)], # Second collection: Handlers for conversation states = { PTOPIC: [MessageHandler(Filters.text,partnerTopic),], PGENDER: [MessageHandler(Filters.text, partnerGender),], PMINAGE: [MessageHandler(Filters.text, partnerMinAge),], PMAXAGE: [MessageHandler(Filters.text, partnerMaxAge)] }, # Third Collection: Exit the conversation fallbacks = [MessageHandler(Filters.regex('^Done$'), pDone)] ) # CONVERSATION PART 3: Matching Conversation Handler mConvo = ConversationHandler( # First collection: Entry to conversation entry_points = [CommandHandler('match', match)], # Second collection: Handlers for conversation states = { MCHOICE: [MessageHandler(Filters.text, mChoice)] }, # Third Collection: Exit the conversation fallbacks = [MessageHandler(Filters.regex('^Done$'), mDone)] ) # CONVERSATION PART 4: Partner Message Conversation Convo = ConversationHandler( # First collection: Entry to conversation entry_points = [CommandHandler('message', message)], # Second collection: Handlers for conversation states = { REPLIES: [MessageHandler((Filters.all), reply),], }, # Third Collection: Exit the conversation fallbacks = [MessageHandler(Filters.regex('^Exit$'), exit)] ) # CONVERSATION PART 5: Elimination (Remove & Delete) Conversation dConvo = ConversationHandler( # First collection: Entry to conversation entry_points = [CommandHandler('remove', remove), CommandHandler('delete', delete)], # Second collection: Handlers for conversation states = { RCHOICE: [MessageHandler(Filters.text, removeChoice),], DCHOICE: [MessageHandler(Filters.text, deleteChoice),] }, # Third Collection: Exit the conversation fallbacks = [] ) # CONVERSATION PART 6: Exchange username eConvo = ConversationHandler( # First collection: Entry to conversation entry_points = [CommandHandler('exchange', exchange)], # Second collection: Handlers for conversation states = { ECHOICE: [MessageHandler((Filters.text), exchangeChoice)] }, # Third Collection: Exit the conversation fallbacks = [MessageHandler(Filters.regex('^Cancel$'), exchangeCancel)] ) # Adding all the command handlers dp.add_handler(CommandHandler('start', start)) dp.add_handler(CommandHandler('profile', userProfile)) dp.add_handler(uConvo) dp.add_handler(pConvo) dp.add_handler(mConvo) dp.add_handler(Convo) dp.add_handler(CommandHandler('partner', partner)) dp.add_handler(dConvo) dp.add_handler(eConvo) dp.add_handler(CommandHandler('help', help)) dp.add_handler(MessageHandler(Filters.regex('^LCG$'), easterCG)) dp.add_handler(MessageHandler(Filters.regex('^CKG$'), easterKG)) # Start the bot updater.start_polling() updater.idle()
from telegram.ext import CallbackQueryHandler as CQH from telegram.ext import CommandHandler, ConversationHandler from foodshare.utils import hard_break, hard_restart from . import ConversationStage as CS from .first_message import ( action_chosing_handler, ask_to_chose_action, meal_action_end, ) meals_handler = ConversationHandler( entry_points=[ CQH(ask_to_chose_action, pattern='meals_asked0523'), ], states={ CS.CHOSING_MEAL: [CQH(action_chosing_handler)], CS.CANCELING: [ CQH(ask_to_chose_action, pattern='back'), CQH(meal_action_end, pattern='confirm'), ], }, fallbacks=[ CommandHandler('stop', hard_break), CommandHandler('start', hard_restart), ], )
def main(): # Create the EventHandler and pass it your bot's token. updater = Updater(botToken) # Get the dispatcher to register handlers dp = updater.dispatcher # Add conversation handler with the states GENDER, PHOTO, LOCATION and BIO conv_handler = ConversationHandler( entry_points=[ CommandHandler('start', start), CommandHandler('transport', bienvenueTransport) ], states={ START: [ RegexHandler('^(Aller manger)$', resto_type_liste), RegexHandler('^(Sortir)$', sortie_type_liste), CommandHandler('retour', start), CommandHandler('transport', bienvenueTransport) ], RESTAURANTS_CHOIX: [ RegexHandler('^(Italien|Asiatique|Grecque|Portugaise|Suisse)$', restaurant_liste), CommandHandler('retour', start), CommandHandler('transport', bienvenueTransport) ], RESTAURANT_RESULTATS: [ RegexHandler( '^(Kebab House|Pizza Express|Kookeat|Tasty chicken spot|Punjabi)$', restaurant_detail), CommandHandler('transport', bienvenueTransport), CommandHandler('retour', resto_type_liste) ], RESTAURANT_DETAIL: [ CommandHandler('retour', restaurant_liste), CommandHandler('transport', bienvenueTransport) ], SORTIE_CHOIX: [ RegexHandler('^(Musée)$', musee_recommendation), RegexHandler('^(Bar)$', bar_recommendation), RegexHandler('^(Club)$', club_recommendation), RegexHandler('^(Restaurant)$', resto_type_liste), CommandHandler('transport', bienvenueTransport), CommandHandler('retour', start) ], SORTIE_RECOMMENDATIONS: [ CommandHandler('retour', sortie_type_liste), CommandHandler('transport', bienvenueTransport) ], TRANSPORT: [ CommandHandler('start', start), MessageHandler(Filters.text, lieu_a_chercher), MessageHandler(Filters.location, coordonnees_a_traiter), CommandHandler('cancel', cancel), MessageHandler(Filters.command, details_arret) ], }, fallbacks=[CommandHandler('cancel', cancel)]) dp.add_handler(conv_handler) # log all errors dp.add_error_handler(error) # Start the Bot updater.start_polling() # Run the bot until you press Ctrl-C or the process receives SIGINT, # SIGTERM or SIGABRT. This should be used most of the time, since # start_polling() is non-blocking and will stop the bot gracefully. updater.idle()
start_handler = ConversationHandler( entry_points=[CommandHandler('start', start)], states={ ROUTE: [ CommandHandler('start', start), CallbackQueryHandler(category_filter, pattern='^' + str('购买商品') + '$'), CallbackQueryHandler(trade_filter, pattern='^' + str('查询订单') + '$'), CallbackQueryHandler(trade_filter, pattern='^' + str('更换支付方式') + '$'), CallbackQueryHandler(trade_filter, pattern='^' + str('取消订单') + '$'), ], CATEGORY: [ CommandHandler('start', start), CallbackQueryHandler(goods_filter, pattern='.*?'), ], PRICE: [ CommandHandler('start', start), CallbackQueryHandler(user_price_filter, pattern='.*?'), ], CHOOSE_PAYMENT_METHOD: [ CommandHandler('start', start), CallbackQueryHandler(choose_payment_method, pattern='.*?'), ], SUBMIT: [ CommandHandler('start', start), CallbackQueryHandler(submit_trade, pattern='^' + str('提交订单') + '$'), CallbackQueryHandler(cancel_trade, pattern='^' + str('下次一定') + '$') ], TRADE: [ CommandHandler('start', start), CallbackQueryHandler(payment_change_or_cancel, pattern='.*?'), MessageHandler(Filters.text, trade_query), ], ConversationHandler.TIMEOUT: [MessageHandler(Filters.all, timeout)], }, fallbacks=[CommandHandler('cancel', cancel)])
validate_handler = MessageHandler( callback=validate_callback, pass_chat_data=True, filters=(Filters.text & ~Filters.regex(back_to_menu_button) & ~Filters.regex(help_button))) def url_functions_callback(update: Update, context: CallbackContext): cid = update.effective_message.chat.id q = update.message.text section_name = context.chat_data['current_section'] mid = context.bot.send_message( chat_id=cid, text=ask_text, reply_markup=kb_dict[section_name]).message_id context.chat_data.update({'message_ids': [mid]}) url_conversation_handler = ConversationHandler( entry_points=[url_handler], states={ URL_FUNCTIONS: [ validate_handler, summarize_handler, extract_article_handler, extract_entity_handler, extract_sentiment_handler, help_handler ] }, fallbacks=[back_to_menu_handler], name='url', persistent=False)
notifications.update_one( { 'chat_id': cursor_notification['chat_id'], 'status': 'in progress' }, {'$set': { 'status': 'forgot' }}) return -1 class notify_filter(BaseFilter): def filter(self, message): return '/notify' in message.text filter_notify = notify_filter() notification_handler = CommandHandler('notify', notify_users) notification_handler_2 = MessageHandler(filter_notify, notify_users) submit_notification_handler = MessageHandler(Filters.text, submit_notification) confirm_notification_handler = MessageHandler(Filters.text, confirm_notification) notificationConversation_states = { 'submit notification': [submit_notification_handler], 'confirm notification': [confirm_notification_handler] } notificationConversation_handler = ConversationHandler( [notification_handler, notification_handler_2], notificationConversation_states, fallbacks=support_handlers, allow_reentry=True)
# Handler for starting the bot updater.dispatcher.add_handler(CommandHandler("start", start)) # Handler for Credentials setup updater.dispatcher.add_handler( ConversationHandler( entry_points=[CommandHandler('setup', start_ip_convo)], states={ CHOOSING: [ MessageHandler( Filters.regex( '^(Username|Password|Ip Address|Port|Cancel|Done)$' ), choice_for_read_or_update_details), ], TYPING_CHOICE: [ MessageHandler(Filters.text, choice_for_read_or_update_details) ], TYPING_REPLY: [ MessageHandler(Filters.text, storing_or_modifying_details), ], }, fallbacks=[ MessageHandler(Filters.regex('^Exit$'), cancel_ip_convo) ])) # updater.dispatcher.add_handler(CommandHandler("s", sample_check)) # Main Monitoring updater.dispatcher.add_handler(
def invoice(bot, update): bot.send_invoice(chat_id=update.message.chat_id, title="title", description="description", payload="payload", provider_token="6037603760376037", start_parameter="", currency="IRR", prices=[LabeledPrice('label1', int(update.message.text))]) return ConversationHandler.END updater = Updater(token='Token', base_url="https://tapi.bale.ai/") conversation_handler = ConversationHandler( entry_points=[CommandHandler('start', start)], states={ INVOICE: [RegexHandler(pattern='^\d+$', callback=invoice)], }, fallbacks=[]) updater.dispatcher.add_handler(conversation_handler) updater.bot.delete_webhook() updater.start_polling(poll_interval=2) # you can replace above line with commented below lines to use webhook instead of polling # updater.start_webhook(listen=os.getenv('WEB_HOOK_IP', ""), port=int(os.getenv('WEB_HOOK_PORT', "")), # url_path=os.getenv('WEB_HOOK_PATH', "")) # updater.bot.set_webhook(url="{}{}".format(os.getenv('WEB_HOOK_DOMAIN', ""), os.getenv('WEB_HOOK_PATH', ""))) updater.idle()
start_handler = CommandHandler('start', start) saveBattleStats_handler = MessageHandler(Filters.all, saveBattleStats) chooseReportType_handler = MessageHandler(Filters.text, chooseReportType) getAttackReport_handler = MessageHandler(Filters.text, getAttackReport) getDefenceReport_handler = MessageHandler(Filters.text, getDefenceReport) calcAttack_handler = MessageHandler(Filters.text, calcAttack) calcDefence_handler = MessageHandler(Filters.text, calcDefence) cancel_handler = CommandHandler('cancel', cancel) stats_calc_conv_handler = ConversationHandler( entry_points = [start_handler], states={ BATTLE_STATS: [saveBattleStats_handler], CHOOSE_REPORT_TYPE: [chooseReportType_handler], ATTACK_REPORT: [getAttackReport_handler], DEFENCE_REPORT: [getDefenceReport_handler], CALC_ATTACK: [calcAttack_handler], CALC_DEFENCE: [calcDefence_handler] }, fallbacks=[cancel_handler] ) dispatcher.add_handler(stats_calc_conv_handler) ''' calcAttackTest_handler = MessageHandler(Filters.text, calcAttackTest) dispatcher.add_handler(calcAttackTest_handler) ''' report_handler = CommandHandler('report', report) dispatcher.add_handler(report_handler)
def telegramBot_main(token): """Creates and launches the Telegram Bot. Parameters ---------- token : str Telegram secret token. """ # Create the Updater and pass it your bot's token. # Make sure to set use_context=True to use the new context based callbacks # Post version 12 this will no longer be necessary updater = Updater(token, use_context=True) # Get the dispatcher to register handlers dp = updater.dispatcher # Add conversation handler conv_handler = ConversationHandler( entry_points=[CommandHandler('start', start)], states={ SELECTING_ACTION: [ CommandHandler('help', display_info), CommandHandler('exit', done), CommandHandler('recetas', display_recipes), # MessageHandler(Filters.regex('^CU01$'), adding_images), # MessageHandler(Filters.regex('^CU02$'), adding_recipe), # MessageHandler(Filters.regex('^CU03A$'), adding_prefs), # MessageHandler(Filters.regex('^CU03B$'), adding_prefs), MessageHandler(Filters.text, detect_intention), ], ADD_RECIPE: [ CommandHandler('recetas', display_recipes), MessageHandler(Filters.regex('^salir$'), start), MessageHandler(Filters.text, save_recipe), ], ADD_PHOTO: [ MessageHandler(Filters.photo, save_image), MessageHandler(Filters.text, get_cheff_response), ], ASK_CHEFF: [ MessageHandler( Filters.regex(r'^(.*?(\b[Ss][IiÍí]\b)[^$]*)$'), show_recipe), MessageHandler( Filters.regex(r'^(.*?(\b[Nn][Oo]\b)[^$]*)$'), start), MessageHandler(Filters.regex('^salir$'), start), MessageHandler(Filters.text, show_recipe), ], SHOW_RECIPE: [ CommandHandler('recetas', display_recipes), MessageHandler(Filters.regex('^salir$'), start), # MessageHandler(Filters.regex(r'^[Ss][IiÍí]$'), start), # MessageHandler(Filters.regex(r'^(.*?(\b[Nn][Oo]\b)[^$]*)$'), done), MessageHandler(Filters.text, show_recipe), ], ADD_PREFS: [ MessageHandler( Filters.regex(r'^(.*?(\b[Ss][IiÍí]\b)[^$]*)$'), adding_prefs), MessageHandler( Filters.regex(r'^(.*?(\b[Nn][Oo]\b)[^$]*)$'), start), MessageHandler(Filters.text, save_prefs), ], CONTINUE: [ MessageHandler( Filters.regex(r'^(.*?(\b[Ss][IiÍí]\b)[^$]*)$'), start), MessageHandler( Filters.regex(r'^(.*?(\b[Nn][Oo]\b)[^$]*)$'), done), ] }, fallbacks=[ CommandHandler('exit', done), MessageHandler(Filters.regex('^Finalizar$'), done), ]) dp.add_handler(conv_handler) # log all errors dp.add_error_handler(error) # Start the Bot updater.start_polling() # Run the bot until you press Ctrl-C or the process receives SIGINT, # SIGTERM or SIGABRT. This should be used most of the time, since # start_polling() is non-blocking and will stop the bot gracefully. updater.idle()
cv_handler = ConversationHandler( entry_points=[ CallbackQueryHandler(callback=request_deal_number, pattern=GlobalTxt.MENU_DEAL_EQUIP_BUTTON_CB) ], states={ State.EQUIP_SET_DEAL_NUMBER: [ MessageHandler(Filters.regex(GlobalTxt.BITRIX_DEAL_NUMBER_PATTERN), set_deal_number) ], State.EQUIP_REPEATEDLY_APPROVE: [ CallbackQueryHandler(callback=equip_repeatedly_approve, pattern=Txt.EQUIP_REPEATEDLY_BUTTON_CB) ], State.EQUIP_SET_PHOTOS: [ MessageHandler(Filters.photo, append_photo), CallbackQueryHandler(callback=finish_photo_loading, pattern=Txt.FINISH_PHOTO_LOADING_CB) ], State.EQUIP_SET_POSTCARD_FACIAL: [MessageHandler(Filters.photo, append_postcard)], State.EQUIP_SET_POSTCARD_REVERSE: [MessageHandler(Filters.photo, append_postcard)], State.EQUIP_SET_CHECKLIST: [MessageHandler(Filters.photo, load_checklist_photo)] }, fallbacks=[ CommandHandler([Cmd.START, Cmd.CANCEL], TgCommons.restart), CommandHandler([Cmd.LOGOUT], TgCommons.logout), CallbackQueryHandler(callback=TgCommons.restart, pattern=GlobalTxt.CANCEL_BUTTON_CB_DATA), MessageHandler(Filters.all, TgCommons.global_fallback), CallbackQueryHandler(callback=TgCommons.global_fallback, pattern=GlobalTxt.ANY_STRING_PATTERN) ], map_to_parent={ State.IN_OPERATOR_MENU: State.IN_OPERATOR_MENU, State.LOGIN_REQUESTED: State.LOGIN_REQUESTED })
def main(production=False): updater = Updater(os.environ.get('api_key'), use_context=True) dp = updater.dispatcher description_conv = ConversationHandler( entry_points=[ CallbackQueryHandler(select_feature, pattern='^' + str(MALE) + '$|^' + str(FEMALE) + '$') ], states={ SELECTING_FEATURE: [ CallbackQueryHandler(ask_for_input, pattern='^(?!' + str(END) + ').*$') ], TYPING: [MessageHandler(Filters.text & ~Filters.command, save_input)], }, fallbacks=[ CallbackQueryHandler(end_describing, pattern='^' + str(END) + '$'), CommandHandler('stop', stop_nested) ], map_to_parent={ END: SELECTING_LEVEL, STOPPING: STOPPING, }) add_member_conv = ConversationHandler( entry_points=[ CallbackQueryHandler(select_level, pattern='^' + str(ADDING_MEMBER) + '$') ], states={ SELECTING_LEVEL: [ CallbackQueryHandler(select_gender, pattern='^{}$|^{}$'.format( str(PARENTS), str(CHILDREN))) ], SELECTING_GENDER: [description_conv] }, fallbacks=[ CallbackQueryHandler(show_data, pattern='^' + str(SHOWING) + '$'), CallbackQueryHandler(end_second_level, pattern='^' + str(END) + '$'), CommandHandler('stop', stop_nested) ], map_to_parent={ SHOWING: SHOWING, END: SELECTING_ACTION, STOPPING: END, }) selection_handlers = [ add_member_conv, CallbackQueryHandler(show_data, pattern='^' + str(SHOWING) + '$'), CallbackQueryHandler(adding_self, pattern='^' + str(ADDING_SELF) + '$'), CallbackQueryHandler(end, pattern='^' + str(END) + '$'), ] conv_handler = ConversationHandler( entry_points=[CommandHandler('start', start)], states={ SHOWING: [CallbackQueryHandler(start, pattern='^' + str(END) + '$')], SELECTING_ACTION: selection_handlers, SELECTING_LEVEL: selection_handlers, DESCRIBING_SELF: [description_conv], STOPPING: [CommandHandler('start', start)], }, fallbacks=[CommandHandler('stop', stop)], ) dp.add_handler(conv_handler) if production: updater.start_webhook(listen='0.0.0.0', port=int(os.environ.get('PORT')), url_path=os.environ.get('api_key')) updater.bot.setWebhook("https://recmoviebot.herokuapp.com/{}".format( os.environ.get('api_key'))) updater.start_polling() updater.idle()
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
return cancel(bot, update) message = "Приветствую тебя, мой капитан! =)\n" update.message.reply_text(message, reply_markup=keyboard_cmds()) ### Handlers ### # Gates command handler gate_handler = ConversationHandler( entry_points=[CommandHandler('gates', gates_cmd)], states={ WorkflowEnum.GATES_SUB_CMD: [ RegexHandler("^(GATE 1|GATE 2|GARAGE|GATE 1 AND GARAGE)$", gates_sub_cmd), RegexHandler("^(CANCEL)$", cancel) ], WorkflowEnum.GATE1_OPEN_CONFIRM: [RegexHandler("^(YES|NO)$", gate1_open_confirm)], WorkflowEnum.GATE2_OPEN_CONFIRM: [RegexHandler("^(YES|NO)$", gate2_open_confirm)], WorkflowEnum.GARAGE_OPEN_CONFIRM: [RegexHandler("^(YES|NO)$", garage_open_confirm)], WorkflowEnum.GATE1_GARAGE_OPEN_CONFIRM: [RegexHandler("^(YES|NO)$", gate1_garage_open_confirm)] }, fallbacks=[CommandHandler('cancel', cancel)]) dispatcher.add_handler(gate_handler) # Conrtollers command handler ctrl_handler = ConversationHandler( entry_points=[CommandHandler('ctrls', ctrls_cmd)], states={ WorkflowEnum.CTRLS_SUB_CMD: [
quote=True) except error.UnknwonError as e: update.message.reply_html(Strings.REMOVE_STICKER_GENERIC_ERROR.format( pack_link, e.message), quote=True) else: # success update.message.reply_html( Strings.REMOVE_STICKER_SUCCESS.format(pack_link), quote=True) finally: # wait for other stickers return WAITING_STICKERS stickersbot.add_handler( ConversationHandler( name='adding_stickers', entry_points=[ CommandHandler(['remove', 'rem', 'r'], on_remove_command) ], states={ WAITING_STICKERS: [ MessageHandler( Filters.sticker | Filters.document.category('image/png'), on_sticker_receive) ] }, fallbacks=[ CommandHandler(['cancel', 'c', 'done', 'd'], cancel_command) ]))
def main(): mybot = Updater(settings.API_KEY) mybot.bot._msg_queue = mq.MessageQueue( ) # обьявляем переменную _msg_queue как mq.MessageQueue() mybot.bot._is_messages_queued_default = True # сообщения по умолчанию должны ставится в очередь logging.info('Бот запускается') dp = mybot.dispatcher #mybot.job_queue.run_repeating(my_test, interval=5) # очередь задач с интервалом 5 сек mybot.job_queue.run_repeating(send_updates, interval=5) # CommandHandler нужно ставить выше MessageHandler - потому что для MessageHandler команда тоже текст # pass_user_data=True - сохранение пользовательских данных и во все функции добавим user_data dp.add_handler(CommandHandler('start', greet_user, pass_user_data=True)) anketa = ConversationHandler(entry_points=[ RegexHandler('^(Заполнить анкету)$', anketa_start, pass_user_data=True) ], states={ 'name': [ MessageHandler(Filters.text, anketa_get_name, pass_user_data=True) ], 'rating': [ RegexHandler('^(1|2|3|4|5)$', anketa_rating, pass_user_data=True) ], 'comment': [ MessageHandler(Filters.text, anketa_comment, pass_user_data=True), CommandHandler('skip', anketa_skip_comment, pass_user_data=True) ] }, fallbacks=[ MessageHandler(Filters.text, dontknow, pass_user_data=True) ]) dp.add_handler(anketa) dp.add_handler(CommandHandler('cat', send_cat_picture, pass_user_data=True)) # команда /cat dp.add_handler( RegexHandler('^(Прислать котика)$', send_cat_picture, pass_user_data=True) ) # если приходит текст с "Прислать котика", то вызываем функцию send_cat_picture dp.add_handler( RegexHandler('^(Сменить аватарку)$', change_avatar, pass_user_data=True)) dp.add_handler(CallbackQueryHandler(inline_button_pressed) ) # функция которая вызывается при срабатывание калбека dp.add_handler( MessageHandler(Filters.contact, get_contact, pass_user_data=True)) dp.add_handler( MessageHandler(Filters.location, get_location, pass_user_data=True)) dp.add_handler(CommandHandler('subscribe', subscribe)) # подписка пользователя dp.add_handler(CommandHandler('unsubscribe', unsubscribe)) # отписка пользователя dp.add_handler( CommandHandler('alarm', set_alarm, pass_args=True, pass_job_queue=True) ) # отправка сообщения пользователю через определенное время, pass_args - текст который пользователь введет после команды бедет разбит по символу пробела и на выходе прийдет список, pass_job_queue - передаем очередь заданий внутрь этой функции dp.add_handler( MessageHandler(Filters.photo, check_user_photo, pass_user_data=True) ) # включаем возможность принимать от пользователей фото dp.add_handler( MessageHandler(Filters.text, talk_to_me, pass_user_data=True)) # обработка текстовых сообщений mybot.start_polling() mybot.idle()
return ConversationHandler.END yesfilter = Filters.regex('^Yes$') nofilter = Filters.regex('^No$') conv_handler = ConversationHandler( entry_points=[CommandHandler("start", welcome)], states={ Decisions.FEEL_OK: [ MessageHandler(yesfilter, wanna_help), MessageHandler(nofilter, cough) ], Decisions.WANNA_HELP: [MessageHandler(yesfilter, desc), MessageHandler(nofilter, bye)], Decisions.COUGH_FEVER: [MessageHandler(yesfilter, desc), MessageHandler(nofilter, stressed)], Decisions.STRESSED_ANXIOUS: [MessageHandler(yesfilter, desc), MessageHandler(nofilter, bye)], Decisions.CASE_DESC: [MessageHandler(Filters.text, forward)], }, fallbacks=[CommandHandler("cancel", cancel)], ) def report_handler(update, context): """Handles the reports of workers""" query = update.callback_query data = update.callback_query.data
def test_channelMessageWithoutChat(self): handler = ConversationHandler(entry_points=[CommandHandler('start', self.start_end)], states={}, fallbacks=[]) message = Message(0, None, None, Chat(0, Chat.CHANNEL, "Misses Test")) update = Update(0, message=message) handler.check_update(update)
def test_per_chat_message_without_chat(self, bot, user1): handler = ConversationHandler( entry_points=[CommandHandler('start', self.start_end)], states={}, fallbacks=[]) cbq = CallbackQuery(0, user1, None, None, bot=bot) update = Update(0, callback_query=cbq) assert not handler.check_update(update)