async def inline_query(query: types.InlineQuery): results = [] user_quizzes = quizzes_database.get(str(query.from_user.id)) if user_quizzes: for quiz in user_quizzes: keyboard = types.InlineKeyboardMarkup() start_quiz_button = types.InlineKeyboardButton( text="Отправить в группу", url=await deep_linking.get_startgroup_link(quiz.quiz_id)) keyboard.add(start_quiz_button) results.append( types.InlineQueryResultArticle( id=quiz.quiz_id, title=quiz.question, input_message_content=types.InputTextMessageContent( message_text= "Нажмите кнопку ниже, чтобы отправить викторину в группу." ), reply_markup=keyboard)) await query.answer(switch_pm_text="Создать викторину", switch_pm_parameter="_", results=results, cache_time=120, is_personal=True)
async def tutorial_callback_query( query: types.CallbackQuery, message: str, media: str, keyboards: typing.Sequence[typing.Tuple[str, str]], ): keyboard_markup = types.InlineKeyboardMarkup() keyboard_markup.row( *[ types.InlineKeyboardButton(label, callback_data=callback_data) for label, callback_data in keyboards ] ) animation = types.InputMediaAnimation( media=types.InputFile(media), caption=message, parse_mode="markdown", ) await types.ChatActions.upload_video() await bot.edit_message_media( media=animation, chat_id=query.message.chat.id, message_id=query.message.message_id, reply_markup=keyboard_markup, )
async def cmd_help(message: types.Message) -> None: if message.chat.id < 0: await message.reply( "Please use this command in private.", reply_markup=types.InlineKeyboardMarkup(inline_keyboard=[[ types.InlineKeyboardButton( "Send help message in private", url="https://t.me/on9wordchainbot?start=help", ) ]]), ) return await message.reply( ("/gameinfo - Game mode descriptions\n" "/troubleshoot - See how to solve common issues\n" "/reqaddword - Request addition of words\n\n" "You may message [Jono](tg://user?id=463998526) in *English or Cantonese* for anything about the bot.\n" "Official Group: @on9wordchain\n" "Word Additions Channel (with status updates): @on9wcwa\n" "Source Code: [Tr-Jono/on9wordchainbot](https://github.com/Tr-Jono/on9wordchainbot)\n" "Epic icon designed by [Adri](tg://user?id=303527690)"), disable_web_page_preview=True, )
async def upload_bukti_ask(message, position=None, state=None, reset_proxy=None, default_proxy=None, btn_msg=None, msg_ask_upload_or_not=None): message_ask_upload_or_not = "Kalau kamu punya bukti berupa screenshoot atau foto, " \ "tolong diupload ya biar Kirana mudah check kendalamu" keyboard_markup = types.InlineKeyboardMarkup(row_width=2) button_msg = 'Upload Foto Bukti' if btn_msg: button_msg = btn_msg if msg_ask_upload_or_not: message_ask_upload_or_not = msg_ask_upload_or_not text_and_data = ( (button_msg, 'req_photo_complain'), ('Tidak', 'no_req_photo_complain'), ) row_btns = (types.InlineKeyboardButton(text, callback_data=data) for text, data in text_and_data) keyboard_markup.row(*row_btns) return await message.answer(message_ask_upload_or_not, reply_markup=keyboard_markup)
async def confirm_delete_button(call: types.CallbackQuery): """Delete order after confirmation button query.""" order_id = call.data.split()[1] order = await database.orders.find_one_and_delete({ "_id": ObjectId(order_id), "user_id": call.from_user.id }) if not order: await call.answer(i18n("delete_order_error")) return location_message_id = int(call.data.split()[2]) keyboard = types.InlineKeyboardMarkup() keyboard.row( types.InlineKeyboardButton( i18n("hide"), callback_data="hide {}".format(location_message_id))) await tg.edit_message_text( i18n("order_deleted"), call.message.chat.id, call.message.message_id, reply_markup=keyboard, )
async def on_msg(message: types.Message): user_id = message.from_user.id chat_id = message.chat.id messageText = message.text.lower() # karma message if message.reply_to_message and message.reply_to_message.from_user.id and user_id != message.reply_to_message.from_user.id: # check user on karmaspam if not is_flood_message(message): karma_changed = await increase_karma( message.reply_to_message.from_user.id, messageText) if karma_changed: msg = await bot.send_message( chat_id, text=karma_changed, reply_to_message_id=message.message_id) await autodelete_message(msg.chat.id, message_id=msg.message_id, seconds=destruction_timeout) # is_python_advice = newbiesModel.predict_senctence(messageText) # if is_python_advice == 1: if 'курсы' in message.text: advice_reply = 'Кто-то сказал курс по питону?\nВот тут мы для тебя все собрали!\n\n#курсы' keyboard = types.InlineKeyboardMarkup() keyboard.add( types.InlineKeyboardButton( text="Курсы без смс и регистрации", url= "https://github.com/vviedienieiev/Learning/blob/main/python_guide_by_vv.ipynb" )) msg = await bot.send_message(chat_id, text=advice_reply, reply_to_message_id=message.message_id, reply_markup=keyboard)
async def base_updates(): # апдейт бд, проверяет БД на наличие изменений while check: try: #чекаем базу на редмет вышедших работать # чекаем клиентосов all_mast = Masters.select().where(Masters.status == 'work') clients = Clients.select().where(Clients.status == 'open') #cursor.execute('SELECT status FROM clients WHERE status="open"') #anser = cursor.fetchall() for i in clients: print(i.chat_id) for f in all_mast: print(f.master_id) try: # функция отправки смс о том что заявка в работе keyboard = types.InlineKeyboardMarkup() callback_button = types.InlineKeyboardButton( text="Принять", callback_data=f"прием {i.chat_id}") keyboard.add(callback_button) print(i.Zayavka, i.adres, 'tut?') await bot.send_message( f.master_id, f'Заявка: {i.Zayavka} Адрес: {i.adres}', reply_markup=keyboard) except: print('Fail') await asyncio.sleep(5) await asyncio.sleep(1) await asyncio.sleep(60) await asyncio.sleep(1) except: print('Fail') await asyncio.sleep(5)
async def notificaion_enable_callback_handler( query: types.CallbackQuery, callback_data: typing.Dict[str, str], user: UserRepository, _: dict, ): action = callback_data['action'] keyboard_markup = types.InlineKeyboardMarkup(row_width=2) notification_setting = await user.get_notification_setting_for_user( query.from_user.id) new_setting_value = not notification_setting.is_enabled if (action != "_"): await user.update_notification_setting(query.from_user.id, new_setting_value) notification_setting = await user.get_notification_setting_for_user( query.from_user.id) keyboard_markup.row( types.InlineKeyboardButton( _[f'setting_notification_set_{int(not notification_setting.is_enabled)}'], callback_data=notification_cb.new(action=new_setting_value), ), ) message_text = _['notification_change_descr'].format(setting=_[ f'setting_notification_{int(notification_setting.is_enabled)}']) await query.message.edit_text( message_text, reply_markup=keyboard_markup, ) await query.answer()
def inlinekeyboard_4(): markup = types.InlineKeyboardMarkup(resize_keyboard=True, selective=True) button_9 = types.InlineKeyboardButton('Программист', callback_data='implementer_button_9') button_10 = types.InlineKeyboardButton( 'Юрист', callback_data='implementer_button_10') button_11 = types.InlineKeyboardButton( 'Экономист', callback_data='implementer_button_11') button_12 = types.InlineKeyboardButton( 'Естественник', callback_data='implementer_button_12') button_13 = types.InlineKeyboardButton( 'Гуманитарий', callback_data='implementer_button_13') button_14 = types.InlineKeyboardButton( 'Технарь', callback_data='implementer_button_14') #button_15 = types.InlineKeyboardButton('Список работ', callback_data='button_15') markup.row(button_9, button_10, button_11) markup.row(button_12, button_13) markup.row(button_14) return markup
async def make_settings_lang_keyboard(user_id: int) -> types.InlineKeyboardMarkup: settings = await SettingsDB.get(user_id) keyboard = types.InlineKeyboardMarkup() if not settings.allow_ru: keyboard.row(types.InlineKeyboardButton("Русский: 🅾 выключен!", callback_data="ru_on")) else: keyboard.row(types.InlineKeyboardButton("Русский: ✅ включен!", callback_data="ru_off")) if not settings.allow_uk: keyboard.row(types.InlineKeyboardButton("Украинский: 🅾 выключен!", callback_data="uk_on")) else: keyboard.row(types.InlineKeyboardButton("Украинский: ✅ включен!", callback_data="uk_off")) if not settings.allow_be: keyboard.row(types.InlineKeyboardButton("Белорусский: 🅾 выключен!", callback_data="be_on")) else: keyboard.row(types.InlineKeyboardButton("Белорусский: ✅ включен!", callback_data="be_off")) keyboard.row(types.InlineKeyboardButton("⬅️ Назад", callback_data="settings_main")) return keyboard
async def make_settings_keyboard_for_user_async( state: FSMContext, lang_code: str) -> types.InlineKeyboardMarkup: kb = types.InlineKeyboardMarkup() data = await get_data(state) wordcount_buttons = [] wordcount = data.get(DBKeys.WORDS_COUNT.value) if wordcount > app_config.min_words: wordcount_buttons.append( types.InlineKeyboardButton( text=all_strings.get(get_language(lang_code)).get("minusword"), callback_data=cb_wordcount.new(change="minus"))) if wordcount < app_config.max_words: wordcount_buttons.append( types.InlineKeyboardButton( text=all_strings.get(get_language(lang_code)).get("plusword"), callback_data=cb_wordcount.new(change="plus"))) kb.add(*wordcount_buttons) if data.get(DBKeys.PREFIXES_SUFFIXES.value, True) is True: kb.add( types.InlineKeyboardButton( text=all_strings.get(get_language(lang_code)).get("minuspref"), callback_data=cb_prefixes.new(action="disable"))) else: kb.add( types.InlineKeyboardButton( text=all_strings.get(get_language(lang_code)).get("pluspref"), callback_data=cb_prefixes.new(action="enable"))) if data.get(DBKeys.SEPARATORS.value, True) is True: kb.add( types.InlineKeyboardButton( text=all_strings.get(get_language(lang_code)).get("minussep"), callback_data=cb_separators.new(action="disable"))) else: kb.add( types.InlineKeyboardButton( text=all_strings.get(get_language(lang_code)).get("plussep"), callback_data=cb_separators.new(action="enable"))) return kb
def create_calendar(year, month): markup = types.InlineKeyboardMarkup() #First row - Month and Year row = [] row.append( types.InlineKeyboardButton(calendar.month_name[month] + " " + str(year), callback_data="ignore")) markup.row(*row) #Second row - Week Days week_days = ["M", "T", "W", "R", "F", "S", "U"] row = [] for day in week_days: row.append(types.InlineKeyboardButton(day, callback_data="ignore")) markup.row(*row) my_calendar = calendar.monthcalendar(year, month) for week in my_calendar: row = [] for day in week: if (day == 0): row.append( types.InlineKeyboardButton(" ", callback_data="ignore")) else: row.append( types.InlineKeyboardButton(str(day), callback_data="calendar-day-" + str(day))) markup.row(*row) #Last row - Buttons row = [] row.append(types.InlineKeyboardButton("<", callback_data="previous-month")) row.append(types.InlineKeyboardButton(" ", callback_data="ignore")) row.append(types.InlineKeyboardButton(">", callback_data="next-month")) markup.row(*row) return markup
def gen_imgur_markup(url): markup = types.InlineKeyboardMarkup() markup.row(types.InlineKeyboardButton(text="Direct", url=url)) markup.row( types.InlineKeyboardButton(text="IQDB", url=f"http://iqdb.org/?url={url}"), types.InlineKeyboardButton( text="Google", url= f"https://www.google.com/searchbyimage?image_url={url}&hl=ru&newwindow=1" )) markup.row( types.InlineKeyboardButton(text="Trace.moe", url=f"https://trace.moe/?url={url}"), types.InlineKeyboardButton( text="SauceNao", url= f"https://saucenao.com/search.php?db=999&dbmaski=32768&url={url}"), types.InlineKeyboardButton(text="TinEye", url=f"https://tineye.com/search?url={url}")) return markup
async def admin_ka(message: types.Message): id = message.from_user.id if id in ADMIN_ID: markup = types.InlineKeyboardMarkup() bat_a = types.InlineKeyboardButton(text='Трафик', callback_data='list_members') bat_b = types.InlineKeyboardButton( text='NEW канал', callback_data='new_channel') # Добавляет 1 канал bat_c = types.InlineKeyboardButton( text='NEW Список', callback_data='new_channels' ) # Добавляет список каналов через пробел bat_d = types.InlineKeyboardButton( text='Удалить канал', callback_data='delite_channel') # Удаляет канал из списка bat_e = types.InlineKeyboardButton(text='Рассылка', callback_data='write_message') bat_j = types.InlineKeyboardButton(text='Скачать базу', callback_data='baza') markup.add(bat_a, bat_b, bat_c, bat_d, bat_e, bat_j) await bot.send_message(message.chat.id, 'Выполнен вход в админ панель', reply_markup=markup)
async def keyboard_attaka(user): keyboard = types.InlineKeyboardMarkup() rows = await sql.sql_select( f"SELECT name, avatar FROM combinations WHERE id > 0 and user_id = {user} ORDER BY id" ) health = (await sql.sql_selectone( f"select health_used from heroes where user_id = {user}"))[0] health_enemy = (await sql.sql_selectone( f"select enemy_health from battle_enemy where user_id = {user}"))[0] health = types.InlineKeyboardButton(text=f"{health} ❤️", callback_data="1") health_enemy = types.InlineKeyboardButton(text=f"{health_enemy} ❤️", callback_data="1") x, y = 1, 1 list_x = [2, 5, 8, 10, 12] list_y = [2, 6, 8, 10, 12] tab = [] # keyboard.row(types.InlineKeyboardButton(text="тут текст", callback_data="1")) keyboard.row( types.InlineKeyboardButton(text=text_ataka[user]["null"], callback_data="1")) for row in rows: if x in list_x: tab.append( types.InlineKeyboardButton(text="➖➖", callback_data="null")) if x == 5: tab.append( types.InlineKeyboardButton(text="➖➖", callback_data="null")) tab.append( types.InlineKeyboardButton(text=row[1], callback_data="fight_%s" % row[0])) if y in list_y: keyboard.row(*tab) tab = [] x += 1 y += 1 keyboard.row(health, health_enemy) return keyboard
async def welcome(mess: types.message): ref = mess.text[7:] sql.reg_user(mess.chat.id, ref) await bot.send_video_note( chat_id=mess.chat.id, video_note= 'DQACAgIAAxkBAAIJfV_teqhyKb1DBbKk3BJopg35r9cHAAJjCgACGtdwS61pwkoRLtxzHgQ' ) await asyncio.sleep(40) markup = types.InlineKeyboardMarkup() bat0 = types.InlineKeyboardButton(text='ДАЛЕЕ', callback_data='none_video') bat1 = types.InlineKeyboardButton( text='ЧАТ', url='https://t.me/joinchat/HXrUH0V-pEm7AiZrWme0dw') bat2 = types.InlineKeyboardButton( text='ИНСТА', url='https://www.instagram.com/nikolanext') markup.add(bat0, bat1, bat2) msq = await bot.send_message(mess.chat.id, video_0, reply_markup=markup, parse_mode='HTML') msq = msq.message_id await asyncio.sleep(100) ##### ЖДЕМ 60 СЕКУНД #### markup = types.InlineKeyboardMarkup() bat0 = types.InlineKeyboardButton(text='ДАЛЕЕ', callback_data='video1') bat1 = types.InlineKeyboardButton( text='ЧАТ', url='https://t.me/joinchat/HXrUH0V-pEm7AiZrWme0dw') bat2 = types.InlineKeyboardButton( text='Инста', url='https://www.instagram.com/nikolanext') markup.add(bat0, bat1, bat2) await bot.edit_message_reply_markup(chat_id=mess.chat.id, message_id=msq, reply_markup=markup)
async def escrow_button(call: types.CallbackQuery, order: OrderType): """React to "Escrow" button by starting escrow exchange.""" if not config.ESCROW_ENABLED: await call.answer(i18n("escrow_unavailable")) return args = call.data.split() currency_arg = args[2] edit = bool(int(args[3])) if currency_arg == "sum_buy": sum_currency = order["buy"] new_currency = order["sell"] new_currency_arg = "sum_sell" elif currency_arg == "sum_sell": sum_currency = order["sell"] new_currency = order["buy"] new_currency_arg = "sum_buy" else: return keyboard = types.InlineKeyboardMarkup() keyboard.row( types.InlineKeyboardButton( i18n("change_to {currency}").format(currency=new_currency), callback_data="escrow {} {} 1".format(order["_id"], new_currency_arg), ) ) answer = i18n("send_exchange_sum {currency}").format(currency=sum_currency) if edit: cancel_data = call.message.reply_markup.inline_keyboard[1][0].callback_data keyboard.row( types.InlineKeyboardButton(i18n("cancel"), callback_data=cancel_data) ) await database.escrow.update_one( {"pending_input_from": call.from_user.id}, {"$set": {"sum_currency": currency_arg}}, ) await call.answer() await tg.edit_message_text( answer, call.message.chat.id, call.message.message_id, reply_markup=keyboard ) else: offer_id = ObjectId() keyboard.row( types.InlineKeyboardButton( i18n("cancel"), callback_data=f"init_cancel {offer_id}" ) ) escrow_type = "buy" if get_escrow_instance(order["buy"]) else "sell" user = database_user.get() init_user = { "id": user["id"], "locale": user["locale"], "mention": user["mention"], } counter_user = await database.users.find_one( {"id": order["user_id"]}, projection={"id": True, "locale": True, "mention": True}, ) await database.escrow.delete_many({"init.send_address": {"$exists": False}}) offer = EscrowOffer( **{ "_id": offer_id, "order": order["_id"], "buy": order["buy"], "sell": order["sell"], "type": escrow_type, "escrow": order[escrow_type], "time": time(), "sum_currency": currency_arg, "init": init_user, "counter": counter_user, "pending_input_from": call.message.chat.id, } ) await offer.insert_document() await call.answer() await tg.send_message(call.message.chat.id, answer, reply_markup=keyboard) await states.Escrow.amount.set()
async def inline(query): try: await bot.answer_callback_query(query.id) user = BotUser(query.from_user.id) data = query.data message_id = query.message.message_id if 'calc_type:' in data: calc_type = data.split(":")[1] period = 0 if calc_type == "half": period = PERIOD else: period = WHOLE_YEAR_PERIOD if not user.logged_in: await bot.send_message(user.id, log_in_first) else: log_in_attempt = user.log_in() if log_in_attempt['logged_in']: await bot.edit_message_text(chat_id=user.id, message_id=message_id, text=getting_marks) calculate_data = user.get_calculate_data(log_in_attempt['session'], period) kb = create_calculate_kb(calculate_data) user.state = 'calculate_choosing_units' await bot.edit_message_text(chat_id=user.id, message_id=message_id, text=calculate_choose_unit, reply_markup=kb) else: await bot.send_message(user.id, error_logging_in) elif 'c:' in data: unit_id = data.split(':')[1] unit_name = user.units[unit_id] average = float(data.split(':')[2]) weight = float(data.split(':')[3]) user.state = f'calculate_choosing_mark:{unit_id}:{average}:{weight}' await bot.edit_message_text(chat_id=user.id, message_id=message_id, text=calculate_choose_mark_format.format(unit_name=unit_name, average=average), reply_markup=marks_kb, parse_mode="HTML") elif 'calc_chosen_mark:' in data: if 'calculate_choosing_mark:' in user.state: unit_id = user.state.split(':')[1] unit_name = user.units[unit_id] average = float(user.state.split(':')[2]) weight = float(user.state.split(':')[3]) chosen_mark = int(data.split(':')[1]) user.state = f'calculate_choosing_weight:{unit_id}:{average}:{weight}:{chosen_mark}' await bot.edit_message_text(chat_id=user.id, message_id=message_id, text=calculate_choose_weight_format.format(unit_name=unit_name, average=average), reply_markup=weights_kb, parse_mode="HTML") elif 'calc_chosen_weight:' in data: if 'calculate_choosing_weight:' in user.state: unit_id = user.state.split(':')[1] unit_name = user.units[unit_id] prev_average = float(user.state.split(':')[2]) prev_weight = float(user.state.split(':')[3]) chosen_mark = int(user.state.split(':')[4]) chosen_weight = float(data.split(':')[1]) new_average, new_weight = calc_average_change(prev_average, prev_weight, chosen_mark, chosen_weight) kb = types.InlineKeyboardMarkup() user.state = f'calc:{unit_name}' kb.add(types.InlineKeyboardButton(text=calculate_more, callback_data=f'c:{unit_id}:{new_average}:{new_weight}')) await bot.edit_message_text(chat_id=user.id, message_id=message_id, text=calculate_result_format.format(chosen_mark=chosen_mark, chosen_weight=chosen_weight, unit_name=unit_name, prev_average=prev_average, new_average=new_average), reply_markup=kb, parse_mode="HTML") elif 'set_notify_type' in data: user.notify_type = data.split(':')[1] await send_notify_settings(user.id, message_id, 1) else: if "IGNORE" in data or "DAY" in data or "PREV-MONTH" in data or "NEXT-MONTH" in data: date = await process_calendar_selection(bot, query) if date[0] == True: if user.state == 'get_homework_choose_day': user.state = 'none' homework_day = int(date[1].timestamp()) ctime_day = time.ctime(homework_day).split()[:3] read_day = WEEK[ctime_day[0]] + ', ' + ctime_day[2] + ' ' + MONTH[ctime_day[1]] await bot.edit_message_text(text="Получаю домашние задания...", chat_id=user.id, message_id=message_id, parse_mode="HTML") log_in_attempt = user.log_in() if log_in_attempt['logged_in']: s = log_in_attempt['session'] homeworks = user.get_homeworks(s, homework_day) msg = f'<b>Домашние задания на {read_day}:</b>' await bot.edit_message_text(text=msg, chat_id=user.id, message_id=message_id, parse_mode="HTML") await send_homeworks(user.id, s, homeworks) else: await bot.send_message(user.id, error_logging_in) elif user.state == 'get_conferences_choose_day': user.state = 'none' conferences_day = int(date[1].timestamp()) ctime_day = time.ctime(conferences_day).split()[:3] read_day = WEEK[ctime_day[0]] + ', ' + ctime_day[2] + ' ' + MONTH[ctime_day[1]] await bot.edit_message_text(text="Получаю конференции...", chat_id=user.id, message_id=message_id, parse_mode="HTML") log_in_attempt = user.log_in() if log_in_attempt['logged_in']: s = log_in_attempt['session'] conferences = user.get_conferences(s, conferences_day) msg = f'<b>Конференции на {read_day}:</b>' await bot.edit_message_text(text=msg, chat_id=user.id, message_id=message_id, parse_mode="HTML") await send_conferences(user.id, s, conferences) else: await bot.send_message(user.id, error_logging_in) elif user.state == 'get_lessons_choose_day': user.state = 'none' lessons_day = int(date[1].timestamp()) ctime_day = time.ctime(lessons_day).split()[:3] read_day = WEEK[ctime_day[0]] + ', ' + ctime_day[2] + ' ' + MONTH[ctime_day[1]] await bot.edit_message_text(text="Получаю расписание...", chat_id=user.id, message_id=message_id, parse_mode="HTML") log_in_attempt = user.log_in() if log_in_attempt['logged_in']: s = log_in_attempt['session'] lessons = user.get_lessons(s, lessons_day) msg = f'<b>Расписание на {read_day}:</b>' await bot.edit_message_text(text=msg, chat_id=user.id, message_id=message_id, parse_mode="HTML") await send_lessons(user.id, s, lessons) else: await bot.send_message(user.id, error_logging_in) except: await bot.send_message('@eschool239boterrors', traceback.format_exc())
async def handle(self, message: types.Message, user: UserRepository, _: dict): await message.bot.send_chat_action(message.from_user.id, ChatActions.TYPING) async with IntercomClient(INTERCOM_TOKEN) as intercom: intercom_user = await get_intercom_contact(message.from_user) conversations = await intercom.find_conversations_for_user( intercom_user["id"]) keyboard_markup = types.InlineKeyboardMarkup(row_width=1) if conversations["total_count"] > 0: for conv in conversations["conversations"][ (1 - 1) * PER_PAGE_CONVERSATIONS:1 * PER_PAGE_CONVERSATIONS]: keyboard_markup.add( types.InlineKeyboardButton( f'#{conv["id"]} - ' + (_["feedback_opened"] if conv["open"] else _["feedback_closed"]), callback_data=conv_cb.new(id=conv["id"], action="open"), )) buttons = [] buttons.append( types.InlineKeyboardButton( _['new_feedback_button'], callback_data=conv_cb.new(id="_", action="new"), )) if (len(conversations["conversations"]) > 1 * PER_PAGE_CONVERSATIONS): buttons.append( types.InlineKeyboardButton( _["next_button"], callback_data=conv_cb.new( id=2, action="page", ), ), ) keyboard_markup.row(*buttons) await message.answer( _["feedback_menu_has_items"].format( open=sum((1 for i in conversations["conversations"] if i["open"]), 0), closed=sum((1 for i in conversations["conversations"] if not i["open"]), 0)), reply_markup=keyboard_markup, ) return keyboard_markup.row( types.InlineKeyboardButton( _['new_feedback_button'], callback_data=conv_cb.new(id="_", action="new"), )) await message.answer( _["feedback_menu_no_items"], reply_markup=keyboard_markup, )
async def laptops_model_menu(message: types.Message): """ This handler will be called when user use `Laptop` buttom """ menu_keyboard = types.InlineKeyboardMarkup(row_width=2) model_keyboard_1 = types.InlineKeyboardButton(text="Acer", callback_data="Acer") model_keyboard_2 = types.InlineKeyboardButton(text="Apple", callback_data="Apple") model_keyboard_3 = types.InlineKeyboardButton(text="Asus", callback_data="Asus") model_keyboard_4 = types.InlineKeyboardButton(text="Dell", callback_data="Dell") model_keyboard_5 = types.InlineKeyboardButton(text="HP", callback_data="HP") model_keyboard_6 = types.InlineKeyboardButton(text="Huawei", callback_data="Huawei") model_keyboard_7 = types.InlineKeyboardButton(text="Microsoft", callback_data="Microsoft") model_keyboard_8 = types.InlineKeyboardButton(text="Sony", callback_data="Sony") model_keyboard_9 = types.InlineKeyboardButton(text="MSI", callback_data="MSI") model_keyboard_10 = types.InlineKeyboardButton(text="Lenovo", callback_data="Lenovo") model_keyboard_11 = types.InlineKeyboardButton(text="Xiaomi", callback_data="Xiaomi") menu_keyboard.add(model_keyboard_1, model_keyboard_2, model_keyboard_3, model_keyboard_4, model_keyboard_5, model_keyboard_6, model_keyboard_7, model_keyboard_8, model_keyboard_9, model_keyboard_10, model_keyboard_11) await bot.send_message( chat_id=message.from_user.id, text="Please, choose model, what would u like to buy.", reply_markup=menu_keyboard)
async def recognize_query_step_1_message(message: types.Message, state: FSMContext): user_data = await state.get_data() folder_info = db.select_folder(user_data["folder_id"]) random_str = generate_random_string(32) path_list = path(message.chat.id, folder_info[1]) if message.content_type == "voice": file_id = message.voice.file_id if message.voice.mime_type == "audio/ogg": query_audio_file_extensions = ".ogg" else: query_audio_file_extensions = ".NULL" # await message.answer("Что-то пошло не так...", True) elif message.content_type == "audio": file_id = message.audio.file_id name_file = message.audio.file_name # New in Bot API 5.0 query_audio_file_extensions = os.path.splitext(name_file)[1] if query_audio_file_extensions.lower() not in ('.aac', '.wav', '.mp3', '.wma', '.ogg', '.flac', '.opus'): keyboard_markup = types.InlineKeyboardMarkup() back_btn = types.InlineKeyboardButton( '« ', callback_data=manage_folder_cb.new(user_data["folder_id"])) keyboard_markup.row(back_btn) await message.reply( 'Мы не можем определить формат аудио записи или мы не поддерживаем его. Возможно название файла очень длинное.\nПовторите попытку еще раз', reply_markup=keyboard_markup) return query_audio_full_name = f"{random_str}{query_audio_file_extensions}" query_audio_name = f"{random_str}" await state.finish() managment_msg = await message.reply('Задача поставлена в поток!') try: # Stage 0 : download file managment_msg = await download_file( managment_msg, file_id, path_list.tmp_query_audio(query_audio_full_name)) # Stage 1 : check audio files for integrity and mormalize, convert them managment_msg = await audio_processing( managment_msg, path_list.tmp_query_audio(query_audio_full_name), path_list.processed_query_audio(query_audio_name + ".mp3")) # Stage 2 : match audio query managment_msg = await match_audio_query( managment_msg, path_list.processed_query_audio(query_audio_name + ".mp3"), path_list.fingerprint_db()) except Exception: await folder_list_menu_message(message, 'start') return else: keyboard_markup = types.InlineKeyboardMarkup() manage_folder_menu_message_btn = types.InlineKeyboardButton( '« Вернутся к текущей папке ', callback_data=manage_folder_cb.new(user_data["folder_id"])) upload_sample_btn = types.InlineKeyboardButton( '» Распознать еще одну запись', callback_data=recognize_query_cb.new(user_data["folder_id"])) keyboard_markup.row(manage_folder_menu_message_btn) keyboard_markup.row(upload_sample_btn) await message.reply('Аудио запись распознана', reply_markup=keyboard_markup) finally: os.remove(path_list.tmp_query_audio(query_audio_full_name)) os.remove(path_list.processed_query_audio(query_audio_name + ".mp3"))
async def upload_audio_sample_step_2_message(message: types.Message, state: FSMContext): # async with state.proxy() as user_data: # user_data['audio_sample_name'] = message.text.replace('\n', ' ') user_data = await state.get_data() folder_info = db.select_folder(user_data["folder_id"]) file_id = user_data["audio_sample_file_info"].file_id audio_sample_name = user_data["audio_sample_name"] audio_sample_full_name = f'{audio_sample_name}{user_data["audio_sample_file_extensions"]}' path_list = path(message.chat.id, folder_info[1]) keyboard_markup = types.InlineKeyboardMarkup() back_btn = types.InlineKeyboardButton('« ', callback_data=manage_folder_cb.new( user_data["folder_id"])) keyboard_markup.row(back_btn) # Проверяем количество символов в названии сэмпла if len(audio_sample_name) >= 180: await message.reply( 'Название сэмпла превышает 180 символов, введите другое имя', reply_markup=keyboard_markup) return # Проверяем строку на недопустимые символы # if check_string_for_except_chars(user_data["audio_sample_name"]): # await message.reply(f'Название сэмпла "{user_data["audio_sample_name"]}" содержит недопустимые символы: {check_string_for_except_chars(audio_sample_name)}\nВведите другое имя', reply_markup=keyboard_markup) # return # Проверяем, существует ли аудио сэмпл с таким же названием if user_data["audio_sample_name"].lower() in [ x[1].lower() for x in db.select_folder_samples(user_data["folder_id"]) ]: await message.reply( "Аудио сэмпл с таким же уже существует, введите другое имя", reply_markup=keyboard_markup) return # await state.finish() managment_msg = await message.reply('Задача поставлена в поток!') await myQueue.put("1") keyboard_markup = types.InlineKeyboardMarkup() manage_folder_menu_message_btn = types.InlineKeyboardButton( '« Вернутся к текущей папке', callback_data=manage_folder_cb.new(user_data["folder_id"])) upload_sample_btn = types.InlineKeyboardButton( '» Загрузить еще один сэмпл', callback_data=upload_audio_sample_cb.new(user_data["folder_id"])) keyboard_markup.row(manage_folder_menu_message_btn) keyboard_markup.row(upload_sample_btn) try: # Stage 0 : download file managment_msg = await download_file( managment_msg, file_id, path_list.tmp_audio_samples(audio_sample_full_name)) # Stage 1 : check audio files for integrity and mormalize, convert them managment_msg = await audio_processing( managment_msg, path_list.tmp_audio_samples(audio_sample_full_name), path_list.processed_audio_samples(audio_sample_name + ".mp3")) # Stage 2 : analyze current audio sample hashes managment_msg = await register_audio_hashes( managment_msg, path_list.processed_audio_samples(audio_sample_name + ".mp3"), path_list.fingerprint_db()) # Stage 3 : register current audio sample hashes db.register_audio_sample( user_data["folder_id"], user_data["audio_sample_name"], user_data["audio_sample_file_info"].file_unique_id) except Exception as ex: logging.exception(ex) await message.reply( f'Во времмя обработки аудио сэмпла с названием "{user_data["audio_sample_name"]}" возникла ошибка', reply_markup=keyboard_markup) else: await message.reply( f'Аудио сэмпл с названием "{user_data["audio_sample_name"]}" успешно сохранён', reply_markup=keyboard_markup) finally: os.remove(path_list.tmp_audio_samples(audio_sample_full_name)) os.remove(path_list.processed_audio_samples(audio_sample_name + ".mp3")) await myQueue.get()
def admin_unchoose(day: int, time: int, status: str) -> types.InlineKeyboardMarkup: return types.InlineKeyboardMarkup().add( types.InlineKeyboardButton(text='Отмена', callback_data=_callback( 'admin_unchoice', day, time, status)))
def _callback(*args): return '-|-'.join([str(i) for i in args]) btn = { 'order': '📝Заказать песню', 'what_playing': '🎧Что играет?', 'help': '⁉️Помощь', 'feedback': '🖌Обратная связь', } order_inline = types.InlineKeyboardMarkup() order_inline.add( types.InlineKeyboardButton("Удобный поиск", switch_inline_query_current_chat="")) start = types.ReplyKeyboardMarkup(row_width=2, resize_keyboard=True) start.add(types.KeyboardButton(btn['what_playing']), types.KeyboardButton(btn['order'])) start.add(types.KeyboardButton(btn['feedback']), types.KeyboardButton(btn['help'])) what_playing = types.InlineKeyboardMarkup(row_width=2) what_playing.add( types.InlineKeyboardButton(text='История', url='https://t.me/rkpi_music')) what_playing.add( types.InlineKeyboardButton(text='Предыдущие треки', callback_data='song_prev'), types.InlineKeyboardButton(text='Следующие треки', callback_data='song_next'))
async def take_from_postomat(call: CallbackQuery, state: FSMContext): await call.answer(cache_time=60) who_pay = call.data print("Попал в хендлер оплаты") print(who_pay) await call.message.delete_reply_markup() await state.update_data(who_pay=who_pay) data = await state.get_data() print(data) # {'parcel_size': {'weight': 0.589, 'volume': 0.002}, 'sender_poshtomat_num': '4966', # 'sender_post_id': 'bd5f4052-dceb-11e8-80d7-1c98ec135261', 'res_poshtomat_num': '4966', # 're_post_num': 'bd5f4052-dceb-11e8-80d7-1c98ec135261', 'res_full_name': '0507723091', 'res_phone': '380507723091', # 'amount_cod': '12', 'card_number': 'IVAB', 'who_pay': 'True'} user_data = await db.get_user_data(call.from_user.id) user_phone = user_data['phone_number'] sender_name = user_data['full_name'] sender_poshtomat_num = data['sender_poshtomat_num'] res_poshtomat_num = data['res_poshtomat_num'] res_full_name = data['res_full_name'] res_phone = data['res_phone'] if 'amount_cod' in data: cardholder_name = data['cardholder_name'] cod = data['amount_cod'] card_number = data['card_number'] parcel_info = f'<b>Відправник </b>: {hbold(sender_name)}\n' \ f'{hcode(user_phone)}\n' \ f'Дані отримання післяплати: {hcode(cardholder_name)}\n' \ f'{hcode(card_number)}\n' \ f'Поштомат №: {hcode(sender_poshtomat_num)}\n' \ f'<b>Отримувач </b>: {hcode(res_full_name)}\n' \ f'<b>Післяплата </b>: {hcode(cod)} грн\n' \ f'{hcode(res_phone)}\n' \ f'Поштомат №: {hcode(res_poshtomat_num)}\n' await call.message.edit_text(f"{parcel_info}") keyboard = types.InlineKeyboardMarkup(row_width=2) keyboard.add( types.InlineKeyboardButton(text="Створити", callback_data="create_parcel")) keyboard.add( types.InlineKeyboardButton(text="До головного меню", callback_data="Cancel3")) await call.message.answer( hbold('Якщо усі дані вірні, натисніть створити'), reply_markup=keyboard) await ParcelCreate.get_result.set() else: print(f"То что мне нужно{data}") parcel_info = f'<b>Відправник </b>: {hbold(sender_name)}\n' \ f'{hcode(user_phone)}\n' \ f'Поштомат №: {hcode(sender_poshtomat_num)}\n' \ f'<b>Отримувач </b>: {hcode(res_full_name)}\n' \ f'{hcode(res_phone)}\n' \ f'Поштомат №: {hcode(res_poshtomat_num)}\n' print(parcel_info) await call.message.edit_text(f"{parcel_info}") keyboard = types.InlineKeyboardMarkup(row_width=2) keyboard.add( types.InlineKeyboardButton(text="Створити", callback_data="create_parcel")) keyboard.add( types.InlineKeyboardButton(text="До головного меню", callback_data="Cancel3")) await call.message.answer( hbold('Якщо усі дані вірні, натисніть створити'), reply_markup=keyboard) await ParcelCreate.get_result.set()
stock_info = f"[INFO]({stock_info})" plot_kline(stock_data=stock.collect_data_daily(time_begin, time_end), title=f'kline of {stock.code}', plot_type='hollow_candle', macd=macd, output=buf) buf.seek(0) kline_caption = (' '.join([stock.code, stock.name, stock_info])).replace('*', '\*') # A-share sucks! if args.md5: # Not open to user input, can only result from inline keyboard callback await query.message.edit_media(types.InputMediaPhoto(media=buf, caption=kline_caption, parse_mode=ParseMode.MARKDOWN)) else: await message.reply_photo(buf, caption=kline_caption, parse_mode=ParseMode.MARKDOWN) else: # get user's selection from inline keyboard keyboard_markup = types.InlineKeyboardMarkup() for stock in stock_list: stock_emoji = _market_emoji[stock.market] keyboard_markup.row(types.InlineKeyboardButton(' '.join([stock_emoji, stock.code, stock.name]), callback_data=' '.join(filter(None, ['/kline', time_arg, '-e', stock.md5, args.keyword[0]])))) # add exit button keyboard_markup.row(types.InlineKeyboardButton('exit', callback_data='exit')) await message.reply_photo(_file_id_inline, caption="Found multiple results", reply_markup=keyboard_markup) @dp.callback_query_handler(lambda cb: '/kline' in cb.data) @dp.callback_query_handler(text='exit') #TODO need expection on multi-user behavior? async def inline_kline_answer_callback_handler(query): logging.info(f'{query.inline_message_id}: {query.data}') if query.data == 'exit': await query.message.delete() return 1 await kline(message.Message(text=query.data), query=query) @dp.message_handler(commands=['define']) async def define(message):
from aiogram import types inline_btn_1 = types.InlineKeyboardButton('Первая кнопка!', callback_data='button1' + btn_id + 'номер_заявки') inline_kb1 = types.InlineKeyboardMarkup().add(inline_btn_1)
async def edit_button(call: types.CallbackQuery): """React to "Edit" button by entering edit mode on order.""" args = call.data.split() order_id = args[1] order = await database.orders.find_one( {"_id": ObjectId(order_id), "user_id": call.from_user.id} ) if not order: await call.answer(i18n("edit_order_error")) return field = args[2] keyboard = types.InlineKeyboardMarkup() unset_button = types.InlineKeyboardButton(i18n("unset"), callback_data="unset") if field == "sum_buy": answer = i18n("send_new_buy_amount") keyboard.row(unset_button) elif field == "sum_sell": answer = i18n("send_new_sell_amount") keyboard.row(unset_button) elif field == "price": user = database_user.get() answer = i18n("new_price {of_currency} {per_currency}") if user.get("invert_order", False): answer = answer.format(of_currency=order["buy"], per_currency=order["sell"]) else: answer = answer.format(of_currency=order["sell"], per_currency=order["buy"]) keyboard.row(unset_button) elif field == "payment_system": answer = i18n("send_new_payment_system") keyboard.row(unset_button) elif field == "duration": answer = i18n("send_new_duration {limit}").format( limit=config.ORDER_DURATION_LIMIT ) keyboard.row( types.InlineKeyboardButton( plural_i18n( "repeat_duration_singular {days}", "repeat_duration_plural {days}", order["duration"], ).format(days=order["duration"]), callback_data="default_duration", ) ) elif field == "comments": answer = i18n("send_new_comments") keyboard.row(unset_button) else: answer = None await call.answer() if not answer: return user = database_user.get() if "edit" in user: await tg.delete_message(call.message.chat.id, user["edit"]["message_id"]) result = await tg.send_message(call.message.chat.id, answer, reply_markup=keyboard,) await database.users.update_one( {"_id": user["_id"]}, { "$set": { "edit.order_message_id": call.message.message_id, "edit.message_id": result.message_id, "edit.order_id": order["_id"], "edit.field": field, "edit.location_message_id": int(args[3]), "edit.one_time": bool(int(args[4])), "edit.show_id": call.message.text.startswith("ID"), STATE_KEY: states.field_editing.state, } }, )
def url(text, url): keyboard = types.InlineKeyboardMarkup(row_width=1) keyboard.add(types.InlineKeyboardButton(text=text, url=url)) return keyboard
async def upload_audio_sample_step_1_message(message: types.Message, state: FSMContext): async with state.proxy() as user_data: user_data['audio_sample_message'] = message user_data['audio_sample_content_type'] = message.content_type if user_data["audio_sample_content_type"] == "document": user_data['audio_sample_file_info'] = user_data[ "audio_sample_message"].document name_file = user_data["audio_sample_message"].document.file_name elif user_data["audio_sample_content_type"] == "audio": user_data['audio_sample_file_info'] = user_data[ "audio_sample_message"].audio name_file = user_data[ "audio_sample_message"].audio.file_name # New in Bot API 5.0 user_data['audio_sample_file_name'] = os.path.splitext(name_file)[0] user_data['audio_sample_file_extensions'] = os.path.splitext( name_file)[1] keyboard_markup = types.InlineKeyboardMarkup() back_btn = types.InlineKeyboardButton('« ', callback_data=manage_folder_cb.new( user_data["folder_id"])) keyboard_markup.row(back_btn) # Проверяем размер файла if int(user_data["audio_sample_file_info"].file_size) >= 20871520: await message.reply( 'Размер файла превышает 20 mb. Отправьте другой файл', reply_markup=keyboard_markup) return # Проверка на загруженность файла в текущей папки через db file_unique_id = user_data["audio_sample_file_info"].file_unique_id for sample in db.select_folder_samples(user_data["folder_id"]): if sample[3] == file_unique_id: await message.reply( f'В папке этот аудио сэмпл уже существует под названием "{sample[1]}"\nОтправьте другой файл', reply_markup=keyboard_markup) return await state.update_data( {'audio_sample_name': user_data["audio_sample_file_name"]}) # Проверяем расширение файла if user_data["audio_sample_file_extensions"].lower() in ('.aac', '.wav', '.mp3', '.wma', '.ogg', '.flac', '.opus'): # await Upload_Sample.step_2.set() # await message.reply( # f'Название вашего аудио файла : <code>{user_data["audio_sample_file_name"]}</code>\n\n' # 'Введите название аудио сэмпла. Это название будет отображатся во время распознавания викторины', # parse_mode="HTML", # reply_markup=keyboard_markup) await upload_audio_sample_step_2_message(message, state) elif not user_data["audio_sample_file_extensions"]: await message.reply( 'Мы не можем определить формат аудио записи. Возможно название файла очень длинное.\nИзмените название файла на более короткую и повторите попытку еще раз', reply_markup=keyboard_markup) return else: await message.reply( f'Мы "{user_data["audio_sample_file_extensions"]}" формат не принемаем, пришлите в другом формате\n\n', reply_markup=keyboard_markup) return