def test_equality(self): a = ReplyKeyboardMarkup.from_column(["button1", "button2", "button3"]) b = ReplyKeyboardMarkup.from_column([ KeyboardButton(text) for text in ["button1", "button2", "button3"] ]) c = ReplyKeyboardMarkup.from_column(["button1", "button2"]) d = ReplyKeyboardMarkup.from_column( ["button1", "button2", "button3.1"]) e = ReplyKeyboardMarkup([["button1", "button1"], ["button2"], ["button3.1"]]) f = InlineKeyboardMarkup.from_column(["button1", "button2", "button3"]) assert a == b assert hash(a) == hash(b) assert a != c assert hash(a) != hash(c) assert a != d assert hash(a) != hash(d) assert a != e assert hash(a) != hash(e) assert a != f assert hash(a) != hash(f)
def test_from_column(self): reply_keyboard_markup = ReplyKeyboardMarkup.from_column([ KeyboardButton(text='button1'), KeyboardButton(text='button2')]).keyboard assert len(reply_keyboard_markup) == 2 assert len(reply_keyboard_markup[0]) == 1 assert len(reply_keyboard_markup[1]) == 1 reply_keyboard_markup = ReplyKeyboardMarkup.from_column(['button1', 'button2']).keyboard assert len(reply_keyboard_markup) == 2 assert len(reply_keyboard_markup[0]) == 1 assert len(reply_keyboard_markup[1]) == 1
def test_from_column(self): reply_keyboard_markup = ReplyKeyboardMarkup.from_column( [KeyboardButton(text="button1"), KeyboardButton(text="button2")]).keyboard assert len(reply_keyboard_markup) == 2 assert len(reply_keyboard_markup[0]) == 1 assert len(reply_keyboard_markup[1]) == 1 reply_keyboard_markup = ReplyKeyboardMarkup.from_column( ["button1", "button2"]).keyboard assert len(reply_keyboard_markup) == 2 assert len(reply_keyboard_markup[0]) == 1 assert len(reply_keyboard_markup[1]) == 1
def taxi_check(update: Update, context: CallbackContext): lang = context.user_data['lang'] text_btn = update.message.text if text_btn == btn_taxi_check[lang][0]: # ha pk = context.user_data['pk'] address = context.user_data['address'] try: address, _ = Address.objects.get_or_create( profile_id=pk, name=address, longitude=context.user_data['long'], latitude=context.user_data['lat'], ) context.user_data['address_id'] = address.pk text = BUYURTMA_TEXT[lang]['payment'] markup = ReplyKeyboardMarkup.from_column(btn_taxi_payment[lang], resize_keyboard=True) update.message.reply_html(text, reply_markup=markup) return PAYMENT except Exception as e: print(e) return ConversationHandler.END else: text = BUYURTMA_TEXT[lang]['geolocation'] pk = context.user_data['pk'] markup = ReplyKeyboardMarkup(btn_taxi_geo(int(pk), lang), resize_keyboard=True) context.bot.send_message(update.effective_user.id, text, reply_markup=markup, parse_mode=ParseMode.HTML) return GEOLOCATION
def chart(update, context): context_clear(context) logger.info(f"BOT: User requesting chart information") update.message.reply_text(f"Finding a chart that you previously saved? Need to add a new chart?", reply_markup=ReplyKeyboardMarkup.from_column(chart_reply_keyboard, one_time_keyboard=True)) return CHART_COMMANDS
def test_equality(self): a = InlineKeyboardMarkup.from_column( [ InlineKeyboardButton(label, callback_data='data') for label in ['button1', 'button2', 'button3'] ] ) b = InlineKeyboardMarkup.from_column( [ InlineKeyboardButton(label, callback_data='data') for label in ['button1', 'button2', 'button3'] ] ) c = InlineKeyboardMarkup.from_column( [InlineKeyboardButton(label, callback_data='data') for label in ['button1', 'button2']] ) d = InlineKeyboardMarkup.from_column( [ InlineKeyboardButton(label, callback_data=label) for label in ['button1', 'button2', 'button3'] ] ) e = InlineKeyboardMarkup.from_column( [InlineKeyboardButton(label, url=label) for label in ['button1', 'button2', 'button3']] ) f = InlineKeyboardMarkup( [ [ InlineKeyboardButton(label, callback_data='data') for label in ['button1', 'button2'] ], [ InlineKeyboardButton(label, callback_data='data') for label in ['button1', 'button2'] ], [ InlineKeyboardButton(label, callback_data='data') for label in ['button1', 'button2'] ], ] ) g = ReplyKeyboardMarkup.from_column(['button1', 'button2', 'button3']) assert a == b assert hash(a) == hash(b) assert a != c assert hash(a) != hash(c) assert a != d assert hash(a) != hash(d) assert a != e assert hash(a) != hash(e) assert a != f assert hash(a) != hash(f) assert a != g assert hash(a) != hash(g)
def square(update, context): global sqr sqr = update.message.text update.message.reply_text( 'Выберите оплату: 1 - только за сутки, 2 - только за месяц, 3 - за месяц, но с учётом посуточных предложений', reply_markup=ReplyKeyboardMarkup.from_column(ALLOWED_PERIODS)) return "next2"
def chats(self, chat_list): self.message.reply_text( 'Seleziona una chat. {}'.format(ANNULLA), reply_markup=ReplyKeyboardMarkup.from_column( [str(chat[0]) for chat in chat_list], resize_keyboard=True, one_time_keyboard=True ), quote=False )
def admin_send_message(update: Update, _: CallbackContext): telegram_id = update.effective_user.id if str(telegram_id) in admin_ids: text = "Yuborgan xabariz hamma foydalanuvchiga yetkaziladi" markup = ReplyKeyboardMarkup.from_column(btn_admin_send_message, True) update.message.reply_html(text, reply_markup=markup) return XABAR else: return ConversationHandler.END
def get_zakazlar(update: Update, _: CallbackContext): telegram_id = update.effective_user.id if str(telegram_id) in admin_ids: text = "Zakaz holatini tanlang" markup = ReplyKeyboardMarkup.from_column(btn_zakaz_state, resize_keyboard=True) update.message.reply_html(text, reply_markup=markup) return ZAKAZ_STATE else: return ConversationHandler.END
def build_reply_keyboard(items: List[str]) -> ReplyKeyboardMarkup: """ Builds a menu to select an item from a list :param items: list of items to choose from :return: reply markup """ items.append(CANCEL_KEYBOARD_COMMAND) keyboard = list(map(lambda x: KeyboardButton(x), items)) # NOTE: the "selective=True" requires the menu to be sent as a reply # (or with an @username mention) return ReplyKeyboardMarkup.from_column(keyboard, one_time_keyboard=True, selective=True)
def display_charts(update, context): chart_choice = update.message.text chat_id = str(update.message.chat.id) chart_names = db_utils.get_chart_names(chat_id) update.message.reply_text(f"Which chart would you like to retrieve or edit?", reply_markup=ReplyKeyboardMarkup.from_column(chart_names, one_time_keyboard=True)) if "Find chart" in chart_choice: return FIND_CHART elif "Delete chart" in chart_choice: return DELETE_CHART
def location_select(chat_txt, locations, location_unit, update): reply_keyboard = [] for i in locations: if location_unit == '읍면동': reply_keyboard.append(i['시도'] + ' ' + i['시군구'] + ' ' + i['읍면동']) elif location_unit == '시군구': reply_keyboard.append(i['시도'] + ' ' + i['시군구']) reply_keyboard.append('이 중에는 없어요') update.message.reply_text(chat_txt + ', 여러 곳이있네. \n이중에 어디를 말하는거니?', reply_markup=ReplyKeyboardMarkup.from_column( reply_keyboard, one_time_keyboard=True)) return LOCATION_SELECT
def fikr_bildirish(update: Update, context: CallbackContext): telegram_id = update.effective_user.id if Profile.objects.filter(telegram_id=telegram_id).exists(): lang = Profile.objects.filter( telegram_id=telegram_id).values_list('language').first()[0] context.user_data['lang'] = lang text = FIKR_TEXT[lang]['entry'] update.message.reply_html(text, reply_markup=ReplyKeyboardMarkup.from_column( btn_back_fikr[lang], True)) return FIKR else: text = ANY_TEXT update.message.reply_html(text, reply_markup=ReplyKeyboardRemove()) return ConversationHandler.END
def taxi_geolocation_btn(update: Update, context: CallbackContext): pk = context.user_data['pk'] lang = context.user_data['lang'] address = update.message.text context.user_data['address'] = address try: address = Address.objects.filter(profile_id=pk, name=address).first() context.user_data['address_id'] = address.pk except Exception as e: print(e) text = BUYURTMA_TEXT[lang]['geolocation'] markup = ReplyKeyboardMarkup(btn_taxi_geo(int(pk), lang), resize_keyboard=True) context.bot.send_message(update.effective_user.id, text, reply_markup=markup, parse_mode=ParseMode.HTML) return GEOLOCATION text = BUYURTMA_TEXT[lang]['payment'] markup = ReplyKeyboardMarkup.from_column(btn_taxi_payment[lang], resize_keyboard=True) update.message.reply_html(text, reply_markup=markup) return PAYMENT
def get_variants(update, context): user = context.chat_data['user'] chosen_variant = update.message.text variants_displayed = context.chat_data['variants_displayed'] chosen_variant_index = variants_displayed.index(chosen_variant) logger.info(f"{user.first_name} chose {chosen_variant}") # Store in context context.chat_data['variants'][chosen_variant_index]['item_url'] = context.chat_data['item_url'] context_store_item_variant(context.chat_data['variants'][chosen_variant_index], context) context.chat_data['chosen_variant'] = chosen_variant context.chat_data['chosen_variant_index'] = chosen_variant_index logger.info(f"CONTEXT: chosen variant: {chosen_variant}, index: {chosen_variant_index}") update.message.reply_text(f"I'll chart out the prices across time to help you with price tracking! \n\n" f"Is there a similar product you'll like to add to the chart? e.g. a similar product on {context.chat_data['channel']}?", reply_markup=ReplyKeyboardMarkup.from_column(add_product_existing_reply_keyboard, one_time_keyboard=True)) return ADD_PRODUCT_CHOICE
def display_threshold(update, context): user = context.chat_data['user'] chat_id = str(update.message.chat.id) text = update.message.text if db_utils.validate_chart_name(chat_id, text) is False: logger.info(f"BOT: {user.first_name}'s chart name is unused") context.chat_data['chart_name'] = text logger.info("Chart name: " + text) update.message.reply_text(f'Shall I send you an alert when the price drops?', reply_markup=ReplyKeyboardMarkup.from_column(threshold_reply_keyboard, one_time_keyboard=True)) logger.info(f"BOT: prompted {user.first_name} for notification threshold") return STORE_THRESHOLD else: logger.info(f"BOT: {user.first_name}'s chart name is used, prompting user for another chart name") update.message.reply_text(f"Oops! You've used this chart name before. Please give your chart another name!") return get_chart_name(update, context)
def sozlamalar_nomer_text(update: Update, context: CallbackContext): lang = context.user_data['lang'] telegram_id = update.effective_user.id nomer = update.message.text if nomer.startswith('+998') or nomer.startswith('998'): try: p = Profile.objects.filter(telegram_id=telegram_id).first() p.phone_number = nomer p.save(update_fields=('phone_number', )) except Exception as e: print(e) text = SOZLAMALAR_TEXT[lang]['nomer_changed'] update.message.reply_html(text, reply_markup=ReplyKeyboardMarkup( btn_menu[lang], True)) return ConversationHandler.END else: text = REG_TEXT[lang]['nomer'] update.message.reply_html(text, reply_markup=ReplyKeyboardMarkup.from_column( btn_nomer[lang], True)) return CHANGE_NOMER
def get_nomer_text(update: Update, context: CallbackContext): lang = context.user_data['lang'] telegram_id = update.effective_user.id nomer = update.message.text if nomer.startswith('+998') or nomer.startswith('998'): try: Profile.objects.create(telegram_id=telegram_id, phone_number=nomer, language=lang) except Exception as e: print(e) text = REG_TEXT[lang]['menu'] update.message.reply_html(text, reply_markup=ReplyKeyboardMarkup( btn_menu[lang], True)) return ConversationHandler.END else: text = REG_TEXT[lang]['nomer'] update.message.reply_html(text, reply_markup=ReplyKeyboardMarkup.from_column( btn_nomer[lang], True)) return NOMER
def get_url_and_display_variant(update, context): user = context.chat_data['user'] search_url = utils.extract_url(update, context) if search_url is not None: logger.info("Bot extracted URL: %s", search_url) channel = utils.extract_domain(search_url) if channel in SUPPORTED_CHANNELS: update.message.reply_text(f"Brb! I'm learning more about this product on {channel}.") item_dict, variants_dict, variants_display_dict = utils.get_item_information(channel, search_url) update.message.reply_markdown(f"Hurray! Ive found \n\n{item_dict['item_name']}\n\n" 'Which of these product variations would you like to track?', reply_markup=ReplyKeyboardMarkup.from_column(variants_display_dict, one_time_keyboard=True)) logger.info(f"BOT: prompted {user.first_name} for variant choice") # Store in context context_store_item(item_dict, context) context.chat_data['item_url'] = utils.shorten_url([search_url])[0] context.chat_data['channel'] = utils.extract_domain(search_url) context.chat_data['variants'] = variants_dict logger.info(context.chat_data['variants']) context.chat_data['variants_displayed'] = variants_display_dict # context.chat_data['item'] = item_dict logger.info(f"CONTEXT: Stored channel, variants, display, url for item {item_dict['item_name']}") return CHOOSE_THRESHOLD else: update.message.reply_text(f"Oops, I do not support {channel} yet. Let's try again.", reply_markup=ReplyKeyboardMarkup(start_reply_keyboard, one_time_keyboard=True)) return INITIAL_CHOICE else: update.message.reply_text("Oops, you did not key in a valid URL. Let's try again.", reply_markup=ReplyKeyboardMarkup(start_reply_keyboard, one_time_keyboard=True)) return INITIAL_CHOICE
def select_user(update: Update, context: CallbackContext) -> str: """ Asks the admin which user is to be banned. Args: update: The update. context: The context as provided by the :class:`telegram.ext.Dispatcher`. """ context.user_data[CONVERSATION_KEY] = CONVERSATION_VALUE context.bot.send_chat_action(chat_id=update.effective_user.id, action=ChatAction.TYPING) orchestra = context.bot_data[ORCHESTRA_KEY] buttons = [] for uid, member in orchestra.members.items(): if uid != context.bot_data[ADMIN_KEY]: user = context.bot.get_chat_member(uid, uid).user if user.username: button_text = f'{member.full_name} ({user.full_name}, @{user.username}), ID:{uid}' else: button_text = f'{member.full_name} ({user.full_name}), ID:{uid}' buttons.append(button_text) if not buttons: update.effective_message.reply_text( text='Es gibt keine Mitglieder, die gebannt werden könnten.') context.user_data[CONVERSATION_KEY] = False return ConversationHandler.END text = 'Wer hat sich denn daneben benommen?' reply_markup = ReplyKeyboardMarkup.from_column(buttons) update.effective_message.reply_text(text=text, reply_markup=reply_markup) return SELECTING_USER
def handle_create_start(update: Update, _: CallbackContext): user: TGUser = update.effective_user msg: TGMessage = update.effective_message MessageToPublish.objects.create(user_id=user.id, message=msg.to_dict()) buttons = [ *UserButtons.buttons_list(user.id), '👍 👎', '✅ ❌', ] buttons = list(OrderedDict.fromkeys(buttons)) # remove duplicated buttons buttons = buttons[:3] msg.reply_text( "Now specify buttons.", reply_markup=ReplyKeyboardMarkup.from_column( [ *buttons, 'none', ], resize_keyboard=True, one_time_keyboard=True, ) ) redis.set_state(user, State.create_buttons)
def taxi_payment(update: Update, context: CallbackContext): lang = context.user_data['lang'] payment = update.message.text telegram_id = update.effective_user.id if payment == btn_taxi_payment[lang][0]: # Naqd pul pk = context.user_data['pk'] address = context.user_data['address'] address_id = context.user_data['address_id'] try: order = Order.objects.filter(profile_id=pk, status='NEW').first() order.status = 'ACTIVE' order.address_id = address_id order.payment_method = payment order.save(update_fields=('status', 'address', 'payment_method')) text = "" cost = 0 baskets = Basket.objects.filter(order_id=order.pk).select_related('food') if lang == 'uz': for b in baskets: vcost = b.quantity * b.food.cost text += f"{quantity_number(b.quantity)} ✖ {b.food.name_uz} = {vcost}\n" cost += vcost if order.delivery_time is not None: text += ORDERS_TEXT[lang]['time'].format(f"{order.delivery_time.strftime('%d/%m/%Y, %H:%M')}") narx = f"\nMahsulotlar: {cost} so'm\nYetkazib berish: {DOSTAVKA_NARX} so'm\n" \ f"Jami: {cost + DOSTAVKA_NARX}" else: # ru qismi for b in baskets: vcost = b.quantity * b.food.cost text += f"{quantity_number(b.quantity)} ✖ {b.food.name_ru} = {vcost}\n" cost += vcost if order.delivery_time is not None: text += ORDERS_TEXT[lang]['time'].format(f"{order.delivery_time.strftime('%d/%m/%Y, %H:%M')}") narx = f"\nТовары: {cost} сум\nДоставка: {DOSTAVKA_NARX} сум\nИтого: {cost + DOSTAVKA_NARX}" status = STATUS[lang][order.status] txt = BUYURTMA_TEXT[lang]['active'].format(order.pk, status, address, text, payment, narx) update.message.reply_html(REG_TEXT[lang]['menu'], reply_markup=ReplyKeyboardMarkup(btn_menu[lang], True)) keyboard = btn_order_cancel(pk, lang, order.pk) update.message.reply_html(txt, reply_markup=InlineKeyboardMarkup(keyboard)) # Adminlarni gruppasiga ketadigan xabar nomer = Profile.objects.filter(pk=pk).values_list('phone_number').first()[0] pro_text = f"<a href='tg://user?id={telegram_id}'>id_{telegram_id}</a> shu id li mijoz\n" \ f"Tel nomer: {nomer}\n\n" + txt keyboard = btn_send_order_to_admins(pk, telegram_id, lang, order.pk) context.bot.send_message(GROUP_ID, pro_text, parse_mode=ParseMode.HTML, reply_markup=InlineKeyboardMarkup(keyboard)) return ConversationHandler.END except Exception as e: print(e) return ConversationHandler.END elif payment == btn_taxi_payment[lang][1]: # Payme update.message.reply_text("Hali processda") text = BUYURTMA_TEXT[lang]['payment'] markup = ReplyKeyboardMarkup.from_column(btn_taxi_payment[lang], resize_keyboard=True) update.message.reply_html(text, reply_markup=markup) return PAYMENT else: # Ortga text = BUYURTMA_TEXT[lang]['geolocation'] pk = context.user_data['pk'] markup = ReplyKeyboardMarkup(btn_taxi_geo(int(pk), lang), resize_keyboard=True) context.bot.send_message(update.effective_user.id, text, reply_markup=markup, parse_mode=ParseMode.HTML) return GEOLOCATION
def start(update, context): """Send a message when the command /start is issued.""" update.message.reply_text(texts.start_message) def help(update, context): """Send a message when the command /help is issued.""" update.message.reply_text(texts.help_message) buttons = ["угадано!", "ошибка :(", "всё."] ready_button = ["хочу слово!"] reply_markup_game = ReplyKeyboardMarkup.from_column(buttons) reply_markup_ready = ReplyKeyboardMarkup.from_column(ready_button) def pretty_turn(turn, context): return "{} -> {}".format(context.bot_data["username" + str(turn[0])], context.bot_data["username" + str(turn[1])]) def start_turn(update, context): user = update.message.from_user text = update.message.text.lower() user_id = user['id'] room = game.room_for_player(user_id) logger.info("start_turn %d %s", user_id, text) reply = context.bot_data["round" + room].start_move(user_id) update.message.reply_text(reply, reply_markup=reply_markup_game)
def command_start(update, context): update.message.reply_text( START_MESSAGE, reply_markup=ReplyKeyboardMarkup.from_column(ALLOWED_SPACES))
def make_favorite_keyboard(favorites): return ReplyKeyboardMarkup.from_column( favorites, one_time_keyboard=True, )