Exemple #1
0
def site_res(admin=False):
    site_result = service.files().list(
        q=f'"{get_root()}" in parents',
        pageSize=10,
        fields="files(id,name, parents)").execute()
    sites = site_result.get('files', [])
    formatted_2d_list = [sites[x:x + 3] for x in range(0, len(sites), 3)]
    site_button = ReplyKeyboardMarkup(
        resize_keyboard=True,
        row_width=3,
        keyboard=[[KeyboardButton(text=x['name']) for x in itm]
                  for itm in formatted_2d_list])
    sites_dict = {site['name']: site['id'] for site in sites}
    service.close()
    if admin:
        site_button.row('Лог использования', 'Аварийно отключить бота')
        site_button.row('Обновить новые "шорткаты"')
    return site_button, sites_dict
def init_main_keyboard(user_data: dict):
    kb = ReplyKeyboardMarkup(resize_keyboard=True)
    if (DataKeys.ON_PROCESSING
            not in user_data) or not user_data[DataKeys.ON_PROCESSING]:
        if DataKeys.CONTENT_FILE_ID not in user_data:
            kb.add(KeyboardButton(CommandText.SET_CONTENT))
        else:
            kb.add(KeyboardButton(CommandText.DO_TRANSFER))
            kb.add(KeyboardButton(CommandText.SET_ANOTHER_CONTENT))
    kb.add(KeyboardButton(CommandText.SHOW_STYLES))
    kb.add(KeyboardButton(CommandText.README),
           KeyboardButton(CommandText.SHOW_RANDOM_EXAMPLE))
    return kb
async def start(message: types.Message):
    #кнопки для волшебного входа
    button_start = KeyboardButton('Зайти в волшебный мир Your Bunny врота🌀')

    magic_start = ReplyKeyboardMarkup(one_time_keyboard=True)

    magic_start.add(button_start)
    await message.answer(
        'Привет👋\n\nЭто Your Bunny Wrote бот и я советую перечитать названия🤠\nА ещё я советую задержаться у нас подольше, у нас тут много интересного\n\nYour Bunny Wrote - место для знакомств : \n - скейтеров🛹\n - хипстеров🦹‍♀️ \n и инопланетян👽',
        reply_markup=magic_start)
    await message.answer_sticker('CAADAgADZgkAAnlc4gmfCor5YbYYRAI')
    if (not db.user_exists(message.from_user.id)):
        #если юзера нет в базе добавляем его
        db.add_user(message.from_user.username, message.from_user.id,
                    message.from_user.full_name)
        await bot.send_message(
            -1001406772763,
            f'Новый пользователь!\nID - {str(message.from_user.id)}\nusername - {str(message.from_user.username)}'
        )
def allItemsMenu(itemsList: list, quantity: str):
    markup = ReplyKeyboardMarkup(resize_keyboard=True, row_width=4)
    markup.add(KeyboardButton('Назад ⬅'))
    markup.add(KeyboardButton('Сортировать по'))
    markup.add(KeyboardButton('🔤'))
    markup.insert(KeyboardButton('💲'))
    markup.insert(KeyboardButton('⚖️'))

    if quantity != '':
        markup.insert(KeyboardButton('🍣🔢'))

    for item in itemsList:
        if quantity != '':
            text = f"{(item[0].title())} | {item[1]} | {item[4]} шт. | {item[2]} грн."
        else:
            text = f"{item[0].title()} | {item[1]} | {item[2]} грн."
        markup.add(KeyboardButton(text=text))
    return markup
async def callback(call: CallbackQuery):
    data = call.data.split(':')
    if data[1] == 'del':
        global questions
        del questions[int(data[2])]
        database.telegram_bot.content.update_one({'_id': 'faq'}, {'$set': {'content': questions}})
        await call.message.answer('OK')

        await send_faq(call.message)

    elif data[1] == 'edit':
        # TODO: Переход в состояние изменение КОНКРЕТНОГО вопроса
        pass
    elif data[1] == 'add':
        edit_keyboard = ReplyKeyboardMarkup(resize_keyboard=True).add(
            KeyboardButton('Отмена')
        )

        await States.faq_add.set()
        await call.message.answer(f'Напишите сообщение в формате:\n<Вопрос>\n\n<Ответ>', reply_markup=edit_keyboard)
async def create_profile(message: types.Message):
    #кнопки отмены
    button_exit = KeyboardButton('Выйти❌')

    menu_exit = ReplyKeyboardMarkup()

    menu_exit.add(button_exit)

    if message.from_user.username != None:
        if (not db.profile_exists(message.from_user.id)):
            await message.answer(
                "Для того что бы создать твою so style анкету нужно заполнить несколько пунктов\nДавайте начнём с твоего имя, как мне тебя называть?😉",
                reply_markup=menu_exit)
            await CreateProfile.name.set()
        elif (db.profile_exists(message.from_user.id)):
            await message.answer('У тебя уже есть активная анкета\n\n')
    else:
        await message.answer(
            '‼️У вас не заполнен username в телеграм!\n\nПожалуйста сделайте это для коректного функционирования бота\nДля этого зайдите в настройки -> Edit Profile(Изменить профиль) и жмякайте add username\n\nТам вводите желаемый никнейм и вуаля'
        )
Exemple #7
0
def kbd(buttons,
        resize=True,
        vert=False,
        one_time=False,
        inline=False,
        row_width=3):
    if isinstance(buttons, str):
        buttons = [[buttons]]
    elif isinstance(buttons, (list, tuple, set)):
        if all(isinstance(b, str) for b in buttons):
            if vert:
                buttons = [[b] for b in buttons]
            else:
                buttons = [buttons]

    buttons = [[KeyboardButton(b) for b in row] for row in buttons]
    return ReplyKeyboardMarkup(buttons,
                               resize_keyboard=resize,
                               one_time_keyboard=one_time,
                               row_width=row_width)
Exemple #8
0
def get_bot_menu(in_set: bool = False) -> ReplyKeyboardMarkup:
    markup: list
    if in_set:
        markup = [[
            KeyboardButton("Добавить✨"),
            KeyboardButton("🔥Набор🔥"),
            KeyboardButton("Наборы📚")
        ]]
    else:
        markup = [[
            KeyboardButton("Добавить✨"),
            KeyboardButton("Зацепиться🖇"),
            KeyboardButton("Наборы📚")
        ]]
    return ReplyKeyboardMarkup(markup, resize_keyboard=True)
Exemple #9
0
 async def roll(message: types.Message):
     text = " ".join(message.text.split()[1:]).strip()
     if not text:
         await message.answer(
             text=
             f"@{message.from_user.username}, scegli cosa tirare 🎲",
             reply_markup=ReplyKeyboardMarkup(
                 [[KeyboardButton(text=f"/roll d20")]],
                 one_time_keyboard=True))
         return
     parsed_text = text
     raw_rolls = re.findall(pattern="[0-9]*d[0-9]+",
                            string=text,
                            flags=re.IGNORECASE)
     averages, scores = [], []
     for roll in raw_rolls:
         multiplier, dice = roll.split("d")
         if not multiplier:
             multiplier = 1
         averages += [int(dice) // 2]
         dice = np.random.randint(1, int(dice))
         scores += [dice]
         parsed_text = re.sub(pattern=roll,
                              repl=f"{multiplier}*{dice}",
                              string=parsed_text,
                              count=1)
     try:
         result = eval(parsed_text, {})
         is_good = True if sum(scores) >= sum(averages) else False
         await message.answer(
             f"@{message.from_user.username} tira un {'bel' if is_good else 'misero'} <b>{result}</b> 🎲 {'📈' if is_good else '📉'}\n\n"
             f"<code>  {text} =\n"
             f"= {parsed_text} = {result}</code>",
             parse_mode="html")
     except Exception as e:
         logging.error(e)
         await message.reply(
             f"Non riesco a capire 😅😅\n"
             f"Prova tipo <code>/roll d20</code> "
             f"o <code>/roll 2d20 + 3</code>",
             parse_mode="html")
def get_feedback_keyboard(lang):
    feedback_keyboard = ReplyKeyboardMarkup(
        keyboard=[[KeyboardButton(text="тнРя╕ПтнРя╕ПтнРя╕ПтнРя╕ПтнРя╕П")],
                  [
                      KeyboardButton(text="тнРя╕ПтнРя╕ПтнРя╕ПтнРя╕П"),
                  ], [
                      KeyboardButton(text="тнРя╕ПтнРя╕ПтнРя╕П"),
                  ], [
                      KeyboardButton(text="тнРя╕ПтнРя╕П"),
                  ], [
                      KeyboardButton(text="тнРя╕П"),
                  ], [KeyboardButton(text=_("ЁЯФЩ Back", locale=lang))]],
        resize_keyboard=True)

    return feedback_keyboard
async def edit_profile_age(message: types.Message):
    try:
        #кнопки для отмены
        button_cancel = KeyboardButton('Отменить❌')

        button_cancel_menu = ReplyKeyboardMarkup(one_time_keyboard=True)

        button_cancel_menu.add(button_cancel)

        if message.text == 'Изменить количество годиков👶':
            await message.answer('Введи свой новый возвраст',
                                 reply_markup=button_cancel_menu)
            await EditProfile.age_edit.set()
        elif message.text == 'Изменить описание анкеты📝':
            await message.answer('Введи новое хайп описание своей анкеты!',
                                 reply_markup=button_cancel_menu)
            await EditProfile.description_edit.set()
    except Exception as e:
        await message.answer(cus_ans.random_reapeat_list())
        print(e)
        return
Exemple #12
0
 def markup(
     self,
     actions: List[Union[str, Dict[str, Union[str, bool, KeyboardButtonPollType]]]],
     schema: List[int],
     resize_keyboard: bool = None,
     one_time_keyboard: bool = None,
     selective: bool = None,
 ) -> ReplyKeyboardMarkup:
     markup = ReplyKeyboardMarkup(
         resize_keyboard=resize_keyboard,
         one_time_keyboard=one_time_keyboard,
         selective=selective,
     )
     markup.row_width = max(schema)
     buttons = list()
     for action in actions:
         self._replace_aliases(action)
         button_data = self._set_poll_property(self._check_properties(action))
         buttons.append(KeyboardButton(**button_data))
     markup.keyboard = self.create_keyboard_layout(buttons, schema)
     return markup
Exemple #13
0
def start_menu():
    menu = ReplyKeyboardMarkup(keyboard=[
        [
            KeyboardButton(text='⛳️Координаты'),
            KeyboardButton(text='🗻Состав грунта'),
            KeyboardButton(text='📉Глубина'),
        ],
        [
            KeyboardButton(text='📈Высота'),
            KeyboardButton(text='🎯Точность'),
            KeyboardButton(text='📦Сохранить точку')
        ],
    ],
                               resize_keyboard=True)

    return menu
Exemple #14
0
def down_level(site: dict, site_name: str):
    if site_name[0] in ['📂', '📋']:
        site_name = site_name[1::]
    new_result = service.files().list(
        q=f"'{site[f'{site_name}']}' in parents",
        pageSize=10,
        fields="nextPageToken, files(id,name, parents, mimeType)").execute()
    items = new_result.get('files', [])
    down_folder = {
        item['name']: [item['id'], item['mimeType']]
        for item in items
    }
    formatted_2d_list = [items[x:x + 3] for x in range(0, len(items), 3)]
    butt = ReplyKeyboardMarkup(
        resize_keyboard=True,
        keyboard=[[
            KeyboardButton(text='📂' +
                           x['name'] if 'application/vnd.google-apps.folder' in
                           x['mimeType'] else '📋' + x['name']) for x in item
        ] for item in formatted_2d_list])
    service.close()
    butt.row('Меню', "Назад")
    return butt, down_folder
async def create_profile_age(message: types.Message, state: FSMContext):
    try:
        if str(message.text) == 'Выйти❌':
            await state.finish()
            await magic_start(message)
            return
        if int(message.text) < 6:
            await message.answer('ой🤭\nТы чёт маловат...')
            await message.answer(cus_ans.random_reapeat_list())

            #прерывание функции
            return
        elif int(message.text) > 54:
            await message.answer('Пажилой человек👨‍')
            await message.answer(cus_ans.random_reapeat_list())

            #прерывание функции
            return
        elif int(message.text) > 6 and int(message.text) < 54:
            await state.update_data(profile_age=message.text)
            #кнопки меню
            button_skip = KeyboardButton('Пропустить')

            skip_input = ReplyKeyboardMarkup(one_time_keyboard=True)
            skip_input.add(button_skip)
            await message.answer(
                'За№бись!!\nПоследний шаг - указать ссылку на свой инстаграмм🤑\nЕсли нет желания - можно пропустить➡🔜',
                reply_markup=skip_input)
            await CreateProfile.next()
        else:
            await answer.message('Укажи правильный возраст, только цифры')
            return
    except:
        await message.answer(cus_ans.random_reapeat_list())
        #прерывание функции
        return
Exemple #16
0
async def custom_cashback_address(call: types.CallbackQuery):
    """Ask for a custom cashback address."""
    currency = call.data.split()[1]
    await states.cashback_address.set()
    await dp.current_state().update_data(currency=currency)
    answer = i18n("send_cashback_address")
    cursor = database.cashback.find({
        "id": call.from_user.id,
        "currency": currency,
        "address": {
            "$ne": None
        }
    }).sort("time", pymongo.DESCENDING)
    addresses = await cursor.distinct("address")
    addresses = addresses[1:]
    await call.answer()
    if addresses:
        keyboard = ReplyKeyboardMarkup(row_width=1)
        keyboard.add(*[KeyboardButton(address) for address in addresses])
        await tg.send_message(call.message.chat.id,
                              answer,
                              reply_markup=keyboard)
    else:
        await tg.send_message(call.message.chat.id, answer)
Exemple #17
0
async def start(message: types.Message):
    phone = ReplyKeyboardMarkup(keyboard=[[
        KeyboardButton(text="Отправить номер телефона", request_contact=True)
    ]])
    id_user = message.from_user.id
    if not db.user_exists(id_user):
        db.add_user(id_user, message.from_user.username)
    # await message.answer('/help - список команд')
    if not db.check_phone(id_user)[0]:
        await message.answer(
            "Дайте доступ к номеру телефона. Для этого нажмите кнопку 'Отправить номер телефона'. Если вы не видите кнопку, возможно, вы её скрыли",
            reply_markup=phone)
        sleep(1)
        directory = "photo_button.png"
        with open(directory, "rb") as f:
            await message.answer_photo(f, "Если кнопка скрыта, нажмите сюда")
    elif not db.check_fullname(id_user)[0]:
        await message.answer("Введите ваше ФИО")
        await FullName.fullname.set()
    else:
        await message.answer(
            'Для выполнения команд нажмите соответствующую кнопку',
            reply_markup=menu_admin
            if db.user_is_admin(message.from_user.id) else menu)
def generate_location_settings_keyboard(notifications, language):
    button_edit_name = KeyboardButton(language.button_edit_name)
    button_edit_step = KeyboardButton(language.button_edit_step)
    button_notifications_on = KeyboardButton(language.button_notifications_on)
    button_notifications_off = KeyboardButton(
        language.button_notifications_off)
    button_delete_location = KeyboardButton(language.button_delete_location)
    button_back = KeyboardButton(language.button_back_to_locations)

    keyboard = ReplyKeyboardMarkup(resize_keyboard=True)
    if notifications:
        keyboard.add(button_edit_name, button_edit_step,
                     button_notifications_off, button_delete_location,
                     button_back)
    else:
        keyboard.add(button_edit_name, button_edit_step,
                     button_notifications_on, button_delete_location,
                     button_back)
    return keyboard
async def stake_3_prompt_1(message: types.Message):

    # Fetch user info
    user = await db_users.find_one({'id': message.from_user.id})

    # Charge balance
    await db_users.update_one(user, {'$inc': {'balance': -25}})

    # Change state
    await StakeState.stake_3_prompt_case.set()

    # Send prompt message
    await message.answer(text=f'Введите число 1-6',
                         reply_markup=ReplyKeyboardMarkup(
                             keyboard=[[
                                 KeyboardButton(text='1'),
                                 KeyboardButton(text="2"),
                                 KeyboardButton(text="3"),
                                 KeyboardButton(text="4"),
                                 KeyboardButton(text="5"),
                                 KeyboardButton(text="6"),
                             ]],
                             resize_keyboard=True))
Exemple #20
0
async def process_help(message: types.Message):
    greet_kb = ReplyKeyboardMarkup(resize_keyboard=True,
                                   row_width=2,
                                   one_time_keyboard=True)
    button_about = KeyboardButton('/about')
    button_menu = KeyboardButton('/menu')
    button_stocks = KeyboardButton('/stocks')
    button_reg = KeyboardButton('/reg')
    button_contact = KeyboardButton('/contact')
    button_comment = KeyboardButton('/comment')
    greet_kb.add(button_about, button_stocks, button_reg, button_menu,
                 button_contact, button_comment)
    await bot.send_message(
        message.chat.id,
        text=md.italic(
            "Все довольно просто, нажимайте на команды, которые указаы ниже\n"
            "Для того чтобы посмотреть информацию о нас выбери команду /about\n"
            "Для того чтобы посмотреть наше меню выбери команду /menu\n"
            "Для того чтобы сделать заказ выбери команду /reg\n"
            "Для того чтобы посмотреть наши контакты  выбери команду /contact\n"
            "Для того чтобы посмотреть отзывы о нас ведери команду /comment\n"
        ),
        reply_markup=greet_kb,
        parse_mode=ParseMode.MARKDOWN)
Exemple #21
0
from aiogram.types import ReplyKeyboardMarkup, KeyboardButton, \
    InlineKeyboardMarkup, InlineKeyboardButton
from aiogram.utils.emoji import emojize

back_to_menu = KeyboardButton(emojize('В главное меню :arrow_left:'))
menu = KeyboardButton(emojize('Меню :book:'))
cart = KeyboardButton(emojize('Корзина :shopping_cart:'))
contacts = KeyboardButton(emojize("Контакты :blue_book:"))
payment = KeyboardButton(emojize('Оплата :dollar:'))
add_img = KeyboardButton(emojize('Добавить фото :framed_picture:'))
menu_btns = ReplyKeyboardMarkup(one_time_keyboard=True, resize_keyboard=True, row_width=2).row(
    menu, cart).row(contacts, payment)
admin_buttons = ReplyKeyboardMarkup(one_time_keyboard=True, resize_keyboard=True, row_width=2).row(
    menu, cart).row(contacts, payment).add(add_img)

del_item = KeyboardButton('Редактировать корзину')
cart_btns = ReplyKeyboardMarkup(resize_keyboard=True, one_time_keyboard=True).row(cart, del_item, back_to_menu)

cash_payment = KeyboardButton(emojize('Оплата наличными :dollar:'))
card_payment = KeyboardButton(emojize('Оплата картой :credit_card:'))
payments = ReplyKeyboardMarkup(one_time_keyboard=True, resize_keyboard=True).row(card_payment, cash_payment)

burgers = KeyboardButton(emojize('Бургеры :hamburger:'))
drinks = KeyboardButton(emojize('Напитки :tropical_drink:'))
pizza = KeyboardButton(emojize("Пицца :pizza:"))
desserts = KeyboardButton(emojize('Десерты :cake:'))
back_to_menu = KeyboardButton(emojize('В главное меню :arrow_left:'))
menu_categories = ReplyKeyboardMarkup(one_time_keyboard=True, resize_keyboard=True).row(burgers, pizza).row(
    desserts, drinks).add(back_to_menu, cart)

from aiogram.types import ReplyKeyboardMarkup, KeyboardButton
# Кнопки выбора типа собеседника: Студент/Работодатель.
btnUserTypeStudent = KeyboardButton("Студент")
btnUserTypeWorker = KeyboardButton("Работодатель")
choose_kb = ReplyKeyboardMarkup(resize_keyboard=True, one_time_keyboard=True)
choose_kb.add(btnUserTypeStudent)
choose_kb.add(btnUserTypeWorker)

# Кнопки заполения резюме студента.
btnUserSendRSummary = KeyboardButton("Заполнить резюме")
btnBack = KeyboardButton("Отмена")
SendRSummary = ReplyKeyboardMarkup(resize_keyboard=True,
                                   one_time_keyboard=True)
SendRSummary.add(btnUserSendRSummary)
SendRSummary.add(btnBack)

BackOnly = ReplyKeyboardMarkup(resize_keyboard=True,
                               one_time_keyboard=True).add(btnBack)
Exemple #23
0
for i in sch.get_classes():
    clas = i.split('.')[0]
    if clas not in lst:
        inlinebtn = InlineKeyboardButton(clas, callback_data='classbtn' + clas)
        inlinekb = inlinekb.insert(inlinebtn)
        lst.append(clas)
#--inline
#--inline--
ITcubeinlinekb = InlineKeyboardMarkup()
for i in database.get_section_name_itcube('all'):
    ITcubeinlinebtn = InlineKeyboardButton(i[1],
                                           callback_data='ITcubesection' +
                                           str(i[0]))
    ITcubeinlinekb = ITcubeinlinekb.insert(ITcubeinlinebtn)
#--inline
kco = KeyboardButton("КЦО🏫")
itcube = KeyboardButton("IT-куб")
settings = KeyboardButton("Настройки⚙️")
schedule = KeyboardButton("Расписание 🗓")
scheduleitcube = KeyboardButton("Расписание занятий🗓")
teachers = KeyboardButton("Учителя 👨‍🏫")
events = KeyboardButton("События🎉")
eventsnear = KeyboardButton("Ближайшие события")
eventsall = KeyboardButton("Все события")
allteachers = KeyboardButton("Список учителей 📝")
searchteacher = KeyboardButton("Поиск учителя 🔎")
btn = KeyboardButton("btn ")
backbtn = KeyboardButton("↩")
changeclass = KeyboardButton("Сменить класс🆙")
andtoto = KeyboardButton("Событ., ФИО учит., и т.д. ...")
changemailingScheduleNO = KeyboardButton("Рассылка расписания🟥")
Exemple #24
0
from aiogram.types import ReplyKeyboardMarkup, KeyboardButton

keyboard = ReplyKeyboardMarkup(keyboard=[
    [KeyboardButton(text="📍", request_location=True)],
],
                               resize_keyboard=True)
Exemple #25
0
from aiogram import Bot, types
from aiogram.types import ReplyKeyboardMarkup, KeyboardButton

butt_fname = KeyboardButton('Фамилия')
butt_name = KeyboardButton('Имя')
butt_oname = KeyboardButton('Отчество')
butt_dolj = KeyboardButton('Должность')
butt_room = KeyboardButton('Кабинет')
butt_phone = KeyboardButton('Телефон')
butt_mail = KeyboardButton('Email')
butt_full = KeyboardButton('Полная')
butt_fio = KeyboardButton('Фио')
butt_new = KeyboardButton('Создать')
butt_change = KeyboardButton('Изменить')
butt_delete = KeyboardButton('Удалить')
butt_save = KeyboardButton('Сохранить')
butt_pars = KeyboardButton('Запуск парсера')
board_1 = ReplyKeyboardMarkup(resize_keyboard=True,
                              one_time_keyboard=True).row(butt_full, butt_fio)
board_3 = ReplyKeyboardMarkup(resize_keyboard=True,
                              one_time_keyboard=True).row(
                                  butt_new, butt_change,
                                  butt_delete).add(butt_save).add(butt_pars)
board_2 = ReplyKeyboardMarkup(resize_keyboard=True,
                              one_time_keyboard=True).row(butt_dolj).row(
                                  butt_fname, butt_name,
                                  butt_oname).row(butt_room, butt_phone,
                                                  butt_mail)
Exemple #26
0
from aiogram.types import ReplyKeyboardMarkup, KeyboardButton

button_report = KeyboardButton('Создать жалобу️️')
button_privacy = KeyboardButton('Политика конфидициальности')
button_about = KeyboardButton('О проекте')
button_feedback = KeyboardButton('Обратная связь')

button_cancel = KeyboardButton('Отмена')

button_anon = KeyboardButton('Анонимно')
button_non_anon = KeyboardButton('Подписать username')

button_back = KeyboardButton('Назад')

button_location = KeyboardButton('Поделиться текущей геолокацией',
                                 request_location=True)

# Возвращение в меню и назад
system_button = ReplyKeyboardMarkup(resize_keyboard=True)
system_button.add(button_back)
system_button.add(button_cancel)

# Возвращение в меню
system_button1 = ReplyKeyboardMarkup(resize_keyboard=True)
system_button1.add(button_cancel)

# Анонимность отправки анкеты
anonymous_button = ReplyKeyboardMarkup(resize_keyboard=True)
anonymous_button.row(button_anon, button_non_anon)
anonymous_button.add(button_cancel)
Exemple #27
0
from aiogram.types import ReplyKeyboardRemove, \
    ReplyKeyboardMarkup, KeyboardButton, \
    InlineKeyboardMarkup, InlineKeyboardButton

# стартовая кнопка
btn_start = KeyboardButton('Начать')
kb_start = ReplyKeyboardMarkup(resize_keyboard=True,
                               one_time_keyboard=True).add(btn_start)

# кнопки со входами в функции бота
btn_weather_now = KeyboardButton('Узнать погоду')
btn_sub_on_notion_menu = KeyboardButton('Настройка уведомлений')
kb_main = ReplyKeyboardMarkup(resize_keyboard=True).row(
    btn_weather_now, btn_sub_on_notion_menu)

# кнопки для работы с уведомлениями
btn_sub_yes = InlineKeyboardButton('Включить ✅', callback_data='sub_yes')
btn_sub_no = InlineKeyboardButton('Выключить ❌', callback_data='sub_no')
kb_sub_yes_or_no = InlineKeyboardMarkup(row_width=2).row(
    btn_sub_yes, btn_sub_no)

# инлайн клавиатура городов
btn_city_1 = KeyboardButton('Москва')
btn_city_2 = KeyboardButton('Санкт-Петербург')
btn_city_3 = KeyboardButton('Калининград')
btn_city_4 = KeyboardButton('Нижний Новгород')
btn_city_exite = KeyboardButton('Выйти')

kb_of_cities = ReplyKeyboardMarkup(resize_keyboard=True)\
    .row(btn_city_1, btn_city_2).row(btn_city_3, btn_city_4).add(btn_city_exite)
Exemple #28
0
async def welcome(message: types.Message):
    button = KeyboardButton(B_REGISTRER)
    button.request_contact = True
    kb = ReplyKeyboardMarkup(resize_keyboard=True).add(button)
    await bot.send_message(message.chat.id, T_HELLO, reply_markup=kb)
    await bot.send_sticker(message.chat.id, 'CAADBAAD8AIAAlI5kwZeZ9hi6NX9qQI')
Exemple #29
0
from aiogram.types import KeyboardButton, ReplyKeyboardMarkup

income = KeyboardButton('Income')
expencese = KeyboardButton('Expencese')
statistics = KeyboardButton('Statistics')
back_to_menu = KeyboardButton('⬅️Back to menu')
enter_curent_ammount = KeyboardButton('Enter current balance')
upgrate_ammount = KeyboardButton('Upgrate ammount')
add_cat = KeyboardButton('➕Add category')
rem_cat = KeyboardButton('❌Remove category')
today = KeyboardButton('Today')
another_day = KeyboardButton('Another day')
previous_month = KeyboardButton('Previous month')
next_month = KeyboardButton('Next month')
details = KeyboardButton('Details')
upd_delete = KeyboardButton('Delete comment')

menu_kb = ReplyKeyboardMarkup(
    resize_keyboard=True).add(expencese).add(income).add(statistics)
back_to_menu_keyboard = ReplyKeyboardMarkup(
    resize_keyboard=True).add(back_to_menu)
start_menu_kb = ReplyKeyboardMarkup(resize_keyboard=True).add(
    enter_curent_ammount).add(expencese).add(income).add(statistics)
add_ammount = ReplyKeyboardMarkup(
    resize_keyboard=True).add(upgrate_ammount).add(back_to_menu)
inex_category = ReplyKeyboardMarkup(
    resize_keyboard=True).add(back_to_menu).add(income).add(expencese)
add_remove_keyboard = ReplyKeyboardMarkup(
    resize_keyboard=True).add(back_to_menu).add(add_cat).add(rem_cat)
edit_budget_category = ReplyKeyboardMarkup(
    resize_keyboard=True).add(back_to_menu).add(today).add(another_day)
Exemple #30
0
async def main_logic(message: types.Message):

    t0 = time.time()
    if message.text == 'clean':
        with open('data2.json', 'rb') as f:
            await bot.edit_message_media(InputMediaDocument(f), admin_id, 4)
    # with open('data.json', 'rb') as f:
    #     print(f)
    #     await bot.send_document(message.chat.id, f)
    print(message.message_id)
    data = await get_data()
    # print(data)
    print(len(data['users']))
    metka2 = False
    for user in data['users']:
        if user['chatid'] == message.chat.id:
            time_user = []
            try:
                for stroka in message.text.split(':'):
                    time_user.append(int(re.search(r'\d+', stroka).group()))

            except Exception as ex:
                # print(ex)
                pass

            print(time_user)
            if len(time_user) == 1:
                if time_user[0] > 0 and time_user[0] < 120:

                    new_time = datetime.datetime.now() + datetime.timedelta(
                        minutes=time_user[0])

                    metka_time = False
                    for time_us in user['calltime']:
                        if (new_time.time().hour +
                                3) == time_us[0] and new_time.time(
                                ).minute == time_us[1]:
                            await bot.send_message(
                                message.chat.id,
                                'На данное время у Вас уже записан звонок')
                            metka_time = True
                            break
                    if metka_time == False:
                        user['calltime'].append(
                            [new_time.time().hour + 3,
                             new_time.time().minute])
                        await save_data(data)
                        await bot.send_message(
                            message.chat.id,
                            'Вы добавили звонок на {}:{}'.format(
                                str(new_time.time().hour + 3),
                                str(new_time.time().minute)))
                else:
                    await bot.send_message(message.chat.id,
                                           'Укажите время от 1 до 120 минут')
            if len(time_user) == 2:
                if time_user[0] >= 0 and time_user[0] <= 24 and time_user[
                        1] >= 0 and time_user[1] <= 60:

                    metka_time = False
                    for time_us in user['calltime']:
                        if time_user[0] == time_us[0] and time_user[
                                1] == time_us[1]:
                            await bot.send_message(
                                message.chat.id,
                                'На данное время уже запланирован звонок')
                            metka_time = True
                            break
                    if metka_time == False:
                        user['calltime'].append([time_user[0], time_user[1]])
                        await save_data(data)
                        await bot.send_message(
                            message.chat.id,
                            'Вы добавили звонок на {}:{}'.format(
                                str(time_user[0]), str(time_user[1])))
                else:
                    await bot.send_message(
                        message.chat.id,
                        'Вы указали неправильное время. Попробуйте занова.')

            if message.text == B_CLEAN:
                user['calltime'].clear()
                await save_data(data)
                await bot.send_message(message.chat.id,
                                       'Все звонки удачно сброшены.')

            if message.text == B_CALL_NOW:
                client = Client(account_sid, auth_token)
                client.calls.create(url='https://ex.ru',
                                    to=user['phones'],
                                    from_='+12027967603')

            if message.text == B_LIST_CALLS:
                if len(user['calltime']) == 0:
                    await bot.send_message(
                        message.chat.id, 'У Вас нет запланированных звонков')
                else:
                    str_call_list = 'Запланированные звонки:\n'
                    for time_call in user['calltime']:
                        str_call_list += str(time_call[0]) + ':' + str(
                            time_call[1]) + '\n'
                    await bot.send_message(message.chat.id, str_call_list)
            if message.text == B_INFO:
                await bot.send_message(message.chat.id, 'Инфо тут')

            metka2 = True
            break
    if metka2 == False:
        button = KeyboardButton(B_REGISTRER)
        button.request_contact = True
        kb = ReplyKeyboardMarkup(resize_keyboard=True).add(button)
        await bot.send_message(
            message.chat.id,
            'Вы не зарегистрированы, нажмите на кнопку "Регистрация"',
            reply_markup=kb)

    if message.text == 'add':
        for number in range(10000):
            data['users'].append({
                'chatid': number,
                'phones': 8917,
                'state': 0,
                'calltime': []
            })

        with open('data3.json', 'w') as json_file:
            json.dump(data, json_file)
        with open('data3.json', 'rb') as f:
            await bot.edit_message_media(InputMediaDocument(f), admin_id, 4)

    t1 = time.time()
    print('end: ' + str(t1 - t0))