Пример #1
0
def forecast(message):
    try:
        words = message.text.split()
        city_name = words[1]
        loc = geolocator.geocode(city_name)
        if loc is None:
            bot.reply_to(message, 'Такой город не найден')
        else:
            forecast_message = bot.send_message(
                chat_id=message.chat.id,
                text='Готовлю прогноз погоды для Вас)',
                reply_to_message_id=message.message_id)

            global forecasts
            forecasts[forecast_message.message_id] = []

            response = requests.get(
                'https://api.openweathermap.org/data/2.5/onecall?lat=' +
                str(loc.latitude) + '&lon=' + str(loc.longitude) +
                '&appid=c1c0032b6ff3be83e44ab641e780fc3d&lang=RU' +
                '&units=metric')

            data = json.loads(response.content)
            destination = loc.address.split(',')

            for i in range(8):
                text = '<b><i>Погода в '
                for j in destination:
                    if j == destination[0]:
                        text += j
                    else:
                        text += ',' + j

                text += '</i></b>\n'
                text += '━━━━━━━━━━━━━━━━━━━━━━━\n'
                text += '<b>Прогноз на ' + time.strftime(
                    "%d/%m", time.gmtime(data['daily'][i]['dt'])) + '</b>\n'
                text += '━━━━━━━━━━━━━━━━━━━━━━━\n'
                text += '<b>' + str(
                    data['daily'][i]['temp']
                    ['day']) + ' °C <i>' + data['daily'][i]['weather'][0][
                        'description'].capitalize() + '</i></b>\n'
                text += '<i>Мин. температура:</i> <b>' + str(
                    data['daily'][i]['temp']['min']) + ' °C</b>\n'
                text += '<i>Макс. температура:</i> <b>' + str(
                    data['daily'][i]['temp']['max']) + ' °C</b>\n'
                text += '<i>Температура утром:</i> <b>' + str(
                    data['daily'][i]['temp']['morn']) + ' °C</b>\n'
                text += '<i>Температура вечером:</i> <b>' + str(
                    data['daily'][i]['temp']['eve']) + ' °C</b>\n'
                text += '<i>Температура ночью:</i> <b>' + str(
                    data['daily'][i]['temp']['night']) + ' °C</b>\n'
                text += '<i>Влажность:</i> <b>' + str(
                    data['daily'][i]['humidity']) + '%</b>\n'
                text += '<i>Давление:</i> <b>' + str(
                    data['daily'][i]['pressure']) + ' гПа</b>\n'
                text += '<i>Скорость ветра:</i> <b>' + str(
                    data['daily'][i]['wind_speed']) + ' м/с</b>\n'
                text += '<i>Облачность:</i> <b>' + str(
                    data['daily'][i]['clouds']) + '%</b>\n'
                text += '<i>UV индекс:</i> <b>' + str(
                    data['daily'][i]['uvi']) + '</b>'

                forecasts[forecast_message.message_id].append(text)

            forecasts[forecast_message.message_id].append(0)
            forecasts[forecast_message.message_id].append(message.from_user.id)

            keyboard = types.InlineKeyboardMarkup(row_width=2)
            key_prev = types.InlineKeyboardButton(
                text='<<', callback_data='forecast_prev')
            key_next = types.InlineKeyboardButton(
                text='>>', callback_data='forecast_next')
            keyboard.add(key_prev, key_next)
            key_close = types.InlineKeyboardButton(
                text='Я прочитал', callback_data='forecast_close')
            keyboard.add(key_close)

            bot.edit_message_text(
                chat_id=message.chat.id,
                message_id=forecast_message.message_id,
                text=forecasts[forecast_message.message_id][0],
                parse_mode='HTML',
                reply_markup=keyboard)

    except Exception:
        bot.reply_to(message, 'Упс... Что-то пошло не так')
Пример #2
0
    def add(message):
        #         def price_finish(message):
        #             zakazi[message.from_user.username]['price']=message.text
        #             mes="""Ваша заявка-{}
        # Цена-{}
        # Категория-{}""".format(zakazi[message.from_user.username]['description'],zakazi[message.from_user.username]['price'],zakazi[message.from_user.username]['category'])
        #             markup=types.InlineKeyboardMarkup()
        #             markup.add(types.InlineKeyboardButton(text='Разместить заявку',callback_data='{},{},{}'.format(zakazi[message.from_user.username]['description'],zakazi[message.from_user.username]['price'],zakazi[message.from_user.username]['category'])))

        #             markup.add(types.InlineKeyboardButton(text='Отмена❌',callback_data='otmena'))
        #             f=bot.send_message(message.from_user.id,mes,reply_markup=markup)

        #         def desc_price(message):
        #             zakazi[message.from_user.username]['description']=message.text
        #             f=bot.send_message(message.from_user.id,'Напишите,сколько вы готовы за это заплатить.(если вы не знаете, отправьте "-")')
        #             bot.register_next_step_handler(f,price_finish)

        if 'category' in message.data and message.from_user.id in users:
            cat = message.data.replace('category', '')
            print(cat)
            bot.send_message(message.from_user.id,
                             'Выбери под-категорию',
                             reply_markup=config.get_dd(cat))
            # users[message.from_user.id]['category']=cat
            # markup=types.InlineKeyboardMarkup()
            # markup.add(types.InlineKeyboardButton(text='Согласен',callback_data='personal'))
            # f=bot.send_message(message.from_user.id,'Согласны ли вы на обработку ваших персональных данных?',reply_markup=markup)

        if 'ctgrt' in message.data and message.from_user.id in users:
            cat = message.data.replace('ctgrt', '')
            users[message.from_user.id]['category'] = cat
            markup = types.InlineKeyboardMarkup()
            markup.add(
                types.InlineKeyboardButton(text='Согласен',
                                           callback_data='personal'))
            f = bot.send_message(
                message.from_user.id,
                'Согласны ли вы на обработку ваших персональных данных?',
                reply_markup=markup)
        if 'personal' in message.data and message.from_user.id in users:
            markup = types.InlineKeyboardMarkup()
            now = datetime.now()  # current date and time
            date_time = now.strftime("%m.%d.%Y")
            sql_query(
                'INSERT INTO workers (name,phone,city,category,username,tid,date) VALUES ({},{},{},{},{},{},{})'
                .format(to_base(users[message.from_user.id]['name']),
                        to_base(users[message.from_user.id]['phone']),
                        to_base(users[message.from_user.id]['city']),
                        to_base(users[message.from_user.id]['category']),
                        to_base(message.from_user.id),
                        to_base(message.from_user.id), to_base(date_time)))
            markup.add(
                types.InlineKeyboardButton(text='Изменить личные данные',
                                           callback_data='change data'))
            markup.add(
                types.InlineKeyboardButton(text='Мои подписки',
                                           callback_data='podpiski'))
            markup.add(
                types.InlineKeyboardButton(text='Наши соц-сети',
                                           callback_data='socset'))
            markup.add(
                types.InlineKeyboardButton(text='Оставить заявку',
                                           callback_data='ispo'))

            f = bot.send_message(
                message.from_user.id,
                'Подписка на наш сервис оформленна, в этот чат вам будут приходить заявки от клиентов. Изменить свои данные вы можете по кнопке ниже🔽',
                reply_markup=markup)
            users.pop(message.from_user.id, 1)

        if 'socset' in message.data:
            mes = 'Текст с соц-сетями'
            markup = types.InlineKeyboardMarkup()
            markup.add(
                types.InlineKeyboardButton(text='Изменить личные данные',
                                           callback_data='change data'))
            markup.add(
                types.InlineKeyboardButton(text='Мои подписки',
                                           callback_data='podpiski'))

            markup.add(
                types.InlineKeyboardButton(text='Наши соц-сети',
                                           callback_data='socset'))
            markup.add(
                types.InlineKeyboardButton(text='Оставить заявку',
                                           callback_data='ispo'))
            f = bot.send_message(message.from_user.id, mes)
        if 'ispo' in message.data:
            mes = 'Чтобы стать заказчиком, напишите этуму боту- @Glosi_bot'
            markup = types.InlineKeyboardMarkup()
            markup.add(
                types.InlineKeyboardButton(text='Изменить личные данные',
                                           callback_data='change data'))
            markup.add(
                types.InlineKeyboardButton(text='Мои подписки',
                                           callback_data='podpiski'))

            markup.add(
                types.InlineKeyboardButton(text='Наши соц-сети',
                                           callback_data='socset'))
            markup.add(
                types.InlineKeyboardButton(text='Оставить заявку',
                                           callback_data='ispo'))
            f = bot.send_message(message.from_user.id,
                                 mes,
                                 reply_markup=markup)

        if 'show' in message.data:
            dat = message.data.replace('show', '').split(',')[1]
            sq = sql_query('SELECT * FROM orders WHERE id={}'.format(
                to_base(dat)))
            sq = sq[0]
            data = sq[3].split(',')

            mes = """Имя-{}
Город-{}
Номер-{}
Ссылка на переписку-[Ссылка](tg://user?id={})
""".format(data[1], data[0], data[2], data[3])
            bot.send_message(message.from_user.id, mes, parse_mode="Markdown")
            sq = sql_query(
                """UPDATE orders SET workers = array_append(workers,{}) WHERE id={}"""
                .format(to_base(message.from_user.id), to_base(dat)))

        # if 'place order' in message.data:
        #     mes='Выберите категорию в которой вам нужно получить услугу(смайлик)'
        #     # инструкция
        #     m=bot.send_message(message.from_user.id, mes,reply_markup=config.get_categoryes())
        # if 'otmena' in message.data:
        #     mes='Заявка отменена, чтобы разместить ее снова, нажмите кнопку ниже(смайлик)'
        #     markup=types.InlineKeyboardMarkup()
        #     markup.add(types.InlineKeyboardButton(text='Разместить заявку еще раз',callback_data='place order'))
        #     markup.add(types.InlineKeyboardButton(text='Изменить личные данные',callback_data='change personal'))
        #     f=bot.send_message(message.from_user.id,mes,reply_markup=markup)

        if 'change data' in message.data:
            markup = types.InlineKeyboardMarkup()
            markup.add(
                types.InlineKeyboardButton(text='Изменить номер телефона',
                                           callback_data='changes,phone'))
            markup.add(
                types.InlineKeyboardButton(text='Изменить имя',
                                           callback_data='changes,name'))
            markup.add(
                types.InlineKeyboardButton(text='Изменить город',
                                           callback_data='changes,city'))

            f = bot.send_message(
                message.from_user.id,
                'Что вы хотите изменить? Нажмите на соответствуюущую кнопку🔽',
                reply_markup=markup)

        if 'podpiski' in message.data:
            sq = sql_query('SELECT category FROM workers WHERE tid={}'.format(
                to_base(message.from_user.id)))
            print(sq)
            markup = types.InlineKeyboardMarkup()
            markup.add(
                types.InlineKeyboardButton(text='Добавить категорию',
                                           callback_data='addcat'))
            markup.add(
                types.InlineKeyboardButton(text='Удалить категорию',
                                           callback_data='deletecat'))

            mes = 'Категории на которые вы подписаны-'
            for i in sq:
                mes += '\n' + i[0]
            bot.send_message(message.from_user.id, mes, reply_markup=markup)
        if 'deletecat' in message.data:
            sq = sql_query('SELECT category FROM workers WHERE tid={}'.format(
                to_base(message.from_user.id)))
            markup = types.InlineKeyboardMarkup()
            if len(sq) > 1:
                for i in sq:
                    markup.add(
                        types.InlineKeyboardButton(text=i[0],
                                                   callback_data='axz' + i[0]))

                mes = 'Выберите подписку от которой хотите отказаться ниже'

                bot.send_message(message.from_user.id,
                                 mes,
                                 reply_markup=markup)
            else:
                markup = types.InlineKeyboardMarkup()
                markup.add(
                    types.InlineKeyboardButton(text='Изменить личные данные',
                                               callback_data='change data'))
                markup.add(
                    types.InlineKeyboardButton(text='Мои подписки',
                                               callback_data='podpiski'))

                markup.add(
                    types.InlineKeyboardButton(text='Наши соц-сети',
                                               callback_data='socset'))
                markup.add(
                    types.InlineKeyboardButton(text='Оставить заявку',
                                               callback_data='ispo'))
                mes = 'Нельзя отменить единственную подписку'

                bot.send_message(message.from_user.id,
                                 mes,
                                 reply_markup=markup)
        if 'axz' in message.data:
            cat = message.data.replace('axz', '')
            sq = sql_query(
                'DELETE FROM workers WHERE tid={} AND category={}'.format(
                    to_base(message.from_user.id), to_base(cat)))
            mes = 'Подписка успешно отменена'
            bot.send_message(message.from_user.id, mes)

        if 'addcat' in message.data:
            mes = 'Выберите категорию по которой хотите получать заказы'
            # users.pop(message.from_user.username,1)
            m = bot.send_message(message.from_user.id,
                                 mes,
                                 reply_markup=config.get_cat2())

        if 'csd' in message.data:
            cat = message.data.replace('csd', '')

            mes = 'Выберите подкатегорию'
            # users.pop(message.from_user.username,1)
            m = bot.send_message(message.from_user.id,
                                 mes,
                                 reply_markup=config.get_ff(cat))
        if 'ctadd' in message.data:
            cat = message.data.replace('ctadd', '')

            mes = 'Подписка на категорию оформленна.'
            markup = types.InlineKeyboardMarkup()
            markup.add(
                types.InlineKeyboardButton(text='Изменить личные данные',
                                           callback_data='change data'))
            markup.add(
                types.InlineKeyboardButton(text='Мои подписки',
                                           callback_data='podpiski'))
            sq = sql_query('SELECT * FROM workers WHERE tid={}'.format(
                to_base(message.from_user.id)))
            sq = sq[0]
            print(sq)
            now = datetime.now()  # current date and time
            date_time = now.strftime("%m.%d.%Y")
            sql_query(
                'INSERT INTO workers (name,phone,city,category,username,tid,date) VALUES ({},{},{},{},{},{},{})'
                .format(to_base(users[message.from_user.id]['name']),
                        to_base(users[message.from_user.id]['phone']),
                        to_base(users[message.from_user.id]['city']),
                        to_base(users[message.from_user.id]['category']),
                        to_base(message.from_user.id),
                        to_base(message.from_user.id), to_base(date_time)))
            markup.add(
                types.InlineKeyboardButton(text='Наши соц-сети',
                                           callback_data='socset'))
            markup.add(
                types.InlineKeyboardButton(text='Оставить заявку',
                                           callback_data='ispo'))
            # users.pop(message.from_user.username,1)
            m = bot.send_message(message.from_user.id,
                                 mes,
                                 reply_markup=markup)

        if 'changes' in message.data:

            def change_data(message, do):
                try:
                    sql_query('UPDATE workers SET {}={} WHERE tid={} '.format(
                        do, to_base(message.text),
                        to_base(message.from_user.id)))
                    markup = types.InlineKeyboardMarkup()
                    markup.add(
                        types.InlineKeyboardButton(
                            text='Изменить личные данные',
                            callback_data='change data'))
                    markup.add(
                        types.InlineKeyboardButton(text='Мои подписки',
                                                   callback_data='podpiski'))

                    markup.add(
                        types.InlineKeyboardButton(text='Наши соц-сети',
                                                   callback_data='socset'))
                    markup.add(
                        types.InlineKeyboardButton(text='Оставить заявку',
                                                   callback_data='ispo'))
                    bot.send_message(message.from_user.id,
                                     'Успешно',
                                     reply_markup=markup)
                except Exception as e:
                    print(e)

            f = False
            do = message.data.split(',')[1]
            if do == 'city':
                f = bot.send_message(message.from_user.id,
                                     'Выбери свой город ниже🔽',
                                     reply_markup=reply_city())
            elif do == 'category':
                f = bot.send_message(message.from_user.id,
                                     'Выбери категорию город ниже🔽',
                                     reply_markup=config.get_cat())

            else:

                rep = {'name': 'Свое имя', 'phone': 'Свой номер'}
                f = bot.send_message(message.from_user.id,
                                     'Напиши мне {} '.format(rep[do]),
                                     reply_markup=types.ReplyKeyboardRemove())
            bot.register_next_step_handler(
                f, lambda message: change_data(message, do))
Пример #3
0
def callback_inline(call):
    if call.data == "doki":
        comproxy_keyboard = types.InlineKeyboardMarkup(row_width=1)
        call_button_evropa = types.InlineKeyboardButton(text="Европа",
                                                        callback_data="evropa")
        call_button_usa = types.InlineKeyboardButton(text="США.Канада",
                                                     callback_data="usa")
        call_button_azia = types.InlineKeyboardButton(text="Азия",
                                                      callback_data="azia")
        call_button_other = types.InlineKeyboardButton(text="Другие страны",
                                                       callback_data="other")
        call_button_back = types.InlineKeyboardButton(text="Назад",
                                                      callback_data="back")
        comproxy_keyboard.add(call_button_evropa, call_button_azia,
                              call_button_usa, call_button_other)
        comproxy_keyboard.add(call_button_back)
        bot.edit_message_text(chat_id=call.message.chat.id,
                              message_id=call.message.message_id,
                              text="Выберите континент:",
                              reply_markup=comproxy_keyboard)

    elif call.data == "cena":
        comproxy_keyboard = types.InlineKeyboardMarkup(row_width=1)
        call_button_evropa = types.InlineKeyboardButton(text="Европа",
                                                        callback_data="evropa")
        call_button_usa = types.InlineKeyboardButton(text="США.Канада",
                                                     callback_data="usa")
        call_button_britania = types.InlineKeyboardButton(
            text="Великобритания", callback_data="britania")
        call_button_azia = types.InlineKeyboardButton(text="Азия",
                                                      callback_data="azia")
        call_button_other = types.InlineKeyboardButton(text="Другие страны",
                                                       callback_data="other")
        call_button_back = types.InlineKeyboardButton(text="Назад",
                                                      callback_data="back")
        comproxy_keyboard.add(call_button_evropa, call_button_usa,
                              call_button_britania, call_button_azia,
                              call_button_other)
        comproxy_keyboard.add(call_button_back)
        bot.edit_message_text(chat_id=call.message.chat.id,
                              message_id=call.message.message_id,
                              text="Выберите континент:",
                              reply_markup=comproxy_keyboard)

    if call.data == "online":
        comproxy_keyboard = types.InlineKeyboardMarkup(row_width=1)
        call_button_oprosnik = types.InlineKeyboardButton(
            text="Скачать опросник", callback_data="dowopr")
        call_button_send = types.InlineKeyboardButton(
            text="Отправить документы", callback_data="sendopr")
        call_button_back = types.InlineKeyboardButton(text="Назад",
                                                      callback_data="back")
        comproxy_keyboard.add(call_button_oprosnik, call_button_send)
        comproxy_keyboard.add(call_button_back)
        bot.edit_message_text(
            chat_id=call.message.chat.id,
            message_id=call.message.message_id,
            text="Если вы не заполняли опросник, выберите 'Скачать опросник'\n"
            "Если вы уже заполнили опросник и подготовили документы\n"
            "нажмите на 'Отправить документв'",
            reply_markup=comproxy_keyboard)

    elif call.data == "dowopr":
        comproxy_keyboard = types.InlineKeyboardMarkup(row_width=1)
        call_button_evopr = types.InlineKeyboardButton(
            text="Опросник для визы в Европу", callback_data="evoopr")
        call_button_usaopr = types.InlineKeyboardButton(
            text="Опросник для визы в США", callback_data="usaopr")
        call_button_britanopr = types.InlineKeyboardButton(
            text="Опросник для визы в Англию", callback_data="bropr")
        call_button_chinaopr = types.InlineKeyboardButton(
            text="Опросник для визы в Китай", callback_data="chinaopr")
        call_button_austopr = types.InlineKeyboardButton(
            text="Опросник для визы в Австралию", callback_data="austopr")
        call_button_back = types.InlineKeyboardButton(text="Назад",
                                                      callback_data="back")
        comproxy_keyboard.add(call_button_evopr, call_button_usaopr,
                              call_button_britanopr, call_button_chinaopr,
                              call_button_austopr, call_button_back)
        bot.edit_message_text(chat_id=call.message.chat.id,
                              message_id=call.message.message_id,
                              text="Что то написать ",
                              reply_markup=comproxy_keyboard)

    elif call.data == "evoopr":
        comproxy_keyboard = types.InlineKeyboardMarkup(row_width=1)
        callback_button_1 = types.InlineKeyboardButton(
            text="Узнать список документов", callback_data="doki")
        call_button_back = types.InlineKeyboardButton(text="Назад",
                                                      callback_data="back")
        comproxy_keyboard.add(callback_button_1, call_button_back)
        bot.edit_message_text(chat_id=call.message.chat.id,
                              message_id=call.message.message_id,
                              text="Можете сразу узнать список документов\n "
                              "или вернуться назад",
                              reply_markup=comproxy_keyboard)
        bot.send_document(chat_id=call.message.chat.id,
                          data=open(
                              "/home/archi/vc/oprosniki/Опросник Шенген.pdf",
                              "rb"))

    elif call.data == "usaopr":
        comproxy_keyboard = types.InlineKeyboardMarkup(row_width=1)
        callback_button_1 = types.InlineKeyboardButton(
            text="Узнать список документов", callback_data="doki")
        call_button_back = types.InlineKeyboardButton(text="Назад",
                                                      callback_data="back")
        comproxy_keyboard.add(callback_button_1, call_button_back)
        bot.edit_message_text(chat_id=call.message.chat.id,
                              message_id=call.message.message_id,
                              text="Можете сразу узнать список документов\n "
                              "или вернуться назад",
                              reply_markup=comproxy_keyboard)
        bot.send_document(
            chat_id=call.message.chat.id,
            data=open("/home/archi/vc/oprosniki/США Опросник-Word.docx", "rb"))

    elif call.data == "bropr":
        comproxy_keyboard = types.InlineKeyboardMarkup(row_width=1)
        callback_button_1 = types.InlineKeyboardButton(
            text="Узнать список документов", callback_data="doki")
        call_button_back = types.InlineKeyboardButton(text="Назад",
                                                      callback_data="back")
        comproxy_keyboard.add(callback_button_1, call_button_back)
        bot.edit_message_text(chat_id=call.message.chat.id,
                              message_id=call.message.message_id,
                              text="Можете сразу узнать список документов\n "
                              "или вернуться назад",
                              reply_markup=comproxy_keyboard)
        bot.send_document(chat_id=call.message.chat.id,
                          data=open(
                              "/home/archi/vc/oprosniki/Опросник Англия.pdf",
                              "rb"))

    elif call.data == "chinaopr":
        comproxy_keyboard = types.InlineKeyboardMarkup(row_width=1)
        callback_button_1 = types.InlineKeyboardButton(
            text="Узнать список документов", callback_data="doki")
        call_button_back = types.InlineKeyboardButton(text="Назад",
                                                      callback_data="back")
        comproxy_keyboard.add(callback_button_1, call_button_back)
        bot.edit_message_text(chat_id=call.message.chat.id,
                              message_id=call.message.message_id,
                              text="Можете сразу узнать список документов\n "
                              "или вернуться назад",
                              reply_markup=comproxy_keyboard)
        bot.send_document(chat_id=call.message.chat.id,
                          data=open(
                              "/home/archi/vc/oprosniki/Опросник Китай.docx",
                              "rb"))

    elif call.data == "austopr":
        comproxy_keyboard = types.InlineKeyboardMarkup(row_width=1)
        callback_button_1 = types.InlineKeyboardButton(
            text="Узнать список документов", callback_data="doki")
        call_button_back = types.InlineKeyboardButton(text="Назад",
                                                      callback_data="back")
        comproxy_keyboard.add(callback_button_1, call_button_back)
        bot.edit_message_text(chat_id=call.message.chat.id,
                              message_id=call.message.message_id,
                              text="Можете сразу узнать список документов\n "
                              "или вернуться назад",
                              reply_markup=comproxy_keyboard)
        bot.send_document(
            chat_id=call.message.chat.id,
            data=open("/home/archi/vc/oprosniki/Опросник Австралия.doc", "rb"))

    if call.data == "sendopr":
        comproxy_keyboard = types.InlineKeyboardMarkup(row_width=1)
        callback_button_1 = types.InlineKeyboardButton(
            text="Узнать список документов", callback_data="doki")
        callback_button_4 = types.InlineKeyboardButton(text="Наш инстаграм",
                                                       callback_data="insta",
                                                       url=links.url_ins_che)
        callback_button_5 = types.InlineKeyboardButton(text="Мы ВКонтакте",
                                                       callback_data="vk",
                                                       url=links.url_vk_che)
        call_button_back = types.InlineKeyboardButton(text="Назад",
                                                      callback_data="back")
        comproxy_keyboard.add(callback_button_1, callback_button_4,
                              callback_button_5, call_button_back)
        bot.edit_message_text(
            chat_id=call.message.chat.id,
            message_id=call.message.message_id,
            text="Sooryy! Уже совсем скоро мы запустим этот раздел",
            reply_markup=comproxy_keyboard)

    if call.data == "evropa":
        comproxy_keyboard = types.InlineKeyboardMarkup(row_width=2)
        call_button_austria = types.InlineKeyboardButton(
            text="Австрия", callback_data="austria", url=vili.austria)
        call_button_belgium = types.InlineKeyboardButton(
            text="Бельгия", callback_data="belgiun", url=vili.belgiun)
        call_button_bulgary = types.InlineKeyboardButton(
            text="Болгария", callback_data="bulgary", url=vili.bulgary)
        call_button_hungary = types.InlineKeyboardButton(
            text="Венгрия", callback_data="hungary", url=vili.hungary)
        call_button_greece = types.InlineKeyboardButton(text="Греция",
                                                        callback_data="greece",
                                                        url=vili.greece)
        call_button_germany = types.InlineKeyboardButton(
            text="Германия", callback_data="germany", url=vili.germany)
        call_button_denmark = types.InlineKeyboardButton(
            text="Дания", callback_data="denmark", url=vili.denmark)
        call_button_spain = types.InlineKeyboardButton(text="Испания",
                                                       callback_data="spain",
                                                       url=vili.spain)
        call_button_italy = types.InlineKeyboardButton(text="Италия",
                                                       callback_data="italy",
                                                       url=vili.italy)
        call_button_cyprus = types.InlineKeyboardButton(text="Кипр",
                                                        callback_data="cyprus",
                                                        url=vili.cyprus)
        call_button_litva = types.InlineKeyboardButton(text="Литва",
                                                       callback_data="litva",
                                                       url=vili.litva)
        call_button_lithua = types.InlineKeyboardButton(text="Латвия",
                                                        callback_data="lithua",
                                                        url=vili.lithua)
        call_button_malta = types.InlineKeyboardButton(text="Мальта",
                                                       callback_data="malta",
                                                       url=vili.malta)
        call_button_niderland = types.InlineKeyboardButton(
            text="Нидерланды", callback_data="niderland", url=vili.niderland)
        call_button_poland = types.InlineKeyboardButton(text="Польша",
                                                        callback_data="poland",
                                                        url=vili.poland)
        call_button_portugal = types.InlineKeyboardButton(
            text="Португалия", callback_data="portugal", url=vili.portugal)
        call_button_romania = types.InlineKeyboardButton(
            text="Румыния", callback_data="romania", url=vili.romania)
        call_button_finland = types.InlineKeyboardButton(
            text="Финляндия", callback_data="finland", url=vili.finland)
        call_button_france = types.InlineKeyboardButton(text="Франция",
                                                        callback_data="france",
                                                        url=vili.france)
        call_button_slovakia = types.InlineKeyboardButton(
            text="Словакия", callback_data="slovakia", url=vili.slovakia)
        call_button_slovenia = types.InlineKeyboardButton(
            text="Словения", callback_data="slovenia", url=vili.slovenia)
        call_button_croatia = types.InlineKeyboardButton(
            text="Хорватия", callback_data="croatia", url=vili.croatia)
        call_button_czech = types.InlineKeyboardButton(text="Чехия",
                                                       callback_data="czech",
                                                       url=vili.czech)
        call_button_switzerland = types.InlineKeyboardButton(
            text="Швейцария",
            callback_data="switzerland",
            url=vili.switzerland)
        call_button_sweden = types.InlineKeyboardButton(text="Швеция",
                                                        callback_data="sweden",
                                                        url=vili.sweden)
        call_button_estonia = types.InlineKeyboardButton(
            text="Эстония", callback_data="estonia", url=vili.estonia)
        call_button_comeback = types.InlineKeyboardButton(
            text="Вернуться назад", callback_data="comeback")
        comproxy_keyboard.add(call_button_austria, call_button_belgium, call_button_bulgary, call_button_hungary, call_button_greece,\
                              call_button_germany, call_button_denmark, call_button_spain, call_button_italy,\
                              call_button_cyprus, call_button_litva, call_button_lithua, call_button_malta,\
                              call_button_niderland, call_button_poland, call_button_portugal, call_button_romania,\
                              call_button_finland, call_button_france, call_button_slovakia, call_button_slovenia,\
                              call_button_croatia, call_button_czech, call_button_switzerland, call_button_sweden,\
                              call_button_estonia,call_button_comeback)
        bot.edit_message_text(
            chat_id=call.message.chat.id,
            message_id=call.message.message_id,
            text="Выберите страну и вы получите список документов?:",
            reply_markup=comproxy_keyboard)

    elif call.data == "usa":
        comproxy_keyboard = types.InlineKeyboardMarkup(row_width=1)
        call_button_usa = types.InlineKeyboardButton(text="США",
                                                     callback_data="usa1",
                                                     url=vili.usa1)
        call_button_canada = types.InlineKeyboardButton(text="Канада",
                                                        callback_data="canada",
                                                        url=vili.canada)
        call_button_comeback = types.InlineKeyboardButton(
            text="Вернуться назад", callback_data="comeback")
        comproxy_keyboard.add(call_button_usa, call_button_canada,
                              call_button_comeback)
        bot.edit_message_text(
            chat_id=call.message.chat.id,
            message_id=call.message.message_id,
            text="Выберите страну и вы узнаете список документов",
            reply_markup=comproxy_keyboard)

    elif call.data == "azia":
        comproxy_keyboard = types.InlineKeyboardMarkup(row_width=1)
        call_button_vietnam = types.InlineKeyboardButton(
            text="Вьетнам", callback_data="vietnam", url=vili.vietnam)
        call_button_indiya = types.InlineKeyboardButton(text="Индия",
                                                        callback_data="indiya",
                                                        url=vili.indiya)
        call_button_china = types.InlineKeyboardButton(text="Китай",
                                                       callback_data="china",
                                                       url=vili.china)
        call_button_thailand = types.InlineKeyboardButton(
            text="Таиланд", callback_data="thailand", url=vili.thailand)
        call_button_singapore = types.InlineKeyboardButton(
            text="Сингапур", callback_data="singapore", url=vili.singapore)
        call_button_japan = types.InlineKeyboardButton(text="Япония",
                                                       callback_data="japan",
                                                       url=vili.japan)
        call_button_korea = types.InlineKeyboardButton(text="Южная Корея",
                                                       callback_data="korea",
                                                       url=vili.korea)
        call_button_comeback = types.InlineKeyboardButton(
            text="Вернуться назад", callback_data="comeback")
        comproxy_keyboard.add(call_button_vietnam, call_button_indiya, call_button_china, call_button_thailand, call_button_singapore,\
                              call_button_japan, call_button_korea, call_button_comeback)
        bot.edit_message_text(
            chat_id=call.message.chat.id,
            message_id=call.message.message_id,
            text="Выберите страну и вы узнате список документов",
            reply_markup=comproxy_keyboard)

    elif call.data == "britania":
        comproxy_keyboard = types.InlineKeyboardMarkup(row_width=1)
        call_button_britan = types.InlineKeyboardButton(text="Англия",
                                                        callback_data="britan",
                                                        url=vili.britan)
        call_button_ireland = types.InlineKeyboardButton(
            text="Ирландия", callback_data="ireland", url=vili.ireland)
        call_button_comeback = types.InlineKeyboardButton(
            text="Вернуться назад", callback_data="comeback")
        comproxy_keyboard.add(call_button_britan, call_button_ireland,
                              call_button_comeback)
        bot.edit_message_text(
            chat_id=call.message.chat.id,
            message_id=call.message.message_id,
            text="Выберите страну и вы узнате список документов",
            reply_markup=comproxy_keyboard)

    elif call.data == "other":
        comproxy_keyboard = types.InlineKeyboardMarkup(row_width=1)
        call_button_australia = types.InlineKeyboardButton(
            text="Австралия", callback_data="australia", url=vili.australia)
        call_button_mexico = types.InlineKeyboardButton(text="Мексика",
                                                        callback_data="mexico",
                                                        url=vili.mexico)
        call_button_comeback = types.InlineKeyboardButton(
            text="Вернуться назад", callback_data="comeback")
        comproxy_keyboard.add(call_button_australia, call_button_mexico,
                              call_button_comeback)
        bot.edit_message_text(
            chat_id=call.message.chat.id,
            message_id=call.message.message_id,
            text="Выберите страну и вы узнате список документов",
            reply_markup=comproxy_keyboard)

    elif call.data == "back":
        comproxy_keyboard = types.InlineKeyboardMarkup(row_width=1)
        callback_button_1 = types.InlineKeyboardButton(
            text="Список документов", callback_data="doki")
        callback_button_2 = types.InlineKeyboardButton(text="Стоимость визы",
                                                       callback_data="cena")
        callback_button_3 = types.InlineKeyboardButton(
            text="Оформить онлайн визу", callback_data="online")
        callback_button_4 = types.InlineKeyboardButton(
            text="Наш инстаграм",
            callback_data="insta",
            url="https://www.instagram.com/liberty_visa/?hl=ru")
        callback_button_5 = types.InlineKeyboardButton(
            text="Мы ВКонтакте",
            callback_data="vk",
            url="https://vk.com/libertyviza")
        callback_button_6 = types.InlineKeyboardButton(
            text="Связаться  с нами", callback_data="contact")
        comproxy_keyboard.add(callback_button_1, callback_button_2,
                              callback_button_3, callback_button_4,
                              callback_button_5, callback_button_6)
        bot.edit_message_text(chat_id=call.message.chat.id,
                              message_id=call.message.message_id,
                              text="Выберите что вы хотели бы узнать?",
                              reply_markup=comproxy_keyboard)

    elif call.data == "comeback":
        comproxy_keyboard = types.InlineKeyboardMarkup(row_width=1)
        call_button_evropa = types.InlineKeyboardButton(text="Европа",
                                                        callback_data="evropa")
        call_button_usa = types.InlineKeyboardButton(text="США.Канада",
                                                     callback_data="usa")
        call_button_britania = types.InlineKeyboardButton(
            text="Великобритания", callback_data="britania")
        call_button_azia = types.InlineKeyboardButton(text="Азия",
                                                      callback_data="azia")
        call_button_other = types.InlineKeyboardButton(text="Другие страны",
                                                       callback_data="other")
        call_button_back = types.InlineKeyboardButton(text="Назад",
                                                      callback_data="back")
        comproxy_keyboard.add(call_button_evropa, call_button_usa,
                              call_button_britania, call_button_azia,
                              call_button_other)
        comproxy_keyboard.add(call_button_back)
        bot.edit_message_text(chat_id=call.message.chat.id,
                              message_id=call.message.message_id,
                              text="Выберите континент:",
                              reply_markup=comproxy_keyboard)

    if call.data == "contact":
        comproxy_keyboard = types.InlineKeyboardMarkup(row_width=1)
        call_button_telefon = types.InlineKeyboardButton(
            text="По номеру телефона", callback_data="telefon_number")
        #call_button_email = types.InlineKeyboardButton(text="Написать email", callback_data="email")
        #call_button_adress = types.InlineKeyboardButton(text="Узнать адрес", callback_data="adress")
        callback_button_4 = types.InlineKeyboardButton(
            text="Написать в Instagram",
            callback_data="insta",
            url=links.url_ins_che)
        callback_button_5 = types.InlineKeyboardButton(text="Написать в VK ",
                                                       callback_data="vk",
                                                       url=links.url_vk_che)
        call_button_back = types.InlineKeyboardButton(text="Назад",
                                                      callback_data="back")
        comproxy_keyboard.add(call_button_telefon, callback_button_4,
                              callback_button_5)
        comproxy_keyboard.add(call_button_back)
        bot.edit_message_text(chat_id=call.message.chat.id,
                              message_id=call.message.message_id,
                              text="Выберите, способ связи с нами:",
                              reply_markup=comproxy_keyboard)

    elif call.data == "telefon_number":
        comproxy_keyboard = types.InlineKeyboardMarkup(row_width=1)
        call_button_chelyabinsk = types.InlineKeyboardButton(
            text='Челябинск', callback_data="chelyabinsk")
        call_button_krasnoyarsk = types.InlineKeyboardButton(
            text='Красноярск', callback_data="krasnoyarsk")
        call_button_surgut = types.InlineKeyboardButton(text='Сургут',
                                                        callback_data="surgut")
        comproxy_keyboard.add(call_button_chelyabinsk, call_button_krasnoyarsk,
                              call_button_surgut)
        bot.edit_message_text(chat_id=call.message.chat.id,
                              message_id=call.message.message_id,
                              text="Выберите город нашего офиса",
                              reply_markup=comproxy_keyboard)

    elif call.data == "chelyabinsk":
        bot.send_contact(chat_id=call.message.chat.id,
                         first_name=links.name_che,
                         last_name='Челябинск',
                         phone_number=links.telefon_che)
        bot.send_message(chat_id=call.message.chat.id, text=links.adres_che)
    elif call.data == "krasnoyarsk":
        bot.send_contact(chat_id=call.message.chat.id,
                         first_name='Визовый центр "Либерти"',
                         last_name='Челябинск',
                         phone_number="+73912630345")
        bot.send_message(chat_id=call.message.chat.id,
                         text="Адрес ВЦ 'Либерти' Красноярск:\n"
                         "улица Маерчака 18, офис 409, Красноярск")
Пример #4
0
def get_text_messages(message):
    if message.text == "Привет":
        bot.send_message(
            message.from_user.id,
            "Привет, сейчас я расскажу тебе гороскоп на сегодня.")
        # Готовим кнопки
        keyboard = types.InlineKeyboardMarkup()
        # По очереди готовим текст и обработчик для каждого знака зодиака
        key_oven = types.InlineKeyboardButton(text='Овен',
                                              callback_data='zodiac')
        # И добавляем кнопку на экран
        keyboard.add(key_oven)
        key_telec = types.InlineKeyboardButton(text='Телец',
                                               callback_data='zodiac')
        keyboard.add(key_telec)
        key_bliznecy = types.InlineKeyboardButton(text='Близнецы',
                                                  callback_data='zodiac')
        keyboard.add(key_bliznecy)
        key_rak = types.InlineKeyboardButton(text='Рак',
                                             callback_data='zodiac')
        keyboard.add(key_rak)
        key_lev = types.InlineKeyboardButton(text='Лев',
                                             callback_data='zodiac')
        keyboard.add(key_lev)
        key_deva = types.InlineKeyboardButton(text='Дева',
                                              callback_data='zodiac')
        keyboard.add(key_deva)
        key_vesy = types.InlineKeyboardButton(text='Весы',
                                              callback_data='zodiac')
        keyboard.add(key_vesy)
        key_scorpion = types.InlineKeyboardButton(text='Скорпион',
                                                  callback_data='zodiac')
        keyboard.add(key_scorpion)
        key_strelec = types.InlineKeyboardButton(text='Стрелец',
                                                 callback_data='zodiac')
        keyboard.add(key_strelec)
        key_kozerog = types.InlineKeyboardButton(text='Козерог',
                                                 callback_data='zodiac')
        keyboard.add(key_kozerog)
        key_vodoley = types.InlineKeyboardButton(text='Водолей',
                                                 callback_data='zodiac')
        keyboard.add(key_vodoley)
        key_ryby = types.InlineKeyboardButton(text='Рыбы',
                                              callback_data='zodiac')
        keyboard.add(key_ryby)
        # Показываем все кнопки сразу и пишем сообщение о выборе

        bot.send_message(message.from_user.id,
                         text='Выбери свой знак зодиака',
                         reply_markup=keyboard)
    elif message.text == "/help":
        bot.send_message(message.from_user.id, "Напиши Привет")
    else:
        bot.send_message(message.from_user.id,
                         "Я тебя не понимаю. Напиши /help.")
Пример #5
0
def change_kol(message):
    chat_id = message.chat.id
    text = message.text
    global BUFFER
    action = BUFFER[str(chat_id)][
        -1]  # Действие которое нужно выполнить(s-spend, b-back)

    name = BUFFER[str(chat_id)][:-1]  # Название материала
    message_id = BUFFER[
        'm_id' + str(chat_id)]  # id сообщения для редактирования количества

    if text == 'Отмена':
        # Меняем текст сообщения (обновляем данные, убираем спец символы)
        button1 = (
            'Израсходовать ' +
            f'(доступно: {str(exp_mat_kol(name, "Расходные материалы"))} {exp_mat_ed_izm(name, "Расходные материалы")})'
        )
        button2 = 'Вернуть'
        keyboard = types.InlineKeyboardMarkup()
        keyboard.add(
            types.InlineKeyboardButton(text=button1,
                                       callback_data='spend_exp_mat' + name))
        keyboard.add(
            types.InlineKeyboardButton(text=button2,
                                       callback_data='cancel_spend_exp_mat' +
                                       name))
        bot.edit_message_text(name, chat_id, message_id, reply_markup=keyboard)
        bot.send_message(chat_id, 'Отменено', reply_markup=main_menu_student())

        del BUFFER[str(chat_id)]
        del BUFFER['m_id' + str(chat_id)]
        return

    try:
        data = float(text.replace(',', '.'))
    except:
        msg = bot.send_message(chat_id, 'Введите число!')
        return bot.register_next_step_handler(msg, change_kol)

    if data <= 0:  # Если пользователь ввел значение меньше нуля
        msg = bot.send_message(chat_id, 'Значение должно быть больше нуля!')
        return bot.register_next_step_handler(msg, change_kol)

    wb = load_workbook('BD.xlsx')
    sheet = wb['Расходные материалы']
    value = float(exp_mat_kol(name, 'Расходные материалы'))
    last_value = value

    if int(last_value) == float(last_value):
        last_value = int(last_value)

    if action == 's':
        value -= data
        if value < 0:  # Если пользователь расходует больше чем доступно
            msg = bot.send_message(
                chat_id,
                f'Такого количества расходного материала нет (доступно: {last_value})'
            )
            return bot.register_next_step_handler(msg, change_kol)
    elif action == 'b':
        value += data

# записывем новое значение в БД
    i = 2
    while (True):
        val = sheet.cell(row=i, column=1).value
        if str(name) == str(val):
            sheet.cell(row=i, column=2).value = value
            wb.save('BD.xlsx')
            break
        i += 1

    # Меняем текст сообщения (количество)
    button1 = (
        'Израсходовать ' +
        f'(доступно: {str(exp_mat_kol(name, "Расходные материалы"))} {exp_mat_ed_izm(name, "Расходные материалы")})'
    )
    button2 = 'Вернуть'
    keyboard = types.InlineKeyboardMarkup()
    keyboard.add(
        types.InlineKeyboardButton(text=button1,
                                   callback_data='spend_exp_mat' + name))
    keyboard.add(
        types.InlineKeyboardButton(text=button2,
                                   callback_data='cancel_spend_exp_mat' +
                                   name))
    bot.edit_message_text(name, chat_id, message_id, reply_markup=keyboard)

    if action == 's':
        bot.send_message(
            chat_id,
            f'Израсходовано {message.text} {exp_mat_ed_izm(name, "Расходные материалы")}',
            reply_markup=main_menu_student())
    if action == 'b':
        bot.send_message(
            chat_id,
            f'Возвращено {message.text} {exp_mat_ed_izm(name, "Расходные материалы")}',
            reply_markup=main_menu_student())
    del BUFFER[str(chat_id)]
    del BUFFER['m_id' + str(chat_id)]
    return
Пример #6
0
def p_chords(message):
    chordsnotemarkup = types.InlineKeyboardMarkup(row_width=3)
    note1 = types.InlineKeyboardButton("A ", callback_data="Ap")
    note2 = types.InlineKeyboardButton("A#/Bb ", callback_data="A#p")
    note3 = types.InlineKeyboardButton("B ", callback_data="Bp")
    note4 = types.InlineKeyboardButton("C ", callback_data="Cp")
    note5 = types.InlineKeyboardButton("C#/Db ", callback_data="C#p")
    note6 = types.InlineKeyboardButton("D ", callback_data="Dp")
    note7 = types.InlineKeyboardButton("D#/Eb ", callback_data="D#p")
    note8 = types.InlineKeyboardButton("E ", callback_data="Ep")
    note9 = types.InlineKeyboardButton("F ", callback_data="Fp")
    note10 = types.InlineKeyboardButton("F#/Gb ", callback_data="F#p")
    note11 = types.InlineKeyboardButton("G ", callback_data="Gp")
    note12 = types.InlineKeyboardButton("G#/Ab ", callback_data="G#p")

    chordsnotemarkup.add(note1, note2, note3, note4, note5, note6, note7,
                         note8, note9, note10, note11, note12)

    bot.send_message(message.chat.id,
                     'Выберите тонику аккорда:',
                     reply_markup=chordsnotemarkup)
Пример #7
0
def callback_inline(call):
    if call.message:
        user_id = call.message.chat.id
        if call.data.find("goA") != -1:
            find_user_id = call.data.replace('goA_', '')
            save_param(find_user_id, 1, 'B')
            message_out = 'Пользователь с id: ' + str(
                find_user_id) + ' Переведен в группу B: '
            keyboard = types.InlineKeyboardMarkup(row_width=1)
            keyboard.add(
                types.InlineKeyboardButton(
                    text='Перевести в группу Нет группы',
                    callback_data='goB_' + str(find_user_id)))
            bot.edit_message_text(chat_id=call.message.chat.id,
                                  message_id=call.message.message_id,
                                  text=message_out,
                                  reply_markup=keyboard,
                                  parse_mode='HTML')

        if call.data.find("goB") != -1:
            find_user_id = call.data.replace('goB_', '')
            save_param(find_user_id, 1, 'No')
            message_out = 'Пользователь с id: ' + str(
                find_user_id) + ' Переведен в группу  Нет группы '
            keyboard = types.InlineKeyboardMarkup(row_width=1)
            keyboard.add(
                types.InlineKeyboardButton(text='Перевести в группу A',
                                           callback_data='goNo_' +
                                           str(find_user_id)))
            bot.edit_message_text(chat_id=call.message.chat.id,
                                  message_id=call.message.message_id,
                                  text=message_out,
                                  reply_markup=keyboard,
                                  parse_mode='HTML')

        if call.data.find("goNo") != -1:
            find_user_id = call.data.replace('goNo_', '')
            save_param(find_user_id, 1, 'A')
            message_out = 'Пользователь с id: ' + str(
                find_user_id) + ' Переведен в группу A: '
            keyboard = types.InlineKeyboardMarkup(row_width=1)
            keyboard.add(
                types.InlineKeyboardButton(text='Перевести в группу B',
                                           callback_data='goA_' +
                                           str(find_user_id)))
            bot.edit_message_text(chat_id=call.message.chat.id,
                                  message_id=call.message.message_id,
                                  text=message_out,
                                  reply_markup=keyboard,
                                  parse_mode='HTML')

        if call.data.find('Bitcoin') != -1:
            message_out = money(10, 'USD', 'BTC')
            bot.edit_message_text(chat_id=call.message.chat.id,
                                  message_id=call.message.message_id,
                                  text=message_out,
                                  parse_mode='HTML')
        if call.data.find('Litecoin') != -1:
            message_out = money(10, 'USD', 'LTC')
            bot.edit_message_text(chat_id=call.message.chat.id,
                                  message_id=call.message.message_id,
                                  text=message_out,
                                  parse_mode='HTML')
        if call.data.find('Dogecoin') != -1:
            message_out = money(10, 'USD', 'DOGE')
            bot.edit_message_text(chat_id=call.message.chat.id,
                                  message_id=call.message.message_id,
                                  text=message_out,
                                  parse_mode='HTML')
        if call.data.find('Ether') != -1:
            message_out = money(10, 'USD', 'ETC')
            bot.edit_message_text(chat_id=call.message.chat.id,
                                  message_id=call.message.message_id,
                                  text=message_out,
                                  parse_mode='HTML')
        if call.data.find('Classic') != -1:
            message_out = money(10, 'USD', 'ETC')
            bot.edit_message_text(chat_id=call.message.chat.id,
                                  message_id=call.message.message_id,
                                  text=message_out,
                                  parse_mode='HTML')
        if call.data.find('NEO') != -1:
            message_out = money(10, 'USD', 'NEO')
            bot.edit_message_text(chat_id=call.message.chat.id,
                                  message_id=call.message.message_id,
                                  text=message_out,
                                  parse_mode='HTML')
        if call.data.find('Qtum') != -1:
            message_out = money(10, 'USD', 'QTUM')
            bot.edit_message_text(chat_id=call.message.chat.id,
                                  message_id=call.message.message_id,
                                  text=message_out,
                                  parse_mode='HTML')
        if call.data.find('NEM') != -1:
            message_out = money(10, 'USD', 'XEM')
            bot.edit_message_text(chat_id=call.message.chat.id,
                                  message_id=call.message.message_id,
                                  text=message_out,
                                  parse_mode='HTML')
        if call.data.find('Monero') != -1:
            message_out = money(10, 'USD', 'XMR')
            bot.edit_message_text(chat_id=call.message.chat.id,
                                  message_id=call.message.message_id,
                                  text=message_out,
                                  parse_mode='HTML')
        if call.data.find('VERGE') != -1:
            message_out = money(10, 'USD', 'XVG')
            bot.edit_message_text(chat_id=call.message.chat.id,
                                  message_id=call.message.message_id,
                                  text=message_out,
                                  parse_mode='HTML')
Пример #8
0
def choose_bet_field(message):
    if message.text == "Начать игру":
        markup = types.InlineKeyboardMarkup()
        button_1 = types.InlineKeyboardButton(text="🔴 1", callback_data="1")
        button_2 = types.InlineKeyboardButton(text="⚫️ 2", callback_data="2")
        button_3 = types.InlineKeyboardButton(text="🔴 3", callback_data="3")
        button_4 = types.InlineKeyboardButton(text="⚫️ 4", callback_data="4")
        button_5 = types.InlineKeyboardButton(text="🔴 5", callback_data="5")
        button_6 = types.InlineKeyboardButton(text="⚫️ 6", callback_data="6")
        button_7 = types.InlineKeyboardButton(text="⚫️ 7", callback_data="7")
        button_8 = types.InlineKeyboardButton(text="🔴 8", callback_data="8")
        button_9 = types.InlineKeyboardButton(text="⚫️ 9", callback_data="9")
        button_10 = types.InlineKeyboardButton(text="🔴 10", callback_data="10")
        button_11 = types.InlineKeyboardButton(text="️️⚫️ 11",
                                               callback_data="11")
        button_12 = types.InlineKeyboardButton(text="🔴 12", callback_data="12")
        button_1_6 = types.InlineKeyboardButton(text="1-6",
                                                callback_data="1-6")
        button_4_9 = types.InlineKeyboardButton(text="4-9",
                                                callback_data="4-9")
        button_7_12 = types.InlineKeyboardButton(text="7-12",
                                                 callback_data="7-12")
        button_even = types.InlineKeyboardButton(text="EVEN",
                                                 callback_data="EVEN")
        button_red = types.InlineKeyboardButton(text="🔴", callback_data="red")
        button_black = types.InlineKeyboardButton(text="⚫️",
                                                  callback_data="black")
        button_odd = types.InlineKeyboardButton(text="ODD",
                                                callback_data="ODD")
        markup.add(button_1, button_2, button_3, button_4, button_5, button_6,
                   button_7, button_8, button_9, button_10, button_11,
                   button_12, button_1_6, button_4_9, button_7_12, button_even,
                   button_red, button_black, button_odd)
        bot.send_message(message.chat.id,
                         "Выберите поля для ставки:",
                         reply_markup=markup)
        print("started game", flush=True)
    elif message.text == "Пополнить баланс":
        address = blockchain.generate_for_user(message.from_user.id)
        bot.send_message(message.chat.id, messages.balance_plus % address)
        print("got money", flush=True)
    elif message.text == "Проверить баланс":
        user = BitcoinBot.query.filter_by(user_id=message.from_user.id).first()
        bot.send_message(
            message.chat.id, messages.balance_message %
            (user.user_balance,
             "t.me/bitcoin_roulette_bot?start=%s" % user.user_id))
        print("Checked", flush=True)
    elif message.text == "Вывести баланс":
        bot.send_message(message.chat.id, messages.out_balance_message)
        print("Went", flush=True)
    elif message.text == "Информация":
        bot.send_message(message.chat.id, messages.bet_message)
        print("Info", flush=True)
    elif message.text.isdigit():
        save_bet_size(message.text, message.from_user.id)
        print("Choose bet", flush=True)
    elif len(message.text.split()[1]) == 35:
        if int(message.text.split()[0]) >= 1000:
            user = BitcoinBot.query.filter_by(
                user_id=message.from_user.id).first()
            if user.user_balance >= int(message.text.split()[0]):
                blockchain.out_balance(message.text.split()[1],
                                       int(message.text.split()[0]) * 0.000001,
                                       message.from_user.id)
                bot.send_message(message.chat.id, messages.sent_money)
            else:
                bot.send_message(message.chat.id, messages.not_enough_money)
        else:
            bot.send_message(message.chat.id, messages.too_little_out_amount)
Пример #9
0
def get_text_messages(message):
    chat_message = message.text
    chat_id = message.chat.id

    if (chat_message == "💁🏻‍♀️ Мой профиль"):
        inline_keyboard = types.InlineKeyboardMarkup(row_width=1)
        inline = types.InlineKeyboardButton(text="Пополнить баланс",
                                            callback_data='DEPOSIT')
        inline_keyboard.add(inline)
        bot.send_message(
            chat_id,
            f"💁🏻‍♀️ *Твой* профиль\n\n🚀 Telegram ID: *{chat_id}*\n💵 Баланс: {others.user_balance(chat_id)} ₽"
            +
            f"\n\n💸 *Количество покупок:* 0\n🤝 *Приглашено*: {others.user_count_ref(chat_id)} пользователей\n💰 *Заработано:* 0 ₽",
            parse_mode="Markdown",
            reply_markup=inline_keyboard)
    elif (chat_message == "♻️ Вопрос - Ответ"):
        inline_keyboard = types.InlineKeyboardMarkup(row_width=1)
        inline = types.InlineKeyboardButton(
            text="Менеджер", url=f'https://t.me/{others.manager}')
        inline_keyboard.add(inline)
        text = str(
            "💁🏻‍♀️ *Ответы* на часто задаваемые вопросы\n\nQ: *Вы продаете если нет 18 лет?*\nA: *Мы не требуем никаких документов для подтверждения Вашего возраста*"
            +
            f"\n\nQ: *Как я получу свой HQD?*\nA: *В большинство городах работают курьеры, которые и доставят Вам максимально быстро и куда угодно*"
            +
            f"\n\nQ: *Что делать если моего города нет в списке?*\nA: *Напишите менеджеру, он решит Вашу проблему*"
            +
            f"\n\nQ: *Как оплатить товар?*\nA: *Мы принимаем только на QIWI Кошелек. Вам нужно будет просто пополнить баланс и посмотреть наш Каталог товаров*"
            +
            f"\n\nQ: *Оригинал или подделка?*\nA: *В нашем магазине исключительно представлен оригинальный продукт*"
            +
            f"\n\nℹ️ Если у Вас остались какие-то вопросы пишите менеджеру. Мы попробуем решить Вашу проблему."
        )

        bot.send_message(chat_id,
                         text,
                         parse_mode="Markdown",
                         reply_markup=inline_keyboard)
    elif (chat_message == "💠 Отзывы"):
        bot.send_message(
            chat_id,
            f"💁🏻‍♀️ *Отзывы* о нас\n\nПосмотреть отзывы Вы можете в нашей группе: [{others.group}]",
            parse_mode="Markdown")
    elif (chat_message == "🚀 Каталог"):
        bot.send_message(
            chat_id,
            "💁🏻‍♀️ Выберите *категорию* которую хотите приобрести",
            parse_mode="Markdown",
            reply_markup=product)
    elif (chat_message == "🍭 Товары Juul"):
        product_juul = types.ReplyKeyboardMarkup(resize_keyboard=True)
        product_1 = types.KeyboardButton('POD-системы JUUL')
        product_2 = types.KeyboardButton('Картриджи JUUL')
        back = types.KeyboardButton('Назад')
        product_juul.add(product_1, product_2)
        product_juul.add(back)
        bot.send_message(chat_id,
                         "💁🏻‍♀️ Выберите категорию товара *Juul*",
                         parse_mode="Markdown",
                         reply_markup=product_juul)
    elif (chat_message == "POD-системы JUUL"):
        product_pod = types.ReplyKeyboardMarkup(resize_keyboard=True)
        product_1 = types.KeyboardButton('Juul Promo Kit')
        product_2 = types.KeyboardButton('Juul Starter Kit')
        product_3 = types.KeyboardButton('Juul Device Kit')
        back = types.KeyboardButton('Назад')
        product_pod.add(product_1, product_2)
        product_pod.add(product_3, back)

        bot.send_message(chat_id,
                         "💁🏻‍♀️ Ниже предоставлены *POD-системы* Juul",
                         parse_mode="Markdown",
                         reply_markup=product_pod)
    elif (chat_message == "Картриджи JUUL"):
        product_catridge = types.ReplyKeyboardMarkup(resize_keyboard=True)
        product_1 = types.KeyboardButton('Манго x2 / x4')
        product_2 = types.KeyboardButton('Фруктовый микс x2 / x4')
        product_3 = types.KeyboardButton('Ваниль x2 / x4')
        product_4 = types.KeyboardButton('Табак x2 / x4')
        product_5 = types.KeyboardButton('Мята x2 / x4')
        product_6 = types.KeyboardButton('Табак Вирджиния x2 / x4')
        back = types.KeyboardButton('Назад')
        product_catridge.add(product_1, product_2)
        product_catridge.add(product_3, product_4)
        product_catridge.add(product_5, product_6)
        product_catridge.add(back)

        bot.send_message(chat_id,
                         "💁🏻‍♀️ Ниже предоставлены *сменные картриджи* Juul",
                         parse_mode="Markdown",
                         reply_markup=product_catridge)
    elif (chat_message == "🍇 Товары HQD"):
        product_hqd = types.ReplyKeyboardMarkup(resize_keyboard=True)
        product_1 = types.KeyboardButton('HQD Cuvie')
        product_2 = types.KeyboardButton('HQD Stark')
        product_3 = types.KeyboardButton('HQD V2')
        product_4 = types.KeyboardButton('HQD Cuvie Plus')
        product_5 = types.KeyboardButton('HQD Maxim')
        product_6 = types.KeyboardButton('HQD Ultra Stick')
        back = types.KeyboardButton('Назад')
        product_hqd.add(product_1, product_2)
        product_hqd.add(product_3, product_4)
        product_hqd.add(product_5, product_6)
        product_hqd.add(back)
        bot.send_message(chat_id,
                         "💁🏻‍♀️ Выберите нужный Вам *HQD*",
                         parse_mode="Markdown",
                         reply_markup=product_hqd)
    elif (chat_message == "Назад"):
        bot.send_message(chat_id,
                         "💁🏻‍♀️ Вы вернулись в *главное* меню",
                         parse_mode="Markdown",
                         reply_markup=markup)
    elif ('HQD' in chat_message):
        try:
            inline_keyboard = types.InlineKeyboardMarkup(row_width=1)
            episodes = chat_message.split(" ")
            if (episodes[1] == "Cuvie"):
                inline = types.InlineKeyboardButton(text="Заказать",
                                                    callback_data='Cuvie')
                inline_keyboard.add(inline)
                bot.send_message(
                    chat_id,
                    f"💁🏻‍♀️ Информация о *{chat_message}*\n\n" +
                    f"*Корпус:* Пластиковый\n*Испаритель:* Одноразовый\n*Затяжек:* 300 - 400\n*Никотин:* 50 МГ (солевой)\n*Стоимость:* {others.get_price_from_name(chat_message)} ₽",
                    parse_mode="Markdown",
                    reply_markup=inline_keyboard)
            elif (episodes[1] == "Stark"):
                inline = types.InlineKeyboardButton(text="Заказать",
                                                    callback_data='Stark')
                inline_keyboard.add(inline)
                bot.send_message(
                    chat_id,
                    f"💁🏻‍♀️ Информация о *{chat_message}*\n\n" +
                    f"*Корпус:* Пластиковый\n*Испаритель:* Одноразовый\n*Затяжек:* 300\n*Никотин:* 50 МГ (солевой)\n*Стоимость:* {others.get_price_from_name(chat_message)} ₽",
                    parse_mode="Markdown",
                    reply_markup=inline_keyboard)
            elif (episodes[1] == "V2"):
                inline = types.InlineKeyboardButton(text="Заказать",
                                                    callback_data='V2')
                inline_keyboard.add(inline)
                bot.send_message(
                    chat_id,
                    f"💁🏻‍♀️ Информация о *{chat_message}*\n\n" +
                    f"*Корпус:* Пластиковый\n*Испаритель:* Одноразовый\n*Затяжек:* 200 - 300\n*Никотин:* 50 МГ (солевой)\n*Стоимость:* {others.get_price_from_name(chat_message)} ₽",
                    parse_mode="Markdown",
                    reply_markup=inline_keyboard)
            elif (episodes[1] == "Cuvie Plus"):
                inline = types.InlineKeyboardButton(text="Заказать",
                                                    callback_data='CuviePlus')
                inline_keyboard.add(inline)
                bot.send_message(
                    chat_id,
                    f"💁🏻‍♀️ Информация о *{chat_message}*\n\n" +
                    f"*Корпус:* Пластиковый\n*Испаритель:* Одноразовый\n*Затяжек:* 500 - 600\n*Никотин:* 50 МГ (солевой)\n*Стоимость:* {others.get_price_from_name(chat_message)} ₽",
                    parse_mode="Markdown",
                    reply_markup=inline_keyboard)
            elif (episodes[1] == "Ultra"):
                inline = types.InlineKeyboardButton(text="Заказать",
                                                    callback_data='Ultra')
                inline_keyboard.add(inline)
                bot.send_message(
                    chat_id,
                    f"💁🏻‍♀️ Информация о *{chat_message}*\n\n" +
                    f"*Корпус:* Пластиковый\n*Испаритель:* Одноразовый\n*Затяжек:* 500\n*Никотин:* 50 МГ (солевой)\n*Стоимость:* {others.get_price_from_name(chat_message)} ₽",
                    parse_mode="Markdown",
                    reply_markup=inline_keyboard)
            elif (episodes[1] == "Maxim"):
                inline = types.InlineKeyboardButton(text="Заказать",
                                                    callback_data='Maxim')
                inline_keyboard.add(inline)
                bot.send_message(
                    chat_id,
                    f"💁🏻‍♀️ Информация о *{chat_message}*\n\n" +
                    f"*Корпус:* Пластиковый\n*Испаритель:* Одноразовый\n*Затяжек:* 400\n*Никотин:* 50 МГ (солевой)\n*Стоимость:* {others.get_price_from_name(chat_message)}",
                    parse_mode="Markdown",
                    reply_markup=inline_keyboard)
            else:
                bot.send_message(chat_id,
                                 "😟 Товар *не найден*",
                                 parse_mode="Markdown")
        except:
            pass
    elif ('Juul' in chat_message):
        try:
            inline_keyboard = types.InlineKeyboardMarkup(row_width=1)
            episodes = chat_message.split(" ")

            if (episodes[1] == "Promo"):
                inline = types.InlineKeyboardButton(text="Заказать",
                                                    callback_data='Promo')
                inline_keyboard.add(inline)
                bot.send_message(
                    chat_id,
                    f"💁🏻‍♀️ Информация о *{chat_message}*\n\n*Артикул:* 202190\n*Бренд:* JUUL Labs\n*Цвет:* Графит\n*Стоимость:* {others.get_price_from_name(chat_message)} ₽",
                    parse_mode="Markdown",
                    reply_markup=inline_keyboard)
            elif (episodes[1] == "Starter"):
                inline = types.InlineKeyboardButton(text="Заказать",
                                                    callback_data='Starter')
                inline_keyboard.add(inline)
                bot.send_message(
                    chat_id,
                    f"💁🏻‍♀️ Информация о *{chat_message}*\n\n*Артикул:* 212591\n*Бренд:* JUUL Labs\n*Цвет:* Графит\n*Стоимость:* {others.get_price_from_name(chat_message)} ₽",
                    parse_mode="Markdown",
                    reply_markup=inline_keyboard)
            elif (episodes[1] == "Device"):
                inline = types.InlineKeyboardButton(text="Заказать",
                                                    callback_data='Device')
                inline_keyboard.add(inline)
                bot.send_message(
                    chat_id,
                    f"💁🏻‍♀️ Информация о *{chat_message}*\n\n*Артикул:* 105593\n*Бренд:* JUUL Labs\n*Цвет:* Графит\n*Стоимость:* {others.get_price_from_name(chat_message)} ₽",
                    parse_mode="Markdown",
                    reply_markup=inline_keyboard)
        except:
            pass
    elif ('x2 / x4' in chat_message):
        try:
            inline_keyboard = types.InlineKeyboardMarkup(row_width=1)
            episodes = chat_message.split(" ")

            if (episodes[0] == "Манго"):
                inline = types.InlineKeyboardButton(text="Заказать",
                                                    callback_data='Mango')
                inline_keyboard.add(inline)
                bot.send_message(
                    chat_id,
                    f"💁🏻‍♀️ Сменный картридж *{episodes[0]}*\n\n*Крепкость:* 5%\n*Бренд:* JUUL Labs\n*Упаковка:* 2 или 4 пода\n*Стоимость:* {others.get_price_from_name(chat_message)} ₽",
                    parse_mode="Markdown",
                    reply_markup=inline_keyboard)
            if (episodes[0] == "Фруктовый"):
                inline = types.InlineKeyboardButton(text="Заказать",
                                                    callback_data='Mix')
                inline_keyboard.add(inline)
                bot.send_message(
                    chat_id,
                    f"💁🏻‍♀️ Сменный картридж *{episodes[0]}*\n\n*Крепкость:* 5%\n*Бренд:* JUUL Labs\n*Упаковка:* 2 или 4 пода\n*Стоимость:* {others.get_price_from_name(chat_message)} ₽",
                    parse_mode="Markdown",
                    reply_markup=inline_keyboard)
            if (episodes[0] == "Ваниль"):
                inline = types.InlineKeyboardButton(text="Заказать",
                                                    callback_data='Vanilla')
                inline_keyboard.add(inline)
                bot.send_message(
                    chat_id,
                    f"💁🏻‍♀️ Сменный картридж *{episodes[0]}*\n\n*Крепкость:* 5%\n*Бренд:* JUUL Labs\n*Упаковка:* 2 или 4 пода\n*Стоимость:* {others.get_price_from_name(chat_message)} ₽",
                    parse_mode="Markdown",
                    reply_markup=inline_keyboard)
            if (episodes[0] == "Табак"):
                inline = types.InlineKeyboardButton(text="Заказать",
                                                    callback_data='Tobacco')
                inline_keyboard.add(inline)
                bot.send_message(
                    chat_id,
                    f"💁🏻‍♀️ Сменный картридж *{episodes[0]}*\n\n*Крепкость:* 5%\n*Бренд:* JUUL Labs\n*Упаковка:* 2 или 4 пода\n*Стоимость:* {others.get_price_from_name(chat_message)} ₽",
                    parse_mode="Markdown",
                    reply_markup=inline_keyboard)
            if (episodes[0] == "Мята"):
                inline = types.InlineKeyboardButton(text="Заказать",
                                                    callback_data='Mint')
                inline_keyboard.add(inline)
                bot.send_message(
                    chat_id,
                    f"💁🏻‍♀️ Сменный картридж *{episodes[0]}*\n\n*Крепкость:* 5%\n*Бренд:* JUUL Labs\n*Упаковка:* 2 или 4 пода\n*Стоимость:* {others.get_price_from_name(chat_message)} ₽",
                    parse_mode="Markdown",
                    reply_markup=inline_keyboard)
            if (episodes[2] == "Вирджиния"):
                inline = types.InlineKeyboardButton(text="Заказать",
                                                    callback_data='Virginia')
                inline_keyboard.add(inline)
                bot.send_message(
                    chat_id,
                    f"💁🏻‍♀️ Сменный картридж *{episodes[0]} {episodes[1]}*\n\n*Крепкость:* 5%\n*Бренд:* JUUL Labs\n*Упаковка:* 2 или 4 пода\n*Стоимость:* {others.get_price_from_name(chat_message)} ₽",
                    parse_mode="Markdown",
                    reply_markup=inline_keyboard)
        except:
            pass
    elif (chat_message == "🎭 Реф. система"):
        inline_keyboard = types.InlineKeyboardMarkup(row_width=1)
        inline = types.InlineKeyboardButton(text="Статистика моих рефералов",
                                            callback_data='REFERAL')
        inline_keyboard.add(inline)
        bot.send_message(
            chat_id,
            "💁🏻‍♀️ *Реферальная* система\n\nПриглашайте новых пользователей и получайте пассивный доход от успешных операций ваших рефералов!"
            +
            f"\n\nИспользуйте уникальную реферальную ссылку для приглашения пользователей. Для достижения высоких результатов, внимательно подходите к поиску целевой аудитории: *привлекайте только тех, кто будет покупать наши услуги.*\n\n[https://t.me/{others.bot_name}?start=ref{chat_id}]",
            parse_mode="Markdown",
            reply_markup=inline_keyboard)
    elif (chat_message == "Реферал") and (chat_id == admin_user_id):
        msg = bot.send_message(chat_id, "💁🏻‍♀️ Впишите User Id")
        bot.register_next_step_handler(msg, getReferal)
    elif (chat_message == "🎉 Бонус"):
        worker = others.found_worker(chat_id)
        if (worker != 0):
            bot.send_message(chat_id,
                             "💁🏻‍♀️ Вы уже получили бонус в размере *50* ₽",
                             parse_mode="Markdown")
        else:
            inline_keyboard = types.InlineKeyboardMarkup(row_width=1)
            inline = types.InlineKeyboardButton(text="Ввести код-приглашение",
                                                callback_data=f'SEND_CODE')
            inline_keyboard.add(inline)
            bot.send_message(
                chat_id,
                "💁🏻‍♀️ Чтобы получить бонус в размере *50* ₽ нужно ввести *код-приглашение* друга",
                parse_mode="Markdown",
                reply_markup=inline_keyboard)
    elif ('/' in chat_message):
        user_id = chat_message.split("/")
        user_id = user_id[1]

        if (others.found_worker(user_id) == chat_id):
            name = others.name_from_id(user_id)
            if ('_' in name):
                name = name.replace('_', '\\_')

            bot.send_message(
                chat_id,
                f"Информация о пользователе *{user_id}*\n\n*Пользователь:* @{name}\n"
                + f"*Баланс:* {others.user_balance(user_id)} ₽",
                parse_mode="Markdown")
    else:
        bot.send_message(chat_id,
                         "💁🏻‍♀️ *Неизвестная* команда",
                         parse_mode="Markdown",
                         reply_markup=markup)
Пример #10
0
def lalala(message):
    if message.chat.type == 'private':
        if message.text == '🧙‍♂️ О гильдии':
            bot.send_message(
                message.chat.id,
                'QA Guild Perm — активное сообщество тестировщиков, в котором мы '
                'делимся своим профессиональным опытом и помогаем друг другу расти.\n\n'
                'Будем обсуждать последние тренды и новые инструменты, вместе решать '
                'проблемы и коллекционировать мемы. Мы открыты для всех, кому интересно '
                'тестирование и обеспечение качества! Присоединяйся и переходи на новый '
                'уровень!')
        elif message.text == '⚔ Я готов!':
            # Form flow
            markup = types.ReplyKeyboardRemove()

            # List = [wrong_answer(), wrong_answer(), correct_answer()]
            # random.shuffle(List)
            # markup = types.ReplyKeyboardMarkup(resize_keyboard=True)
            # item1 = types.KeyboardButton(List[0])
            # item2 = types.KeyboardButton(List[1])
            # item3 = types.KeyboardButton(List[2])
            #
            # markup.add(item1, item2, item3)

            bot.send_message(
                message.chat.id,
                "Отлично. Докажи мне, что ты не собираешься продвигать криптопирамиды. Сколько будет "
                "{}+{}?".format(key[0], key[1]),
                reply_markup=markup)

        elif message.text == str(key[2]):
            link = bot.export_chat_invite_link(chat_id=config.CHAT_ID)
            markup = types.InlineKeyboardMarkup(row_width=1)
            item1 = types.InlineKeyboardButton('🚀 Присоединиться', url=link)
            markup.add(item1)

            bot.send_message(
                message.chat.id,
                'Такс, ответ верный. Может все таки ты и не бот. Вот '
                'твоя invite-ссылка!',
                reply_markup=markup)

            # @bot.message_handler(content_types=['text'])
            # def lalala(message):
            #     if message.chat.type == 'private':
            #         bot.send_message(message.chat.id,
            #                                  'Ok, {}!. Теперь назови компанию, в которой ты работаешь:'.format(message))
            #
            #         @bot.message_handler(content_types=['text'])
            #         def lalala(message):
            #             if message.chat.type == 'private':
            #                 bot.send_message(message.chat.id,
            #                                          'Неплохо. Теперь назови компанию, в которой ты работаешь:')
            #
            #                 @bot.message_handler(content_types=['text'])
            #                 def lalala(message):
            #                     if message.chat.type == 'private':
            #                         bot.send_message(message.chat.id,
            #                          'Понятненько. Последний вопросец. Что тебе сейчас наиболее интересно '
            #                          'в тестировании?')
            #
            #                         @bot.message_handler(content_types=['text'])
            #                         def lalala(message):
            #                             if message.chat.type == 'private':
            #                                 link = bot.export_chat_invite_link(chat_id=config.CHAT_ID)
            #                                 markup = types.InlineKeyboardMarkup(row_width=1)
            #                                 item1 = types.InlineKeyboardButton('🚀 Присоединиться',
            #                                                                            url=link)
            #                                 markup.add(item1)
            #
            #                                 bot.send_message(message.chat.id,
            #                                     'Такс, с бумажной волокитой закончили. Вот '
            #                                     'твоя invite-ссылка!', reply_markup=markup)

        else:
            bot.send_message(
                message.chat.id,
                'Ты Меня потестить решил что-ли?😡 Мне нужен правильный ответ')
            bot.send_message(
                message.chat.id,
                'Если у тебя возникла проблема, или хочешь задать вопрос, то пиши в ЛС '
                '{}'.format('@honeydonut95'))
Пример #11
0
            redis.sadd('files',fileid)
            link = urllib2.Request("https://api.pwrtelegram.xyz/bot{}/getFile?file_id={}".format(token,fileid))
            open = urllib2.build_opener()
            f = open.open(link)
            link1 = f.read()
            jdat = json.loads(link1)
            patch = jdat['result']['file_path']
            send = 'https://storage.pwrtelegram.xyz/{}'.format(patch)
            link = urllib2.Request("http://api.gpmod.ir/shorten/?url={}&username={}".format(opizo_email,send))
            opeen = urllib2.build_opener()
            j = opeen.open(link)
            lin1 = j.read()
            bot.send_message(m.chat.id,'در حال آپلود فایل....')
            bot.send_message(m.chat.id,'<b>تبریک فایل آپلود شد!</b>\n\n<b>لینک فایل شما:</b>\n{}\n\n<b>ساخته شده توسط:</b> \nsewper | @sewper'.format(lin1),parse_mode='HTML')
  except:
   bot.send_message(m.chat.id,link1)



@bot.message_handler(commands=['rate'])
def rate(m):
      markup = types.InlineKeyboardMarkup()
      rate = types.InlineKeyboardButton('Rate',url='https://telegram.me/storebot?start=YourBotID')
      markup.add(rate)
      bot.send_message(m.chat.id,'If you like me, please give 5 star rating at: https://telegram.me/storebot?start=YourBotID\nYou can also recommend me @YourBotID to your friends.\nHave a nice day!',reply_markup=markup)


bot.polling(True)

# dev by : @MutePuker
Пример #12
0
def get_text_messages(message):
    if message.text.lower() == 'аниме':
        msg = animelist.L[random.randint(0,35)]
        bot.send_message(message.chat.id, msg)
        bot.send_message(message.chat.id, 'Приятного просмотра!')
    elif message.text.lower() == 'погода':
        city = bot.send_message(message.chat.id, "В каком городе вам показать погодку?")
        bot.register_next_step_handler(city, weath)
    elif message.text.lower() == 'гороскоп':
        keyboard = types.InlineKeyboardMarkup()
        key_oven = types.InlineKeyboardButton(text='Овен', callback_data='oven')
        keyboard.add(key_oven)
        key_telec = types.InlineKeyboardButton(text='Телец', callback_data='telec')
        keyboard.add(key_telec)
        key_bliznecy = types.InlineKeyboardButton(text='Близнецы', callback_data='blizneci')
        keyboard.add(key_bliznecy)
        key_rak = types.InlineKeyboardButton(text='Рак', callback_data='rak')
        keyboard.add(key_rak)
        key_lev = types.InlineKeyboardButton(text='Лев', callback_data='lev')
        keyboard.add(key_lev)
        key_deva = types.InlineKeyboardButton(text='Дева', callback_data='deva')
        keyboard.add(key_deva)
        key_vesy = types.InlineKeyboardButton(text='Весы', callback_data='vesi')
        keyboard.add(key_vesy)
        key_scorpion = types.InlineKeyboardButton(text='Скорпион', callback_data='skorpion')
        keyboard.add(key_scorpion)
        key_strelec = types.InlineKeyboardButton(text='Стрелец', callback_data='strelec')
        keyboard.add(key_strelec)
        key_kozerog = types.InlineKeyboardButton(text='Козерог', callback_data='kozerog')
        keyboard.add(key_kozerog)
        key_vodoley = types.InlineKeyboardButton(text='Водолей', callback_data='vodoley')
        keyboard.add(key_vodoley)
        key_ryby = types.InlineKeyboardButton(text='Рыбы', callback_data='ribi')
        keyboard.add(key_ryby)
        bot.send_message(message.from_user.id, text='Я забыла ваш знак зодиака... Можете мне напомнить?',reply_markup=keyboard)
    elif message.text.lower() == 'привет':
        bot.send_message(message.chat.id, "Привет. Я рада что вы вернулись!")
        bot.send_sticker(message.chat.id, 'CAACAgEAAxkBAAICRV8Lv6tpgZOsaNHDfSnY7DPxZYUjAAIyAQACf1l6B2LeEZ66E2ceGgQ')
    elif message.text.lower() == 'прощай':
        bot.send_message(message.chat.id, "До встречи.")
        bot.send_sticker(message.chat.id, 'CAACAgEAAxkBAAICTV8Lv9T75Gj2HWBz6N9OX-jGG0UNAAK8AQACf1l6Bz7wIprXdBt0GgQ')
    else:
        bot.send_message(message.from_user.id, 'Простите, я пока еще этого не знаю. Используйте только мои знания.')
        bot.send_sticker(message.chat.id, 'CAACAgIAAxkBAAIBtF8Lr-sqKTQAASzugq5CDgN7uTNZQwACYAADzGguDgr63zDtxpdOGgQ')
Пример #13
0
 def rieltor(m):
     key = types.InlineKeyboardMarkup()
     rieltor = types.InlineKeyboardButton(text='📞', url='t.me/medianadmin')
     key.add(rieltor)
     bot.send_chat_action(m.chat.id, action='typing')
     bot.send_message(m.chat.id, 'Риелтор', reply_markup=key)
Пример #14
0
def handle_query(message):
    chat_id = message.message.chat.id
    message_id = message.message.message_id
    data = message.data
    global last_data
    global open_basket
    global menu_id

    # Храним информацию только о 50 последних пользователях
    if len(last_data) > 50:
        last_data = {}
    if len(open_basket) > 50:
        open_basket = {}

    # Проверка что пользователь не нажал две клавиши на одном этапе меню
    if chat_id in last_data.keys() and data == last_data[chat_id]:
        return
    last_data[chat_id] = data
    print(chat_id, ':', data)

    # Список торговых центров
    if data == 'start':
        menu_id[chat_id] = message_id  # Запоминаем номер сообщения с меню
        bot.edit_message_text(chat_id=chat_id,
                              message_id=message_id,
                              text='Список торговых центров',
                              reply_markup=makeKeyboard_TC(DB.TC_list()),
                              parse_mode='HTML')
    # Список фудкортов
    elif data.startswith('{"TC"'):
        menu_id[chat_id] = message_id  # Запоминаем номер сообщения с меню
        TC_name = json.loads(data)['TC']

        bot.edit_message_text(chat_id=chat_id,
                              message_id=message_id,
                              text=TC_name + '\nСписок фудкортов',
                              reply_markup=makeKeyboard_FC(
                                  DB.FC_list(TC_name)),
                              parse_mode='HTML')
    # Список ресторанов
    elif data.startswith('{"FC"'):
        menu_id[chat_id] = message_id  # Запоминаем номер сообщения с меню
        data = json.loads(data)

        TC_name = data['FC'][1]  # TC_name
        FC_name = data['FC'][0]  # FC_name
        if FC_name:
            txt = f'{TC_name}\n{FC_name}\n'
        else:
            txt = f'{TC_name}\n'
        bot.edit_message_text(chat_id=chat_id,
                              message_id=message_id,
                              text=txt + 'Список ресторанов',
                              reply_markup=makeKeyboard_rest(
                                  DB.rest_list(TC_name=TC_name, FC=FC_name)),
                              parse_mode='HTML')

    # Ктегории ресторана
    elif data.startswith('{"rest_id"'):
        menu_id[chat_id] = message_id  # Запоминаем номер сообщения с меню
        data = json.loads(data)
        rest_id = data['rest_id']
        categories = DB.categories_rest(rest_id=rest_id)
        FC = categories["FC"]
        if FC:
            txt = f'{categories["TC_name"]}\n{FC}\n{categories["rest_name"]}\n'
        else:
            txt = f'{categories["TC_name"]}\n{categories["rest_name"]}\n'
        bot.edit_message_text(chat_id=chat_id,
                              message_id=message_id,
                              text=txt + 'Категории',
                              reply_markup=makeKeyboard_categories(categories),
                              parse_mode='HTML')

    # Меню ресторана
    elif data.startswith('{"cat"'):
        menu_id[chat_id] = message_id  # Запоминаем номер сообщения с меню
        data = json.loads(data)
        rest_id = data['cat'][1]
        category = data['cat'][0]
        menu = DB.menu_rest(rest_id=rest_id, category=category)
        rest_name = menu['rest_name']

        photo = data['cat'][2]
        if not photo:
            bot.edit_message_text(chat_id=chat_id,
                                  message_id=message_id,
                                  text=rest_name + '\nМеню\n' + category,
                                  reply_markup=makeKeyboard_menu(menu),
                                  parse_mode='HTML')
        else:
            bot.send_message(chat_id=chat_id,
                             text=rest_name + '\nМеню\n' + category,
                             reply_markup=makeKeyboard_menu(menu),
                             parse_mode='HTML')
            # Удаление старого сообщения
            bot.delete_message(chat_id=chat_id, message_id=message_id)

    # Список товаров (меню рестрана)
    elif data.startswith('{"menu"'):
        menu_id[chat_id] = message_id  # Запоминаем номер сообщения с меню
        data = json.loads(data)
        rest_id = data['menu'][2]
        category = data['menu'][1]
        index = data['menu'][0]

        # Отправка изображния
        menu = DB.menu_rest(rest_id=rest_id, category=category)
        try:
            img = open(menu['menu'][index]['img'], 'rb')
        except:
            print('Image not found:', menu['menu'][index]['img'])
            img = open(error_img_path, 'rb')

        bot.send_photo(chat_id=chat_id,
                       photo=img,
                       reply_markup=makeKeyboard_food(menu, index))

        # Удаление старого сообщения
        bot.delete_message(chat_id=chat_id, message_id=message_id)

        # Если корзина открыта, закрываем
        if chat_id in open_basket.keys() and open_basket[chat_id]:
            bot.delete_message(chat_id=chat_id,
                               message_id=open_basket[chat_id])
            open_basket[chat_id] = False

    # Взаимодействие с товаром
    elif data.startswith('{"food'):
        # '{"food": [rest_id, category, index, action]}'
        data = json.loads(data)['food']
        rest_id = data[0]
        category = data[1]
        index = data[2]
        action = data[3]
        menu = DB.menu_rest(rest_id=rest_id, category=category)

        if '-' in action:
            quantity = int(data[3][1:])
            if quantity == 1:
                return
            quantity -= 1
            bot.edit_message_reply_markup(chat_id=chat_id,
                                          message_id=message_id,
                                          reply_markup=makeKeyboard_food(
                                              menu, index, quantity=quantity))
        elif '+' in action:
            quantity = int(data[3][1:])
            quantity += 1
            bot.edit_message_reply_markup(chat_id=chat_id,
                                          message_id=message_id,
                                          reply_markup=makeKeyboard_food(
                                              menu, index, quantity=quantity))
        elif 'sruct' in action:

            bot.answer_callback_query(callback_query_id=message.id,
                                      show_alert=True,
                                      text='Состав:\n' +
                                      menu['menu'][index]['composition'])
        elif 'add' in action:
            rest_name = menu['rest_name']

            # Проверка если начали добавлять товары другого ресторана
            basket = read_basket(chat_id)
            update_text = ''
            if basket and int(rest_id) != int(basket[0]['rest_id']):
                del_basket(chat_id)
                update_text = 'Корзина обновлена '

            food_name = menu['menu'][index]['name']
            prise = menu['menu'][index]['price']
            quantity = int(data[3][3:])

            add_basket(chat_id, food_name, quantity, prise, rest_id=rest_id)

            bot.answer_callback_query(
                callback_query_id=message.id,
                show_alert=False,
                text=
                f'{update_text}В корзину добавлено {food_name} {quantity} шт.')

            bot.send_message(chat_id=chat_id,
                             text=rest_name + '\nМеню',
                             reply_markup=makeKeyboard_menu(menu),
                             parse_mode='HTML')

            menu_id[
                chat_id] = message_id + 1  # Запоминаем номер сообщения с меню

            # Удаление старого сообщения
            bot.delete_message(chat_id=chat_id, message_id=message_id)

            # Если корзина открыта, закрываем
            if chat_id in open_basket.keys() and open_basket[chat_id]:
                bot.delete_message(chat_id=chat_id,
                                   message_id=open_basket[chat_id])
                open_basket[chat_id] = False

    # Взаимодействие с корзиной
    elif data.startswith('{"basket"'):
        data = json.loads(data)
        action = data['basket']
        if action == 'close':
            bot.delete_message(chat_id=chat_id, message_id=message_id)
            open_basket[chat_id] = False
        elif 'clear' in action:
            del_basket(chat_id)
            bot.answer_callback_query(callback_query_id=message.id,
                                      show_alert=False,
                                      text='Корзина очищена')
            bot.delete_message(chat_id=chat_id, message_id=message_id)
            open_basket[chat_id] = False

        elif 'change' in action:
            basket = read_basket(str(chat_id))
            bot.edit_message_text(chat_id=chat_id,
                                  message_id=message_id,
                                  text='<b>Корзина</b> (изменение)',
                                  reply_markup=makeKeyboard_changeBasket(
                                      basket=basket, chat_id=chat_id),
                                  parse_mode='HTML')
    # Изменение корзины
    elif data.startswith('{"change"'):
        # {"change": ["Шашлык куриный", "+2"]}
        data = json.loads(data)['change']

        # Кнопка сохранить
        if data == 'save':
            save_basket(chat_id)
            items = read_basket(str(chat_id))

            if not items:
                bot.edit_message_text(
                    chat_id=chat_id,
                    message_id=message_id,
                    text='<b>Корзина пуста</b>',
                    reply_markup=makeKeyboard_basket(clear=True),
                    parse_mode='HTML')
                return

            basket_text, amount, basket_info = makeBasket(items)
            rest_id = items[0]['rest_id']
            restaurant = DB.categories_rest(rest_id)
            rest_name = restaurant['rest_name']

            bot.edit_message_text(
                chat_id=chat_id,
                message_id=message_id,
                text=
                f'<b>Корзина</b>\n{rest_name}\n\n<i>{basket_text}</i>\nИтого: <i>{amount} руб.</i>',
                reply_markup=makeKeyboard_basket(),
                parse_mode='HTML')
            return

        # Кнопки - и +
        food_name = data[0]
        action = data[1]
        if '-' in action:
            quantity = int(data[1][1:])
            if quantity == 0:
                return
            quantity = -1
            add_basket(chat_id=chat_id, food_name=food_name, quantity=quantity)
            basket = read_basket(chat_id)
            bot.edit_message_reply_markup(
                chat_id=chat_id,
                message_id=message_id,
                reply_markup=makeKeyboard_changeBasket(basket,
                                                       chat_id=chat_id))
        elif '+' in action:
            quantity = 1
            add_basket(chat_id=chat_id, food_name=food_name, quantity=quantity)
            basket = read_basket(chat_id)
            bot.edit_message_reply_markup(
                chat_id=chat_id,
                message_id=message_id,
                reply_markup=makeKeyboard_changeBasket(basket,
                                                       chat_id=chat_id))
    # Формирование заказа
    elif data == 'pay':
        bot.delete_message(chat_id=chat_id, message_id=message_id)

        markup = types.InlineKeyboardMarkup()
        markup.add(
            types.InlineKeyboardButton(text='Оплатить', pay=True),
            types.InlineKeyboardButton(text='Удалить',
                                       callback_data='del_order_or_receipt'))

        items = read_basket(str(chat_id))
        basket_text, amount, basket_info = makeBasket(items)
        rest_id = items[0]['rest_id']
        restaurant = DB.categories_rest(rest_id)
        rest_name = restaurant['rest_name']
        print(rest_name)

        prices = []
        for i in basket_info:
            food_name = i['food_name']
            quantity = i['quantity']
            price = i['price']
            prices.append(
                types.LabeledPrice(label=food_name + ' ' + str(quantity) +
                                   ' шт.',
                                   amount=price * quantity * 100))
        print(items)
        bot.send_invoice(chat_id=chat_id,
                         title=rest_name,
                         description=basket_text,
                         invoice_payload={"bla": "bla"},
                         provider_token=PROVIDER_TOKEN,
                         start_parameter="mybot",
                         currency="RUB",
                         prices=prices,
                         reply_markup=markup)

        open_basket[chat_id] = False

    # Удаление заказа или чека
    elif data == 'del_order_or_receipt':
        bot.delete_message(chat_id=chat_id, message_id=message_id)
Пример #15
0
    def chord(P_note):
        if call.message:
            if call.message:
                if call.data == f'{P_note}p':
                    bot.send_message(call.message.chat.id,
                                     f'Вы выбрали {P_note}')

                    bot.answer_callback_query(callback_query_id=call.id,
                                              show_alert=False,
                                              text=f"Вы выбрали {P_note}")

                    chordsmarkup = types.InlineKeyboardMarkup(row_width=3)

                    chord1 = types.InlineKeyboardButton(
                        f"{P_note}", callback_data=f"{P_note}_major")
                    chord2 = types.InlineKeyboardButton(
                        f"{P_note}m", callback_data=f"{P_note}_minor")
                    chord3 = types.InlineKeyboardButton(
                        f"{P_note}5", callback_data=f"{P_note}5")
                    chord4 = types.InlineKeyboardButton(
                        f"{P_note}6", callback_data=f"{P_note}6")
                    chord5 = types.InlineKeyboardButton(
                        f"{P_note}6 add9", callback_data=f"{P_note}6_9")
                    chord6 = types.InlineKeyboardButton(
                        f"{P_note}7", callback_data=f"{P_note}7")
                    chord7 = types.InlineKeyboardButton(
                        f"{P_note} maj7", callback_data=f"{P_note}_maj7")
                    chord8 = types.InlineKeyboardButton(
                        f"{P_note} maj9", callback_data=f"{P_note}_maj9")
                    chord9 = types.InlineKeyboardButton(
                        f"{P_note}7-5", callback_data=f"{P_note}7-5")
                    chord10 = types.InlineKeyboardButton(
                        f"{P_note}7+5", callback_data=f"{P_note}7+5")
                    chord11 = types.InlineKeyboardButton(
                        f"{P_note}9", callback_data=f"{P_note}9")
                    chord12 = types.InlineKeyboardButton(
                        f"{P_note}11", callback_data=f"{P_note}11")
                    chord13 = types.InlineKeyboardButton(
                        f"{P_note}13", callback_data=f"{P_note}13")
                    chord14 = types.InlineKeyboardButton(
                        f"{P_note} aug", callback_data=f"{P_note}_aug")
                    chord15 = types.InlineKeyboardButton(
                        f"{P_note} aug7", callback_data=f"{P_note}_aug7")
                    chord16 = types.InlineKeyboardButton(
                        f"{P_note} dim", callback_data=f"{P_note}_dim")
                    chord17 = types.InlineKeyboardButton(
                        f"{P_note} dim7", callback_data=f"{P_note}_dim7")
                    chord18 = types.InlineKeyboardButton(
                        f"{P_note}m6", callback_data=f"{P_note}m6")
                    chord19 = types.InlineKeyboardButton(
                        f"{P_note}m7", callback_data=f"{P_note}m7")
                    chord20 = types.InlineKeyboardButton(
                        f"{P_note}m7(b5)", callback_data=f"{P_note}m7b5")
                    chord21 = types.InlineKeyboardButton(
                        f"{P_note}m9", callback_data=f"{P_note}m9")
                    chord22 = types.InlineKeyboardButton(
                        f"{P_note}m11", callback_data=f"{P_note}m11")
                    chord23 = types.InlineKeyboardButton(
                        f"{P_note}m13", callback_data=f"{P_note}m13")
                    chord24 = types.InlineKeyboardButton(
                        f"{P_note}m maj7", callback_data=f"{P_note}m_maj7")
                    chord25 = types.InlineKeyboardButton(
                        f"{P_note} add2", callback_data=f"{P_note}_add2")
                    chord26 = types.InlineKeyboardButton(
                        f"{P_note} add9", callback_data=f"{P_note}_add9")
                    chord27 = types.InlineKeyboardButton(
                        f"{P_note} sus2", callback_data=f"{P_note}_sus2")
                    chord28 = types.InlineKeyboardButton(
                        f"{P_note} sus4", callback_data=f"{P_note}_sus4")

                    chordsmarkup.add(chord1, chord2, chord3, chord4, chord5,
                                     chord6, chord7, chord8, chord9, chord10,
                                     chord11, chord12, chord13, chord14,
                                     chord15, chord16, chord17, chord18,
                                     chord19, chord20, chord21, chord22,
                                     chord23, chord24, chord25, chord26,
                                     chord27, chord28)

                    bot.send_message(call.message.chat.id,
                                     'Выберите аккорд:',
                                     reply_markup=chordsmarkup)
            if call.message:
                if call.data == f'{P_note}_major':
                    bot.send_message(call.message.chat.id,
                                     f'Вы выбрали {P_note} major')
                    bot.answer_callback_query(
                        callback_query_id=call.id,
                        show_alert=False,
                        text=f"Вы выбрали {P_note} major")

                    Pmajor = open(f'bot_files/p_chords/{P_note}/{P_note}.png',
                                  'rb')

                    bot.send_photo(call.message.chat.id, Pmajor)
                    Pmajor.close()

            if call.message:
                if call.data == f'{P_note}_minor':
                    bot.send_message(call.message.chat.id,
                                     f'Вы выбрали {P_note} minor')
                    bot.answer_callback_query(
                        callback_query_id=call.id,
                        show_alert=False,
                        text=f"Вы выбрали {P_note} minor (Ля минор)")

                    Pminor = open(f'bot_files/p_chords/{P_note}/{P_note}m.png',
                                  'rb')

                    bot.send_photo(call.message.chat.id, Pminor)
                    Pminor.close()

            if call.message:
                if call.data == f'{P_note}5':
                    bot.send_message(call.message.chat.id,
                                     f'Вы выбрали {P_note}5')
                    bot.answer_callback_query(callback_query_id=call.id,
                                              show_alert=False,
                                              text=f"Вы выбрали {P_note}5")

                    a5p = open(f'bot_files/p_chords/{P_note}/{P_note}5.png',
                               'rb')

                    bot.send_photo(call.message.chat.id, a5p)
                    a5p.close()

            if call.message:
                if call.data == f'{P_note}6':
                    bot.send_message(call.message.chat.id,
                                     f'Вы выбрали {P_note}6')
                    bot.answer_callback_query(callback_query_id=call.id,
                                              show_alert=False,
                                              text=f"Вы выбрали {P_note}6")

                    a6p = open(f'bot_files/p_chords/{P_note}/{P_note}6.png',
                               'rb')

                    bot.send_photo(call.message.chat.id, a6p)
                    a6p.close()

            if call.message:
                if call.data == f'{P_note}6_9':
                    bot.send_message(call.message.chat.id,
                                     f'Вы выбрали {P_note}6add9')
                    bot.answer_callback_query(callback_query_id=call.id,
                                              show_alert=False,
                                              text="Вы выбрали A6add9")

                    a6_9p = open(
                        f'bot_files/p_chords/{P_note}/{P_note}6_9.png', 'rb')

                    bot.send_photo(call.message.chat.id, a6_9p)
                    a6_9p.close()

            if call.message:
                if call.data == f'{P_note}7':
                    bot.send_message(call.message.chat.id,
                                     f'Вы выбрали {P_note}7')
                    bot.answer_callback_query(callback_query_id=call.id,
                                              show_alert=False,
                                              text=f"Вы выбрали {P_note}7")

                    a7p = open(f'bot_files/p_chords/{P_note}/{P_note}7.png',
                               'rb')

                    bot.send_photo(call.message.chat.id, a7p)
                    a7p.close()

            if call.message:
                if call.data == f'{P_note}_maj7':
                    bot.send_message(call.message.chat.id,
                                     f'Вы выбрали {P_note} maj7')
                    bot.answer_callback_query(callback_query_id=call.id,
                                              show_alert=False,
                                              text="Вы выбрали A maj7")

                    a_maj7p = open(
                        f'bot_files/p_chords/{P_note}/{P_note}maj7.png', 'rb')

                    bot.send_photo(call.message.chat.id, a_maj7p)
                    a_maj7p.close()

            if call.message:
                if call.data == f'{P_note}_maj9':
                    bot.send_message(call.message.chat.id,
                                     f'Вы выбрали {P_note} maj9')
                    bot.answer_callback_query(callback_query_id=call.id,
                                              show_alert=False,
                                              text=f"Вы выбрали {P_note} maj9")

                    a_maj9p = open(
                        f'bot_files/p_chords/{P_note}/{P_note}maj9.png', 'rb')

                    bot.send_photo(call.message.chat.id, a_maj9p)
                    a_maj9p.close()

            if call.message:
                if call.data == f'{P_note}7-5':
                    bot.send_message(call.message.chat.id,
                                     f'Вы выбрали {P_note}7-5')
                    bot.answer_callback_query(callback_query_id=call.id,
                                              show_alert=False,
                                              text=f"Вы выбрали {P_note}7-5")

                    a7minus5p = open(
                        f'bot_files/p_chords/{P_note}/{P_note}7minus5.png',
                        'rb')

                    bot.send_photo(call.message.chat.id, a7minus5p)
                    a7minus5p.close()

            if call.message:
                if call.data == f'{P_note}7+5':
                    bot.send_message(call.message.chat.id,
                                     f'Вы выбрали {P_note}7+5')
                    bot.answer_callback_query(callback_query_id=call.id,
                                              show_alert=False,
                                              text=f"Вы выбрали {P_note}7+5")

                    a7plus5p = open(
                        f'bot_files/p_chords/{P_note}/{P_note}7plus5.png',
                        'rb')

                    bot.send_photo(call.message.chat.id, a7plus5p)
                    a7plus5p.close()

            if call.message:
                if call.data == f'{P_note}9':
                    bot.send_message(call.message.chat.id,
                                     f'Вы выбрали {P_note}9')
                    bot.answer_callback_query(callback_query_id=call.id,
                                              show_alert=False,
                                              text=f"Вы выбрали {P_note}9")

                    a9p = open(f'bot_files/p_chords/{P_note}/{P_note}9.png',
                               'rb')

                    bot.send_photo(call.message.chat.id, a9p)
                    a9p.close()

            if call.message:
                if call.data == f'{P_note}11':
                    bot.send_message(call.message.chat.id,
                                     f'Вы выбрали {P_note}11')
                    bot.answer_callback_query(callback_query_id=call.id,
                                              show_alert=False,
                                              text=f"Вы выбрали {P_note}7")

                    a11p = open(f'bot_files/p_chords/{P_note}/{P_note}11.png',
                                'rb')

                    bot.send_photo(call.message.chat.id, a11p)
                    a11p.close()

            if call.message:
                if call.data == f'{P_note}13':
                    bot.send_message(call.message.chat.id,
                                     f'Вы выбрали {P_note}13')
                    bot.answer_callback_query(callback_query_id=call.id,
                                              show_alert=False,
                                              text=f"Вы выбрали {P_note}13")

                    a13p = open(f'bot_files/p_chords/{P_note}/{P_note}13.png',
                                'rb')

                    bot.send_photo(call.message.chat.id, a13p)
                    a13p.close()

            if call.message:
                if call.data == f'{P_note}_aug':
                    bot.send_message(call.message.chat.id,
                                     f'Вы выбрали {P_note} aug')
                    bot.answer_callback_query(callback_query_id=call.id,
                                              show_alert=False,
                                              text=f"Вы выбрали {P_note} aug")

                    a_augp = open(
                        f'bot_files/p_chords/{P_note}/{P_note}aug.png', 'rb')

                    bot.send_photo(call.message.chat.id, a_augp)
                    a_augp.close()

            if call.message:
                if call.data == f'{P_note}_aug7':
                    bot.send_message(call.message.chat.id,
                                     f'Вы выбрали {P_note} aug7')
                    bot.answer_callback_query(callback_query_id=call.id,
                                              show_alert=False,
                                              text=f"Вы выбрали {P_note} aug7")

                    a_aug7p = open(
                        f'bot_files/p_chords/{P_note}/{P_note}aug7.png', 'rb')

                    bot.send_photo(call.message.chat.id, a_aug7p)
                    a_aug7p.close()

            if call.message:
                if call.data == f'{P_note}_dim':
                    bot.send_message(call.message.chat.id,
                                     f'Вы выбрали {P_note} dim')
                    bot.answer_callback_query(callback_query_id=call.id,
                                              show_alert=False,
                                              text=f"Вы выбрали {P_note} dim")

                    a_dimp = open(
                        f'bot_files/p_chords/{P_note}/{P_note}dim.png', 'rb')

                    bot.send_photo(call.message.chat.id, a_dimp)
                    a_dimp.close()

            if call.message:
                if call.data == f'{P_note}_dim7':
                    bot.send_message(call.message.chat.id,
                                     f'Вы выбрали {P_note} dim7')
                    bot.answer_callback_query(callback_query_id=call.id,
                                              show_alert=False,
                                              text=f"Вы выбрали {P_note} dim7")

                    a_dim7p = open(
                        f'bot_files/p_chords/{P_note}/{P_note}dim7.png', 'rb')

                    bot.send_photo(call.message.chat.id, a_dim7p)
                    a_dim7p.close()

            if call.message:
                if call.data == f'{P_note}m6':
                    bot.send_message(call.message.chat.id,
                                     f'Вы выбрали {P_note}m6')
                    bot.answer_callback_query(callback_query_id=call.id,
                                              show_alert=False,
                                              text=f"Вы выбрали {P_note}m6")

                    am6p = open(f'bot_files/p_chords/{P_note}/{P_note}m6.png',
                                'rb')

                    bot.send_photo(call.message.chat.id, am6p)
                    am6p.close()

            if call.message:
                if call.data == f'{P_note}m7':
                    bot.send_message(call.message.chat.id,
                                     f'Вы выбрали {P_note}m7')
                    bot.answer_callback_query(callback_query_id=call.id,
                                              show_alert=False,
                                              text=f"Вы выбрали {P_note}m7")

                    am7p = open(f'bot_files/p_chords/{P_note}/{P_note}m7.png',
                                'rb')

                    bot.send_photo(call.message.chat.id, am7p)
                    am7p.close()

            if call.message:
                if call.data == f'{P_note}m7b5':
                    bot.send_message(
                        call.message.chat.id,
                        f'Вы выбрали {P_note}m7(b5) ({P_note}m7-5) ')
                    bot.answer_callback_query(
                        callback_query_id=call.id,
                        show_alert=False,
                        text=f"Вы выбрали {P_note}m7(b5)")

                    am7b5p = open(
                        f'bot_files/p_chords/{P_note}/{P_note}m7b5.png', 'rb')

                    bot.send_photo(call.message.chat.id, am7b5p)
                    am7b5p.close()

            if call.message:
                if call.data == f'{P_note}m9':
                    bot.send_message(call.message.chat.id,
                                     f'Вы выбрали {P_note}m9')
                    bot.answer_callback_query(callback_query_id=call.id,
                                              show_alert=False,
                                              text=f"Вы выбрали {P_note}m9")

                    am9p = open(f'bot_files/p_chords/{P_note}/{P_note}m9.png',
                                'rb')

                    bot.send_photo(call.message.chat.id, am9p)
                    am9p.close()

            if call.message:
                if call.data == f'{P_note}m11':
                    bot.send_message(call.message.chat.id,
                                     f'Вы выбрали {P_note}m11')
                    bot.answer_callback_query(callback_query_id=call.id,
                                              show_alert=False,
                                              text=f"Вы выбрали {P_note}m11")

                    am11p = open(
                        f'bot_files/p_chords/{P_note}/{P_note}m11.png', 'rb')

                    bot.send_photo(call.message.chat.id, am11p)
                    am11p.close()

            if call.message:
                if call.data == f'{P_note}m13':
                    bot.send_message(call.message.chat.id,
                                     f'Вы выбрали {P_note}m13')
                    bot.answer_callback_query(callback_query_id=call.id,
                                              show_alert=False,
                                              text=f"Вы выбрали {P_note}m13")

                    am13p = open(
                        f'bot_files/p_chords/{P_note}/{P_note}m13.png', 'rb')

                    bot.send_photo(call.message.chat.id, am13p)
                    am13p.close()

            if call.message:
                if call.data == f'{P_note}m_maj7':
                    bot.send_message(call.message.chat.id,
                                     f'Вы выбрали {P_note}m maj7')
                    bot.answer_callback_query(
                        callback_query_id=call.id,
                        show_alert=False,
                        text=f"Вы выбрали {P_note}m maj7")

                    am_maj7p = open(
                        f'bot_files/p_chords/{P_note}/{P_note}minmaj7.png',
                        'rb')

                    bot.send_photo(call.message.chat.id, am_maj7p)
                    am_maj7p.close()

            if call.message:
                if call.data == f'{P_note}_add2':
                    bot.send_message(call.message.chat.id,
                                     f'Вы выбрали {P_note} add2 ({P_note}2)')
                    bot.answer_callback_query(
                        callback_query_id=call.id,
                        show_alert=False,
                        text=f"Вы выбрали {P_note} add2 ({P_note}2)")

                    a_add2p = open(
                        f'bot_files/p_chords/{P_note}/{P_note}add2.png', 'rb')

                    bot.send_photo(call.message.chat.id, a_add2p)
                    a_add2p.close()

            if call.message:
                if call.data == f'{P_note}_add9':
                    bot.send_message(call.message.chat.id,
                                     f'Вы выбрали {P_note}_add9')
                    bot.answer_callback_query(callback_query_id=call.id,
                                              show_alert=False,
                                              text=f"Вы выбрали {P_note}_add9")

                    a_add9p = open(
                        f'bot_files/p_chords/{P_note}/{P_note}add9.png', 'rb')

                    bot.send_photo(call.message.chat.id, a_add9p)
                    a_add9p.close()

            if call.message:
                if call.data == f'{P_note}_sus2':
                    bot.send_message(call.message.chat.id,
                                     f'Вы выбрали {P_note} sus2')
                    bot.answer_callback_query(callback_query_id=call.id,
                                              show_alert=False,
                                              text=f"Вы выбрали {P_note} sus2")

                    a_sus2p = open(
                        f'bot_files/p_chords/{P_note}/{P_note}sus2.png', 'rb')

                    bot.send_photo(call.message.chat.id, a_sus2p)
                    a_sus2p.close()

            if call.message:
                if call.data == f'{P_note}_sus4':
                    bot.send_message(call.message.chat.id,
                                     f'Вы выбрали {P_note} sus4')
                    bot.answer_callback_query(callback_query_id=call.id,
                                              show_alert=False,
                                              text=f"Вы выбрали {P_note} sus4")

                    a_sus4p = open(
                        f'bot_files/p_chords/{P_note}/{P_note}sus4.png', 'rb')

                    bot.send_photo(call.message.chat.id, a_sus4p)
                    a_sus4p.close()
Пример #16
0
def answer(call):
    chat_id = call.message.chat.id
    try:
        if (call.data) == "Cuvie":
            inline_keyboard = types.InlineKeyboardMarkup(row_width=1)
            inline = types.InlineKeyboardButton(text="Отменить покупку",
                                                callback_data='CANCEL')
            inline_keyboard.add(inline)

            user_dict[chat_id] = User(chat_id)
            user = user_dict[chat_id]
            user.name = 'HQD Cuvie'

            user.id = '0'

            msg = bot.send_message(
                chat_id,
                "💁🏻‍♀️ Этап покупки *HQD Cuvie*\n\nВыберите *вкус*",
                parse_mode="Markdown",
                reply_markup=tastes)
            bot.register_next_step_handler(msg, enterTastes)
        elif (call.data) == "Stark":
            inline_keyboard = types.InlineKeyboardMarkup(row_width=1)
            inline = types.InlineKeyboardButton(text="Отменить покупку",
                                                callback_data='CANCEL')
            inline_keyboard.add(inline)

            user_dict[chat_id] = User(chat_id)
            user = user_dict[chat_id]
            user.name = 'HQD Stark'
            user.id = '0'

            msg = bot.send_message(
                chat_id,
                "💁🏻‍♀️ Этап покупки *HQD Stark*\n\nВыберите *вкус*",
                parse_mode="Markdown",
                reply_markup=tastes)
            bot.register_next_step_handler(msg, enterTastes)
        elif (call.data) == "V2":
            inline_keyboard = types.InlineKeyboardMarkup(row_width=1)
            inline = types.InlineKeyboardButton(text="Отменить покупку",
                                                callback_data='CANCEL')
            inline_keyboard.add(inline)

            user_dict[chat_id] = User(chat_id)
            user = user_dict[chat_id]
            user.name = 'HQD V2'
            user.id = '0'

            msg = bot.send_message(
                chat_id,
                "💁🏻‍♀️ Этап покупки *HQD V2*\n\nВыберите *вкус*",
                parse_mode="Markdown",
                reply_markup=tastes)
            bot.register_next_step_handler(msg, enterTastes)
        elif (call.data) == "CuviePlus":
            inline_keyboard = types.InlineKeyboardMarkup(row_width=1)
            inline = types.InlineKeyboardButton(text="Отменить покупку",
                                                callback_data='CANCEL')
            inline_keyboard.add(inline)

            user_dict[chat_id] = User(chat_id)
            user = user_dict[chat_id]
            user.name = 'HQD Cuvie Plus'
            user.id = '0'

            msg = bot.send_message(
                chat_id,
                "💁🏻‍♀️ Этап покупки *HQD Cuvie Plus*\n\nВыберите *вкус*",
                parse_mode="Markdown",
                reply_markup=tastes)
            bot.register_next_step_handler(msg, enterTastes)
        elif (call.data) == "Ultra":
            inline_keyboard = types.InlineKeyboardMarkup(row_width=1)
            inline = types.InlineKeyboardButton(text="Отменить покупку",
                                                callback_data='CANCEL')
            inline_keyboard.add(inline)

            user_dict[chat_id] = User(chat_id)
            user = user_dict[chat_id]
            user.name = 'HQD Ultra Stick'
            user.id = '0'

            msg = bot.send_message(
                chat_id,
                "💁🏻‍♀️ Этап покупки *HQD Ultra Stick*\n\nВыберите *вкус*",
                parse_mode="Markdown",
                reply_markup=tastes)
            bot.register_next_step_handler(msg, enterTastes)
        elif (call.data) == "Maxim":
            inline_keyboard = types.InlineKeyboardMarkup(row_width=1)
            inline = types.InlineKeyboardButton(text="Отменить покупку",
                                                callback_data='CANCEL')
            inline_keyboard.add(inline)

            user_dict[chat_id] = User(chat_id)
            user = user_dict[chat_id]
            user.name = 'HQD Maxim'
            user.id = '0'

            msg = bot.send_message(
                chat_id,
                "💁🏻‍♀️ Этап покупки *HQD Maxim*\n\nВыберите *вкус*",
                parse_mode="Markdown",
                reply_markup=tastes)
            bot.register_next_step_handler(msg, enterTastes)
        elif (call.data == "Promo"):
            inline_keyboard = types.InlineKeyboardMarkup(row_width=1)
            inline = types.InlineKeyboardButton(text="Отменить покупку",
                                                callback_data='CANCEL')
            inline_keyboard.add(inline)

            user_dict[chat_id] = User(chat_id)
            user = user_dict[chat_id]
            user.name = 'Juul Promo Kit'
            user.id = '0'

            msg = bot.send_message(
                chat_id,
                "💁🏻‍♀️ Этап покупки *Juul Promo Kit*\n\nВыберите *вкус*",
                parse_mode="Markdown",
                reply_markup=tastes_juul)
            bot.register_next_step_handler(msg, enterTastesJuul)
        elif (call.data == "Device"):
            inline_keyboard = types.InlineKeyboardMarkup(row_width=1)
            inline = types.InlineKeyboardButton(text="Отменить покупку",
                                                callback_data='CANCEL')
            inline_keyboard.add(inline)

            user_dict[chat_id] = User(chat_id)
            user = user_dict[chat_id]
            user.name = 'Juul Device Kit'
            user.id = '0'

            msg = bot.send_message(
                chat_id,
                "💁🏻‍♀️ Этап покупки *Juul Device Kit*\n\nВыберите *вкус*",
                parse_mode="Markdown",
                reply_markup=tastes_juul)
            bot.register_next_step_handler(msg, enterTastesJuul)
        elif (call.data == "Starter"):
            inline_keyboard = types.InlineKeyboardMarkup(row_width=1)
            inline = types.InlineKeyboardButton(text="Отменить покупку",
                                                callback_data='CANCEL')
            inline_keyboard.add(inline)

            user_dict[chat_id] = User(chat_id)
            user = user_dict[chat_id]
            user.name = 'Juul Starter Kit'
            user.id = '0'

            msg = bot.send_message(
                chat_id,
                "💁🏻‍♀️ Этап покупки *Juul Starter Kit*\n\nВыберите *вкус*",
                parse_mode="Markdown",
                reply_markup=tastes_juul)
            bot.register_next_step_handler(msg, enterTastesJuul)
        elif (call.data) == "CANCEL":
            bot.clear_step_handler_by_chat_id(chat_id=call.message.chat.id)
        elif (call.data == "DEPOSIT"):
            inline_keyboard = types.InlineKeyboardMarkup(row_width=1)
            inline_1 = types.InlineKeyboardButton(
                text="Прямой перевод QIWI 0%", callback_data='QIWI')
            inline_2 = types.InlineKeyboardButton(
                text="Crystal Pay (Card, Yandex, Qiwi) 2%",
                callback_data='CARD')
            inline_keyboard.add(inline_1, inline_2)
            bot.edit_message_text(
                chat_id=call.message.chat.id,
                message_id=call.message.message_id,
                text=
                "💁🏻‍♀️ Пополнение *баланса*\n\nВыберите желаемый метод пополнения",
                parse_mode="Markdown",
                reply_markup=inline_keyboard)
        elif (call.data) == "QIWI":
            try:
                create_session(chat_id)
            except:
                pass
        elif (call.data) == "CARD":
            if (others.user_exists_bill(chat_id) == False):
                msg = bot.send_message(
                    chat_id,
                    f"💁🏻‍♀️ Введите *сумму пополнения* баланса. Минимальное пополнение — *200 рублей*",
                    parse_mode="Markdown")
                bot.register_next_step_handler(msg, enterDeposit)
            else:
                bot.send_message(
                    chat_id,
                    "💁🏻‍♀️ У вас есть *активная* сессия. Для создания новой, Вы должны завершить предыдущую сессию.",
                    parse_mode="Markdown")
        elif (call.data) == "BUY":
            chat_message = call.message.text
            chat_message = chat_message.split("\n")
            price_split = chat_message[4].split(":")
            price = int(price_split[1])
            others.user_un_balance(chat_id, price)
            if (others.user_un_balance(chat_id, price) == True):
                bot.send_message(
                    chat_id,
                    "💁🏻‍♀️ Товар *успешно* куплен. Ваша заявка в очереди, с Вами свяжется спец-менеджер.",
                    parse_mode="Markdown")
            else:
                bot.send_message(
                    chat_id,
                    "💁🏻‍♀️ Ошибка покупки: *недостаточно* средств на балансе.",
                    parse_mode="Markdown")
        elif (call.data) == "REFERAL":
            if (others.user_count_ref(chat_id) > 0):
                ref_ = ''
                for referal in others.user_referals(chat_id):
                    ref_ += f"{referal}\n"

                bot.send_message(
                    chat_id,
                    f"💁🏻‍♀️ *Ваши* рефералы\n\nКоличество приглашенных: *{others.user_count_ref(chat_id)}*\nЗаработано: *0* ₽\n\nДля достижения высоких результатов, внимательно подходите к поиску целевой аудитории: *привлекайте только тех, кто будет покупать наши услуги.*\n\n*Telegram ID:*`\n{ref_}`",
                    parse_mode="Markdown")
            else:
                bot.send_message(
                    chat_id,
                    "💁🏻‍♀️ У вас нет *рефералов*\n\nИспользуйте свою реферальную ссылку для привлечения новых пользователей и зарабатывайте на этом!",
                    parse_mode="Markdown")
        elif ("CHECK-" in call.data):
            code = call.data
            code = code.split("-")
            code = code[1]

            request = requests.get(
                f'https://api.crystalpay.ru/api.php?s={others.secret}&n={others.login}&o=checkpay&i={code}'
            )
            js = request.json()

            if (js['state'] == "payed"):
                payment = int(js['amount'])

                bot.send_message(
                    chat_id,
                    f"💁🏻‍♀️ Пополнение баланса *завершено*\n\nПополнение счета на сумму *{payment}* ₽ успешно завершено.",
                    parse_mode="Markdown")
                others.user_update_balance(chat_id, int(payment))

                notification(chat_id, payment)

                others.user_delete_bill(chat_id)
                bot.delete_message(chat_id=call.message.chat.id,
                                   message_id=call.message.message_id)
            else:
                bot.send_message(
                    chat_id,
                    "😟 Платеж *не был найден.* Повторите попытку снова или свяжитесь с поддержкой",
                    parse_mode="Markdown")
        elif (call.data == "Mango"):
            inline_keyboard = types.InlineKeyboardMarkup(row_width=1)
            inline = types.InlineKeyboardButton(text="Отменить покупку",
                                                callback_data='CANCEL')
            inline_keyboard.add(inline)

            user_dict[chat_id] = User(chat_id)
            user = user_dict[chat_id]
            user.name = 'Манго'
            user.id = '1'

            msg = bot.send_message(
                chat_id,
                f"💁🏻‍♀️ Этап покупки картридж *{user.name}*\n\nВыберите упаковку _(2 или 4)_",
                parse_mode="Markdown")
            bot.register_next_step_handler(msg, enterCount)
        elif (call.data == "Mix"):
            inline_keyboard = types.InlineKeyboardMarkup(row_width=1)
            inline = types.InlineKeyboardButton(text="Отменить покупку",
                                                callback_data='CANCEL')
            inline_keyboard.add(inline)

            user_dict[chat_id] = User(chat_id)
            user = user_dict[chat_id]
            user.name = 'Микс'
            user.id = '1'

            msg = bot.send_message(
                chat_id,
                f"💁🏻‍♀️ Этап покупки картридж *{user.name}*\n\nВыберите упаковку _(2 или 4)_",
                parse_mode="Markdown")
            bot.register_next_step_handler(msg, enterCount)
        elif (call.data == "Vanilla"):
            inline_keyboard = types.InlineKeyboardMarkup(row_width=1)
            inline = types.InlineKeyboardButton(text="Отменить покупку",
                                                callback_data='CANCEL')
            inline_keyboard.add(inline)

            user_dict[chat_id] = User(chat_id)
            user = user_dict[chat_id]
            user.name = 'Ваниль'
            user.id = '1'

            msg = bot.send_message(
                chat_id,
                f"💁🏻‍♀️ Этап покупки картридж *{user.name}*\n\nВыберите упаковку _(2 или 4)_",
                parse_mode="Markdown")
            bot.register_next_step_handler(msg, enterCount)
        elif (call.data == "Mint"):
            inline_keyboard = types.InlineKeyboardMarkup(row_width=1)
            inline = types.InlineKeyboardButton(text="Отменить покупку",
                                                callback_data='CANCEL')
            inline_keyboard.add(inline)

            user_dict[chat_id] = User(chat_id)
            user = user_dict[chat_id]
            user.name = 'Мята'
            user.id = '1'

            msg = bot.send_message(
                chat_id,
                f"💁🏻‍♀️ Этап покупки картридж *{user.name}*\n\nВыберите упаковку _(2 или 4)_",
                parse_mode="Markdown")
            bot.register_next_step_handler(msg, enterCount)
        elif (call.data == "Tobacco"):
            inline_keyboard = types.InlineKeyboardMarkup(row_width=1)
            inline = types.InlineKeyboardButton(text="Отменить покупку",
                                                callback_data='CANCEL')
            inline_keyboard.add(inline)

            user_dict[chat_id] = User(chat_id)
            user = user_dict[chat_id]
            user.name = 'Табак'
            user.id = '1'

            msg = bot.send_message(
                chat_id,
                f"💁🏻‍♀️ Этап покупки картридж *{user.name}*\n\nВыберите упаковку _(2 или 4)_",
                parse_mode="Markdown")
            bot.register_next_step_handler(msg, enterCount)
        elif (call.data == "Virginia"):
            inline_keyboard = types.InlineKeyboardMarkup(row_width=1)
            inline = types.InlineKeyboardButton(text="Отменить покупку",
                                                callback_data='CANCEL')
            inline_keyboard.add(inline)

            user_dict[chat_id] = User(chat_id)
            user = user_dict[chat_id]
            user.name = 'Вирджиния'
            user.id = '1'

            msg = bot.send_message(
                chat_id,
                f"💁🏻‍♀️ Этап покупки картридж *{user.name}*\n\nВыберите упаковку _(2 или 4)_",
                parse_mode="Markdown")
            bot.register_next_step_handler(msg, enterCount)
        elif (call.data == "SEND_CODE"):
            msg = bot.send_message(
                chat_id,
                f"💁🏻‍♀️ Бонус *50* ₽\n\nВведите *код-приглашение*",
                parse_mode="Markdown")
            bot.register_next_step_handler(msg, user_invite_code)
    except:
        pass
Пример #17
0
def key(message):
    keymarkup = types.InlineKeyboardMarkup(row_width=3)
    key1 = types.InlineKeyboardButton('A', callback_data='A')
    key2 = types.InlineKeyboardButton('A#/Bb', callback_data='A#')
    key3 = types.InlineKeyboardButton('B', callback_data='B')
    key4 = types.InlineKeyboardButton('C', callback_data='C')
    key5 = types.InlineKeyboardButton('C#/Db', callback_data='C#')
    key6 = types.InlineKeyboardButton('D', callback_data='D')
    key7 = types.InlineKeyboardButton('D#/Eb', callback_data='D#')
    key8 = types.InlineKeyboardButton('E', callback_data='E')
    key9 = types.InlineKeyboardButton('F', callback_data='F')
    key10 = types.InlineKeyboardButton('F#/Gb', callback_data='F#')
    key11 = types.InlineKeyboardButton('G', callback_data='G')
    key12 = types.InlineKeyboardButton('G#/Ab', callback_data='G#')

    keymarkup.add(key1, key2, key3, key4, key5, key6, key7, key8, key9, key10,
                  key11, key12)

    bot.send_message(message.chat.id,
                     'Выберите тонику:',
                     reply_markup=keymarkup)
Пример #18
0
 def LanguageKeyboard(self):
     keyboard=types.InlineKeyboardMarkup()
     languages=f"{self.conf.get('Languages','languages')}".split(' ')
     for lang in languages:
         keyboard.add(types.InlineKeyboardButton(text=lang, callback_data=f"set_language {lang}"))
     return keyboard
Пример #19
0
def repeat_all_messages(message):
    user_id = message.from_user.id
    message_in = message.text
    username = message.from_user.username
    first_name = message.from_user.first_name
    last_name = message.from_user.last_name
    date = message.date
    logsystem('message', str(message_in), str(user_id))
    status = load_staus(user_id)

    if 'Пополнить' == message_in:
        markup = menu_schet()
        message_out = 'Ваш баланс'
        bot.send_message(user_id,
                         message_out,
                         parse_mode='HTML',
                         reply_markup=markup)
        sale(user_id)

    if 'Пользователи' == message_in:
        markup = menu_users()

        message_out = 'Список пользователей'
        bot.send_message(user_id,
                         message_out,
                         parse_mode='HTML',
                         reply_markup=markup)
        conn = sqlite3.connect("user.sqlite")

        cursor = conn.cursor()
        sql = "select id,user_id,status from user where 1=1 "
        cursor.execute(sql)
        data = cursor.fetchall()
        for row in data:
            id_v, user_id_v, status_v = row
            grup = load_param(user_id_v, 1)

            username_v, first_name_v, last_name_v = load__FIO(user_id)
            message_out = 'Пользователь с id: ' + str(
                user_id_v
            ) + '\nЛогин: ' + username_v + '\nИмя: ' + first_name_v + '\nФамилия: ' + last_name_v + '\n'

            labelm = ''
            if grup == 'B':
                message_out = message_out + ' в группе B'
                labelm = 'B'
                keyboard = types.InlineKeyboardMarkup(row_width=1)
                keyboard.add(
                    types.InlineKeyboardButton(
                        text='Перевести в группу Нет группы',
                        callback_data='goB_' + str(user_id_v)))
                bot.send_message(user_id,
                                 message_out,
                                 parse_mode='HTML',
                                 reply_markup=keyboard)
            if grup == 'A':
                labelm = 'A'
                message_out = message_out + ' в группе A'
                keyboard = types.InlineKeyboardMarkup(row_width=1)
                keyboard.add(
                    types.InlineKeyboardButton(text='Перевести в группу  B',
                                               callback_data='goA_' +
                                               str(user_id_v)))
                bot.send_message(user_id,
                                 message_out,
                                 parse_mode='HTML',
                                 reply_markup=keyboard)

            if labelm == '':
                message_out = message_out + ' в группе Нет группы'
                keyboard = types.InlineKeyboardMarkup(row_width=1)
                keyboard.add(
                    types.InlineKeyboardButton(text='Перевести в группу A',
                                               callback_data='goNo_' +
                                               str(user_id_v)))
                bot.send_message(user_id,
                                 message_out,
                                 parse_mode='HTML',
                                 reply_markup=keyboard)

    if 'Мои каналы' == message_in:
        markup = menu_my_kanal()
        message_out = 'Мои каналы'
        bot.send_message(user_id,
                         message_out,
                         parse_mode='HTML',
                         reply_markup=markup)

    if 'Счет' == message_in:
        markup = menu_schet()
        message_out = 'Счет'
        bot.send_message(user_id,
                         message_out,
                         parse_mode='HTML',
                         reply_markup=markup)

    if 'Статистика' == message_in:
        markup = menu_ls()
        message_out = 'Статистика'
        bot.send_message(user_id,
                         message_out,
                         parse_mode='HTML',
                         reply_markup=markup)

    if 'Регистрация' == message_in:
        markup = menu_ls()
        message_out = 'Регистрация'
        bot.send_message(user_id,
                         message_out,
                         parse_mode='HTML',
                         reply_markup=markup)

    if 'Личный кабинет' == message_in:
        markup = menu_ls()
        message_out = 'Личный кабинет'
        bot.send_message(user_id,
                         message_out,
                         parse_mode='HTML',
                         reply_markup=markup)

    if 'Тест' == message_in:
        markup = menu_test()
        message_out = 'Тест'
        bot.send_message(user_id,
                         message_out,
                         parse_mode='HTML',
                         reply_markup=markup)

    if 'Админка' == message_in:
        markup = menu_admin()
        message_out = 'Админка'
        bot.send_message(user_id,
                         message_out,
                         parse_mode='HTML',
                         reply_markup=markup)

    if 'Список' == message_in:
        markup = menu_list()
        message_out = 'Список'
        bot.send_message(user_id,
                         message_out,
                         parse_mode='HTML',
                         reply_markup=markup)

    if 'Отправить группе B' == message_in:
        send_m('B', user_id)

    if 'Отправить группе A' == message_in:
        send_m('A', user_id)

    if 'Отмена' == message_in:
        message_out = 'Отмена сообщения'
        markup = menu_main()
        bot.send_message(user_id,
                         message_out,
                         parse_mode='HTML',
                         reply_markup=markup)

    if 'Главное меню' == message_in:
        message_out = 'Главное меню'
        markup = menu_main()
        bot.send_message(user_id,
                         message_out,
                         parse_mode='HTML',
                         reply_markup=markup)

    if status.find('testA') != -1:
        message_out = 'Получено новое сообщение группы A'
        markup = menu_send_A()
        bot.send_message(user_id,
                         message_out,
                         parse_mode='HTML',
                         reply_markup=markup)
        save_status(user_id, username, '')
        save_param(user_id, 3, message_in)

    if status.find('testB') != -1:
        message_out = 'Получено новое сообщение для группы B'
        markup = menu_send_B()
        bot.send_message(user_id,
                         message_out,
                         parse_mode='HTML',
                         reply_markup=markup)
        save_status(user_id, username, '')
        save_param(user_id, 3, message_in)

    if '=> Группа A' == message_in:
        message_out = 'Введите сообшение для отправки группе A'
        markup = menu_main()
        bot.send_message(user_id,
                         message_out,
                         parse_mode='HTML',
                         reply_markup=markup)
        save_status(user_id, username, 'testA')
        label = 'yes'

    if '=> Группа B' == message_in:
        message_out = 'Введите сообшение для отправки группе B'
        markup = menu_main()
        bot.send_message(user_id,
                         message_out,
                         parse_mode='HTML',
                         reply_markup=markup)
        save_status(user_id, username, 'testB')
        label = 'yes'

    if message_in == 'Админка2':
        message_out = 'Список пользователей'
        bot.send_message(user_id, message_out, parse_mode='HTML')
        conn = sqlite3.connect("user.sqlite")

        cursor = conn.cursor()
        sql = "select id,user_id,status from user where 1=1 "
        cursor.execute(sql)
        data = cursor.fetchall()
        for row in data:
            id_v, user_id_v, status_v = row
            grup = load_param(user_id_v, 1)

            username_v, first_name_v, last_name_v = load__FIO(user_id)
            message_out = 'Пользователь с id: ' + str(
                user_id_v
            ) + '\nЛогин: ' + username_v + '\nИмя: ' + first_name_v + '\nФамилия: ' + last_name_v + '\n'

            labelm = ''
            if grup == 'B':
                message_out = message_out + ' в группе B'
                labelm = 'B'
                keyboard = types.InlineKeyboardMarkup(row_width=1)
                keyboard.add(
                    types.InlineKeyboardButton(
                        text='Перевести в группу Нет группы',
                        callback_data='goB_' + str(user_id_v)))
                bot.send_message(user_id,
                                 message_out,
                                 parse_mode='HTML',
                                 reply_markup=keyboard)

            if grup == 'A':
                labelm = 'A'
                message_out = message_out + ' в группе A'
                keyboard = types.InlineKeyboardMarkup(row_width=1)
                keyboard.add(
                    types.InlineKeyboardButton(text='Перевести в группу  B',
                                               callback_data='goA_' +
                                               str(user_id_v)))
                bot.send_message(user_id,
                                 message_out,
                                 parse_mode='HTML',
                                 reply_markup=keyboard)

            if labelm == '':
                message_out = message_out + ' в группе Нет группы'
                keyboard = types.InlineKeyboardMarkup(row_width=1)
                keyboard.add(
                    types.InlineKeyboardButton(text='Перевести в группу A',
                                               callback_data='goNo_' +
                                               str(user_id_v)))
                bot.send_message(user_id,
                                 message_out,
                                 parse_mode='HTML',
                                 reply_markup=keyboard)

    if message_in == 'Оплата':
        message_out = 'Ваш баланс составляет:\nПодписка действует до'
        bot.send_message(user_id, message_out, parse_mode='HTML')
        save_status(user_id, username, 'q01')
        sale(user_id)
Пример #20
0
 def UrlDownload(self,url,text):
     keyboard = types.InlineKeyboardMarkup()
     download_url = types.InlineKeyboardButton(text=text, url=url)
     keyboard.add(download_url)
     return keyboard
Пример #21
0
def close_dialogue(type_id,
                   id,
                   pay=False,
                   silent=False,
                   notify_admin_group=True):
    """ Change client state in DB to CLOSED and update pinned message with new info
        Optionally send client closing message """

    time.sleep(1)
    user_state = get_info('state', type_id, id)

    # Return if client not found in DB
    if not user_state:
        return

    # Point that dialogue is already closed and return to prevent multiple closing messages for client
    if user_state in ["CLOSED", "ONE MESSAGE"]:
        bot.send_message(config.group_id, "Диалог уже закрыт")
        return

    update_clients([type_id, id], ["state", "CLOSED"], ["rate", "0"],
                   ["review_time", "0"], ["received", "NO"])

    if notify_admin_group:
        bot.send_message(config.group_id, f"Диалог закрыт\n{id}")

    update_pinned_top()

    if pay:
        update_clients([type_id, id], ["verified", 1])

    # Do not send any message to client
    if silent or pay:
        return

    if type_id == "tg_id":
        # Ask client to rate support
        buttons = types.InlineKeyboardMarkup()
        buttons.add(
            types.InlineKeyboardButton(text="\U0001F92C 1", callback_data="1"))
        buttons.add(
            types.InlineKeyboardButton(text="\U00002639	2", callback_data="2"))
        buttons.add(
            types.InlineKeyboardButton(text="\U0001F610 3", callback_data="3"))
        buttons.add(
            types.InlineKeyboardButton(text="\U0001F642 4", callback_data="4"))
        buttons.add(
            types.InlineKeyboardButton(text="\U0001F600 5", callback_data="5"))

        bot.send_message(id, messages.close, reply_markup=buttons)

    elif type_id == "vk_id":
        keyboard = VkKeyboard(inline=True)

        keyboard.add_button("\U0001F92C 1")
        keyboard.add_line()
        keyboard.add_button("\U00002639	2")
        keyboard.add_line()
        keyboard.add_button("\U0001F610 3")
        keyboard.add_line()
        keyboard.add_button("\U0001F642 4")
        keyboard.add_line()
        keyboard.add_button("\U0001F600 5")

        vk_send_message(id, messages.close, keyboard=keyboard.get_keyboard())

    elif type_id == "fb_id":
        buttons = [
            Button(title='\U0001F92C Плохо', type='postback', payload='2'),
            Button(title='\U0001F610 Нормально', type='postback', payload='4'),
            Button(title='\U0001F600 Отлично', type='postback', payload='5')
        ]

        fb_bot.send_button_message(recipient_id=id,
                                   text=messages.close,
                                   buttons=buttons)
Пример #22
0
def get_keyboard(url):
    examples = url['examples']
    markup = types.InlineKeyboardMarkup()
    if examples:
        markup.add(types.InlineKeyboardButton(text='Examples', url=examples))
    return markup
Пример #23
0
def text(message: Message):
    print('Что-то написали', message.json)

    chat_id = message.chat.id

    # Переход в режим Администратора
    if message.text == config.ADMIN_PASS:
        add_user(chat_id, key='admin')
        bot.send_message(chat_id,
                         'Вы успешно зарегистрировались как Администратор!',
                         reply_markup=keyboard_main_menu_admin())

    # Если пользователь что-то написал до регистрации
    if not str(chat_id) in read():
        bot.send_message(message.chat.id, 'Вы ещё не зарегистрировались!')
        registration(message)
        return

    # Присваивание статуса пользователю
    user_status = read()[str(chat_id)]['status']

    #===========================ДЛЯ АДМИНИСТРАТОРА==============================#
    if user_status == 'admin':
        if message.text == 'Основное меню':
            bot.send_message(chat_id,
                             'Возвращено в основное меню',
                             reply_markup=keyboard_main_menu_admin())
        if message.text == 'Написать сообщение посетителям':
            markup = types.ReplyKeyboardMarkup(one_time_keyboard=True,
                                               resize_keyboard=True)
            btn1 = types.KeyboardButton('Отмена')
            markup.add(btn1)
            msg = bot.send_message(
                chat_id,
                'Введите сообщение для отправки (после того как вы отпраите сообщение в чат, оно придёт всем посетителям)',
                reply_markup=markup)
            bot.register_next_step_handler(msg, send_message_visitors)

        if message.text == 'Написать сообщение студентам':
            markup = types.ReplyKeyboardMarkup(one_time_keyboard=True,
                                               resize_keyboard=True)
            btn1 = types.KeyboardButton('Отмена')
            markup.add(btn1)
            msg = bot.send_message(
                chat_id,
                'Введите сообщение для отправки (после того как вы отпраите сообщение в чат, оно придёт всем посетителям)',
                reply_markup=markup)
            bot.register_next_step_handler(msg, send_message_students)

#===========================================================================#

#===========================ДЛЯ ПОСЕТИТЕЛЕЙ=================================#

    if user_status == 'visitor':
        # Расписание
        if message.text == 'Расписание занятий':
            bot.send_message(chat_id, timetable_visitor(chat_id))

        # Отработка
        elif message.text == 'Ближайшая отработка':
            bot.send_message(chat_id, otrabotka(chat_id))

        # Задолжность по оплате
        elif message.text == 'Задолжность по оплате':
            bot.send_message(chat_id, owe(chat_id))

            # Основное меню для посетителей
        elif message.text == 'Основное меню':
            bot.send_message(chat_id,
                             'Возвращено в основное меню',
                             reply_markup=keyboard_main_menu_visitor())
        else:
            bot.send_message(chat_id, 'Я вас не понимаю')
            bot.send_message(chat_id,
                             'Выберите пункт из меню',
                             reply_markup=keyboard_main_menu_visitor())

#===========================ДЛЯ СТУДЕНТОВ=================================#

    if user_status == 'student':
        # Вывод списка оборудования
        if message.text == 'Оборудование':
            eq = change_BD('Оборудование')
            bot.send_message(message.chat.id,
                             'Список оборудования:',
                             reply_markup=main_menu_student())
            for i in range(len(eq)):
                button = 'Описание'
                keyboard = types.InlineKeyboardMarkup()
                keyboard.add(
                    types.InlineKeyboardButton(text=button,
                                               callback_data='info_eq' +
                                               change_BD('Оборудование')[i]))
                bot.send_message(message.chat.id,
                                 change_BD('Оборудование')[i],
                                 reply_markup=keyboard)
        # Вывод списка инструментов
        elif message.text == 'Инструмент':
            tools = change_BD('Инструмент')
            tools_str = ''
            bot.send_message(message.chat.id,
                             'Доступный инструмент:',
                             reply_markup=main_menu_student())
            for i in tools:
                tools_str = tools_str + i
            bot.send_message(message.chat.id, tools_str)

        # Вывод списка расходных материалов
        elif message.text == 'Расходные материалы':
            eq = change_BD('Расходные материалы')

            bot.send_message(message.chat.id,
                             'Расходные материалы:',
                             reply_markup=main_menu_student())
            for i in range(len(eq)):
                name = change_BD('Расходные материалы')[i][:-1]
                button1 = (
                    'Израсходовать ' +
                    f'(доступно: {str(exp_mat_kol(name, "Расходные материалы"))} {exp_mat_ed_izm(name, "Расходные материалы")})'
                )
                button2 = 'Вернуть'
                keyboard = types.InlineKeyboardMarkup()
                keyboard.add(
                    types.InlineKeyboardButton(text=button1,
                                               callback_data='spend_exp_mat' +
                                               name))
                keyboard.add(
                    types.InlineKeyboardButton(
                        text=button2,
                        callback_data='cancel_spend_exp_mat' + name))
                bot.send_message(message.chat.id, name, reply_markup=keyboard)

        # Вывод расписания кабинета
        elif message.text == 'Расписание кабинета':
            timetable(chat_id)

        # Кнопка отмена для студентов
        elif message.text == 'Отмена':
            bot.send_message(chat_id,
                             'Отменено',
                             reply_markup=keyboard_main_menu_student())

        # Кнопка основное меню для студентов
        elif message.text == 'Основное меню':
            bot.send_message(chat_id,
                             'Возвращено в основное меню',
                             reply_markup=keyboard_main_menu_student())

        else:
            bot.send_message(chat_id, 'Я вас не понимаю')
            bot.send_message(chat_id,
                             'Выберите пункт из меню',
                             reply_markup=keyboard_main_menu_student())
Пример #24
0
lang_keys = types.ReplyKeyboardMarkup(
    resize_keyboard=True,
    one_time_keyboard=True
    )
lang_keys.keyboard = select_lang_markup





################# ADDRESS 
en_confirm_markup = types.InlineKeyboardMarkup(row_width=2)
it_confirm_markup = types.InlineKeyboardMarkup()

en_confirm_btn = types.InlineKeyboardButton(text="Confirm", callback_data="confirm_address")
en_modify_btn = types.InlineKeyboardButton(text="Cancel", callback_data="cancel_address")

it_confirm_btn = types.InlineKeyboardButton(text="Confermare", callback_data="confirm_address")
it_modify_btn = types.InlineKeyboardButton(text="Annulla", callback_data="cancel_address")

# en_confirm_markup.keyboard = [[en_confirm_btn], [en_modify_btn]]
# it_confirm_markup.keyboard = [[it_confirm_btn], [it_modify_btn]]

en_confirm_markup.add(en_confirm_btn, en_modify_btn)
it_confirm_markup.add(it_confirm_btn, it_modify_btn)


confirm = {
    "en": en_confirm_markup,
    "it": it_confirm_markup
Пример #25
0
def ans(message: Message):
    print('Кнопка', message.message.json)
    chat_id = message.message.chat.id
    global BUFFER
    # регистрация студента
    if message.data == 'student':
        if str(chat_id) in read() and not check_start_reg(chat_id):
            bot.send_message(chat_id, 'Вы уже зарегистрированы!')
            return

        if not check_start_reg(chat_id, True):
            BUFFER[chat_id] = 'студент'
            msg = bot.send_message(chat_id, 'Введите ФИО (через пробел)')
            bot.register_next_step_handler(msg, ask_name)

    # Регистрация посетителя
    if message.data == 'visitor':
        if str(chat_id) in read() and not check_start_reg(chat_id):
            bot.send_message(chat_id, 'Вы уже зарегистрированы!')
            return

        if not check_start_reg(chat_id, True):
            BUFFER[chat_id] = 'посетитель'
            msg = bot.send_message(chat_id, 'Введите номер договора')
            bot.register_next_step_handler(msg, ask_contract)

    # Описание оборудования
    if message.data[:7] == 'info_eq':
        name = message.data[7:-1]
        keyboard = types.InlineKeyboardMarkup()
        button = 'Свернуть описание'
        keyboard.add(
            types.InlineKeyboardButton(text=button,
                                       callback_data='close_info_eq' + name))

        bot.edit_message_text(name + info_equipment(name, 'Оборудование'),
                              chat_id,
                              message.message.message_id,
                              reply_markup=keyboard)

    # Свернуть описание обоудования
    if message.data[:13] == 'close_info_eq':
        name = message.data[13:]

        keyboard = types.InlineKeyboardMarkup()
        button = 'Описание'
        keyboard.add(
            types.InlineKeyboardButton(text=button,
                                       callback_data='info_eq' + name + '\n'))

        bot.edit_message_text(name,
                              chat_id,
                              message.message.message_id,
                              reply_markup=keyboard)

    # Кнопка израсходовать
    if message.data[:13] == 'spend_exp_mat':
        name = message.data[13:]
        if str(chat_id) in BUFFER and BUFFER[str(chat_id)][-1] == 's':

            bot.send_message(
                chat_id,
                f'Вы уже нажали на кнопку Израсходовать  ({BUFFER[str(chat_id)][:-1]})'
                + '\nВведите количество, либо нажмите кнопку Отмена')

        elif str(chat_id) in BUFFER and BUFFER[str(chat_id)][-1] == 'b':

            bot.send_message(
                chat_id,
                f'Вы уже нажали на кнопку Вернуть  ({BUFFER[str(chat_id)][:-1]})'
                + '\nВведите количество, либо нажмите кнопку Отмена')
        else:

            markup = types.ReplyKeyboardMarkup(one_time_keyboard=False,
                                               resize_keyboard=True)
            btn = types.KeyboardButton('Отмена')
            markup.add(btn)

            button1 = (
                '➡️ Израсходовать ' +
                f'(доступно: {str(exp_mat_kol(name, "Расходные материалы"))} {exp_mat_ed_izm(name, "Расходные материалы")})  ⬅'
            )
            button2 = 'Вернуть'
            keyboard = types.InlineKeyboardMarkup()
            keyboard.add(
                types.InlineKeyboardButton(text=button1,
                                           callback_data='spend_exp_mat' +
                                           name))
            keyboard.add(
                types.InlineKeyboardButton(
                    text=button2, callback_data='cancel_spend_exp_mat' + name))

            bot.edit_message_text(
                name + '\n\nВведите количество, которое хотите израсходовать',
                chat_id,
                message.message.message_id,
                reply_markup=keyboard)

            BUFFER[str(
                chat_id
            )] = name + 's'  # Записываем в буфер название материала который выбрал пользователь и действие (s-spend)
            BUFFER['m_id' + str(
                chat_id
            )] = message.message.message_id  #записываем в буфер id сообщения для дальнейшего редактирования

            msg = bot.send_message(
                chat_id,
                name + '\nВведите количество, которое хотите израсходовать',
                reply_markup=markup)
            bot.register_next_step_handler(msg, change_kol)

    # Кнопка вернуть
    if message.data[:20] == 'cancel_spend_exp_mat':
        name = message.data[20:]

        if str(chat_id) in BUFFER and BUFFER[str(chat_id)][-1] == 'b':

            bot.send_message(
                chat_id,
                f'Вы уже нажали на кнопку Вернуть ({BUFFER[str(chat_id)][:-1]})'
                + '\nВведите количество, либо нажмите кнопку Отмена')

        elif str(chat_id) in BUFFER and BUFFER[str(chat_id)][-1] == 's':

            bot.send_message(
                chat_id,
                f'Вы уже нажали на кнопку Израсходовать  ({BUFFER[str(chat_id)][:-1]})'
                + '\nВведите количество, либо нажмите кнопку Отмена')

        else:

            markup = types.ReplyKeyboardMarkup(one_time_keyboard=False,
                                               resize_keyboard=True)
            btn = types.KeyboardButton('Отмена')
            markup.add(btn)

            button1 = (
                'Израсходовать ' +
                f'(доступно: {str(exp_mat_kol(name, "Расходные материалы"))} {exp_mat_ed_izm(name, "Расходные материалы")})'
            )
            button2 = '➡️ Вернуть ⬅'
            keyboard = types.InlineKeyboardMarkup()
            keyboard.add(
                types.InlineKeyboardButton(text=button1,
                                           callback_data='spend_exp_mat' +
                                           name))
            keyboard.add(
                types.InlineKeyboardButton(
                    text=button2, callback_data='cancel_spend_exp_mat' + name))

            bot.edit_message_text(
                name + '\n\nВведите количество, которое хотите вернуть',
                chat_id,
                message.message.message_id,
                reply_markup=keyboard)

            BUFFER[str(
                chat_id
            )] = name + 'b'  # Записываем в буфер название материала который выбрал пользователь и действие (b-back)
            BUFFER['m_id' + str(
                chat_id
            )] = message.message.message_id  # Записываем в буфер id сообщения для дальнейшего редактирования

            msg = bot.send_message(
                chat_id,
                name + '\nВведите количество, которое хотите вернуть',
                reply_markup=markup)
            bot.register_next_step_handler(msg, change_kol)
Пример #26
0
import telebot
from telebot import types
import time
from support import get_token, logging
import stock
import threading

update_stocks_base = threading.Thread(target=stock.fill_data)
update_stocks_base.start()

bot = telebot.TeleBot(get_token())

# Main menu
menu_keyboard = types.InlineKeyboardMarkup()
menu_keyboard.add(
    types.InlineKeyboardButton(text="Получить данные акции",
                               callback_data="stocks"))

# Menu to choose ticket of stock
stocks_keyboard = types.InlineKeyboardMarkup()
for ticker in stock.MOEX_TICKERS:
    stocks_keyboard.add(
        types.InlineKeyboardButton(text=f"{ticker}",
                                   callback_data=f"ticker_{ticker}"))


@bot.message_handler(commands=['start'])
def send_welcome(message):
    logging(message)
    bot.send_message(message.from_user.id, "Стартуем")

def callback_work(call):
    if call.data == "weight":
        bot.send_message(
            call.message.chat.id,
            "The presented weight loss training at home is intended for people who do not have sports equipment. Despite the lack of shells, classes are no less effective and productive. The most important thing is to warm up well and strictly follow the techniques of each exercise."
            "You'll find 9 exercises (8 exercises in total, but the last exercise is performed first on the right side, then on the left) + 1 minute of rest after completion. This means about 10 min for 1 lap.\nPerform the exercises for the specified time sequentially one after another, then repeat the training from the beginning in 3-4 circles. Beginners can complete 2 laps."
            "\nOptions for performing circular training:\n>>>>>>>>>>By time:\n45 seconds of work / 15 seconds of rest\n>>>>>>>>>>By number of repetitions:\nspecified in the article after each exercise"
            "\n1. PUSH-UPS + PULL-UPS:\nTaking the emphasis lying down, press down, almost touching the surface of the floor. Keep your back straight and look straight ahead. When you return to the starting phase, pull your arms up to your chest one at a time, pulling your elbows back. After lifting your hands, repeat the process again. If you find it difficult to perform push-UPS, get down on your knees or push-UPS from the bench.)"
            "\n2. LUNGES FORWARD:\nPut your hands on your waist and your feet a little narrower than your shoulders. Step forward, bending the leg at the knee to a right angle. The foot stands firmly on the foot. The foot behind stands on the toe, and the knee does not touch the floor. The back is tense, fixed straight, does not slouch. Get up and repeat with the other leg.)"
            "\n3. 'GOOD MORNING':\nStand with your hands behind your head. Bend your knees slightly and tilt your body forward to a 90-degree angle. At the same time, do not slouch, straighten your shoulders, keep a natural deflection in the lower back. Stretching from the lower point to the upper, rely only on the work of the back muscles.)"
            "\n5. KNEE-ELBOW TWIST:\nIn the standing position, place your hands on the back of your head. Feet are shoulder-width apart. Alternately stretch the opposite elbows and knees to each other at the level below the chest, turning the body. Take your time, making short pauses at the peak point.)"
            "\n6. STATIC SQUAT:\nDo this with your back straight and your feet shoulder-width apart. Hold in the lower position, observing the right angle in the knee joint. Extend your arms forward for better balance.)"
            "\n7. SPIDER PLANK:\nTake the position of the bar at arm's length, put your feet next to each other. Now alternately stretch your right and left knees to the elbows of your hands, emphasizing the work of the lateral abdominal muscles. The back and lower back do not bend, forming a straight line.)"
            "\n8. HAND TOUCH OF THE FOOT:\nLie down on the gym carpet and spread your arms out to the sides. The legs are also slightly apart. Now pull your right leg up while reaching for her foot with your left hand. Look directly at the ceiling without turning your head. Back in the starting phase, switch sides.)"
        )
        # sendPhoto
        photo1 = open("PUSH-PULL.png", 'rb')
        bot.send_photo(call.from_user.id, photo1)
        bot.send_message(call.message.chat.id, "1. PUSH-UPS + PULL-UPS")
        #
        photo2 = open("LUNGES FORWARD.png", 'rb')
        bot.send_photo(call.from_user.id, photo2)
        bot.send_message(call.message.chat.id, "2. LUNGES FORWARD")
        #
        photo3 = open("GOOD MORNING.png", 'rb')
        bot.send_photo(call.from_user.id, photo3)
        bot.send_message(call.message.chat.id, "3. 'GOOD MORNING'")
        #
        photo4 = open("KNEE-ELBOW TWIST.png", 'rb')
        bot.send_photo(call.from_user.id, photo4)
        bot.send_message(call.message.chat.id, "5. KNEE-ELBOW TWIST")
        #
        photo5 = open("STATIC SQUAT.png", 'rb')
        bot.send_photo(call.from_user.id, photo5)
        bot.send_message(call.message.chat.id, "6. STATIC SQUAT")
        #
        photo6 = open("SPIDER PLANK.png", 'rb')
        bot.send_photo(call.from_user.id, photo6)
        bot.send_message(call.message.chat.id, "7. SPIDER PLANK")
        #
        photo7 = open("HAND TOUCH OF THE FOOT.png", 'rb')
        bot.send_photo(call.from_user.id, photo7)
        bot.send_message(call.message.chat.id, "8. HAND TOUCH OF THE FOOT")

    elif call.data == "muscle":
        bot.send_message(call.from_user.id, "What are we going to pump today?")

        keyboard = types.InlineKeyboardMarkup()

        key_legs = types.InlineKeyboardButton(text='Leg training',
                                              callback_data='leg')
        keyboard.add(key_legs)
        key_press = types.InlineKeyboardButton(text='Press training',
                                               callback_data='press')
        keyboard.add(key_press)
        key_chest = types.InlineKeyboardButton(text='Back training',
                                               callback_data='back')
        keyboard.add(key_chest)
        bot.send_message(call.from_user.id,
                         text='Choose what you want',
                         reply_markup=keyboard)
    elif call.data == "leg":
        bot.send_message(
            call.message.chat.id,
            "Exercise 'Pistol':\nApproaches: 3\nReplays: 14\nRest: 30 seconds\n(We stand with our legs narrowly apart and lift one of them off the floor. After that, bend the leg on which we stand at the knee and squat as low as possible, trying to keep your back straight. Now push off and return to the starting position, change the leg and repeat)."
            "\n============================="
            "\nBurpee:\nApproaches: 3\nReplays: 20\nRest: 30 seconds"
            "\n============================="
            "\n\nWalking on your hands against the wall:\nApproaches: 3\nReplays: 10\nRest: 30 seconds\n(We take a position on our hands (standing on our hands) with our feet leaning against the wall. Now move your hands forward and 'go' down the wall until your feet reach the floor.)"
            "\n============================="
            "\n\nJumping to the side:\nApproaches: 3\nReplays: 30\nRest: 30 seconds\n(We stand with our feet shoulder-width apart. Then we go down and abruptly push off from the floor with our right foot in order to jump to the left side and land on the left foot. Immediately after landing, push off with your left foot and repeat the movement, this time to the right Side)"
            "\n============================="
            "\n\nThe long jump from the place:\nApproaches: 3\nReplays: 8\nRest: 30 seconds\n(We go down to the squat position with our feet shoulder-width apart. We pull our arms back and use them to push ourselves forward when jumping, and for additional inertia, we throw our legs in front of us. We jump as far as possible and land on the soles of our feet.)"
        )
        photo0 = open("Pistol.png", 'rb')
        bot.send_photo(call.from_user.id, photo0)
        bot.send_message(call.message.chat.id, "Exercise 'Pistol'")
        ###########################################################
        photo1 = open("one.png", 'rb')
        bot.send_photo(call.from_user.id, photo1)
        ############################################################
        photo2 = open("two.png", 'rb')
        bot.send_photo(call.from_user.id, photo2)
        ###############################################################
        photo3 = open("three.png", 'rb')
        bot.send_photo(call.from_user.id, photo3)
        bot.send_message(call.message.chat.id, "Exercise 'Burpee'")
        ############################################################
        photo4 = open("w1.png", 'rb')
        bot.send_photo(call.from_user.id, photo4)
        ################################################################
        photo5 = open("w2.png", 'rb')
        bot.send_photo(call.from_user.id, photo5)
        bot.send_message(call.message.chat.id,
                         "Walking on your hands against the wall")
        ###########################################################
        photo6 = open("j1.png", 'rb')
        bot.send_photo(call.from_user.id, photo6)
        ####################################################################
        photo7 = open("j2.png", 'rb')
        bot.send_photo(call.from_user.id, photo7)
        bot.send_message(call.message.chat.id, "Jumping to the side")
        ##################################################################
        photo8 = open("l1.png", 'rb')
        bot.send_photo(call.from_user.id, photo8)
        ###############################################################
        photo9 = open("l2.png", 'rb')
        bot.send_photo(call.from_user.id, photo9)
        bot.send_message(call.message.chat.id, "Jumping to the side")

    elif call.data == "press":
        bot.send_message(
            call.message.chat.id,
            "Reverse twists:\nApproaches: 5\nReplays: 60\nRest: 120 seconds\n(lie on your back with your hands on the floor at your sides, palms facing down. We bend the knees and pull them to the chest, squeezing the abdominal muscles. At the same time, lift your hips off the floor. In the upper position of the movement, squeeze the muscles, and then slowly lower until the hips are perpendicular to the floor.)"
            "\n============================="
            "\n\nSit-UPS:\nApproaches: 5\nReplays: 60\nRest: 120 seconds\n(We lie down on the floor and bend our knees. If possible, fix the feet under any object, so that the legs do not move when performing the exercise. Hold your hands behind your head and lift your torso, straining your abdominal muscles. As a result, the upper body and thighs should have the shape of the Latin letter V.)"
            "\n============================="
            "\n\n'Rock climber':Approaches: 5\nReplays: 60\nRest: 120 seconds\n(We take a position on the floor (similar to the position of a Sprinter on the starting lane - one leg is bent at the knee so that the foot is directly under the waist, and the other is straightened behind. Now abruptly change the position of the legs)"
        )
    elif call.data == "back":
        bot.send_message(
            call.message.chat.id,
            "Exercise 'Superman':\nApproaches: 3\nReplays: 30\nRest: 30 seconds\n(Lie on your stomach, stretch your arms above your head, stretch out and lift your chest and knees off the floor. Hold for 3-5 seconds and return to the starting position)"
        )
    elif call.data == "weight_f":
        bot.send_message(
            call.message.chat.id,
            "The presented weight loss training at home is intended for people who do not have sports equipment. Despite the lack of shells, classes are no less effective and productive. The most important thing is to warm up well and strictly follow the techniques of each exercise."
            "You'll find 9 exercises (8 exercises in total, but the last exercise is performed first on the right side, then on the left) + 1 minute of rest after completion. This means about 10 min for 1 lap.\nPerform the exercises for the specified time sequentially one after another, then repeat the training from the beginning in 3-4 circles. Beginners can complete 2 laps."
            "\nOptions for performing circular training:\n>>>>>>>>>>By time:\n45 seconds of work / 15 seconds of rest\n>>>>>>>>>>By number of repetitions:\nspecified in the article after each exercise"
            "\n1. PUSH-UPS + PULL-UPS:\nTaking the emphasis lying down, press down, almost touching the surface of the floor. Keep your back straight and look straight ahead. When you return to the starting phase, pull your arms up to your chest one at a time, pulling your elbows back. After lifting your hands, repeat the process again. If you find it difficult to perform push-UPS, get down on your knees or push-UPS from the bench.)"
            "\n2. LUNGES FORWARD:\nPut your hands on your waist and your feet a little narrower than your shoulders. Step forward, bending the leg at the knee to a right angle. The foot stands firmly on the foot. The foot behind stands on the toe, and the knee does not touch the floor. The back is tense, fixed straight, does not slouch. Get up and repeat with the other leg.)"
            "\n3. 'GOOD MORNING':\nStand with your hands behind your head. Bend your knees slightly and tilt your body forward to a 90-degree angle. At the same time, do not slouch, straighten your shoulders, keep a natural deflection in the lower back. Stretching from the lower point to the upper, rely only on the work of the back muscles.)"
            "\n5. KNEE-ELBOW TWIST:\nIn the standing position, place your hands on the back of your head. Feet are shoulder-width apart. Alternately stretch the opposite elbows and knees to each other at the level below the chest, turning the body. Take your time, making short pauses at the peak point.)"
            "\n6. STATIC SQUAT:\nDo this with your back straight and your feet shoulder-width apart. Hold in the lower position, observing the right angle in the knee joint. Extend your arms forward for better balance.)"
            "\n7. SPIDER PLANK:\nTake the position of the bar at arm's length, put your feet next to each other. Now alternately stretch your right and left knees to the elbows of your hands, emphasizing the work of the lateral abdominal muscles. The back and lower back do not bend, forming a straight line.)"
            "\n8. HAND TOUCH OF THE FOOT:\nLie down on the gym carpet and spread your arms out to the sides. The legs are also slightly apart. Now pull your right leg up while reaching for her foot with your left hand. Look directly at the ceiling without turning your head. Back in the starting phase, switch sides.)"
        )
    elif call.data == "muscle_f":
        bot.send_message(
            call.message.chat.id,
            "Exercise 'Pistol':\nApproaches: 3\nReplays: 14\nRest: 30 seconds\n(We stand with our legs narrowly apart and lift one of them off the floor. After that, bend the leg on which we stand at the knee and squat as low as possible, trying to keep your back straight. Now push off and return to the starting position, change the leg and repeat)."
            "\n============================="
            "\n\nWalking on your hands against the wall:\nApproaches: 3\nReplays: 10\nRest: 30 seconds\n(We take a position on our hands (standing on our hands) with our feet leaning against the wall. Now move your hands forward and 'go' down the wall until your feet reach the floor.)"
            "\n============================="
            "\n\nJumping to the side:\nApproaches: 3\nReplays: 30\nRest: 30 seconds\n(We stand with our feet shoulder-width apart. Then we go down and abruptly push off from the floor with our right foot in order to jump to the left side and land on the left foot. Immediately after landing, push off with your left foot and repeat the movement, this time to the right Side)"
            "\n============================="
            "\n\nThe long jump from the place:\nApproaches: 3\nReplays: 8\nRest: 30 seconds\n(We go down to the squat position with our feet shoulder-width apart. We pull our arms back and use them to push ourselves forward when jumping, and for additional inertia, we throw our legs in front of us. We jump as far as possible and land on the soles of our feet.)"
        )
Пример #28
0
def pent_rus(message):
    pentmarkup = types.InlineKeyboardMarkup(row_width=3)
    pent1 = types.InlineKeyboardButton('A', callback_data='Apt')
    pent2 = types.InlineKeyboardButton('A#/Bb', callback_data='A#pt')
    pent3 = types.InlineKeyboardButton('B', callback_data='Bpt')
    pent4 = types.InlineKeyboardButton('C', callback_data='Cpt')
    pent5 = types.InlineKeyboardButton('C#/Db', callback_data='C#pt')
    pent6 = types.InlineKeyboardButton('D', callback_data='Dpt')
    pent7 = types.InlineKeyboardButton('D#/Eb', callback_data='D#pt')
    pent8 = types.InlineKeyboardButton('E', callback_data='Ept')
    pent9 = types.InlineKeyboardButton('F', callback_data='Fpt')
    pent10 = types.InlineKeyboardButton('F#/Gb', callback_data='F#pt')
    pent11 = types.InlineKeyboardButton('G', callback_data='Gpt')
    pent12 = types.InlineKeyboardButton('G#/Ab', callback_data='G#pt')

    pentmarkup.add(pent1, pent2, pent3, pent4, pent5, pent6, pent7, pent8,
                   pent9, pent10, pent11, pent12)

    bot.send_message(message.chat.id,
                     'Выберите тонику:',
                     reply_markup=pentmarkup)
Пример #29
0
def callback_inline(call):
    # Если сообщение из чата с ботом
    if call.message:
        if (call.data[0] == "l"):  #Модификатор уровня сложности
            levels[call.message.chat.id] = int(call.data[1:])
            keyboard = types.InlineKeyboardMarkup()
            clb1 = types.InlineKeyboardButton(text=x, callback_data="sx")
            clb2 = types.InlineKeyboardButton(text=o, callback_data="s0")
            keyboard.add(clb1, clb2)
            bot.edit_message_text(text="Choose your side",
                                  chat_id=call.message.chat.id,
                                  message_id=call.message.message_id,
                                  reply_markup=keyboard)
        elif (call.data[0] == "s"):  #Первоначальное создание поля
            sides[call.message.chat.id] = call.data[1:]
            if (sides[call.message.chat.id] == "x"):
                cpts[call.message.chat.id] = "0"
            elif (sides[call.message.chat.id] == "0"):
                cpts[call.message.chat.id] = "x"
                # Now AI move
                if (levels[call.message.chat.id] == 1):
                    skynet.jun(fields[call.message.chat.id],
                               cpts[call.message.chat.id])
                elif (levels[call.message.chat.id] == 2):
                    lucky = skynet.random.choice([1, 2])
                    if (lucky == 1):
                        skynet.jun(fields[call.message.chat.id],
                                   cpts[call.message.chat.id])
                    else:
                        skynet.sen(fields[call.message.chat.id],
                                   cpts[call.message.chat.id],
                                   sides[call.message.chat.id],
                                   counters[call.message.chat.id])
                elif (levels[call.message.chat.id] == 3):
                    skynet.sen(fields[call.message.chat.id],
                               cpts[call.message.chat.id],
                               sides[call.message.chat.id],
                               counters[call.message.chat.id])
                counters[call.message.chat.id] += 1
            # Отрисовка пользователю
            keyboard = draw_field(fields[call.message.chat.id])
            bot.edit_message_text(text="You will play as " +
                                  sides[call.message.chat.id] + ", get ready!",
                                  chat_id=call.message.chat.id,
                                  message_id=call.message.message_id,
                                  reply_markup=keyboard)
        elif (call.data[0] == "i"):
            crds = str.split(call.data[1:], ';')
            if (fields[call.message.chat.id][int(crds[0])][int(crds[1])] !=
                    '-'):
                bot.answer_callback_query(
                    callback_query_id=call.id,
                    show_alert=False,
                    text="Нельзя ставить туда, где уже поставлено!")
                print(call.data)
            else:
                # bot.edit_message_text(chat_id=call.message.chat.id, message_id=call.message.message_id, text=x)
                # Human move
                fields[call.message.chat.id][int(crds[0])][int(
                    crds[1])] = sides[call.message.chat.id]
                counters[call.message.chat.id] += 1
                res = skynet.is_win(fields[call.message.chat.id])
                if (res[0] == True):
                    print(counters[call.message.chat.id])
                    keyboard = types.InlineKeyboardMarkup()
                    clb1 = types.InlineKeyboardButton(text="Hell yeah!",
                                                      callback_data="ny")
                    clb2 = types.InlineKeyboardButton(text="No, I`m scared",
                                                      callback_data="nn")
                    keyboard.add(clb1, clb2)
                    text = ""
                    for i in range(len(fields[call.message.chat.id])):
                        for j in range(len(fields[call.message.chat.id][i])):
                            if (fields[call.message.chat.id][i][j] == '-'):
                                text += e + " "
                            elif (fields[call.message.chat.id][i][j] == 'x'):
                                text += x + " "
                            else:
                                text += o + " "
                        text += "\n"
                    text += "You are crazy ass muthafucka! Do you want a rematch?"
                    bot.edit_message_text(text=text,
                                          chat_id=call.message.chat.id,
                                          message_id=call.message.message_id,
                                          reply_markup=keyboard)
                elif (counters[call.message.chat.id] == 9):
                    print(counters[call.message.chat.id])
                    keyboard = types.InlineKeyboardMarkup()
                    clb1 = types.InlineKeyboardButton(text="Hell yeah!",
                                                      callback_data="ny")
                    clb2 = types.InlineKeyboardButton(text="No, I`m scared",
                                                      callback_data="nn")
                    keyboard.add(clb1, clb2)
                    text = ""
                    for i in range(len(fields[call.message.chat.id])):
                        for j in range(len(fields[call.message.chat.id][i])):
                            if (fields[call.message.chat.id][i][j] == '-'):
                                text += e + " "
                            elif (fields[call.message.chat.id][i][j] == 'x'):
                                text += x + " "
                            else:
                                text += o + " "
                        text += "\n"
                    text += "It`s draw! Do you want a rematch?"
                    bot.edit_message_text(text=text,
                                          chat_id=call.message.chat.id,
                                          message_id=call.message.message_id,
                                          reply_markup=keyboard)
                else:
                    # Now AI move
                    if (levels[call.message.chat.id] == 1):
                        skynet.jun(fields[call.message.chat.id],
                                   cpts[call.message.chat.id])
                    elif (levels[call.message.chat.id] == 2):
                        lucky = skynet.random.choice([1, 2])
                        if (lucky == 1):
                            skynet.jun(fields[call.message.chat.id],
                                       cpts[call.message.chat.id])
                        else:
                            skynet.sen(fields[call.message.chat.id],
                                       cpts[call.message.chat.id],
                                       sides[call.message.chat.id],
                                       counters[call.message.chat.id])
                    elif (levels[call.message.chat.id] == 3):
                        skynet.sen(fields[call.message.chat.id],
                                   cpts[call.message.chat.id],
                                   sides[call.message.chat.id],
                                   counters[call.message.chat.id])
                    counters[call.message.chat.id] += 1
                    res = skynet.is_win(fields[call.message.chat.id])
                    if (res[0] == True):
                        keyboard = types.InlineKeyboardMarkup()
                        clb1 = types.InlineKeyboardButton(text="Hell yeah!",
                                                          callback_data="ny")
                        clb2 = types.InlineKeyboardButton(
                            text="No, I`m scared", callback_data="nn")
                        keyboard.add(clb1, clb2)
                        text = ""
                        for i in range(len(fields[call.message.chat.id])):
                            for j in range(len(
                                    fields[call.message.chat.id][i])):
                                if (fields[call.message.chat.id][i][j] == '-'):
                                    text += e + " "
                                elif (fields[call.message.chat.id][i][j] == 'x'
                                      ):
                                    text += x + " "
                                else:
                                    text += o + " "
                            text += "\n"
                        text += "Oh, what`s happen? You lose! Do you want a rematch?"
                        bot.edit_message_text(
                            text=text,
                            chat_id=call.message.chat.id,
                            message_id=call.message.message_id,
                            reply_markup=keyboard)
                    elif (counters[call.message.chat.id] == 9):
                        keyboard = types.InlineKeyboardMarkup()
                        clb1 = types.InlineKeyboardButton(text="Hell yeah!",
                                                          callback_data="ny")
                        clb2 = types.InlineKeyboardButton(
                            text="No, I`m scared", callback_data="nn")
                        keyboard.add(clb1, clb2)
                        text = ""
                        for i in range(len(fields[call.message.chat.id])):
                            for j in range(len(
                                    fields[call.message.chat.id][i])):
                                if (fields[call.message.chat.id][i][j] == '-'):
                                    text += e + " "
                                elif (fields[call.message.chat.id][i][j] == 'x'
                                      ):
                                    text += x + " "
                                else:
                                    text += o + " "
                            text += "\n"
                        text += "It`s draw! Do you want a rematch?"
                        bot.edit_message_text(
                            text=text,
                            chat_id=call.message.chat.id,
                            message_id=call.message.message_id,
                            reply_markup=keyboard)
                    else:
                        # Отрисовка пользователю
                        keyboard = draw_field(fields[call.message.chat.id])
                        bot.edit_message_reply_markup(
                            chat_id=call.message.chat.id,
                            message_id=call.message.message_id,
                            reply_markup=keyboard)
                        bot.answer_callback_query(callback_query_id=call.id,
                                                  show_alert=False,
                                                  text=call.data)
                        print(call.data)
        elif (call.data[0] == "n"):
            answer = call.data[1:]
            if (answer == "y"):
                keyboard = types.InlineKeyboardMarkup()
                clb1 = types.InlineKeyboardButton(text="Junior",
                                                  callback_data="l1")
                clb2 = types.InlineKeyboardButton(text="Middle",
                                                  callback_data="l2")
                clb3 = types.InlineKeyboardButton(text="Senior",
                                                  callback_data="l3")
                keyboard.add(clb1, clb2, clb3)
                clear(call.message.chat.id)
                bot.edit_message_text(text="Choose difficulty level:",
                                      chat_id=call.message.chat.id,
                                      message_id=call.message.message_id,
                                      reply_markup=keyboard)
            else:
                bot.edit_message_text(text="Chao-cacao",
                                      chat_id=call.message.chat.id,
                                      message_id=call.message.message_id)
Пример #30
0
def call_handler(call):
    if call.data == 'forecast_prev':
        if call.from_user.id == forecasts[call.message.message_id][9]:
            if not forecasts[call.message.message_id][8] <= 0:
                forecasts[call.message.message_id][8] -= 1
                keyboard = types.InlineKeyboardMarkup(row_width=2)
                key_prev = types.InlineKeyboardButton(
                    text='<<', callback_data='forecast_prev')
                key_next = types.InlineKeyboardButton(
                    text='>>', callback_data='forecast_next')
                keyboard.add(key_prev, key_next)
                key_close = types.InlineKeyboardButton(
                    text='Я прочитал', callback_data='forecast_close')
                keyboard.add(key_close)

                bot.edit_message_text(chat_id=call.message.chat.id,
                                      message_id=call.message.message_id,
                                      text=forecasts[call.message.message_id]
                                      [forecasts[call.message.message_id][8]],
                                      parse_mode='HTML',
                                      reply_markup=keyboard)
            else:
                bot.answer_callback_query(callback_query_id=call.id,
                                          text='Это начало списка')
        else:
            bot.answer_callback_query(
                callback_query_id=call.id,
                text=
                'Нельзя управлять меню прогноза погоды другого пользователя')

    elif call.data == 'forecast_next':
        if call.from_user.id == forecasts[call.message.message_id][9]:
            if not forecasts[call.message.message_id][8] >= 7:
                forecasts[call.message.message_id][8] += 1
                keyboard = types.InlineKeyboardMarkup(row_width=2)
                key_prev = types.InlineKeyboardButton(
                    text='<<', callback_data='forecast_prev')
                key_next = types.InlineKeyboardButton(
                    text='>>', callback_data='forecast_next')
                keyboard.add(key_prev, key_next)
                key_close = types.InlineKeyboardButton(
                    text='Я прочитал', callback_data='forecast_close')
                keyboard.add(key_close)

                bot.edit_message_text(chat_id=call.message.chat.id,
                                      message_id=call.message.message_id,
                                      text=forecasts[call.message.message_id]
                                      [forecasts[call.message.message_id][8]],
                                      parse_mode='HTML',
                                      reply_markup=keyboard)
            else:
                bot.answer_callback_query(callback_query_id=call.id,
                                          text='Это конец списка')
        else:
            bot.answer_callback_query(
                callback_query_id=call.id,
                text=
                'Нельзя управлять меню прогноза погоды другого пользователя')

    elif call.data == 'forecast_close':
        if call.from_user.id == forecasts[call.message.message_id][9]:
            forecasts.pop(call.message.message_id)
            bot.delete_message(chat_id=call.message.chat.id,
                               message_id=call.message.message_id)
        else:
            bot.answer_callback_query(
                callback_query_id=call.id,
                text=
                'Нельзя управлять меню прогноза погоды другого пользователя')

    elif call.data == 'weather_close':
        if call.from_user.id == weathers[call.message.message_id]:
            weathers.pop(call.message.message_id)
            bot.delete_message(chat_id=call.message.chat.id,
                               message_id=call.message.message_id)
        else:
            bot.answer_callback_query(
                callback_query_id=call.id,
                text=
                'Нельзя управлять меню прогноза погоды другого пользователя')