Exemple #1
0
def notify_new_order(order: Order, total_sum: float, count_orders: int):
    notification_chats = notifyservice.get_all_notification_chats()
    notification_message = strings.from_order_notification(
        order, total_sum, count_orders)
    markup = InlineKeyboardMarkup()
    markup.add(
        InlineKeyboardButton(strings.get_string('notifications.accept'),
                             callback_data='accept' + str(order.id)))
    markup.add(
        InlineKeyboardButton(strings.get_string('notifications.cancel'),
                             callback_data='cancel' + str(order.id)))
    for chat in notification_chats:
        try:
            telegram_bot.send_message(chat.chat_id,
                                      notification_message,
                                      reply_markup=markup,
                                      parse_mode='HTML')
            if order.location:
                telegram_bot.send_location(chat.chat_id,
                                           order.location.latitude,
                                           order.location.longitude)
        except ApiException:
            pass
Exemple #2
0
def send_welcome(message):
    keyboard = InlineKeyboardMarkup(row_width=1)  # Клавиатура с одной кнопкой
    yes = InlineKeyboardButton(text='Конечно',
                               url='https://t.me/CourseworkBot?start=start')
    keyboard.add(yes)
    bot.send_message(
        message.chat.id,
        'Здравствуйте я бот для сбора мнений по фильмам.\nЕсли хотите со мной '
        'пообщаться, перейдите по ссылке.\n (Если нет, просто игнорируйте это сообщение '
        'и можете покинуть группу)',
        reply_markup=keyboard)
    bot.delete_message(
        message.chat.id,
        message.message_id)  # удаляем ненужное страрт, чтобы не захламлять
Exemple #3
0
def get_list(message):
    global name
    button_list = []
    connection = sqlite3.connect(":memory:")
    cursor = connection.cursor()
    sql_file = open(scddata)
    sql_as_string = sql_file.read()
    cursor.executescript(sql_as_string)
    like = " LIKE '%" + name.upper() + "%'"
    for row in cursor.execute("SELECT name, id FROM dance WHERE ucname" + like):
        button_list.append(InlineKeyboardButton(str(row[0]), callback_data=str(row[1])))
    reply_markup = InlineKeyboardMarkup(
    build_menu(button_list, n_cols=1))
    bot.send_message(message.from_user.id, 'Choose the dance:', reply_markup=reply_markup)
Exemple #4
0
def generate_markup2():
    ''' Reply language for user first seen '''

    markup = InlineKeyboardMarkup()
    markup.row_width = 1

    # Receive all aviable language from DB
    rows = DB_Worker().get_lang()

    for row in rows:
        markup.add(InlineKeyboardButton(row[0],
                                        callback_data=f'lang|{row[1]}'))

    return markup
Exemple #5
0
def send_what_film(call: CallbackQuery):
    bot.delete_message(call.message.chat.id, call.message.message_id)
    new = utils.BD('BD.sqlite')
    if call.data == 'yes':
        file_user = open(dir_user_kash + str(call.from_user.id) + '.txt', "r")
        film_name = file_user.read()
        file_user.close()
        new.resize_second_check(new.film_name_to_id(film_name),
                                call.from_user.id, 1)
    elif call.data == 'no':
        file_user = open(dir_user_kash + str(call.from_user.id) + '.txt', "r")
        film_name = file_user.read()
        file_user.close()
        new.resize_second_check(new.film_name_to_id(film_name),
                                call.from_user.id, 0)
    keyboard = InlineKeyboardMarkup(row_width=2)
    question = 'Спасибо, я тебя понял. Ходил(а) недавно в кино?'
    yes = InlineKeyboardButton(text='Да', callback_data='y2')
    no = InlineKeyboardButton(text='Нет', callback_data='n2')
    keyboard.add(yes, no)
    bot.send_message(call.message.chat.id,
                     text=question,
                     reply_markup=keyboard)
Exemple #6
0
def sub_cat(call):
    subcats_kb = InlineKeyboardMarkup()
    subcats_buttons = []
    category = Category.objects.get(id=call.data.split('_')[1])
    for i in category.sub_categories:
        callback_data = 'category_' + str(i.id)

        if i.is_parent:
            callback_data = 'subcategory_' + str(i.id)
        subcats_buttons.append(InlineKeyboardButton(text=i.title,
                                                    callback_data=callback_data))

    subcats_kb.add(*subcats_buttons)
    bot.send_message(call.message.chat.id, text='subcat example', reply_markup=subcats_kb)
Exemple #7
0
def show_parameters_to_change(call):
    event_id = call.data.split('_')[1]

    change_event_keyboard = InlineKeyboardMarkup()
    change_event_keyboard.add(
        InlineKeyboardButton(text='Назва заходу',
                             callback_data=f'name_{event_id}'))
    change_event_keyboard.add(
        InlineKeyboardButton(text='Місце проведення',
                             callback_data=f'place_{event_id}'))
    change_event_keyboard.add(
        InlineKeyboardButton(text='Дата проведення',
                             callback_data=f'date_{event_id}'))
    change_event_keyboard.add(
        InlineKeyboardButton(text='Час проведення',
                             callback_data=f'time_{event_id}'))

    bot.edit_message_text(
        chat_id=call.from_user.id,
        message_id=call.message.message_id,
        text=
        f'Що потрібно змінити в заході {Event.get_event(event_id=event_id).name}?',
        reply_markup=change_event_keyboard)
Exemple #8
0
def make_consent(call):
    text = "Отлично👍 Осталось немного!\n\n" \
           "Нажмите: _Ввести данные_, чтобы заполнить необходимую информацию\n" \
           "Старайтесь вводить данные без лишних символов:)"
    if call.data == "agreed":
        postgre.sign_consent(call.message.chat.id)
        markup = InlineKeyboardMarkup()
        markup.add(InlineKeyboardButton("Даю согласие✅", callback_data="disagree"),
                   InlineKeyboardButton("Прочитать согласие", callback_data='send_consent'))

        bot.answer_callback_query(call.id, "Согласие получено, продолжаем!")
        bot.edit_message_reply_markup(chat_id=call.message.chat.id, message_id=call.message.message_id,
                                      reply_markup=markup)

        markup1 = InlineKeyboardMarkup()
        markup1.add(InlineKeyboardButton("Ввести данные", callback_data="register"))
        bot.send_message(chat_id=call.message.chat.id, text=text,
                         timeout=100, reply_markup=markup1, parse_mode='Markdown')

    elif call.data == 'disagree':
        bot.answer_callback_query(call.id, "Вы уже подписали согласие, продолжаем!")
    else:
        bot.answer_callback_query(call.id, "Файл отправлен!")
Exemple #9
0
def show_programs(call, bot):
    program_buttons = [
        InlineKeyboardButton(program_key,
                             callback_data='program:{}'.format(program_key))
        for program_key in settings.AVAILIBLE_PROGRAMS
    ]

    menu_markup = InlineKeyboardMarkup()
    for button in program_buttons:
        menu_markup.row(button)

    bot.send_message(call.message.chat.id,
                     'Хорошо. Выбери программу из списка, чтобы начать',
                     reply_markup=menu_markup)
Exemple #10
0
def show_exercises(program_key, exercises, call, bot):
    buttons = [
        InlineKeyboardButton(title,
                             callback_data='exercise:{}:{}'.format(
                                 program_key, exercise_id))
        for exercise_id, title in exercises.items()
    ]
    menu_markup = InlineKeyboardMarkup()
    for button in buttons:
        menu_markup.row(button)

    bot.send_message(call.message.chat.id,
                     'Теперь выбери упражнение',
                     reply_markup=menu_markup)
Exemple #11
0
def get_inline_no_query() -> List:
    """Возвращает ответ на пустую строку запроса."""
    markup = InlineKeyboardMarkup()
    markup.row(InlineKeyboardButton('Бота в другой чат', switch_inline_query=''))
    markup.row(
        InlineKeyboardButton('Дзен', switch_inline_query_current_chat='zen '),
        InlineKeyboardButton('Поиск PEP', switch_inline_query_current_chat='pep '),
    )
    markup.row(
        InlineKeyboardButton('На pythonz.net', url='http://pythonz.net/'),
    )

    results = [
        telebot.types.InlineQueryResultArticle(
            'index',
            'Пульт управления роботом',
            telebot.types.InputTextMessageContent(
                'Нажимайте на кнопки, расположенные ниже, — получайте результат.'),
            description='Нажмите сюда, чтобы вызвать пульт.',
            reply_markup=markup,
        )
    ]
    return results
Exemple #12
0
def set_order(game):
    keyboard = InlineKeyboardMarkup(row_width=8)
    keyboard.add(*[
        InlineKeyboardButton(text=f'{i + 1}',
                             callback_data=f'append to order {i + 1}')
        for i, player in enumerate(game['players'])
    ])
    keyboard.row(
        InlineKeyboardButton(text='Познакомиться с командой',
                             callback_data='mafia team'))
    keyboard.row(
        InlineKeyboardButton(text='Закончить выбор',
                             callback_data='end order'))

    message_id = bot.send_message(
        game['chat'],
        f'{role_titles["don"].capitalize()}, тебе предстоит сделать свой выбор и определить порядок выстрелов твоей команды.\nДля этого последовательно нажимай на номера игроков, а после этого нажми на кнопку "Закончить выбор".',
        reply_markup=keyboard).message_id

    database.games.update_one({'_id': game['_id']},
                              {'$set': {
                                  'message_id': message_id
                              }})
Exemple #13
0
def show_schedule_menu(message):
    keyboard = InlineKeyboardMarkup()

    bot.send_chat_action(message.chat.id, 'typing')

    for item in schedule_menu:
        keyboard.add(
            InlineKeyboardButton(text=item['name'],
                                 callback_data=item['value']))

    delete_message(message)
    bot.send_message(message.chat.id,
                     messages['schedule'],
                     reply_markup=keyboard)
Exemple #14
0
def don_stage(game):
    keyboard = InlineKeyboardMarkup(row_width=8)
    keyboard.add(*[
        InlineKeyboardButton(text=f'{i + 1}',
                             callback_data=f'check don {i + 1}')
        for i, player in enumerate(game['players']) if player['alive']
    ])

    bot.edit_message_text(
        f'{role_titles["mafia"].capitalize()} засыпает. {role_titles["don"].capitalize()} совершает свою проверку.\n'
        + format_roles(game),
        chat_id=game['chat'],
        message_id=game['message_id'],
        reply_markup=keyboard)
Exemple #15
0
def get_main_inline_markup():
    markup = InlineKeyboardMarkup()
    markup.row_width = 3
    markup.add(
        InlineKeyboardButton("Понедельник", callback_data="Понедельник"),
        InlineKeyboardButton("Вторник", callback_data="Вторник"),
        InlineKeyboardButton("Среда", callback_data="Среда"))

    markup.add(InlineKeyboardButton("Четверг", callback_data="Четверг"),
               InlineKeyboardButton("Пятница", callback_data="Пятница"),
               InlineKeyboardButton("Суббота", callback_data="Суббота"))

    markup.add(InlineKeyboardButton("Сегодня", callback_data="Сегодня"),
               InlineKeyboardButton("Завтра", callback_data="Завтра"))

    return markup
Exemple #16
0
def start(message):

    if Users.objects.filter(user_id=str(message.chat.id)):
        cb = f'initiate{SP}existing'
    else:
        if len(message.text.split()) > 1:
            cb = f'initiate{SP}{message.text.split()[1]}'
        else:
            cb = f'initiate{SP}new'

    kb = InlineKeyboardMarkup()
    kb.add(*[InlineKeyboardButton(LANGUAGE_KB[code], callback_data=f'{cb}{SP}{code}') for code in LANGUAGE_KB.keys()])

    bot.send_message(message.chat.id, 'Выберите язык / Choose your language', reply_markup=kb)
Exemple #17
0
def inline_keyboard(menu):
    keyboard = InlineKeyboardMarkup()
    for rows in menu:
        buttons = []
        for label, data in rows:
            buttons.append(
                InlineKeyboardButton(
                    text=label,
                    callback_data=data,
                ))

        keyboard.row(*buttons)

    return keyboard
Exemple #18
0
def get_cat_or_products(call):
    kb = InlineKeyboardMarkup()
    category = Category.objects.get(id=call.data.split('_')[1])
    if category.subcategory:
        buttons = [
            InlineKeyboardButton(text=cat.title,
                                 switch_inline_query_current_chat='subcat_' +
                                 str(cat.id)) for cat in category.subcategory
        ]
    kb.add(*buttons)
    bot.edit_message_text(text=category.title,
                          message_id=call.message.message_id,
                          chat_id=call.message.chat.id,
                          reply_markup=kb)
Exemple #19
0
def show_cart(message):
    lng = get_lang(message)
    current_user = User.objects.get(user_id=message.from_user.id)
    cart = Cart.objects.filter(user=current_user, is_archived=False).first()

    if not cart:
        bot.send_message(message.chat.id, WORDS[lng]['empty'])
        return

    if not cart.products:
        bot.send_message(message.chat.id, WORDS[lng]['empty'])

    sum_cart = 0
    for prod in cart.products:
        text = f'{prod.title}  `$`*{prod.price / 100}*'
        remove_kb = InlineKeyboardMarkup()
        remove_button = InlineKeyboardButton(text=WORDS[lng]['remove'],
                                             callback_data='rmproduct_' +
                                             str(prod.id))
        remove_kb.add(remove_button)
        bot.send_message(message.chat.id,
                         text,
                         reply_markup=remove_kb,
                         parse_mode='Markdown')
        sum_cart += prod.price

    text = f'`{WORDS[lng]["order_sum"]}  ${sum_cart / 100}`\n*{WORDS[lng]["confirm"]}*'

    submit_kb = InlineKeyboardMarkup()
    submit_button = InlineKeyboardButton(text=WORDS[lng]['checkout'],
                                         callback_data='submit')

    submit_kb.add(submit_button)
    bot.send_message(message.chat.id,
                     text,
                     reply_markup=submit_kb,
                     parse_mode='Markdown')
Exemple #20
0
def Bots_UZ():
    markup = types.ReplyKeyboardMarkup(resize_keyboard=True)
    markup.row(InlineKeyboardButton('Chat bo\'ti'),
               InlineKeyboardButton('Axborot bo\'ti'))
    markup.row(InlineKeyboardButton('Yordamchi bo\'t'),
               InlineKeyboardButton('Onlayn do\'kon'))
    markup.row(InlineKeyboardButton('Asosiy Menu'),
               InlineKeyboardButton('🔙Orqaga'))
    return markup
Exemple #21
0
def manage_users_balance(user_id, page=1):
    # Manage the users balance
    users = User.objects.all().order_by('id')

    pagesize = 90
    offset = (page - 1) * pagesize + 1
    page_lbound = offset
    page_ubound = offset + pagesize
    prev_page = max(1, (page - 1))
    next_page = page + 1
    total_num_page = math.ceil(len(users) / pagesize)

    print("Users length = {}, Page = {}. Lower bound = {}, Upper bound = {}".
          format(len(users), page, page_lbound, page_ubound))
    print("Prev page = {}, Next page = {}, Total #pages = {}".format(
        prev_page, next_page, total_num_page))

    markup = InlineKeyboardMarkup()
    for user in users[page_lbound:page_ubound + 1]:
        btn_text = f'{user.full_name} (${user.balance})'
        markup.add(
            InlineKeyboardButton(
                btn_text,
                callback_data=f'manage_users_balance-{user.user_id}'))

    # Add the navigation buttons
    if page > 1:  # No prev page if we are in page 1
        markup.row(
            InlineKeyboardButton(
                "⏮️ Previous page",
                callback_data=f'navigateto_balance_users_page-{prev_page}'))
    if next_page <= total_num_page:  # No next button if we are in the last page
        markup.row(
            InlineKeyboardButton(
                "Next page ⏭️",
                callback_data=f'navigateto_balance_users_page-{next_page}'))
    return markup
Exemple #22
0
def Settings_Ru():
    markup = ReplyKeyboardMarkup(resize_keyboard=True)
    markup.row(InlineKeyboardButton("O\'zbek tili"),
               InlineKeyboardButton("Русский язык"))
    markup.row(InlineKeyboardButton("Изменить Имя"),
               InlineKeyboardButton("Оценить Сервис"))
    markup.row(InlineKeyboardButton('Основное Меню'),
               InlineKeyboardButton('🔙Назад'))
    return markup
    def __ProcessChangeFeeType(self, msg: str):
        if msg == ld.CancelKey or msg == "/start":
            print(self.username +
                  " has been cancelled changing request process")
            self.__deleteProcessMessage()
            self.Start()
            return
        if not (msg == ld.SkipKey):
            self.__feeType = FeeTypes.Nobody
            if msg == ld.SellerKey:
                self.__feeType = FeeTypes.Seller
            elif msg == ld.BuyerKey:
                self.__feeType = FeeTypes.Buyer

        self.__deleteProcessMessage()
        keyboard = InlineKeyboardMarkup(row_width=1)
        msg = ld.get_translate(self.__db, self.username, ld.EnterFeeMsgKey)
        if self.__feeType == FeeTypes.Nobody or self.__feeType == -1:
            if self.__feeType == FeeTypes.Nobody:
                self.__fee = 0.0
            self.currentStep = RequestSteps.ChangeBank
            msg = ld.get_translate(self.__db, self.username,
                                   ld.EnterBankNameKey)
        else:
            self.currentStep = RequestSteps.ChangeFee

        keyboard.row(
            InlineKeyboardButton(ld.get_translate(self.__db, self.username,
                                                  ld.CancelKey),
                                 callback_data=ld.CancelKey),
            InlineKeyboardButton(ld.get_translate(self.__db, self.username,
                                                  ld.SkipKey),
                                 callback_data=ld.SkipKey))
        reply = self.__bot.send_message(self.__chatId,
                                        msg,
                                        reply_markup=keyboard)
        self.__processMsgId = reply.message_id
Exemple #24
0
def Bots_RU():
    markup = types.ReplyKeyboardMarkup(resize_keyboard=True)
    markup.row(InlineKeyboardButton('Чат-боты'),
               InlineKeyboardButton('Боты-Информаторы'))
    markup.row(InlineKeyboardButton('Боты-асистенты'),
               InlineKeyboardButton('Онлайн Магазин'))
    markup.row(InlineKeyboardButton('Основное Меню'),
               InlineKeyboardButton('🔙Назад.'))
    return markup
Exemple #25
0
    def _process_mail_users(self, message, **kwargs):
        """
        :param auditory: "all" to mail all, else set it to one of auditory type from ejf_table
        :param user: user object from db
        """
        auditory = kwargs["auditory"]
        user = kwargs["user"]

        text = str()
        photo = str()
        url = str()
        markup = InlineKeyboardMarkup()

        if message.content_type == "text":
            text = message.text

        elif message.content_type == "photo":
            text = message.caption
            photo = message.photo[-1].file_id

        else:
            self.mail_all(user)
            return

        # find if there is link in text and form markup
        try:
            if text:
                text_splitted = text.split("\n")
                last_row = text_splitted[-1]
                if "https" in last_row and "->" in last_row:
                    text = "\n".join(text_splitted[:-1])

                    # form button
                    url, btn_text = last_row.split("->")
                    btn = InlineKeyboardButton(text=btn_text, url=url)
                    markup.add(btn)
        except Exception as e:
            print(f"{e} during mailing")
            self.bot.send_message(message.chat.id,
                                  text=f"Щось пішло не так з посиланням - {e}")

        self.send_message_to_auditory(
            admin_chat_id=message.chat.id,
            text=text,
            photo=photo,
            markup=markup,
            user=user,
            auditory=auditory,
        )
 def _summary_method(self, message):
     self._remove_chat_button()
     query_text = ' '.join(
         [w.capitalize() for w in message.text.split(' ')])
     if self._get_summary(query_text):
         button_link = InlineKeyboardButton(
             text='Link to article in wikipedia',
             url=self._get_url(query_text))
         self._kb.add(button_link)
         self._bot.send_message(message.chat.id,
                                self._get_summary(query_text),
                                reply_markup=self._kb)
     else:
         self._bot.send_message(message.chat.id, 'No results')
     self._save_query(message.chat.id, query_text)
Exemple #27
0
def show_product_or_sub_category(call):
    obj_id = call.data.split('_')[1]
    category = models.Category.objects(id=obj_id).get()
    if category.is_parent:
        kb = keyboards.InlineKB(
            iterable=category.subcategory,
            lookup_fields='id',
            named_arg='category',
        )
        kb.generate_kb()
        kb.add(
            InlineKeyboardButton(text=f'<<',
                                 callback_data=f'back_{category.id}'))
        bot.edit_message_text(text=category.title,
                              chat_id=call.message.chat.id,
                              message_id=call.message.message_id,
                              reply_markup=kb)
    else:
        products = Product.objects(category=obj_id)
        for product in products:
            photo = product.photo_product.read()
            keyboard = InlineKeyboardMarkup(row_width=2)
            buttons = [
                InlineKeyboardButton(f'{i}',
                                     callback_data=f'{key}_{product.id}')
                for key, i in keyboards.product_kb.items()
            ]
            keyboard.add(*buttons)
            bot.send_photo(
                chat_id=call.message.chat.id,
                photo=photo,
                caption=
                f'<b>{product.title}</b>  Цена: <i> {product.get_price} 💵 </i> '
                f' <code> {product.description} </code>',
                reply_markup=keyboard,
                parse_mode='HTML')
Exemple #28
0
def get_topics_keyboard(state_button=4):
    with DBHelper() as db:
        topics = db.get_post_topics()

    keyboard = InlineKeyboardMarkup()

    for i in range(state_button - 4, state_button):
        if i < len(topics):
            keyboard.add(
                InlineKeyboardButton(text=topics[i],
                                     callback_data=f'topic_{topics[i]}'))
        else:
            break

    button_next = InlineKeyboardButton(text="»", callback_data="next")
    button_prev = InlineKeyboardButton(text="«", callback_data="prev")
    if state_button == 4 and state_button < len(topics):
        keyboard.add(button_next)
    elif state_button > 4 and state_button < len(topics):
        keyboard.add(button_prev, button_next)
    elif state_button > 4:
        keyboard.add(button_prev)

    return keyboard
Exemple #29
0
def show_options(call):
    chat_id = call.message.chat.id
    bot.send_chat_action(chat_id, 'typing')
    time.sleep(0.5)
    try:
        bot.delete_message(chat_id, call.message.message_id)
    except Exception:
        pass
    markup = InlineKeyboardMarkup()
    options = db.get_options(id_section=call.data.split("-")[1])
    i = 0
    btn = []
    limit = int(len(options) / 2)
    for option in options:
        if i != 2:
            btn.append(
                InlineKeyboardButton(text=option[2],
                                     callback_data="content" + "-" +
                                     str(option[0]) + "-" +
                                     str(call.data.split("-")[1])))
            i += 1
        if i == 2:
            markup.add(btn[0], btn[1])
            limit -= 1
            i = 0
            btn = []
        elif limit == 0:
            markup.add(
                InlineKeyboardButton(text=option[2],
                                     callback_data="content" + "-" +
                                     str(option[0]) + "-" +
                                     str(call.data.split("-")[1])))
    markup.add(InlineKeyboardButton("بازگشت", callback_data="section"))
    bot.send_message(call.message.chat.id,
                     "در چه زمینه ای سوال دارید؟",
                     reply_markup=markup)
 def __GetMarkupForAssetList(self,
                             assetsList: list,
                             withSkipBtn: bool = False):
     assetsCount = len(assetsList)
     rowsCount = assetsCount // 5
     if assetsCount % 5 > 0:
         rowsCount += 1
     keyboard = InlineKeyboardMarkup(row_width=rowsCount + 1)
     buttons = [
         InlineKeyboardButton(a, callback_data=a) for a in assetsList
     ]
     keyboard.add(*buttons)
     secondaryButtons = [
         InlineKeyboardButton(ld.get_translate(self.__db, self.username,
                                               ld.CancelKey),
                              callback_data=ld.CancelKey)
     ]
     if withSkipBtn:
         secondaryButtons.append(
             InlineKeyboardButton(ld.get_translate(self.__db, self.username,
                                                   ld.SkipKey),
                                  callback_data=ld.SkipKey))
     keyboard.row(*secondaryButtons)
     return keyboard