async def get_updates(res):
    ID, user_id, date, time_1, time_2, master, service, master_id, service_id = \
        res[0], res[1], res[2], res[3], res[4], res[5], res[6], res[7], res[8]
    get_dates = r.get_date(service_id, master_id)
    if not get_dates:
        return
    dates = []
    for datee in get_dates:
        times = r.get_time(datee, service_id, master_id)
        for time in times:
            dates.append(time[:-3])

    conn = mysql.connector.connect(host=c.host,
                                   user=c.user,
                                   passwd=c.password,
                                   database=c.db)
    cursor = conn.cursor(buffered=True)
    deleteQuery = "DELETE FROM users WHERE ID=(%s)"
    text = "*Доступна запись!*\n\n"
    send = False
    for datee in dates:
        for hour in range(time_1, time_2 + 1):
            if date == datee[:10] and hour == int(datee[-5:-3]):
                tm, td, tt = datee[5:7], datee[8:10], datee[11:16]
                text += f"*Дата:* `{td}.{tm}` в `{tt}`\n"
                cursor.execute(deleteQuery, [ID])
                conn.commit()
                send = True
    conn.close()
    key = types.InlineKeyboardMarkup()
    key.add(
        types.InlineKeyboardButton(
            "Онлайн-запись",
            f"https://beauty.dikidi.net/ru/record/{c.service}"))
    if send:
        try:
            await bot.send_message(
                user_id,
                f"{text}\n*Специалист:* {master}\n*Услуга:* {service}\n\n",
                parse_mode="Markdown",
                reply_markup=key)
        except utils.exceptions.BotBlocked:
            pass
Exemple #2
0
async def cmd_auth(message: types.Message, state: FSMContext):
    await message.answer("Расскажи о себе",
                         reply_markup=types.ReplyKeyboardRemove())
    await message.answer('Какой кофе любишь?')
    await AuthState.coffee_type.set()
    coffees = [
        'Ristretto', 'Espresso', 'Americano', 'Double_espresso', 'Kapucino',
        'Latte', 'Kakao', 'Marshmello', 'Закончить выбор'
    ]
    btns = list()
    media = types.InlineKeyboardMarkup(row_width=1)
    for coffee in coffees:
        btns.append(
            types.InlineKeyboardButton(
                "{}".format(coffee),
                callback_data='add_coffee_{}'.format(coffee)))
    media.add(*btns)
    await message.answer('Выберите какие виды вы педпочитаете:',
                         reply_markup=media)
Exemple #3
0
async def create_folder_step_2_message(message: types.Message,
                                       state: FSMContext):
    async with state.proxy() as user_data:
        user_data['folder_name'] = message.text.replace('\n', ' ')

    keyboard_markup = types.InlineKeyboardMarkup()
    back_btn = types.InlineKeyboardButton('«      ',
                                          callback_data='folders_list')
    keyboard_markup.row(back_btn)

    # Проверяем количество символов в названии папки
    if len(user_data['folder_name']) >= 20:
        await message.reply('Название папки превышает 20 символов',
                            reply_markup=keyboard_markup)
        return

    # Ищем название данной папки в БД
    if user_data['folder_name'].lower() in [
            x[1].lower() for x in db.select_user_folders(message.chat.id)
    ]:
        await message.reply('Данная папка уже существует! Введите другое имя',
                            reply_markup=keyboard_markup)
        return

    # Проверяем название папки на недопустимые символы
    # if check_string_for_except_chars(user_data['folder_name']):
    #     await message.reply(f'Название папки "{user_data["folder_name"]}" содержит недопустимые символы: {check_string_for_except_chars(user_data["folder_name"])}', reply_markup=keyboard_markup)
    #     return

    await state.finish()

    path_list = path(message.chat.id, user_data['folder_name'])
    os.makedirs(path_list.tmp_audio_samples())
    os.makedirs(path_list.processed_audio_samples())
    os.makedirs(path_list.tmp_query_audio())
    os.makedirs(path_list.processed_query_audio())
    os.makedirs(path_list.fingerprint_db_dir_path(), exist_ok=True)

    db.create_folder(message.chat.id, user_data['folder_name'])

    await message.reply(f'Папка "{user_data["folder_name"]}" создана!')
    await folder_list_menu_message(message, 'start')
Exemple #4
0
async def make_post(message, data):
    key = types.InlineKeyboardMarkup()

    first_name = str(message.from_user.first_name).replace('_', '\\_').replace(
        '*', '\\*').replace('`', '\\`').replace('[', '\\[')
    username = str(message.from_user.username).replace('_', '\\_').replace(
        '*', '\\*').replace('`', '\\`').replace('[', '\\[')
    comm = str(data['comm']).replace('_', '\\_').replace('*', '\\*').replace(
        '`', '\\`').replace('[', '\\[')
    await bot.send_photo(
        c.admin1,
        data['pay_photo'],
        f"Оплата: [{first_name}](tg://user?id={message.from_user.id})\n"
        f"@{username}\n\nКомментарий: {comm}",
        parse_mode=types.ParseMode.MARKDOWN)
    if data['photo']:
        if len(data['photo']) == 1:
            key.add(
                types.InlineKeyboardButton("Опубликовать",
                                           callback_data="post"))
            await bot.send_photo(c.admin1,
                                 data['photo'][0],
                                 caption=data['text'],
                                 reply_markup=key)
        else:
            key.add(
                types.InlineKeyboardButton("Опубликовать",
                                           callback_data="post_group"))
            photos = [types.InputMediaPhoto(data['photo'][0], caption=data['text'])] \
                + [types.InputMediaPhoto(x) for x in data['photo'][1:]]
            m = await bot.send_media_group(c.admin1, photos)
            await bot.send_message(
                c.admin1,
                f'{data["text"]}\n\n{{"photo_group": {[x.photo[-1].file_id for x in m]}}}',
                reply_markup=key)
    elif data['video']:
        key.add(
            types.InlineKeyboardButton("Опубликовать", callback_data="post"))
        await bot.send_video(c.admin1,
                             data['video'],
                             caption=data['text'],
                             reply_markup=key)
Exemple #5
0
    async def search_books_by_series(cls, msg: Message, series_id: int, page: int, after_download: bool = False):
        await cls.bot.send_chat_action(msg.chat.id, 'typing')

        settings = await SettingsDB.get(msg.chat.id)

        search_result = await SequenceAPI.get_by_id(series_id, settings.get(), ELEMENTS_ON_PAGE, page)

        if search_result is None:
            await cls.bot.edit_message_text('Произошла ошибка :( Попробуйте позже', 
                                            chat_id=msg.chat.id, message_id=msg.message_id)
            return

        books = search_result.books
        if not books:
            return await cls.try_reply_or_send_message(msg.chat.id, 'Ошибка! Книги в серии не найдены!',
                                                       reply_to_message_id=msg.message_id)
        page_max = search_result.count // ELEMENTS_ON_PAGE + (1 if search_result.count % ELEMENTS_ON_PAGE != 0 else 0)
        msg_text = f"<b>{search_result.name}:</b>\n\n" + \
                   '\n\n\n'.join([book.to_send_book for book in books]
                           ) + f'\n\n<code>Страница {page}/{page_max}</code>'

        if not msg.reply_to_message:
            keyboard = await get_keyboard(1, page_max, 'bs') 
        else:
            keyboard = await get_keyboard(page, page_max, 'bs')

        if keyboard is None:
            keyboard = types.InlineKeyboardMarkup()
        
        if not after_download:
            keyboard.row(types.InlineKeyboardButton("⬇️ Скачать серию", callback_data=f"download_c_{series_id}"))
        else:
            keyboard.row(types.InlineKeyboardButton("✅ Книги отправляются!", 
                                                    callback_data=f"download_c_{series_id}"))

        if not msg.reply_to_message:
            await cls.try_reply_or_send_message(msg.chat.id, msg_text, parse_mode='HTML', 
                                                reply_markup=keyboard,
                                                reply_to_message_id=msg.message_id)
        else:
            await cls.bot.edit_message_text(msg_text, msg.chat.id, msg.message_id, parse_mode='HTML',
                                            reply_markup=keyboard)
Exemple #6
0
async def start_game(callback_query: types.CallbackQuery):
    """
    В зависимости от нажатой кнопки в функции greetings здесь запускается
    одна из игр, определенных как машины состояний в словаре GAMES
    :param callback_query:
    :return:
    """

    # Считываем из callback код игры и язык, если мультиязычность включена (IS_MULTILINGUAL_MODE)
    language = 'en'
    if IS_MULTILINGUAL_MODE:
        language = callback_query.data[5:7]
        code_of_game = callback_query.data[len('lang_xx' +
                                               CALLBACK_SELECT_GAME):]
    else:
        code_of_game = callback_query.data[len(CALLBACK_SELECT_GAME):]

    # Сохраняем в глобальный словарь код игры
    all_codes_of_game[callback_query.from_user.id] = code_of_game

    # Сохраняем в глобальный словарь язык игры
    language_of_games[callback_query.from_user.id] = language

    # Скрываем кнопки после выбора игры
    await bot.delete_message(chat_id=callback_query.message.chat.id,
                             message_id=callback_query.message.message_id)

    await callback_query.message.reply(
        "You choose the '{0}' game on {1} language!".format(
            GAMES_NAMES[code_of_game], LANGUAGES[language]),
        reply=False)

    conditional_text_keyboard = types.InlineKeyboardMarkup(
        resize_keyboard=True, one_time_keyboard=True, reply=False)
    conditional_text_keyboard.add(
        types.InlineKeyboardButton('Yes', callback_data='conditional_1'),
        types.InlineKeyboardButton('No', callback_data='conditional_0'))

    await callback_query.message.reply(
        "Would you like to write some initial text?",
        reply_markup=conditional_text_keyboard,
        reply=False)
Exemple #7
0
async def change_coins_for_account_callback_handler(
    query: types.CallbackQuery,
    callback_data: typing.Dict[str, str],
    user: UserRepository,
    _: dict,
):
    keyboard_markup = types.InlineKeyboardMarkup(row_width=2)

    btn_list = []

    for coin in await user.get_coins(query.from_user.id, ):
        if coin.is_enabled:
            btn_list.append(
                types.InlineKeyboardButton(
                    f"{Coin(coin.coin_id).name} ✅",
                    callback_data=coin_account_cb.new(id=coin.coin_id,
                                                      action="off"),
                ), )
        else:
            btn_list.append(
                types.InlineKeyboardButton(
                    f"{Coin(coin.coin_id).name} ❌",
                    callback_data=coin_account_cb.new(id=coin.coin_id,
                                                      action="on"),
                ), )

    for i in grouper(2, btn_list):
        keyboard_markup.add(*i)
    '''keyboard_markup.add(
        types.InlineKeyboardButton(
            _["back_to_account_list_button"],
            callback_data=menu_cb.new(
                id="_", type="menu", action="main_menu"
            ),
        ),
    )'''

    await query.message.edit_text(
        _["coin_list_descr"],
        reply_markup=keyboard_markup,
    )
    await query.answer()
Exemple #8
0
async def text_message(msg: types.Message):
    if msg.text and not msg.text.startswith("/"):
        if msg.text.lower() == "привет":
            await bot.send_message(msg.from_user.id, "Привет!")
        elif msg.text.lower() == "как дела?":
            await bot.send_message(msg.from_user.id, "Хорошо! А у тебя как?")
        elif msg.text.lower() == "как тебя зовут?" or msg.text.lower(
        ) == "как тебя зовут":
            await bot.send_message(msg.from_user.id, "quazun")
        elif msg.text.lower() == "фото":
            await bot.send_photo(msg.from_user.id, photo)
        elif msg.text.lower() == "текст":
            await msg.answer("обычный, *жирный* , _курсив_ , `ошибка`",
                             parse_mode="Markdown")
        elif msg.text.lower() == "эмодзи":
            await msg.reply(emojize(":fire:") + emojize(":ghost:"))
        elif msg.text.lower() == "кто твой папочка" or msg.text.lower(
        ) == "кто твой папочка?":
            button = types.InlineKeyboardButton(
                text="Папочка всех ботов", url="tg://resolve?domain=quazun")
            keyboard = types.InlineKeyboardMarkup()
            keyboard.add(button)
            await msg.answer("Мой батька:", reply_markup=keyboard)
        elif msg.text.lower() == "стикер":
            await bot.send_sticker(
                msg.from_user.id,
                "CAACAgQAAxkBAAIBL2BXOUXucU8oG9GXxB28tyd5TospAAKFAwACyt9oBeyJQn52NhMoHgQ"
            )
        elif msg.text.lower() == "текст2":
            await msg.answer(fmt.text(fmt.text(fmt.hunderline("подчеркнутый")),
                                      fmt.text(
                                          fmt.hstrikethrough("зачеркнутый")),
                                      sep="\n"),
                             parse_mode="HTML")
        else:
            await bot.send_message(
                msg.from_user.id,
                msg.from_user.first_name + ", я тебя непонял")
    else:
        await bot.send_message(msg.from_user.id,
                               "`У меня нет такой команды`",
                               parse_mode="Markdown")
Exemple #9
0
    async def send_tutorial(self, query: types.InlineQuery) -> str:
        """Gets all the important data and sends messages to user"""

        all_messages = [
            await self.get_tutorial_description_message, await
            self.get_test_record, await self.get_record_user_name_review, await
            self.get_record_service_name, await self.record_description_review,
            await self.record_time_review, await self.record_phone_review,
            await self.answer_review
        ]

        for message in all_messages:
            if message == await self.get_test_record:
                markup = types.InlineKeyboardMarkup()
                button1 = types.InlineKeyboardButton("Указать как выполненый!",
                                                     callback_data="tutorial")
                markup.add(button1)
                await query.message.answer(message, reply_markup=markup)
            else:
                await query.message.answer(message)
Exemple #10
0
async def call_confirm(call: types.CallbackQuery):
    try:
        if call.data == 'confirm':
            d2 = today.strftime("%B, %Y")
            await bot.send_message(call.message.chat.id, CONFIRMMESSAGE_ALERT)
            markup = types.InlineKeyboardMarkup()
            b = types.InlineKeyboardButton(ACCEPTBUTTONTEXT, callback_data='accept')
            markup.add(b)
            await bot.send_message(GROUP_ID, GROUP_SEND_MESSAGE.format(username=user_info['username'],
                                                                                       quantity=user_info['quantity'],
                                                                                       price=user_info['price'],
                                                                                       date=user_info['date'],
                                                                                       todey=d2,
                                                                                       latitude=user_info['latitude'],
                                                                                       longitude=user_info['longitude']),
                                   reply_markup=markup)
            await dp.storage.close()

    except Exception as e:
        print(repr(e))
Exemple #11
0
async def count_users(message):
    if message.chat.type == 'private':
        st = Switch(db)
        status = st.status()
        if message.text == 'Кого я добавил❓':
            if status == True:
                count = Get_info(db)
                c = count.users_count(message.chat.id)
                inline_m = types.InlineKeyboardMarkup(row_width=1)
                list_button = types.InlineKeyboardButton("Отобразить список",
                                                         callback_data='list')
                inline_m.add(list_button)
                tick_list = Get_info(db)
                tickets_list = tick_list.user_tikets(message.chat.id)
                await message.answer(
                    f"{message.from_user.full_name}, Вы добавили {c} человек(а).\nВаши номера: {tickets_list}",
                    reply_markup=inline_m)

            elif status == False:
                await message.answer("На данный момент конкурса нет")
Exemple #12
0
def inline(array, callback=None):
    array = to2Array(array)
    if callback != None:
        callback = to2Array(callback)
    else:
        callback = array

    # print(array, callback)
    max_len = len(max(array, key=len))
    keyboard = types.InlineKeyboardMarkup(row_width=max_len)
    for i, line in enumerate(array):
        buttons = []
        for j, text in enumerate(line):
            button = types.InlineKeyboardButton(text=text,
                                                callback_data=callback[i][j])
            buttons.append(button)
        # print("new line")
        keyboard.add(*buttons)

    return keyboard
Exemple #13
0
async def notify_users_about_new_wod_result(user_id, wod) -> None:
    diff = datetime.now().date() - wod.wod_day

    if diff.days < 2:
        author = await user_db.get_user(user_id)
        name = f'{author.name} {author.surname}' if author.surname else author.name
        msg = f'{name} записал результат за {wod.title}'

        wod_results = await wod_result_db.get_wod_results(wod.id)
        for wr in wod_results:
            if wr.user_id == user_id:
                continue

            st = dp.current_state(chat=wr.user_id, user=wr.user_id)
            await st.update_data(view_wod_id=wod.id)

            reply_markup = types.InlineKeyboardMarkup()
            reply_markup.add(types.InlineKeyboardButton(BTN_VIEW_RESULT, callback_data=BTN_VIEW_RESULT))

            await bot.send_message(wr.user_id, msg, reply_markup=reply_markup)
Exemple #14
0
    async def start_setting_default_mode(c):
        user_db = ForwardsToTextUser(c.from_user.id)
        anonimous_mode_button_text = 'Анонимный' if not user_db.default_mode == 'anonimous' else '☑ Анонимный'
        public_mode_button_text = 'Публичный' if not user_db.default_mode == 'public' else '☑ Публичный'
        kb = tg_types.InlineKeyboardMarkup()
        anonimous_mode_button = tg_types.InlineKeyboardButton(
            anonimous_mode_button_text,
            callback_data='fwd_to_text settings set_default_mode anonimous')
        public_mode_button = tg_types.InlineKeyboardButton(
            public_mode_button_text,
            callback_data='fwd_to_text settings set_default_mode public')
        back_button = tg_types.InlineKeyboardButton(
            '🔙Назад', callback_data='fwd_to_text settings')
        kb.add(anonimous_mode_button, public_mode_button)
        kb.add(back_button)

        await bot.edit_message_text('Выберите режим по умолчанию',
                                    c.message.chat.id,
                                    c.message.message_id,
                                    reply_markup=kb)
Exemple #15
0
async def outside(exp):
    equip = packages.db.get_info(exp.id)
    key = types.InlineKeyboardMarkup()
    but_1 = types.InlineKeyboardButton(text='Надесь маску -5%',
                                       callback_data='Надеть маску')
    but_2 = types.InlineKeyboardButton(text='Помыть руки -2% ',
                                       callback_data='Помыть руки')
    but_3 = types.InlineKeyboardButton(text='Исследовать',
                                       callback_data='Исследовать')
    but_4 = types.InlineKeyboardButton(text='Вернуться', callback_data='back')
    but_5 = types.InlineKeyboardButton(text='Информация', callback_data='info')
    if exp.exploring is None:
        if equip['masked'] is False and exp.masks > 0:
            key.add(but_1)
        if (equip['washed_hands'] is False) and (exp.water >=
                                                 5) and (exp.medicines > 0):
            key.add(but_2)
    key.add(but_3)
    key.add(but_4, but_5)
    return key
Exemple #16
0
def generate_post_kboard(
        username: str, user_url: str,
        post_link: str, user_id: int) -> types.InlineKeyboardMarkup:
    common_buttons = [
        types.InlineKeyboardButton(text=username, url=user_url),
        types.InlineKeyboardButton(text="post link", url=post_link),
    ]
    admin_buttons = [
        types.InlineKeyboardButton(
            text="reddit", callback_data="reddit"),
        types.InlineKeyboardButton(text="delete", callback_data="delete"),
    ]

    post_kboard = types.InlineKeyboardMarkup(row_width=2)
    post_kboard.add(*common_buttons)

    if str(user_id) in config.admins:
        post_kboard.add(*admin_buttons)

    return post_kboard
Exemple #17
0
async def start_cmd_handler(message: types.Message):
    keyboard_markup = types.InlineKeyboardMarkup(row_width=3)
    # default row_width is 3, so here we can omit it actually
    # kept for clearness

    text_and_data = (
        ('Yes!', 'yes'),
        ('No!', 'no'),
    )
    # in real life for the callback_data the callback data factory should be used
    # here the raw string is used for the simplicity
    row_btns = (types.InlineKeyboardButton(text, callback_data=data) for text, data in text_and_data)

    keyboard_markup.row(*row_btns)
    keyboard_markup.add(
        # url buttons have no callback data
        types.InlineKeyboardButton('aiogram source', url='https://github.com/aiogram/aiogram'),
    )

    await message.reply("Hi!\nDo you love aiogram?", reply_markup=keyboard_markup)
Exemple #18
0
def generate_submission_info_kboard(submission) -> types.InlineKeyboardMarkup:
    buttons = [
        types.InlineKeyboardButton(
            text="link",
            url=f'{config.REDDIT_BASE_URL}{submission.permalink}',
        ),
        types.InlineKeyboardButton(
            text="crosspost",
            callback_data=redditor_cb.new(id=submission.id, action="crosspost"),
        ),
        types.InlineKeyboardButton(
            text="delete submission",
            callback_data=redditor_cb.new(id=submission.id, action="delete_submission"),
        ),
    ]

    submission_kboard = types.InlineKeyboardMarkup(row_width=1)
    submission_kboard.add(*buttons)

    return submission_kboard
Exemple #19
0
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_e = types.InlineKeyboardButton(text='Рассылка',
                                           callback_data='write_message')
        bat_j = types.InlineKeyboardButton(text='Скачать базу',
                                           callback_data='baza')
        bat_setin = types.InlineKeyboardButton(text='Настройка трафика',
                                               callback_data='settings')
        bat_modern = types.InlineKeyboardButton(text='Права администраторов',
                                                callback_data='but_adm')
        markup.add(bat_a, bat_e, bat_j)
        markup.add(bat_setin)
        markup.add(bat_modern)
        await bot.send_message(message.chat.id,
                               'Выполнен вход в админ панель',
                               reply_markup=markup)
Exemple #20
0
async def add_adm12(call: types.callback_query, state: FSMContext):
    markup = types.InlineKeyboardMarkup()
    bat_a = types.InlineKeyboardButton(text='ОТМЕНА', callback_data='otemena')
    markup.add(bat_a)

    q = await bot.send_message(
        call.message.chat.id,
        text=
        'Что бы изменить права текущего админа или добавить нового, вводи :\n\n'
        '@namechannel-@username-0\n'
        '<b>Вводи без пробелов!\n\n'
        '0 - Разрешено работать\n'
        '1 - Разрешено менять 1 канал\n'
        '2 - Разрешено менять 2 канала\n'
        '3 - Разрешено менять 3 канала\n\n'
        '9 - Удалить из админов</b>',
        parse_mode='html',
        reply_markup=markup)
    await state.update_data(mess1=q.message_id)
    await reg_admink.adm1.set()
Exemple #21
0
def format_post(post_id: str, post: dict) -> (str, types.InlineKeyboardMarkup):
    text = f"{md.hbold(post['title'])}\n" \
        f"{md.quote_html(post['body'])}\n" \
        f"\n" \
        f"Votes: {post['votes']}"

    markup = types.InlineKeyboardMarkup()
    markup.row(
        types.InlineKeyboardButton('👍',
                                   callback_data=posts_cb.new(id=post_id,
                                                              action='like')),
        types.InlineKeyboardButton('👎',
                                   callback_data=posts_cb.new(
                                       id=post_id, action='unlike')),
    )
    markup.add(
        types.InlineKeyboardButton('<< Back',
                                   callback_data=posts_cb.new(id='-',
                                                              action='list')))
    return text, markup
Exemple #22
0
async def manage_mods(user: types.User, state: FSMContext):
    await state.finish()
    mods = await db.get_role_users('moderator')
    kbd = types.InlineKeyboardMarkup()
    if not mods:
        content = tr(('admin', 'no_mods'))
    else:
        content = tr(('admin', 'mod_list')) + ':\n\n'
        for i, mod in enumerate(mods, 1):
            content += f'{i}. {mod.name}\n'
            kbd.insert(
                types.InlineKeyboardButton(
                    f'❌ {i} {mod.name}',
                    callback_data=MOD_REMOVE_CB.new(id=str(mod.id))))
        content += '\n' + tr(('admin', 'mod_help'))
    kbd.insert(
        types.InlineKeyboardButton(tr(('edit', 'cancel')),
                                   callback_data=MOD_REMOVE_CB.new(id='-')))
    await bot.send_message(user.id, content, reply_markup=kbd)
    await ModState.mod.set()
Exemple #23
0
def gen_dupe_markup(service, dupe_id):
    dupe_markup = types.InlineKeyboardMarkup()
    dupe_markup.row_width = 2
    dupe_markup.row(
        types.InlineKeyboardButton(
            text="Походу это дубликат",
            url="".join(["https://", service_db[service]['post_url'],
                         dupe_id])))
    dupe_markup.add(
        types.InlineKeyboardButton(
            emojize(":white_heavy_check_mark: Оставить"),
            callback_data=dupes_cb.new(service=service,
                                       dupe_id=dupe_id,
                                       action="allow")),
        types.InlineKeyboardButton(emojize(":cross_mark: Удалить"),
                                   callback_data=dupes_cb.new(
                                       service=service,
                                       dupe_id=dupe_id,
                                       action="delete")))
    return dupe_markup
Exemple #24
0
async def cat(message: types.Message):
    cat_url = get_random_cat_image_url()
    cat_gender = bool(random.getrandbits(1))
    variant_1, variant_2 = (
        "Правильно", "Не правильно :(") if cat_gender else ("Не правильно :(",
                                                            "Правильно")

    keyboard = types.InlineKeyboardMarkup()
    # keyboard.add(types.InlineKeyboardButton(text="😻", callback_data="counter|😻|0"))
    keyboard.add(
        types.InlineKeyboardButton(text="Кіт",
                                   callback_data=f'print|{variant_1}'))
    keyboard.add(
        types.InlineKeyboardButton(text="Кітесса",
                                   callback_data=f'print|{variant_2}'))
    await bot.send_photo(chat_id=message.chat.id,
                         reply_to_message_id=message.message_id,
                         caption='Кіт чи кітесса?',
                         photo=cat_url,
                         reply_markup=keyboard)
Exemple #25
0
async def edit_person_in_bd(person: Person, message: types.Message,
                            state: FSMContext):

    keyboard = types.ReplyKeyboardMarkup(resize_keyboard=True)
    full_text = profile_info(person)
    print('Будем редактировать - ', person)
    await message.answer(full_text, reply_markup=keyboard)

    text_and_data = [('Редактировать!', 'yes'), ('Отмена!', 'no')]
    row_btns = (types.InlineKeyboardButton(text, callback_data=data)
                for text, data in text_and_data)
    inline_kb1 = types.InlineKeyboardMarkup().add(*row_btns)
    await message.answer(f'Хотите начать редактирование данного пользователя?',
                         reply_markup=inline_kb1)

    # сохраняем данные... person
    # async with state.proxy() as data:
    #     data['person'] = person

    await OrderEditUser.step_2.set()
Exemple #26
0
async def cmd_test1(message: types.Message):
    if message.from_user.id in usersAllowed:

        await message.answer(f"Ваш ID: {message.from_user.id}")
        await message.answer('Hello my Master')

        buttons = [
            types.InlineKeyboardButton(
                text="Stop Nextcloud", callback_data='Action 1'),
            types.InlineKeyboardButton(
                text="Start Nextcloud", callback_data='Action 2')
        ]

        keyboard = types.InlineKeyboardMarkup()
        keyboard.add(*buttons)

        await message.answer("Select an Actions", reply_markup=keyboard)

    else:
        await message.reply('This is not for you')
Exemple #27
0
async def page_sport(message):
    auth = await authentication(message)
    if not auth: return
    answer = await api_request(message, path=c.api_sport)
    if answer is None: return

    with open(c.strings_file, encoding='utf-8') as f:
        strings = json.load(f)
    if not answer:
        await message.answer(strings[auth[mu.ResTypes.LANG]]['not_found'])
        return
    key = types.InlineKeyboardMarkup()
    for a in answer:
        key.add(
            types.InlineKeyboardButton(a['sport'],
                                       callback_data=set_callback(
                                           mu.CallbackFuncs.SPORT_TYPE,
                                           a['sportid'])))
    await message.answer(strings[auth[mu.ResTypes.LANG]]['page_sport'],
                         reply_markup=key)
Exemple #28
0
async def start_game_multilingual(callback_query: types.CallbackQuery):

    # Скрываем кнопки после выбора игры и пробрасываем в следующий хендлер где создается экземпляр класса игры
    await bot.edit_message_reply_markup(
        chat_id=callback_query.message.chat.id,
        message_id=callback_query.message.message_id)

    select_language_keyboard = types.InlineKeyboardMarkup(
        resize_keyboard=True, one_time_keyboard=True, reply=False)
    select_language_keyboard.add(
        types.InlineKeyboardButton('English',
                                   callback_data='lang_en' +
                                   callback_query.data),
        types.InlineKeyboardButton('Russian',
                                   callback_data='lang_ru' +
                                   callback_query.data))

    await callback_query.message.reply("On what language do you want to play?",
                                       reply_markup=select_language_keyboard,
                                       reply=False)
Exemple #29
0
async def profile(call: types.callback_query):
    s = requests.Session()
    s.headers['authorization'] = 'Bearer ' + QIWI_TOKEN
    parameters = {'rows': '50'}
    h = s.get('https://edge.qiwi.com/payment-history/v1/persons/' + QIWI_ACCOUNT + '/payments', params=parameters)
    req = json.loads(h.text)

    random_code = randint(0, 999999999)


    markup = types.InlineKeyboardMarkup()
    bat_a = types.InlineKeyboardButton(text='🔁 Проверить', callback_data='proverka_balans')
    bat_b = types.InlineKeyboardButton(text='❌ Отменить', callback_data='otmena_balans')
    markup.add(bat_a,bat_b)
    await bot.edit_message_text(chat_id=call.message.chat.id,message_id=call.message.message_id, text=
                    '⚠️ Пополнение баланса\n\n'
                    '🥝 Оплата киви:\n\n'
                    '👉 Номер  +79534501775\n'
                    f'👉 Коментарий {random_code}\n'
                    '👉 Сумма  от 1 до 15000 рублей',reply_markup=markup)
Exemple #30
0
async def edit_person_in_bd(db: DB, person: Person, message: types.Message,
                            state: FSMContext):

    keyboard = types.ReplyKeyboardMarkup(resize_keyboard=True)
    full_text = profile_info(person)
    print('Будем редактировать - ', person)
    await message.answer(full_text, reply_markup=keyboard)

    text_and_data = [('Редактировать!', 'yes'), ('Отмена!', 'отмена')]
    row_btns = (types.InlineKeyboardButton(text, callback_data=data)
                for text, data in text_and_data)
    inline_kb1 = types.InlineKeyboardMarkup().add(*row_btns)
    await message.answer(f'Хотите начать редактирование данного пользователя?',
                         reply_markup=inline_kb1)

    # state = await state.get_data()
    # print(state)
    # state = await state.update_data(db=db)
    await state.update_data(person=person)
    await OrderEditUser.step_2.set()  # Устанавливаем состояние step_2