async def cmd_start(message: types.Message): """ Conversation's entry point """ # Set state and language global lang, id, name locale = message.from_user.locale lang = locale.language id = message.from_user.id name = message.from_user.first_name # Si no reconoce idioma, por defecto activa el español if lang not in ["en","es","ca"]: lang = "es" #await bot.set_webhook(WEBHOOK_URL, drop_pending_updates=False) await Form.menu.set() markup = types.ReplyKeyboardMarkup(resize_keyboard=True, selective=True) markup.add("Add data", "Delete data") markup.add("About", "Exit") await message.reply("Welcome to covid scipy %s. Select one of the following" %name, reply_markup=markup)
async def send_welcome(message): print(message.text, 'я хз вообще') #если в базе есть, пишет "Снова привет" check_master = Masters.select().where( Masters.status == 'work', Masters.master_id == message.chat.id).count() if check_master > 0: print("Снова привет") await bot.send_message(message.chat.id, "Снова привет") else: print(check_master, "ЧО бляяяя") replye_mark = types.ReplyKeyboardMarkup(True, False) button_phone = types.KeyboardButton(text='Отправить номер телефона', request_contact=True) replye_mark.add(button_phone) await bot.send_message( message.chat.id, "Добавляем в базу мастеров, нажмите на 'Отправить номер телефона'", reply_markup=replye_mark) print("Добавляемся") new_master = Masters(master_id=message.chat.id) new_master.save()
async def start_cmd_handler(message: types.Message): keyboard_markup = types.ReplyKeyboardMarkup(row_width=3) # default row_width is 3, so here we can omit it actually # kept for clearness btns_text = ('Yes!', 'No!') keyboard_markup.row(*(types.KeyboardButton(text) for text in btns_text)) # adds buttons as a new row to the existing keyboard # the behaviour doesn't depend on row_width attribute more_btns_text = ( "I don't know", "Who am i?", "Where am i?", "Who is there?", ) keyboard_markup.add(*(types.KeyboardButton(text) for text in more_btns_text)) # adds buttons. New rows are formed according to row_width parameter await message.reply("Hi!\nDo you like aiogram?", reply_markup=keyboard_markup)
async def process_callback_queries(call: types.CallbackQuery, state: FSMContext): # lambda callback: callback.data in language = call.data.split(':')[-1] await call.answer(text=locale.get_text('language_set', language)) await call.message.delete() keyboard = types.ReplyKeyboardMarkup(keyboard=[[ types.KeyboardButton(text=locale.get_text('btn_request_contact', language), request_contact=True) ]], one_time_keyboard=True, resize_keyboard=True, row_width=1) await call.message.answer( text=f"{locale.get_text('msg_request_contact', language)}", reply_markup=keyboard) async with state.proxy() as data: data['lang'] = language await UserRegister.next()
async def callback_letter(call): if call.message: alph = [ '1', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' ] tickersList = tickers_list([]) if call.data in alph: #чистим базу h = call.message.chat.id a = VolDb(db) a.destroy(h) list1 = alphab_lists(call.data) keyboard_symb = types.InlineKeyboardMarkup(row_width=2) for symb in list1: keyboard_symb.add( types.InlineKeyboardButton(text=symb, callback_data=symb)) await call.message.answer('Choose your asset:', reply_markup=keyboard_symb) elif call.data in tickersList: ticker = call.data print(ticker) user_id = call.from_user.id c = VolDb(db) c.insert_user_id_vol(user_id) a = VolDb(db) a.insert_ticker(ticker, user_id) price = get_price(call.data) b = VolDb(db) b.insert_price(price, user_id) resetBut = types.ReplyKeyboardMarkup(resize_keyboard=True) DelBut = types.KeyboardButton("❌Reset token settings") back = types.KeyboardButton("↩Back to main menu") resetBut.add(DelBut, back) await call.message.answer( f"{call.data} сurrent price - {price},\nInsert Your risk per trade in $:\n(with a sign '$' at the end).\nFor example: 10$ or 10.5$", reply_markup=resetBut)
async def preparing_func(message: types.Message): """ This func does some preparations before the setting of some user's data """ markup = types.ReplyKeyboardMarkup(resize_keyboard=True, one_time_keyboard=True) button = types.KeyboardButton("Розпочати заповнення") markup.add(button) await message.answer( "✅Воу,тепер тобі треба заповнити такі данні:\n\n1)Курс якої валюти ти хочеш відслідковувати.\n" + "2)Діапазон курсу(від)\n" + "3)Діапазон курсу(до)\n\n" + "👌І вуаля,ти отримаєш повідомлення коли курс тієї чи іншої валюти" + "опинеться у вказаному тобою проміжку.\n\n" + "Ну що?!Поїхалиииии!!!🚗", reply_markup=markup) #Change state to PREPARE2 current = dp.current_state(user=message.from_user.id) await current.set_state(StatesTest.all()[1])
async def process_gender(message: types.Message, state: FSMContext): async with state.proxy() as data: data['gender'] = message.text # Remove keyboard markup = types.ReplyKeyboardMarkup(resize_keyboard=True, selective=True) markup.add("Yes", "No") markup.add("Cancel") # And send message await bot.send_message( message.chat.id, md.text( md.text('Sending ', md.code(data['age']) + ' GRIN'), md.text('on :', md.bold(data['method'])), md.text('To adress: ', data['gender']), sep='\n', ), reply_markup=markup, parse_mode=ParseMode.MARKDOWN, ) await Form.next()
async def grave(message: types.Message): markup = types.ReplyKeyboardMarkup(resize_keyboard=True, row_width=5) item1 = types.KeyboardButton("Грежул") item2 = types.KeyboardButton("Шемира") item3 = types.KeyboardButton("Торан") item4 = types.KeyboardButton("Изабелла") item5 = types.KeyboardButton("Нара") item6 = types.KeyboardButton("Фераэль") item7 = types.KeyboardButton("Баден") item8 = types.KeyboardButton("Кельтур") item9 = types.KeyboardButton("Оден") item10 = types.KeyboardButton("Изольд") item11 = types.KeyboardButton("Торн") item12 = types.KeyboardButton("Дэймон") back = types.KeyboardButton("Назад") markup.add(item1, item2, item3, item4, item5, item6, item7, item8, item9, item10, item11, item12, back) await bot.send_message(message.chat.id, "Герои фракции Могилорождённые", parse_mode='html', reply_markup=markup)
async def process_start(message: types.Message, state: FSMContext): """ Обработка состояния start, переход в состояние len_password либо остановка бота. """ async with state.proxy() as data: data['start'] = message.text.lower() if data['start'] == 'сгенерировать пароль': markup = types.ReplyKeyboardMarkup(resize_keyboard=True, selective=True) markup.add('Включить', 'Выключить') await message.answer( 'Включить или выключить специальные символы в пароле? (!@#$%^&*()_=+[]{};:\\"|,)', reply_markup=markup) await Form.next() elif data['start'] == 'не, спасибо': await state_finish(message, state) else: await message.reply('Тут два варианта:\n' 'Левая кнопка - генерирую пароль.\n' 'Правая кнопка - выход (/q).')
async def commands(message: Message, state=FSMContext): try: print(message.text) lang = await get_lang(chat_id=message.chat.id) if message.text == lang_list(lang, 'report_btn'): await report_violation(message, lang) if message.text == lang_list(lang, 'instruction_btn'): await instruction(message, lang) if message.text == lang_list(lang, 'switch_btn'): if lang == 'ru': lang = 'kz' else: lang = 'ru' if await is_have_phone(message.chat.id): await update_lang(message.chat.id, lang) await main_menu(message, lang) else: await update_lang(message.chat.id, lang) markup = await reg_buttons(lang) await send_message(message.chat.id, lang_list(lang, 'start'), reply_markup=markup) if message.text == lang_list(lang, 'verification_btn'): await send_message(message.chat.id, 'verification') if message.text == lang_list(lang, 'vote_btn'): markup = types.ReplyKeyboardMarkup(resize_keyboard=True) markup.add(lang_list(lang, 'back_btn')) await state.update_data(lang=lang) await send_message(message.chat.id, lang_list(lang, 'voted_photo'), reply_markup=markup) await States.vote.set() if message.text == lang_list(lang, 'area_btn'): await choose_area(message, lang) if message.text == '>>' or message.text == '<<' or message.text == 'Назад': await slider(message, state, lang) except Exception as e: logger.error(e)
async def contin(message: types.Message): """Preparing for image processing.""" # Let's make sure that the user has added both images. if not (content_flag * style_flag): # Conjunction await message.answer(text="You haven't uploaded both images yet.") return # Adding answer options. res = types.ReplyKeyboardMarkup(resize_keyboard=True, one_time_keyboard=True) res.add(types.KeyboardButton(text="Low")) res.add(types.KeyboardButton(text="Medium")) res.add(types.KeyboardButton(text="High")) await message.answer(text="Okay, now it's time to choose the quality" " (resolution) of the future image. The better " "the quality, the slower the processing time." " If you want to start all over again at this" " step, just send me the content image again," " and then the style image.", reply_markup=res)
async def add_user_to_bd_step_1(message: types.Message): logger.info( f'Хэндлер add_me запущен пользователем с id {message.from_user.id} ' f'({message.from_user.full_name}, {message.from_user.username})') await types.ChatActions.typing() db = DB() if db.is_tg_account_exists(message.from_user.id): await message.answer( str(message.from_user.first_name) + ", вы уже были зарегистрированы ранее." + "\nДля внесения изменений воспользуйтесь командой: /edit_me" ) else: tg_account = TG_Account( id=message.from_user.id, username=message.from_user.username, first_name=message.from_user.first_name, is_bot=message.from_user.is_bot, language_code=message.from_user.language_code, modified_at=datetime.now() ) person = Person(tg_account=tg_account) try: db.session.add(person) db.session.commit() await message.answer( str(message.from_user.first_name) + ", спасибо за регистрацию." + "\nДля внесения изменений воспользуйтесь командой: /edit_me" ) except Exception as ex: db.session.rollback() logger.error(ex) keyboard = types.ReplyKeyboardMarkup(resize_keyboard=True) keyboard.add("отмена") await message.answer( "Для правильной работы сообщите мне ACTIVISION_ID:\n" + "\nпример: Ivan_Ivanov#123456789" , reply_markup=keyboard) await OrderAddUser.waiting_for_enter_activision_id.set()
async def get(message: types.Message): if message.text == "Поиск свободного времени": cancel_key = types.ReplyKeyboardMarkup(resize_keyboard=True) cancel_key.add(types.KeyboardButton("⬅ Назад")) await message.answer("Выберите нужный вариант", reply_markup=cancel_key) masters = r.masters() key = types.InlineKeyboardMarkup() for master in masters: key.add( types.InlineKeyboardButton(masters[master], callback_data=master)) await message.answer("Выберите специалиста", reply_markup=key) await Form.master.set() elif message.text == "Список мониторинга": await monitor_list(message) elif message.text == "⬅ Назад": key = start_button() await message.answer("Отменено, можете начать новый поиск", reply_markup=key) elif re.search(r"^/\d+$", message.text): conn = mysql.connector.connect(host=c.host, user=c.user, passwd=c.password, database=c.db) cursor = conn.cursor(buffered=True) existsQuery = "SELECT EXISTS (SELECT ID FROM users WHERE ID=(%s) AND user_id=(%s))" deleteQuery = "DELETE FROM users WHERE ID=(%s)" cursor.executemany(existsQuery, [(message.text[1:], message.chat.id)]) exist = cursor.fetchone()[0] if exist == 0: await message.reply("Неправильный номер записи!") conn.close() return cursor.execute(deleteQuery, [message.text[1:]]) conn.commit() conn.close() await message.answer("Мониторинг успешно удалён!")
async def buttons_cmd(message: types.Message): user = message.from_user chat = message.chat args = message.get_args() chats: dict = ... # your db data: list = chats[chat.id] if chat.type == "private": return await message.answer("I only work in chat") markup = types.ReplyKeyboardMarkup(row_width=10) try: check_user = await chat.get_member(user.id) if check_user.status == "creator" or user.id in data: rn = int(args.split()[0]) text = args.split(maxsplit=1)[1] b = types.KeyboardButton(text) if rn >= 11: return await message.reply("<b>RANGE</b> must be from 1 to 10") for _ in range(rn): markup.add(b, b, b, b, b, b, b, b, b, b) return await message.reply("Done!", reply_markup=markup) except (IndexError, ValueError): try: b = types.KeyboardButton(args or "No arguments.") for _ in range(10): markup.add(b, b, b, b, b, b, b, b, b, b) return await message.reply("Done!", reply_markup=markup) except Exception as e: return await message.reply(f"Error: {e}") except Exception as e: return await message.reply(f"Error: {e}")
async def lightbringers(message: types.Message): markup = types.ReplyKeyboardMarkup(resize_keyboard=True, row_width=5) item1 = types.KeyboardButton("Люций") item2 = types.KeyboardButton("Белинда") item3 = types.KeyboardButton("Рован") item4 = types.KeyboardButton("Эстрильда") item5 = types.KeyboardButton("Райна") item6 = types.KeyboardButton("Фокс") item7 = types.KeyboardButton("Тэйн") item8 = types.KeyboardButton("Хендрик") item9 = types.KeyboardButton("Гвинет") item10 = types.KeyboardButton("Розалина") item11 = types.KeyboardButton("Сесилия", ) item12 = types.KeyboardButton("Ригби") item13 = types.KeyboardButton("Оскар") back = types.KeyboardButton("Назад") markup.add(item1, item2, item3, item4, item5, item6, item7, item8, item9, item10, item11, item12, item13, back) await bot.send_message(message.chat.id, "Герои фракции Носители света", parse_mode='html', reply_markup=markup)
def get_buttons(commands): commands_kw = {} if commands: if commands.type == ButtonsTypes.keyboard: keyboard_markup = types.ReplyKeyboardMarkup(resize_keyboard=True) for row in commands: keyboard_markup.row( *[types.KeyboardButton(text) for text in row]) commands_kw = {"reply_markup": keyboard_markup} elif commands.type == ButtonsTypes.inline: inline_markup = types.InlineKeyboardMarkup(resize_keyboard=True) for row in commands: inline_markup.row(*[ types.InlineKeyboardButton(text, callback_data=command) for text, command in row ]) commands_kw = {"reply_markup": inline_markup} elif commands is False: commands_kw = {"reply_markup": ReplyKeyboardRemove()} return commands_kw
async def thugs(message: types.Message): markup = types.ReplyKeyboardMarkup(resize_keyboard=True, row_width=5) item1 = types.KeyboardButton("Брутус") item2 = types.KeyboardButton("Хасос") item3 = types.KeyboardButton("Вурк") item4 = types.KeyboardButton("Нумису") item5 = types.KeyboardButton("Скрег") item6 = types.KeyboardButton("Варек") item7 = types.KeyboardButton("Антандра") item8 = types.KeyboardButton("Сафия") item9 = types.KeyboardButton("Сатрана") item10 = types.KeyboardButton("Тайдус") item11 = types.KeyboardButton("Скриат", ) item12 = types.KeyboardButton("Аноки") item13 = types.KeyboardButton("Дрез") back = types.KeyboardButton("Назад") markup.add(item1, item2, item3, item4, item5, item6, item7, item8, item9, item10, item11, item12, item13, back) await bot.send_message(message.chat.id, "Герои фракции Громилы", parse_mode='html', reply_markup=markup)
async def check(): global num while True: f = open('text.txt', 'r+', encoding='utf8') text = [str(i) for i in f.read().split('|')] f.close() if text[0] == 'Bot__admin': open('text.txt', 'w').close() num = int(text[1]) # главная функия диалога markup = types.ReplyKeyboardMarkup( row_width=1, one_time_keyboard=True) # создание клавиатуры item1 = types.KeyboardButton(bot_admin[num][0][0]) item2 = types.KeyboardButton(bot_admin[num][1][0]) markup.add(item1, item2) # добовляем эелементы в клавиатуру await bot.send_message(config.ID_PERSON, text[2], reply_markup=markup) await asyncio.sleep(1)
def settingsMarkup(user: User): data = db.getCurrencyList() markup = types.ReplyKeyboardMarkup(resize_keyboard=True, one_time_keyboard=True) backButton = types.KeyboardButton('Назад ⬅') if user.location is None: mainCity = types.KeyboardButton( f'Указать основной населенный пункт для погоды') else: mainCity = types.KeyboardButton( f'Населенный пункт для погоды - {user.getMainCity()}') mainCurrency = types.KeyboardButton( f"Основная валюта - {user.currency} {data[user.currency]['Emoji']}") dayForShow = types.KeyboardButton( f'Количество дней для вывода курса: {user.dayForShow}') currencyList = types.KeyboardButton( f'Список валют в главном меню: {user.getUsedCurrency()}') markup.add(backButton) markup.add(mainCurrency) markup.add(mainCity) markup.add(dayForShow) markup.add(currencyList) if user.notify is None: markup.add( types.KeyboardButton('Указать время для отправки уведомлений')) else: markup.add(types.KeyboardButton(f"Время уведомлений: {user.notify}"), types.KeyboardButton('Отключить уведомления')) if user.id in ADMINS: markup.add( types.KeyboardButton(f'Количетсво уникальных пользователей - ' f'{getUsersMarkup(db, returnNumber=True)}')) return markup
async def question_and_multiple_followers(message: types.Message): await asyncio.sleep(3) cur_mes = bot_server.get_current_message(message.chat.id) # все варианты ответов переводим в нижний регистр options_answer = [x.lower() for x in cur_mes['options_answer']] # проверяем чтобы пользователь ввел # существующий вариант ответа if message.text.lower() in options_answer: bot_server.set_answer_user(message.chat.id, cur_mes['id'], message.text) if cur_mes['delay'] > 10: await bot.send_message(message.chat.id, "Пожалуйста, немного подождите") await asyncio.sleep(cur_mes['delay']) # в таблице БД пользователей указан номер сообщения, # которое для пользователя является текущим # bot_server.get_next_fullmessage принимает номер # текущего сообщения и устанавливает в БД, что # теперь текущим сообщением становится # следующее сообщение, то есть потомок текущего # сообщения, если потомок не один # то он устанавливается исходя из ответа # на текущее сообщение bot_server.get_next_fullmessage(message.chat.id, cur_mes['id'], message.text) await checking_message(message.chat.id) else: keyboard = types.ReplyKeyboardMarkup(resize_keyboard=True, one_time_keyboard=True) buttons = cur_mes['options_answer'] keyboard.add(*buttons) await bot.send_message(message.chat.id, "Выбран не существующий вариант," " попробуйте ещё раз.", reply_markup=keyboard)
async def start(message: types.Message): s = message.text s = s.split(' ', 1) if len(s) != 1: await idd(message, tags='id:' + s[1]) else: try: keyboard_markup = types.ReplyKeyboardMarkup(row_width=1) btns_text = ('Anime', 'Uncensored (18+)', 'Hentai (18+)') keyboard_markup.row(*(types.KeyboardButton(text) for text in btns_text)) btns_text = ('Wallpaper', 'Ecchi (18+)', 'Yuri (18+)') keyboard_markup.row(*(types.KeyboardButton(text) for text in btns_text)) btns_text = ('Loli (18+)', 'Neko') keyboard_markup.row(*(types.KeyboardButton(text) for text in btns_text)) await message.reply( "Yoo!\nHy there ! I am your personal assistant in the anime world! Yoroshiku onegaishimasu!\n\nUse the keyboard below to navigate the menu.\n\nDeveloper: @RikonAsw", reply_markup=keyboard_markup) stick = random.randint(0, len(stickers) - 1) await message.answer_sticker(sticker=stickers[stick]) except Exception: traceback.print_exc()
async def start(message: types.Message): s = message.text s = s.split(' ', 1) if len(s) != 1: await idd(message, tags='id:' + s[1]) else: try: keyboard_markup = types.ReplyKeyboardMarkup(row_width=1) btns_text = ('Anime', 'Uncensored (18+)', 'Hentai (18+)') keyboard_markup.row(*(types.KeyboardButton(text) for text in btns_text)) btns_text = ('Wallpaper', 'Ecchi (18+)', 'Yuri (18+)') keyboard_markup.row(*(types.KeyboardButton(text) for text in btns_text)) btns_text = ('Loli (18+)', 'Neko') keyboard_markup.row(*(types.KeyboardButton(text) for text in btns_text)) await message.reply( "𝙔𝙊𝙊!\n𝖬𝖸 𝖲𝖤𝖫𝖥 𝖢𝖮𝖥𝖥𝖨𝖭 𝖷 𝖠𝖭𝖨𝖬𝖤 𝖡𝖮𝖳! 𝖨 𝖠𝖬 𝖸𝖮𝖴𝖱 𝖯𝖤𝖱𝖲𝖮𝖭𝖠𝖫 𝖠𝖲𝖲𝖨𝖲𝖳𝖠𝖭𝖳 𝖨𝖭 𝖠𝖭𝖨𝖬𝖤 𝖶𝖮𝖱𝖫𝖣! 𝙋𝙊𝙒𝙀𝙍𝙀𝘿 𝘽𝙔 𝘾𝙊𝙁𝙁𝙄𝙉 𝙓\n\n𝚄𝚂𝙴 𝚃𝙷𝙴 𝙺𝙴𝚈𝙱𝙾𝙰𝚁𝙳 𝙱𝙴𝙻𝙾𝚆 𝚃𝙾 𝙽𝙰𝚅𝙸𝙶𝙰𝚃𝙴 𝚃𝙷𝙴 𝙼𝙴𝙽𝚄.\n\nSᴜᴘᴘᴏʀᴛ Gʀᴏᴜᴘ: @CoffinXsupport", reply_markup=keyboard_markup) stick = random.randint(0, len(stickers) - 1) await message.answer_sticker(sticker=stickers[stick]) except Exception: traceback.print_exc()
async def start_search_deletion(message: types.Message): """Start search deletion conversation.""" exisiting_searches = db_aps.get_user_existing_searches(message.chat.id) if not exisiting_searches: await message.answer(phrases.no_searches_found) bot_logger.debug( f'Got delete request from user ({message.chat.id}) with no searches' ) return text = phrases.search_deletion keyboard = types.ReplyKeyboardMarkup(resize_keyboard=True, one_time_keyboard=True) for search_number, search_url in sorted(exisiting_searches.items()): text += dedent(f'''\ {search_number}-й поиск: {search_url}\n ''') keyboard.insert(types.KeyboardButton(search_number)) text += phrases.send_cancel await DelSearch.waiting_search_number.set() await message.answer(text, reply_markup=keyboard, disable_web_page_preview=True) bot_logger.debug(f'Start search deletion for {message.chat.id}')
async def message_handler(message: types.Message, state: FSMContext): if await _back_client(message, state): return data = await state.get_data() if message.text == Buttons.done: price = get_price(data) key = types.ReplyKeyboardMarkup(resize_keyboard=True) key.add(Buttons.accept) key.add(Buttons.support) key.add(Buttons.back) await state.update_data({'price': price}) await NewOrder.accepting.set() await message.answer( f"Our price for your order is ${price}. If you like it just click accept! " "You won't have to pay until one of our tutors accepts your order.", reply_markup=key) return elif message.text: if len(message.text) > 500: await message.answer("Too long message, please try again") return if len(str(data.get('add_text'))) + len(message.text) > 500: await message.answer( "The text that has already been sent is too long") return await state.update_data({'add_text': message.text}) elif message.photo: if message.caption: if len(str(data.get('add_text'))) + len(message.caption) > 500: await message.answer( "The text that has already been sent is too long") else: await state.update_data({'add_text': message.caption}) await state.update_data({'add_photo': message.photo[-1].file_id}) elif message.document: await state.update_data({'add_document': message.document.file_id})
async def start_search_deletion(message: types.Message): """Start search deletion conversation.""" exisiting_searches = db_aps.get_user_existing_searches(message.chat.id) if not exisiting_searches: await message.answer('У вас нет запущенных поисков') bot_logger.debug( f'Got delete request from user ({message.chat.id}) with no searches' ) return text = 'Вот список запущенных поисков.\nВыбери номер поиска, который хочешь удалить:\n\n' keyboard = types.ReplyKeyboardMarkup(resize_keyboard=True, one_time_keyboard=True) for search_number, search_url in exisiting_searches.items(): text += dedent(f'''\ {search_number}-й поиск: {search_url}\n ''') keyboard.insert(types.KeyboardButton(search_number)) text += 'Отправь /cancel, чтобы отменить удаление поиска' await DelSearch.waiting_search_number.set() await message.answer(text, reply_markup=keyboard, disable_web_page_preview=True) bot_logger.debug(f'Start search deletion for {message.chat.id}')
async def remove_audio_sample_message(call: types.CallbackQuery, callback_data: dict, state: FSMContext): folder_id = int(callback_data['folder_id']) folder_info = db.select_folder(folder_id) folder_samples = db.select_folder_samples(folder_id) if len(folder_samples) == 0: await call.answer(f'В папке "{folder_info[1]}" нету аудио сэмлов', True) return keyboard = types.ReplyKeyboardMarkup(resize_keyboard=True, one_time_keyboard=True) keyboard.add("<<< Отмена >>>") for sample in folder_samples: keyboard.add(sample[1]) await call.message.delete() await call.message.answer("Выберите аудио сэмпл который хотите удалить:", reply_markup=keyboard) await RemoveSample.step_1.set() await state.update_data({"folder_id": folder_id}) await call.answer()
async def lang_callback_handler( query: types.CallbackQuery, callback_data: typing.Dict[str, str], user: UserRepository, _: dict, ): from bot.common.lang import texts lang_id = int(callback_data["id"]) lang_name = Lang(lang_id).name await user.update_user_lang(query.from_user.id, lang_id) _ = texts[lang_name] keyboard_markup = types.ReplyKeyboardMarkup(row_width=2, resize_keyboard=True) btns_text = (_['cabinet'], _['faq']) keyboard_markup.row(*(types.KeyboardButton(text) for text in btns_text)) btns_text = [_['setting']] #, _['feedback_button'] keyboard_markup.row(*(types.KeyboardButton(text) for text in btns_text)) await query.message.delete() await query.message.answer(_['lang_changed'], reply_markup=keyboard_markup)
async def start_message(message: types.Message): #Кнопки markup = types.ReplyKeyboardMarkup(resize_keyboard=True, selective=True) ###markup = types.ReplyKeyboardMarkup(row_width=2) itembtn4 = types.KeyboardButton('/start') itembtn5 = types.KeyboardButton('/get_file') itembtn6 = types.KeyboardButton('/get_log') ###markup.add(itembtn1, itembtn2, itembtn3 ,itembtn4,itembtn5,itembtn6) markup.add(itembtn4, itembtn5, itembtn6) tg_nick = message.from_user.username await message.answer( 'Привет, бот для синхронизации файлов.' + '\n👉 /get_file через пробел указываем название желаемого файла' + '\n👉 что бы сохранить документ,просто отправь его мне. В данный момент бот принимает только файлы с разрешением .py' + '\n👉 /get_log возвращает лог', reply_markup=markup) if message.from_user.id == id_admin: await message.answer( 'ооо,какие люди в нашей деревне,проходи садись,устраивайся поудобней.' + '\n /get_file,/get_log') else: await message.answer('Бот на обслуживании , сорян...') print('Старт от: ', str(message.from_user.id))
async def cmd_start(message: types.Message): """ Conversation's entry point """ state = dp.current_state(chat=message.chat.id, user=message.from_user.id) await state.set_state(NAME) new_user = User( **{ "chat_id": message.chat.id, "is_active": True, **message.chat.to_python(), **message.from_user.to_python() }) res = await new_user.save(insert=True, conflict="update") log.debug(f"Save user {res}") reply_markup = types.ReplyKeyboardMarkup( [["Добавить сериал", "Список сериалов"]], resize_keyboard=True) await bot.send_message( message.chat.id, emojize( "Привет! Давай поищем твои любимые сериалы!:smile:\nВведи название:" ), reply_markup=reply_markup)
def get_next_question(tg_user_id: int, answer_type: str) -> View: """ Возвращает View со следующим вопросом для пользователя """ try: with Actions() as act: question, current_question_number, questions_count = act.get_next_test( tg_user_id) except NoNewQuestionsException: return View("В базе не осталось новых вопросов") if answer_type == AnswerTypes.VOICE.value: call_to_action = "голосом" else: call_to_action = "текстом" answer_text = render_message( get_template("20_question"), question=question.text_question.strip(), question_category=question.question_category.strip(), call_to_action=call_to_action, current_question_number=current_question_number, questions_count=questions_count, ) row_buttons = [ aiotypes.KeyboardButton("🤷♂️ Не понял вопрос"), aiotypes.KeyboardButton("🙅🏻♀️ Не знаю ответ"), ] reply_kb = aiotypes.ReplyKeyboardMarkup(one_time_keyboard=True, resize_keyboard=True) reply_kb.row(*row_buttons) return View(answer_text, reply_kb, question.id)