Example #1
0
def build_step(bot,
               update,
               step,
               job_queue,
               player_quest,
               text="Вы победили!"):
    if step:
        if step.image:
            bot.send_photo(update.message.chat_id, photo=step.image)

        options_temp = step.options.all()
        options = []
        changes = player_quest.changes.all()
        for option in options_temp:
            is_hidden = option.is_hidden
            if option in changes:
                is_hidden = not option.is_hidden
            if not is_hidden:
                options.append(option)

        if options:
            button_list = [KeyboardButton(option.text) for option in options]
            button_list.append(
                KeyboardButton(quest_utils.menu_text_full("MAIN_MENU")))
            reply_markup = ReplyKeyboardMarkup(
                build_menu(button_list, n_cols=1),
                resize_keyboard=True,
                one_time_keyboard=True,
            )
            send_step_partly(
                bot,
                update,
                job_queue,
                step.description,
                step.delay,
                reply_markup=reply_markup,
            )
        else:
            # Step has no options - Lose
            button_list = [
                KeyboardButton(quest_utils.menu_text_full("ASK_TO_RESTART")),
                KeyboardButton(quest_utils.menu_text_full("MAIN_MENU")),
            ]
            reply_markup = ReplyKeyboardMarkup(build_menu(button_list,
                                                          n_cols=1),
                                               resize_keyboard=True)
            bot.send_message(update.effective_chat.id,
                             step.description,
                             reply_markup=reply_markup)
    else:
        button_list = [
            KeyboardButton(quest_utils.menu_text_full("ASK_TO_RESTART")),
            KeyboardButton(quest_utils.menu_text_full("MAIN_MENU")),
        ]
        reply_markup = ReplyKeyboardMarkup(build_menu(button_list, n_cols=1),
                                           resize_keyboard=True)
        bot.send_message(
            update.effective_chat.id,
            text + "\nНачать заново?",
            reply_markup=reply_markup,
        )
Example #2
0
PORT = int(os.environ.get('PORT', 5000))

# Enable logging
logging.basicConfig(
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    level=logging.INFO,
    filename='khaandaan-bot.log',
    filemode='a')

logger = logging.getLogger(__name__)

LOCATION, PHOTO, DIET, SERVINGS, TIME, CONFIRMATION = range(6)

reply_keyboard = [['Confirm', 'Restart']]
markup = ReplyKeyboardMarkup(reply_keyboard,
                             resize_keyboard=True,
                             one_time_keyboard=True)

TOKEN = 'Your_Bot_Token_Goes_Here'
bot = telegram.Bot(token=TOKEN)

chat_id = "@YOURCHANNELNAME"

GMAPS_TOKEN = 'Your Geocoding API goes here '
gmaps = GoogleMaps(GMAPS_TOKEN)


def facts_to_str(user_data):
    facts = list()

    for key, value in user_data.items():
Example #3
0
    def start(self, update, ctx):  ## команда начала работы бота
        con = sqlite3.connect('for_wo.db')  ## подключение курсора
        cur = con.cursor()
        user_id = update['message']['chat'][
            'id']  ## получаем имя и id пользователя
        user_name = update['message']['chat']['first_name']
        req = """SELECT * from users WHERE user_id='{n}'""".format(n=user_id)
        res = cur.execute(req).fetchall()  ## проверяем, есть ли он в нашей бд
        if res == []:  ## если он впервые пользуется нашим ботом
            req = """INSERT INTO users VALUES ('{n1}', '{n2}', '', '', '', '', '', '', '')""".format(
                n1=user_id, n2=user_name)
            cur.execute(req).fetchall()
            con.commit()  ## заводим главные переменные, которые гарантируют
            ## работу бота без сбоев

            reply_keyboard = [
                [
                    'Почитать о воркауте',  ## предлагаем пользователю наши функции
                    'Глянуть на разряды'
                ],
                [
                    'Посмотреть базу данных упражнений',
                    'Получить советы по тренировкам'
                ],
                ['Прочитать крутой лайфхак', 'Определить свой уровень'],
                ['Связаться с Диной']
            ]

            req = """SELECT some from other WHERE what='{n}'""".format(
                n='hello')  ## достаем из бд приветственный текст
            hello = '\n'.join(cur.execute(req).fetchall()[0][0].split(
                '&'
                ''))  ## приводим его к нормальному виду

            update.message.reply_text(
                hello, reply_markup=ReplyKeyboardMarkup(reply_keyboard))
        else:  ## есди пользователь есть в бд
            reply_keyboard = [
                [
                    'Почитать о воркауте',  ##  та же клавиатура
                    'Глянуть на разряды'
                ],
                [
                    'Посмотреть базу данных упражнений',
                    'Получить советы по тренировкам'
                ],
                ['Прочитать крутой лайфхак', 'Определить свой уровень'],
                ['Связаться с Диной']
            ]

            update.message.reply_text(
                'Хорошо :)', reply_markup=ReplyKeyboardMarkup(reply_keyboard))

            req_list = [
                'read_about_wo', 'read_categories', 'read_db', 'read_s',
                'read_lifehaks', 'read_level', 'read_con'
            ]
            for i in range(len(req_list)):
                req = 'UPDATE users SET {n}="" WHERE user_id="{n2}"'.format(
                    n=req_list[i], n2=user_id)
                cur.execute(req).fetchall()
                con.commit(
                )  ## обнуляем все главные переменные, чтобы не возникло сбоев в работе бота
Example #4
0
from telegram import (InlineKeyboardButton, InlineKeyboardMarkup,
                      ReplyKeyboardMarkup, KeyboardButton, ReplyKeyboardRemove)

REMOVE_KB = ReplyKeyboardRemove()

START_KB = ReplyKeyboardMarkup([[KeyboardButton('/start')]],
                               resize_keyboard=True)

YES_NO_KB = InlineKeyboardMarkup([[
    InlineKeyboardButton('Да', callback_data='type_of_hotel'),
    InlineKeyboardButton('Нет', callback_data='back_to_main')
]])

TYPE_HOTEL_KB = InlineKeyboardMarkup(
    [[
        InlineKeyboardButton('Отели, минигостиницы, ботели',
                             callback_data='th1')
    ],
     [
         InlineKeyboardButton('Гостевые дома, апартаменты, лоджи',
                              callback_data='th2')
     ],
     [
         InlineKeyboardButton('Хостелы', callback_data='th3'),
         InlineKeyboardButton('Не важно', callback_data='th0')
     ], [InlineKeyboardButton('Назад', callback_data='back_to_main')]])

QUALITY_HOTEL_KB = InlineKeyboardMarkup(
    [[
        InlineKeyboardButton('Достаточно хорошо: 6+', callback_data='qh60'),
        InlineKeyboardButton('Хорошо: 7+', callback_data='qh70')
Example #5
0
    CommandHandler,
    ConversationHandler,
    CallbackQueryHandler,
    Filters,
    MessageHandler
)
import config

languages = InlineKeyboardMarkup([
    [InlineKeyboardButton(text='Русский 🇷🇺', callback_data='ru'),
     InlineKeyboardButton(text='O`zbek 🇺🇿', callback_data='uz'),
     InlineKeyboardButton(text='English 🇬🇧', callback_data='en')]
])
# Keyboard to share contact
share_contact_ru = ReplyKeyboardMarkup([
    [KeyboardButton(text='Отправить номер телефона', request_contact=True)],
    [KeyboardButton(text='Назад 🔙')]
], resize_keyboard=True, one_time_keyboard=True)
share_contact_en = ReplyKeyboardMarkup([
    [KeyboardButton(text='Share phone number', request_contact=True)],
    [KeyboardButton(text='Back 🔙')]
], resize_keyboard=True, one_time_keyboard=True)
share_contact_uz = ReplyKeyboardMarkup([
    [KeyboardButton(text='Telefon raqamini jonatish', request_contact=True)],
    [KeyboardButton(text='Ortga qaytish 🔙')]
], resize_keyboard=True, one_time_keyboard=True)
# Keyboard to share location
share_location_ru = ReplyKeyboardMarkup([
    [KeyboardButton(text='Отправить локацию', request_location=True)],
    [KeyboardButton(text='Назад 🔙')]
], resize_keyboard=True, one_time_keyboard=True)
share_location_en = ReplyKeyboardMarkup([
Example #6
0
 def gen_keyboard(self, update):
     return ReplyKeyboardMarkup(self.get_markup(update),
                                resize_keyboard=True)
def get_keyboard():
    my_keyboard = ReplyKeyboardMarkup([['Заполнить анкету']], resize_keyboard=True)
    return my_keyboard
Example #8
0
def get_weather_start(update, context):
    reply_markup = ReplyKeyboardMarkup([[KeyboardButton('send my location', request_location=True)]])
    update.message.reply_text('Send me the coordinates or /cancel', reply_markup=reply_markup)
    return 0
Example #9
0
def act_task(update, context, newly_created=False):
    handler = db_connector.DataBaseConnector()
    chat_id = update.message.chat.id
    user_id = update.message.from_user.id
    user_data = context.user_data
    try:
        text_task_id = _get_task_id(update.message.text)
        if text_task_id and not newly_created:
            task_id = int(text_task_id)
            user_data['task id'] = task_id
        else:
            task_id = user_data['task id']
        task_info = handler.task_info(task_id)
        user_data['chat id'] = task_info['chat_id']
        task_chat = update.message.bot.get_chat(task_info['chat_id'])

        if task_chat.id != chat_id and user_id not in task_info['workers']:
            update.message.reply_text('Вы не можете управлять этой задачей',
                                      disable_notification=True,
                                      reply_markup=ReplyKeyboardRemove())
            return end_conversation(update, context)

        if task_chat.type == 'private':
            is_admin = False
        else:
            is_admin = user_id in [
                admin.user.id
                for admin in update.message.bot.get_chat_administrators(
                    task_info['chat_id'])
            ]
        buttons = [[]]
        cols = 0
        if (user_id in task_info['workers'] or is_admin
                or task_info['chat_id'] == chat_id and not task_info['workers']
                or task_info['creator_id'] == user_id):
            buttons[-1] += ['Закрыть задачу']
            cols += 1

        if user_id in task_info['workers']:
            cols += 1
            buttons[-1] += ['Отказаться']

        elif task_info['chat_id'] == chat_id and not task_info['workers']:
            if not cols % 2:
                buttons.append([])
            cols += 1
            buttons[-1] += ['Взять']

        if task_info['creator_id'] == user_id or is_admin:
            if task_info['deadline']:
                buttons.append([])
                buttons[-1] += ['Изменить срок']
                buttons[-1] += ['Удалить срок']
                cols = 0
            else:
                if not cols % 2:
                    buttons.append([])
                buttons[-1] += ['Установить срок']
                cols += 1

            if not cols % 2:
                buttons.append([])
            if task_info['marked']:
                buttons[-1] += ['Снять отметку']
            else:
                buttons[-1] += ['Отметить']
            cols += 1

        if not cols % 2:
            buttons.append([])
        buttons[-1] += ['Создать напоминание']

        buttons.append([])
        buttons[-1] += ['Покинуть меню']

        markup = ReplyKeyboardMarkup(buttons,
                                     selective=True,
                                     resize_keyboard=True,
                                     one_time_keyboard=True)
        if newly_created:
            msg = 'Вы можете выбрать действие для этой задачи'
        else:
            msg = 'Выберите действие с задачей'

    except (ValueError, ConnectionError, TelegramError, KeyError):
        update.message.reply_text(_ERR_MSG, disable_notification=True)
        log_msg = 'Unable to create task action menu'
        _LOGGER.exception(log_msg)
        return end_conversation(update, context)

    update.message.reply_text(msg,
                              reply_markup=markup,
                              disable_notification=True)
    return CHOOSING_COMMAND
Example #10
0
def start(update: Update, context: CallbackContext) -> None:
    update.message.reply_text('Используйте команду /set <seconds>, чтобы запустить постинг мемов по времени', \
                              reply_markup = ReplyKeyboardMarkup(reply_keyboard, one_time_keyboard=False))
    return BOT_STATE_INITIAL
Example #11
0
def taxi_around_me(bot, update):
    """ Find Taxis Around me """
    # Detect if in group
    chat_type = update.message.chat.type
    senderid = update.message.from_user.id
    senderusername = update.message.from_user.username

    text_bot = [
        'I go see see look look... :eyes:', 'Get ready to run :running:',
        'I find where they hiding now :eyes: :eyes:',
        'Usually if i want to go somewhere i let my fingers do the walking :v:'
    ]

    if chat_type == 'private':

        success_status = False

        # Run Code
        try:
            # If already sent the message
            send_long = update.message.location.longitude
            send_lat = update.message.location.latitude
            success_status = True
        except:
            # If have not sent the message
            location_keyboard = KeyboardButton(text="/taxi_near_me",
                                               request_location=True)
            custom_keyboard = [[location_keyboard]]
            reply_markup = ReplyKeyboardMarkup(custom_keyboard,
                                               one_time_keyboard=True,
                                               selective=True)
            bot.sendMessage(senderid,
                            'Click the button below scan for Available Taxis!',
                            reply_markup=reply_markup)

        if success_status:
            bot.sendMessage(update.message.chat_id,
                            text=emojize(random.choice(text_bot),
                                         use_aliases=True),
                            parse_mode='HTML')
            bot.sendChatAction(update.message.chat_id,
                               action=ChatAction.TYPING)

            taxi = gov.taxi_get(send_long, send_lat)
            text_ = "There are a total of " + str(taxi['count_number']) + \
                " Available Taxis (not uber/grab) in a 200M radius Around you!"
            bot.sendMessage(update.message.chat_id,
                            text=text_,
                            parse_mode='HTML')

            if taxi['count_number'] > 0:
                bot.sendChatAction(update.message.chat_id,
                                   action=ChatAction.TYPING)
                bot.sendPhoto(update.message.chat_id, photo=taxi['url'])
                bot.sendMessage(update.message.chat_id,
                                text='Run my child, run...',
                                parse_mode='HTML')
            else:
                bot.sendMessage(update.message.chat_id,
                                text='No taxi!?! Why u at ulu place?',
                                parse_mode='HTML')
            botan_track(update.message.from_user.id, update.message,
                        update.message.text)

    else:
        # If in group chat... send PM
        location_keyboard = KeyboardButton(text="/taxi_near_me",
                                           request_location=True)
        custom_keyboard = [[location_keyboard]]
        reply_markup = ReplyKeyboardMarkup(custom_keyboard,
                                           one_time_keyboard=True,
                                           selective=True)
        pm_try = False

        try:
            # Try to send PM, will have an error if never added before
            bot.sendMessage(senderid,
                            'Click the button below scan for Available Taxis!',
                            reply_markup=reply_markup)
            pm_try = True
        except:

            # Promo Feature with Inline Keyboard
            promo_keyboard = InlineKeyboardButton(
                text="PM Me!", url="https://telegram.me/shiokbot?start")
            custom_keyboard = [[promo_keyboard]]
            reply_markup = InlineKeyboardMarkup(custom_keyboard)

            message_ = "You have to start a convo with me first! @ShiokBot before I can send you this info!\n\nAfter starting the PM with me try /taxi_near_me again"
            bot.sendMessage(update.message.chat_id,
                            text=message_,
                            parse_mode='HTML',
                            reply_markup=reply_markup)

        if pm_try:
            message_ = senderusername + \
                ", I sent you a love note. Location can only be shared in private"
            bot.sendMessage(update.message.chat_id,
                            text=message_,
                            parse_mode='HTML')
Example #12
0
# -*- coding: utf-8 -*-
import os
from telegram import InlineKeyboardButton, InlineKeyboardMarkup, ReplyKeyboardMarkup
from telegram.ext import (Updater, CommandHandler, CallbackQueryHandler,
                          MessageHandler, Filters, ConversationHandler)
import telegram
from maxsulot import *
from function import *
import json
import ast
import datetime

Token = '1573065998:AAEp502bdMmXOnBboaZ8_PZcTz81cN8VcY0'
bot = telegram.Bot(Token)
Uzbutton = ReplyKeyboardMarkup(
    [["✏️ Buyurtma berish"],
     ["⚙️ Bizning hizmatlar", "📞 Biz bilan bog'lanish"]],
    resize_keyboard=True)

global i, index, Zakzlar, add, S, Jami, User, Users, JamiNarx
Zakazlar = []
add = {
    'Nomi': '',
    'Rangi': '',
    'Kg': '',
    'Narx': '',
    'Dona': '',
    'Karobka': '',
    'Jami': ''
}
i = 0
index = -1
Example #13
0
from telegram import KeyboardButton, ReplyKeyboardMarkup, InlineKeyboardButton, InlineKeyboardMarkup

keyboard = [[
    KeyboardButton('🤠 Пользователь', callback_data='user'),
    KeyboardButton('💸 Спонсор', callback_data='sponsor'),
], [
    KeyboardButton('Главное меню', callback_data='menu'),
]]

keyboard_1 = ReplyKeyboardMarkup(keyboard, resize_keyboard=True)

kb = [[
    InlineKeyboardButton('🎦 Посмотреть', callback_data='1'),
    InlineKeyboardButton('🍽️ Покушать', callback_data='2'),
],
      [
          InlineKeyboardButton('🎡 Развлекательное', callback_data='3'),
          InlineKeyboardButton('🖼️ Познавательное', callback_data='4'),
      ],
      [
          InlineKeyboardButton('🧗 Активный отдых', callback_data='5'),
          InlineKeyboardButton('🛍️ Что купить?', callback_data='6'),
      ], [
          InlineKeyboardButton('🔝 Топ 10', callback_data='top'),
      ]]

keyboard_2 = InlineKeyboardMarkup(kb, resize_keyboard=True)


def get_keyboard(choose):
    kb_1 = [
Example #14
0
def start(update, context):
    bot_keyboard = [['covid', 'top-right'], ['bottom-left', 'bottom-right']]
    reply_markup = ReplyKeyboardMarkup(bot_keyboard)
    context.bot.send_message(chat_id=update.effective_chat.id,
                             text="I'm a bot, please talk to me!",
                             reply_markup=reply_markup)
def get_keyboard_order():
    order = ReplyKeyboardMarkup([['Рестораны']], resize_keyboard=True)
    return order
Example #16
0
from telegram import Update, ReplyKeyboardMarkup
from telegram.ext import CommandHandler, CallbackContext, ConversationHandler, MessageHandler, Filters

keyboard = ReplyKeyboardMarkup([['ADD', 'REMOVE'], ['UPDATE DIGIKALA ACCOUNT'],
                                ['CONTACT US', 'SUPPORT US']])


def say_hello(update: Update, context: CallbackContext):
    context.user_data.clear()

    chat_id = update.message.chat.id
    name = update.message.from_user.first_name

    context.bot.send_message(
        chat_id,
        ('Hello {}!\n'.format(name) +
         'Welcome to Digi-Reserve! you can use commands to navigate bot\n' +
         'enjoy it :)\n'),
        reply_markup=keyboard,
        parse_mode='Markdown')


def home(update, context):
    context.user_data.clear()

    chat_id = update.message.chat.id
    name = update.message.from_user.first_name

    context.bot.send_message(chat_id,
                             'What can i do for you *{}*'.format(name),
                             parse_mode='Markdown')
Example #17
0
def keyboard(bot, update):

    reply_markup = ReplyKeyboardMarkup(custom_keyboard)
    calc_bot_welcome = 'Calculator. Press the buttons one by one and you will get a result. To hide the keyboard enter /hidecalc'
    bot.send_message(update.message.chat_id, calc_bot_welcome, reply_markup = reply_markup)
Example #18
0
from telegram.ext import Updater, MessageHandler, Filters, ConversationHandler
from telegram import ReplyKeyboardRemove
from telegram import ReplyKeyboardMarkup
from telegram.ext import CommandHandler

reply_keyboard = [['/address', '/phone'], ['/site', '/work_time']]
markup = ReplyKeyboardMarkup(reply_keyboard, one_time_keyboard=False)
TOKEN = '1626176954:AAFdiHbSGPA8td6gFYQx_XI-Wb6pEwJAWcs'


def close_keyboard(update, context):
    update.message.reply_text("Ok", reply_markup=ReplyKeyboardRemove())


def start(update, context):
    context.user_data['locality'] = None
    update.message.reply_text(
        "Привет. Пройдите небольшой опрос, пожалуйста!\n"
        "Вы можете прервать опрос, послав команду /stop.\n"
        "В каком городе вы живёте?\n"
        "Если не хотите отвечать, напишите команду /skip.")

    return 1


def first_response(update, context):
    context.user_data['locality'] = update.message.text
    update.message.reply_text("Какая погода в городе {0}?".format(
        context.user_data['locality']))
    return 2
Example #19
0
def processtext(bot, update):
    """Process user message."""
    response = requests.get('http://127.0.0.1:8000/account/users/',
                            params={'id': bot.message.chat_id})
    user = response.json().get('status')

    if user:
        response = requests.get('http://127.0.0.1:8000/questiontag/question/',
                                params={'id': bot.message.chat_id})
        qtag = response.json()

        data_params = {
            'id': bot.message.chat_id,
        }

        if qtag.get('status') and qtag.get('tag') == 'prof_gender_new':
            gender = ['male', 'female', 'others']

            if str(bot.message.text).lower() in gender:

                data_params['type'] = 'gender',
                data_params['gender'] = str(bot.message.text).capitalize()

                response = requests.patch(
                    'http://127.0.0.1:8000/account/users/', params=data_params)
                up_user = response.json().get('status')

                if up_user:
                    bot.message.reply_text(
                        text='Your gender has been updated successfully.')

                response = requests.patch(
                    'http://127.0.0.1:8000/questiontag/question/',
                    params={
                        'id': bot.message.chat_id,
                        'tag': 'prof_loc_new'
                    })
                qt_up = response.json().get('status')

                if qt_up:
                    keyboard = [[
                        KeyboardButton('Abuja'),
                        KeyboardButton('Enugu'),
                        KeyboardButton('Ekiti'),
                        KeyboardButton('Lagos'),
                        KeyboardButton('Ogun'),
                        KeyboardButton('Port Harcourt')
                    ]]
                    reply_markup = ReplyKeyboardMarkup(keyboard,
                                                       one_time_keyboard=True,
                                                       resize_keyboard=True)
                    bot.message.reply_text(
                        text='Send me your location to update your profile.',
                        reply_markup=reply_markup)

            else:
                bot.message.reply_text(
                    text=
                    'Invalid gender. Gender must either be (Male, Female or others).'
                )

        if qtag.get('status') and qtag.get('tag') == 'prof_loc_new':
            location = [
                'lagos', 'ogun', 'ekiti', 'port harcourt', 'abuja', 'enugu'
            ]

            if str(bot.message.text).lower() in location:

                data_params['type'] = 'location',
                data_params['location'] = str(bot.message.text).capitalize()

                response = requests.patch(
                    'http://127.0.0.1:8000/account/users/', params=data_params)
                up_user_lc = response.json().get('status')

                if up_user_lc:
                    response = requests.patch(
                        'http://127.0.0.1:8000/questiontag/question/',
                        params={
                            'id': bot.message.chat_id,
                            'tag': 'none'
                        })
                    qt_up_lc = response.json().get('status')
                    if qt_up_lc:
                        bot.message.reply_text(
                            text='Your location has been updated successfully.'
                        )
                        bot.message.reply_text(
                            text='<b>Profile setup complete</b>.',
                            parse_mode=ParseMode.HTML)
                        help(bot, update)

            else:
                bot.message.reply_text(
                    text=
                    'Invalid location. Location must either be (lagos, ogun, ekiti, port harcourt, abuja or enugu).'
                )

        if qtag.get('status') and qtag.get('tag') == 'prof_gender':
            gender = ['male', 'female', 'others']

            if str(bot.message.text).lower() in gender:

                data_params['type'] = 'gender',
                data_params['gender'] = str(bot.message.text).capitalize()

                response = requests.patch(
                    'http://127.0.0.1:8000/account/users/', params=data_params)
                up_user = response.json().get('status')

                if up_user:
                    bot.message.reply_text(
                        text='Your gender has been updated successfully.')

                response = requests.patch(
                    'http://127.0.0.1:8000/questiontag/question/',
                    params={
                        'id': bot.message.chat_id,
                        'tag': 'none'
                    })
                response.json().get('status')

            else:
                bot.message.reply_text(
                    text=
                    'Invalid gender. Gender must either be (Male, Female or others).'
                )

        if qtag.get('status') and qtag.get('tag') == 'prof_location':
            location = [
                'lagos', 'ogun', 'ekiti', 'port harcourt', 'abuja', 'enugu'
            ]

            if str(bot.message.text).lower() in location:

                data_params['type'] = 'location',
                data_params['location'] = str(bot.message.text).capitalize()

                response = requests.patch(
                    'http://127.0.0.1:8000/account/users/', params=data_params)
                up_user_lc = response.json().get('status')

                if up_user_lc:
                    response = requests.patch(
                        'http://127.0.0.1:8000/questiontag/question/',
                        params={
                            'id': bot.message.chat_id,
                            'tag': 'none'
                        })
                    qt_up_lc = response.json().get('status')
                    if qt_up_lc:
                        bot.message.reply_text(
                            text='Your location has been updated successfully.'
                        )
            else:
                bot.message.reply_text(
                    text=
                    'Invalid location. Location must either be (lagos, ogun, ekiti, port harcourt, abuja or enugu).'
                )

        if qtag.get('status') and str(qtag.get('tag')).startswith('add_cart'):

            if str(bot.message.text).isnumeric():
                cartid = str(qtag['tag']).replace('add_cart_', '')

                response = requests.post('http://127.0.0.1:8000/order/',
                                         data={
                                             'id': int(cartid),
                                             'chatid': bot.message.chat_id,
                                             'qty': int(bot.message.text)
                                         })
                cart = response.json()

                if cart.get('status'):
                    bot.message.reply_text(text="<b>" + str(cart.get('qty')) +
                                           " " + str(cart.get('item')) +
                                           "</b> has been added to your cart",
                                           parse_mode=ParseMode.HTML)
                    response = requests.patch(
                        'http://127.0.0.1:8000/questiontag/question/',
                        params={
                            'id': bot.message.chat_id,
                            'tag': 'none'
                        })
                    resp_cart = response.json().get('status')
                else:
                    bot.message.reply_text(
                        text=
                        "Unable to add item to cart. Please try again later.",
                        parse_mode=ParseMode.HTML)

            else:
                bot.message.reply_text(text="Quantity must be an integer")

        if qtag.get('status') and str(qtag.get('tag')) == 'trackorder':

            if str(bot.message.text).isnumeric():
                response = requests.get('http://127.0.0.1:8000/account/users/',
                                        params=data_params)
                chkuser = response.json().get('status')

                if chkuser:
                    response = requests.patch(
                        'http://127.0.0.1:8000/questiontag/question/',
                        params={
                            'id': bot.message.chat_id,
                            'tag': 'none'
                        })
                    up_qt = response.json().get('status')

                    if up_qt:
                        bot.message.reply_text(
                            text="Searching for order: <b>" +
                            bot.message.text + "</b> please wait...",
                            parse_mode=ParseMode.HTML)

                        orders(bot, update, bot.message.text)
            else:
                bot.message.reply_text(
                    text="Order id can only be an integer number")
Example #20
0
options = {
    PHONE_NR: "Phone number",
    ACCOUNT_NR: "Telegram ID",
    BANK_NAME: "Name of bank account owner",
    REMARK: "DNA",
    ATTACHMENT: "Attachment"
}

# Enable reverse lookup
for k, v in list(options.items()):
    options[v] = k

_grid = [[options[ACCOUNT_NR]], [options[BANK_NAME]], [options[PHONE_NR]],
         [options[REMARK]], [options[ATTACHMENT]], ['/cancel']]

CAT_KEYBOARD = ReplyKeyboardMarkup(_grid, selective=True)
DB_NAME = 'bot.sqlite'

state = dict()

logging.basicConfig(
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    level=logging.DEBUG)
logger = logging.getLogger(__name__)

u = Updater(TOKEN)
dp = u.dispatcher

db.bind('sqlite', DB_NAME, create_db=True)
db.generate_mapping(create_tables=True)
Example #21
0
def sortbutton(bot, update):

    query = bot.callback_query
    data = query.data

    if data == 'register_profile':

        firstname = bot.callback_query.message.chat.first_name
        lastname = bot.callback_query.message.chat.last_name

        params = {
            'id': query.message.chat_id,
            'firstname': firstname,
            'lastname': lastname if lastname else '',
        }

        response = requests.post('http://127.0.0.1:8000/account/users/',
                                 data=params)
        user = response.json()

        if user.get('status'):
            query.message.reply_text(
                text=
                """<b>Your profile has been registered.</b> Complete the following process to complete your profile"""
                + u'\u270A',
                parse_mode=ParseMode.HTML)

            up_param = {
                'id': query.message.chat_id,
                'tag': 'prof_gender_new',
            }

            response = requests.post(
                'http://127.0.0.1:8000/questiontag/question/', data=up_param)
            userprocess = response.json()

            if userprocess.get('status'):

                keyboard = [[
                    KeyboardButton('Male'),
                    KeyboardButton('Female'),
                    KeyboardButton('Others')
                ]]
                reply_markup = ReplyKeyboardMarkup(keyboard,
                                                   one_time_keyboard=True,
                                                   resize_keyboard=True)
                query.message.reply_text(
                    text='Send me your gender to update your profile.',
                    reply_markup=reply_markup)
            else:
                query.message.reply_text(text='Error updating your profile.')
        else:
            query.message.reply_text(text=user.get('message'),
                                     parse_mode=ParseMode.HTML)

    elif data == 'prof_gender':
        up_param = {
            'id': query.message.chat_id,
            'tag': 'prof_gender',
        }

        response = requests.post('http://127.0.0.1:8000/questiontag/question/',
                                 data=up_param)
        userprocess = response.json()
        if userprocess.get('status'):
            keyboard = [[
                KeyboardButton('Male'),
                KeyboardButton('Female'),
                KeyboardButton('Others')
            ]]
            reply_markup = ReplyKeyboardMarkup(keyboard,
                                               one_time_keyboard=True,
                                               resize_keyboard=True)
            query.message.reply_text(
                text='OK. Send me your new gender to update your profile.',
                reply_markup=reply_markup)

    elif data == 'prof_location':
        up_param = {
            'id': query.message.chat_id,
            'tag': 'prof_location',
        }

        response = requests.post('http://127.0.0.1:8000/questiontag/question/',
                                 data=up_param)
        userprocess = response.json()

        if userprocess.get('status'):
            keyboard = [[
                KeyboardButton('Abuja'),
                KeyboardButton('Enugu'),
                KeyboardButton('Ekiti'),
                KeyboardButton('Lagos'),
                KeyboardButton('Ogun'),
                KeyboardButton('Port Harcourt')
            ]]
            reply_markup = ReplyKeyboardMarkup(keyboard,
                                               one_time_keyboard=True,
                                               resize_keyboard=True)
            query.message.reply_text(
                text='OK. Send me your new location to update your profile.',
                reply_markup=reply_markup)

    elif data.startswith('add_cart'):

        itemid = str(data).replace('add_cart_', '')

        response = requests.get('http://127.0.0.1:8000/order/getitem/',
                                params={'id': int(itemid)})
        item = response.json()

        response = requests.patch(
            'http://127.0.0.1:8000/questiontag/question/',
            params={
                'id': query.message.chat_id,
                'tag': 'add_cart_' + itemid
            })
        resp_cart = response.json().get('status')

        if item['status'] and resp_cart:
            query.message.reply_text(
                text="""OK. How many <b>""" + str(item['name']) +
                """</b> do you want to order?\n <b>Unit Price: </b>""" +
                f"{float(item['price']):,.2f}",
                parse_mode=ParseMode.HTML)
        else:
            query.message.reply_text(
                text="""Unable to process your request at the moment.""",
                parse_mode=ParseMode.HTML)

    elif data.startswith('restaurant_'):
        vendor_q = data.split('_')

        if len(vendor_q) == 2:
            response = requests.get('http://127.0.0.1:8000/products/menu',
                                    params={'id': int(vendor_q[1])})
            menu = response.json()

            if menu.get('status'):
                keyboard = []
                temp_key = []

                for men in menu['menu']:
                    if len(temp_key) == 2:
                        keyboard.append(temp_key)
                        temp_key = []
                    print(men[0], vendor_q[1], men[1])
                    temp_key.append(
                        InlineKeyboardButton(u'' + str(men[0]).capitalize(),
                                             callback_data='restaurant_' +
                                             str(vendor_q[1]) + '_' +
                                             str(men[1])))

                if len(temp_key) != 0:
                    keyboard.append(temp_key)
                    temp_key = []

                reply_markup = InlineKeyboardMarkup(keyboard)
                update.bot.edit_message_text(
                    chat_id=query.message.chat_id,
                    message_id=query.message.message_id,
                    text="<b>" + str(menu['name']) +
                    " Menu</b> \n\n Please select and item from the categroies to view products available for purchase",
                    parse_mode=ParseMode.HTML,
                    reply_markup=reply_markup)
            else:
                query.message.reply_text(text=str(menu['message']),
                                         parse_mode=ParseMode.HTML)

        if len(vendor_q) == 3:

            response = requests.get('http://127.0.0.1:8000/products/menuitem',
                                    params={'id': int(vendor_q[2])})
            item = response.json()

            if item.get('status'):

                for i in item['item']:
                    keyboard = []

                    keyboard.append([
                        InlineKeyboardButton(u'Add to cart',
                                             callback_data='add_cart_' +
                                             str(i[1]))
                    ])

                    query.message.reply_photo(photo=str(i[4]))
                    reply_markup = InlineKeyboardMarkup(keyboard)
                    query.message.reply_text(text="<b>Name: </b>" + str(i[0]) +
                                             " \n<b>Description: </b>" +
                                             str(i[2]) + " \n<b>Price: </b>" +
                                             str(i[3]),
                                             parse_mode=ParseMode.HTML,
                                             reply_markup=reply_markup)

            else:
                query.message.reply_text(text=str(item['message']),
                                         parse_mode=ParseMode.HTML)

    elif data.startswith('gadgets_'):
        vendor_q = data.split('_')

        if len(vendor_q) == 2:
            response = requests.get('http://127.0.0.1:8000/products/menu',
                                    params={'id': int(vendor_q[1])})
            menu = response.json()

            if menu.get('status'):
                keyboard = []
                temp_key = []

                for men in menu['menu']:
                    if len(temp_key) == 2:
                        keyboard.append(temp_key)
                        temp_key = []
                    print(men[0], vendor_q[1], men[1])
                    temp_key.append(
                        InlineKeyboardButton(u'' + str(men[0]).capitalize(),
                                             callback_data='gadgets_' +
                                             str(vendor_q[1]) + '_' +
                                             str(men[1])))

                if len(temp_key) != 0:
                    keyboard.append(temp_key)
                    temp_key = []

                reply_markup = InlineKeyboardMarkup(keyboard)
                update.bot.edit_message_text(
                    chat_id=query.message.chat_id,
                    message_id=query.message.message_id,
                    text="<b>" + str(menu['name']) +
                    " Menu</b> \n\n Please select and item from the categroies to view products available for purchase",
                    parse_mode=ParseMode.HTML,
                    reply_markup=reply_markup)
            else:
                query.message.reply_text(text=str(menu['message']),
                                         parse_mode=ParseMode.HTML)

        if len(vendor_q) == 3:

            response = requests.get('http://127.0.0.1:8000/products/menuitem',
                                    params={'id': int(vendor_q[2])})
            item = response.json()

            if item.get('status'):

                for i in item['item']:
                    keyboard = []

                    keyboard.append([
                        InlineKeyboardButton(u'Add to cart',
                                             callback_data='add_cart_' +
                                             str(i[1]))
                    ])

                    query.message.reply_photo(photo=str(i[4]))
                    reply_markup = InlineKeyboardMarkup(keyboard)
                    query.message.reply_text(text="<b>Name: </b>" + str(i[0]) +
                                             " \n<b>Description: </b>" +
                                             str(i[2]) + " \n<b>Price: </b>" +
                                             str(i[3]),
                                             parse_mode=ParseMode.HTML,
                                             reply_markup=reply_markup)

            else:
                query.message.reply_text(text=str(item['message']),
                                         parse_mode=ParseMode.HTML)

    elif data.startswith('fashion_'):
        vendor_q = data.split('_')

        if len(vendor_q) == 2:
            response = requests.get('http://127.0.0.1:8000/products/menu',
                                    params={'id': int(vendor_q[1])})
            menu = response.json()

            if menu.get('status'):
                keyboard = []
                temp_key = []

                for men in menu['menu']:
                    if len(temp_key) == 2:
                        keyboard.append(temp_key)
                        temp_key = []
                    print(men[0], vendor_q[1], men[1])
                    temp_key.append(
                        InlineKeyboardButton(u'' + str(men[0]).capitalize(),
                                             callback_data='fashion_' +
                                             str(vendor_q[1]) + '_' +
                                             str(men[1])))

                if len(temp_key) != 0:
                    keyboard.append(temp_key)
                    temp_key = []

                reply_markup = InlineKeyboardMarkup(keyboard)
                update.bot.edit_message_text(
                    chat_id=query.message.chat_id,
                    message_id=query.message.message_id,
                    text="<b>" + str(menu['name']) +
                    " Menu</b> \n\n Please select and item from the categroies to view products available for purchase",
                    parse_mode=ParseMode.HTML,
                    reply_markup=reply_markup)
            else:
                query.message.reply_text(text=str(menu['message']),
                                         parse_mode=ParseMode.HTML)

        if len(vendor_q) == 3:

            response = requests.get('http://127.0.0.1:8000/products/menuitem',
                                    params={'id': int(vendor_q[2])})
            item = response.json()

            if item.get('status'):

                for i in item['item']:
                    keyboard = []

                    keyboard.append([
                        InlineKeyboardButton(u'Add to cart',
                                             callback_data='add_cart_' +
                                             str(i[1]))
                    ])

                    query.message.reply_photo(photo=str(i[4]))
                    reply_markup = InlineKeyboardMarkup(keyboard)
                    query.message.reply_text(text="<b>Name: </b>" + str(i[0]) +
                                             " \n<b>Description: </b>" +
                                             str(i[2]) + " \n<b>Price: </b>" +
                                             str(i[3]),
                                             parse_mode=ParseMode.HTML,
                                             reply_markup=reply_markup)

            else:
                query.message.reply_text(text=str(item['message']),
                                         parse_mode=ParseMode.HTML)

    elif data == 'remove_all':
        response = requests.patch(
            'http://127.0.0.1:8000/questiontag/question/',
            params={
                'id': query.message.chat_id,
                'tag': 'remove_cart'
            })
        qt_cart = response.json().get('status')

        if qt_cart:
            removeitem(query, update, 'all')

    elif data == 'checkout':
        checkoutitem(query, update)
Example #22
0
    def great_messages(self, update,
                       context):  ## обработка остальных сообщений

        incorrect = False  ## эта переменная нужна для ответа пользователю в случае неправильного ввода
        ## какого-лиюо текста

        con = sqlite3.connect('for_wo.db')  ##  подключаем бд
        cur = con.cursor()
        user_id = update['message']['chat']['id']  ## получаем id пользователя
        #user_name = update['message']['chat']['first_name']

        req = "SELECT * FROM users WHERE user_id='{n}'".format(n=user_id)
        big_res = cur.execute(req).fetchall()[
            0]  ## получаем значение переменных из бд

        some_text = update.message.text
        ## текст, введенный пользователем

        if some_text in self.great_messages_list and big_res[2:] == (
                '', '', '', '', '', '', ''):
            if some_text == 'Почитать о воркауте':  ##   ну, здесь и так понятно
                req = """UPDATE users SET read_about_wo = 'True' WHERE user_id = '{n}'""".format(
                    n=user_id)
                cur.execute(req).fetchall()
                con.commit()

                req = """SELECT some from other WHERE what=='{n}'""".format(
                    n='about_WO')
                about_WO = cur.execute(req).fetchall()[0][0]
                update.message.reply_text(
                    about_WO)  ## отправка сообщения на запрос пользователя

                req = """UPDATE users SET read_about_wo = '' WHERE user_id = '{n}'""".format(
                    n=user_id)
                cur.execute(req).fetchall()
                con.commit()

                req_list = [
                    'read_categories', 'read_db', 'read_s', 'read_lifehaks',
                    'read_level', 'read_con'
                ]
                for i in range(len(req_list)):
                    req = 'UPDATE users SET {n}="" WHERE user_id="{n2}"'.format(
                        n=req_list[i], n2=user_id)
                    cur.execute(req).fetchall()
                    con.commit()  ## обнуляем переменные

            elif some_text == 'Глянуть на разряды':  ## аналогичная работа
                wich_category = 'Какой разряд вас интересует?'
                reply_keyboard = [['I', 'II', 'III', 'IV'], ['V', 'VI', 'VII'],
                                  ['ОБРАТНО']]

                update.message.reply_text(
                    wich_category,
                    reply_markup=ReplyKeyboardMarkup(reply_keyboard))

                req = """UPDATE users SET read_categories = 'True' WHERE user_id = '{n}'""".format(
                    n=user_id)
                cur.execute(req).fetchall()
                con.commit()

                req_list = [
                    'read_about_wo', 'read_db', 'read_s', 'read_lifehaks',
                    'read_level', 'read_con'
                ]
                for i in range(len(req_list)):
                    req = 'UPDATE users SET {n}="" WHERE user_id="{n2}"'.format(
                        n=req_list[i], n2=user_id)
                    cur.execute(req).fetchall()
                    con.commit()

            elif some_text == 'Прочитать крутой лайфхак':

                req = """UPDATE users SET read_lifehaks = 'True' WHERE user_id = '{n}'""".format(
                    n=user_id)
                cur.execute(req).fetchall()
                con.commit()

                req = """SELECT * from lifehaks"""
                lifehaks = cur.execute(req).fetchall()
                my_live_hak = choice(lifehaks)
                print(my_live_hak)
                maybe_image = my_live_hak[2][:]
                print('d', maybe_image)
                my_live_hak = my_live_hak[0] + '\n' + my_live_hak[1]
                update.message.reply_text(my_live_hak)
                update.message.reply_photo(maybe_image)

                req = """UPDATE users SET read_lifehaks = '' WHERE user_id = '{n}'""".format(
                    n=user_id)
                cur.execute(req).fetchall()
                con.commit()

                req_list = [
                    'read_about_wo', 'read_categories', 'read_db', 'read_s',
                    'read_level', 'read_con'
                ]
                for i in range(len(req_list)):
                    req = 'UPDATE users SET {n}="" WHERE user_id="{n2}"'.format(
                        n=req_list[i], n2=user_id)
                    print(req)
                    cur.execute(req).fetchall()
                    con.commit()

            elif some_text == 'Посмотреть базу данных упражнений':

                req = """UPDATE users SET read_db = 'True' WHERE user_id = '{n}'""".format(
                    n=user_id)
                cur.execute(req).fetchall()
                con.commit()

                reply_keyboard = [['ОТЖИМАНИЯ ОТ ПОЛА', 'ПОДТЯГИВАНИЯ'],
                                  ['ВИСЫ, БАЛАНСЫ И СТАТИКА', 'ПРОЧЕЕ'],
                                  ['НАЗАД']]

                update.message.reply_text(
                    'Выбери тот раздел, к которому относится упражнение, о котором ты хочешь узнать подробнее!',
                    reply_markup=ReplyKeyboardMarkup(reply_keyboard))

                req_list = [
                    'read_about_wo', 'read_categories', 'read_s',
                    'read_lifehaks', 'read_level', 'read_con'
                ]
                for i in range(len(req_list)):
                    req = 'UPDATE users SET {n}="" WHERE user_id="{n2}"'.format(
                        n=req_list[i], n2=user_id)
                    cur.execute(req).fetchall()
                    con.commit()

            elif some_text == 'Определить свой уровень':

                req = 'UPDATE users SET read_level="True" WHERE user_id="{n}"'.format(
                    n=user_id)
                cur.execute(req).fetchall()
                con.commit()

                reply_keyboard = [
                    [
                        'Я ПЕРЕДУМАЛ',
                    ],
                ]

                update.message.reply_text(
                    'Введите через пробел, сколько раз вы можете'
                    ' подтянуться, отжаться и продержать уголок под турником(в секундах)',
                    reply_markup=ReplyKeyboardMarkup(reply_keyboard))

                req_list = [
                    'read_about_wo', 'read_categories', 'read_db', 'read_s',
                    'read_lifehaks', 'read_con'
                ]
                for i in range(len(req_list)):
                    req = 'UPDATE users SET {n}="" WHERE user_id="{n2}"'.format(
                        n=req_list[i], n2=user_id)
                    print(req)
                    cur.execute(req).fetchall()
                    con.commit()

            elif some_text == 'Получить советы по тренировкам':
                req = 'UPDATE users SET read_s="True" WHERE user_id="{n}"'.format(
                    n=user_id)
                cur.execute(req).fetchall()
                con.commit()

                req = 'SELECT some FROM other WHERE what="{n}"'.format(
                    n='my_s')
                my_s = cur.execute(req).fetchall()[0][0]

                update.message.reply_text(my_s)

                update.message.reply_sticker(
                    'CAACAgIAAxkBAAJfTl6x3vRTquhJCYJnrTVxE31T8871AAINAAPANk8TpPnh9NR4jVMZBA'
                )

                req_list = [
                    'read_about_wo', 'read_level', 'read_categories',
                    'read_db', 'read_s', 'read_lifehaks', 'read_con'
                ]
                for i in range(len(req_list)):
                    req = 'UPDATE users SET {n}="" WHERE user_id="{n2}"'.format(
                        n=req_list[i], n2=user_id)
                    print(req)
                    cur.execute(req).fetchall()
                    con.commit()

            elif some_text == 'Связаться с Диной':
                if self.my_id == str(user_id):
                    print('dfdd')
                    update.message.reply_text('<Режим "хозяин" активирован>')

                    req = "SELECT * from comments WHERE is_read=''"
                    comments = cur.execute(req).fetchall()
                    print(comments)
                    if comments == []:
                        update.message.reply_text(
                            'Пока новых сообщений для тебя нет ')
                    else:
                        for i in range(len(comments)):
                            text = 'Пользователь с id {n} оставил сообщение: <{n2}>'.format(
                                n=comments[i][0], n2=comments[i][1])
                            comments[i] = text
                        req = "UPDATE comments SET is_read='True'"
                        cur.execute(req).fetchall()
                        con.commit()
                        text = '\n'.join(comments)
                        update.message.reply_text(text)

                    req_list = [
                        'read_about_wo', 'read_level', 'read_categories',
                        'read_db', 'read_s', 'read_lifehaks', 'read_con'
                    ]
                    for i in range(len(req_list)):
                        req = 'UPDATE users SET {n}="" WHERE user_id="{n2}"'.format(
                            n=req_list[i], n2=user_id)
                        cur.execute(req).fetchall()
                        con.commit()

                else:
                    req = 'UPDATE users SET read_con="True" WHERE user_id="{n}"'.format(
                        n=user_id)
                    cur.execute(req).fetchall()
                    con.commit()

                    reply_keyboard = [
                        [
                            'В СЛЕДУЮЩИЙ РАЗ',
                        ],
                    ]

                    dina = 'Если есть какие-то вопросы - пиши Дине в ВК, https://vk.com/dina_galeyeva. Лайкай фотки)'

                    update.message.reply_text(
                        dina, reply_markup=ReplyKeyboardMarkup(reply_keyboard))
                    update.message.reply_sticker(
                        'CAACAgIAAxkBAAJfUF6x4F7CWcllCSIUU6zoiP2prC27AAIFAAPANk8T-WpfmoJrTXUZBA'
                    )

                    comment = 'Но лучше напиши свой вопрос мне сейчас, а я перешлю Дине. Не забудь оставить свои контакты!'
                    update.message.reply_text(comment)

            else:
                incorrect = True

        elif big_res[8] == 'True':  ## связь со мной
            if str(
                    user_id
            ) != self.my_id:  ## если пользователь хочет отправить мне сообщение

                if some_text == 'В СЛЕДУЮЩИЙ РАЗ':  ## сли передумал
                    text = 'Если что - обращайся!'

                    reply_keyboard = [
                        [
                            'Почитать о воркауте',  ##  та же клавиатура
                            'Глянуть на разряды'
                        ],
                        [
                            'Посмотреть базу данных упражнений',
                            'Получить советы по тренировкам'
                        ],
                        [
                            'Прочитать крутой лайфхак',
                            'Определить свой уровень'
                        ],
                        ['Связаться с Диной']
                    ]

                    update.message.reply_text(
                        text, reply_markup=ReplyKeyboardMarkup(reply_keyboard))

                else:  ## если все-таки решил отправить сообщение

                    req = 'INSERT INTO comments VALUES ("{n}", "{n2}", "")'.format(
                        n=user_id, n2=some_text)
                    cur.execute(req).fetchall()
                    con.commit()

                    update.message.reply_text(
                        'Отлично! Я отправил сообщение Дине. Если захочешь'
                        ' написать еще какое-то сообщение по улучшению моей работы,'
                        ' то еще раз нажми на "Связаться с Диной"')

                req_list = [
                    'read_about_wo', 'read_level', 'read_categories',
                    'read_db', 'read_s', 'read_lifehaks', 'read_con'
                ]
                for i in range(len(req_list)):
                    req = 'UPDATE users SET {n}="" WHERE user_id="{n2}"'.format(
                        n=req_list[i], n2=user_id)
                    cur.execute(req).fetchall()
                    con.commit()

        elif some_text in self.exc_list and big_res[
                4] != '':  ## помощь в показе категорий упражнений в воркауте

            if some_text != 'НАЗАД':

                req = """UPDATE users SET  read_db= '{n1}' WHERE user_id = '{n2}'""".format(
                    n1=some_text, n2=user_id)
                cur.execute(req).fetchall()
                con.commit()

                req = """SELECT title, link FROM wo WHERE category = '{n}'""".format(
                    n=some_text)
                con = sqlite3.connect('for_wo.db')
                cur = con.cursor()
                res = cur.execute(req).fetchall()
                for i in range(len(res)):
                    res[i] = str(i + 1) + '. ' + res[i][0]
                self.category = some_text[:]
                res.append(
                    'Выше ты увидел список известных мне упражнений. А хочешь увидеть'
                    ' исполнение? Напиши мне его номер без точки')

                update.message.reply_text('\n'.join(res))
                del res[-1]
            elif some_text == 'НАЗАД':

                req = """UPDATE users SET read_db = '' WHERE user_id = '{n}'""".format(
                    n=user_id)
                cur.execute(req).fetchall()
                con.commit()

                reply_keyboard = [
                    ['Почитать о воркауте', 'Глянуть на разряды'],
                    [
                        'Посмотреть базу данных упражнений',
                        'Получить советы по тренировкам'
                    ], ['Прочитать крутой лайфхак', 'Определить свой уровень'],
                    ['Связаться с Диной']
                ]

                update.message.reply_text('Если что - обращайся!',
                                          reply_markup=ReplyKeyboardMarkup(
                                              reply_keyboard,
                                              one_time_keyboard=True))
            else:
                incorrect = True

        elif big_res[4] != '' and big_res[
                4] != 'True':  ## описание эллемента из бд
            try:
                number = int(some_text) - 1
                if number < 0:
                    ## если номер упражнения некорректный, то мы гордо уйдем в except
                    proverka = 1 / 0
                req = """SELECT link FROM wo WHERE category = '{n}'""".format(
                    n=big_res[4])
                res = cur.execute(req).fetchall()[number][0] + '.mp4'
                any_text = 'Тут ⬇️ видео - обучалка или просто запись элемента'
                update.message.reply_text(any_text)
                update.message.reply_text(res)
            except:
                incorrect = True

        elif some_text in self.categories and big_res[
                3] == 'True':  ##  читаем о разрядах в воркауте
            if some_text != 'ОБРАТНО':
                req = 'SELECT about FROM categories WHERE category="{n}"'.format(
                    n=some_text)
                res = '\n'.join(cur.execute(req).fetchall()[0][0].split('&'))
                update.message.reply_text(
                    res)  ## сообщение о том, что нужно для сдачи разряда
            elif some_text == 'ОБРАТНО':
                req = """UPDATE users SET read_categories = '' WHERE user_id = '{n}'""".format(
                    n=user_id)
                cur.execute(req).fetchall()
                con.commit()

                reply_keyboard = [
                    ['Почитать о воркауте', 'Глянуть на разряды'],
                    [
                        'Посмотреть базу данных упражнений',
                        'Получить советы по тренировкам'
                    ], ['Прочитать крутой лайфхак', 'Определить свой уровень'],
                    ['Связаться с Диной']
                ]

                update.message.reply_text('Если что - обращайся!',
                                          reply_markup=ReplyKeyboardMarkup(
                                              reply_keyboard,
                                              one_time_keyboard=True))
            else:
                incorrect = True

        elif big_res[
                7] == 'True':  ## если вы захотели опредедить уровень подготовки в воркауте:
            if some_text == 'Я ПЕРЕДУМАЛ':
                any_text = 'Если что - обращайся!'
                req = 'UPDATE users SET read_level="" WHERE user_id="{n}"'.format(
                    n=user_id)
                cur.execute(req).fetchall()
                con.commit()

                reply_keyboard = [
                    ['Почитать о воркауте', 'Глянуть на разряды'],
                    [
                        'Посмотреть базу данных упражнений',
                        'Получить советы по тренировкам'
                    ], ['Прочитать крутой лайфхак', 'Определить свой уровень'],
                    ['Связаться с Диной']
                ]

                update.message.reply_text(
                    any_text, reply_markup=ReplyKeyboardMarkup(reply_keyboard))
            else:
                try:
                    a, b, c = list(
                        map(lambda x: abs(int(x)), some_text.split(' ')))
                    print(a, b, c)
                    level, res = self.your_level(a, b, c)
                    your_level = 'Вы - {n}, уровень вашего мастерства в WorkOut - {n2}%'.format(
                        n=level, n2=res)

                    reply_keyboard = [[
                        'Почитать о воркауте', 'Глянуть на разряды'
                    ],
                                      [
                                          'Посмотреть базу данных упражнений',
                                          'Получить советы по тренировкам'
                                      ],
                                      [
                                          'Прочитать крутой лайфхак',
                                          'Определить свой уровень'
                                      ], ['Связаться с Диной']]

                    update.message.reply_text(
                        your_level,
                        reply_markup=ReplyKeyboardMarkup(reply_keyboard))

                    req_list = [
                        'read_about_wo', 'read_categories', 'read_db',
                        'read_s', 'read_lifehaks', 'read_level', 'read_con'
                    ]

                    for i in range(len(req_list)):  ## обнуляем переменные
                        req = 'UPDATE users SET {n}="" WHERE user_id="{n2}"'.format(
                            n=req_list[i], n2=user_id)
                        cur.execute(req).fetchall()
                        con.commit()

                except:  ## ответ на некорректное значение
                    update.message.reply_text(
                        'Введи-ка нормальные значения :)')
                    incorrect = True

        else:  ## иначе - ответ на некорректное значение
            incorrect = True

        if incorrect:
            ## на случай, когда было введено некорректное значение
            ## три варианта ответа бота:
            incorrect_list = ['malina', 'sticker', 'wolf']
            incorrect = choice(incorrect_list)
            if incorrect == 'malina':  ## картинка с малиной,
                update.message.reply_text(
                    'Что-то неправильно... Посмотри лучше на малину!')
                update.message.reply_photo(
                    'https://i.ibb.co/C6hWm5B/222717-Sepik.jpg')
            elif incorrect == 'sticker':  ## стикер с вишней
                update.message.reply_text('Э-э, так не пойдет!')
                update.message.reply_sticker(
                    'CAACAgIAAxkBAAJfRF6x0_-vbNQKavUiHRm4jzarD6QaAAIgAAPANk8T9A8ruj5f9M8ZBA'
                )
            elif incorrect == 'wolf':  ## фото волка
                update.message.reply_text('Одумайся.')
                update.message.reply_photo(
                    'https://i.ibb.co/jbqS9rX/07ecd61ec447b9e88ab667cfb545693b.jpg'
                )

            incorrect = False  ## на всякий случай обнуляем переменную, отвечающую за эту функцию
Example #23
0
from telegram import KeyboardButton, ReplyKeyboardMarkup

from ethdroid.languages import *

################   Main Menu Keyboard   ################
keyboard_ru = [[KeyboardButton(RUSSIAN['MENU_CHECK_ALL_BALANCE']), KeyboardButton(RUSSIAN['MENU_ADD_ETH_WALLET'])],
              [KeyboardButton(RUSSIAN['MENU_SHARE_BOT']), KeyboardButton(RUSSIAN['MENU_DEL_ETH_WALLET'])]]

keyboard_es = [[KeyboardButton(SPANISH['MENU_CHECK_ALL_BALANCE']), KeyboardButton(SPANISH['MENU_ADD_ETH_WALLET'])],
              [KeyboardButton(SPANISH['MENU_SHARE_BOT']), KeyboardButton(SPANISH['MENU_DEL_ETH_WALLET'])]]

keyboard_en = [[KeyboardButton(ENGLISH['MENU_CHECK_ALL_BALANCE']), KeyboardButton(ENGLISH['MENU_ADD_ETH_WALLET'])],
              [KeyboardButton(ENGLISH['MENU_SHARE_BOT']), KeyboardButton(ENGLISH['MENU_DEL_ETH_WALLET'])]]

# create userkeyboard, resize = true, autohide=false
reply_markup_ru = ReplyKeyboardMarkup(keyboard_ru, True, False)
reply_markup_es = ReplyKeyboardMarkup(keyboard_es, True, False)
reply_markup_en = ReplyKeyboardMarkup(keyboard_en, True, False)

################   Back Menu Keyboard   ################
keyboard_back_ru = [[KeyboardButton(RUSSIAN['MENU_GO_BACK'])]]

keyboard_back_es = [[KeyboardButton(SPANISH['MENU_GO_BACK'])]]

keyboard_back_en = [[KeyboardButton(ENGLISH['MENU_GO_BACK'])]]

# create userkeyboard, resize = true, autohide=false
reply_markup_back_ru = ReplyKeyboardMarkup(keyboard_back_ru, True, False)
reply_markup_back_es = ReplyKeyboardMarkup(keyboard_back_es, True, False)
reply_markup_back_en = ReplyKeyboardMarkup(keyboard_back_en, True, False)
    def _get_msg_kwargs(self, data):
        """Get parameters in message data kwargs."""
        def _make_row_inline_keyboard(row_keyboard):
            """Make a list of InlineKeyboardButtons.

            It can accept:
              - a list of tuples like:
                `[(text_b1, data_callback_b1),
                (text_b2, data_callback_b2), ...]
              - a string like: `/cmd1, /cmd2, /cmd3`
              - or a string like: `text_b1:/cmd1, text_b2:/cmd2`
            """

            buttons = []
            if isinstance(row_keyboard, str):
                for key in row_keyboard.split(","):
                    if ":/" in key:
                        # commands like: 'Label:/cmd' become ('Label', '/cmd')
                        label = key.split(":/")[0]
                        command = key[len(label) + 1:]
                        buttons.append(
                            InlineKeyboardButton(label, callback_data=command))
                    else:
                        # commands like: '/cmd' become ('CMD', '/cmd')
                        label = key.strip()[1:].upper()
                        buttons.append(
                            InlineKeyboardButton(label, callback_data=key))
            elif isinstance(row_keyboard, list):
                for entry in row_keyboard:
                    text_btn, data_btn = entry
                    buttons.append(
                        InlineKeyboardButton(text_btn, callback_data=data_btn))
            else:
                raise ValueError(str(row_keyboard))
            return buttons

        # Defaults
        params = {
            ATTR_PARSER: self._parse_mode,
            ATTR_DISABLE_NOTIF: False,
            ATTR_DISABLE_WEB_PREV: None,
            ATTR_REPLY_TO_MSGID: None,
            ATTR_REPLYMARKUP: None,
            ATTR_TIMEOUT: None,
            ATTR_MESSAGE_TAG: None,
        }
        if data is not None:
            if ATTR_PARSER in data:
                params[ATTR_PARSER] = self._parsers.get(
                    data[ATTR_PARSER], self._parse_mode)
            if ATTR_TIMEOUT in data:
                params[ATTR_TIMEOUT] = data[ATTR_TIMEOUT]
            if ATTR_DISABLE_NOTIF in data:
                params[ATTR_DISABLE_NOTIF] = data[ATTR_DISABLE_NOTIF]
            if ATTR_DISABLE_WEB_PREV in data:
                params[ATTR_DISABLE_WEB_PREV] = data[ATTR_DISABLE_WEB_PREV]
            if ATTR_REPLY_TO_MSGID in data:
                params[ATTR_REPLY_TO_MSGID] = data[ATTR_REPLY_TO_MSGID]
            if ATTR_MESSAGE_TAG in data:
                params[ATTR_MESSAGE_TAG] = data[ATTR_MESSAGE_TAG]
            # Keyboards:
            if ATTR_KEYBOARD in data:
                keys = data.get(ATTR_KEYBOARD)
                keys = keys if isinstance(keys, list) else [keys]
                if keys:
                    params[ATTR_REPLYMARKUP] = ReplyKeyboardMarkup(
                        [[key.strip() for key in row.split(",")]
                         for row in keys])
                else:
                    params[ATTR_REPLYMARKUP] = ReplyKeyboardRemove(True)

            elif ATTR_KEYBOARD_INLINE in data:
                keys = data.get(ATTR_KEYBOARD_INLINE)
                keys = keys if isinstance(keys, list) else [keys]
                params[ATTR_REPLYMARKUP] = InlineKeyboardMarkup(
                    [_make_row_inline_keyboard(row) for row in keys])
        return params
Example #25
0
def get_contact_view():
    button = KeyboardButton("Отправить номер", request_contact=True, one_time_keyboard=True)
    reply_markup = ReplyKeyboardMarkup.from_button(button, resize_keyboard=True)
    return {
        'reply_markup': reply_markup,
        'text': 'Для авторизации в боте отправьте номер телефона'}
def careem(update, context):
    if not startcommandused:
        context.bot.send_message(
            chat_id=update.effective_chat.id,
            text=
            "You need to use the /start command first to register the User ID, try again"
        )
        return
    context.bot.send_message(
        chat_id=update.effective_chat.id,
        text=
        "Note: You can use the /cancel command to cancel the ordering process at any time. \nLoading the Careem webpage, please wait..."
    )
    global driver
    driver = webdriver.Firefox()
    # VPN PROCESS BELOW, MIGHT NOT BE NEEDED IF YOU'RE IN A CAREEM-SUPPORTED COUNTRY
    # -----------------------------------------------------------------------------

    extension_dir = '/root/.mozilla/firefox/siro1t0y.default-release/extensions/'
    extensions = ['{fca67f41-776b-438a-9382-662171858615}.xpi']
    for extension in extensions:
        driver.install_addon(extension_dir + extension, temporary=True)
    time.sleep(10)
    pyautogui.click(1220, 110)  # extension icon
    time.sleep(3)
    pyautogui.click(1080, 570)  # thanks
    time.sleep(3)
    pyautogui.click(1145, 445)  # agree
    time.sleep(3)
    pyautogui.click(1010, 240)  # us
    time.sleep(3)
    pyautogui.click(1035, 310)  # algeria
    time.sleep(10)
    pyautogui.hotkey('ctrl', 'w')

    # -------------------------------------------------------------------
    # VPN PROCESS DONE

    driver.get("https://app.careem.com/rides")
    wait(driver, 30).until(
        EC.element_to_be_clickable(
            (By.CLASS_NAME, "selected-dial-code"))).click()
    wait(driver, 10).until(
        EC.element_to_be_clickable(
            (By.XPATH, "//span[text()='+964']"))).click()
    global user
    user = driver.find_element_by_id('mobileNumber')
    context.bot.send_message(
        chat_id=update.effective_chat.id,
        text="Careem page loaded! Send your phone number, using plain text.",
        reply_markup=ReplyKeyboardMarkup(
            [["/cancel", "/restart", "/screenshot"]], one_time_keyboard=True))
    if checkifregistered(theuserid):
        context.bot.send_message(
            chat_id=update.effective_chat.id,
            text=
            "You have saved info, would you like to use it? Type 'use' if you want to, or carry on like usual.",
            reply_markup=ReplyKeyboardMarkup(
                [["use", "/cancel", "/restart", "/screenshot"]],
                one_time_keyboard=True))
    return PHONE
Example #27
0
def cart_message() -> dict:
    action_buttons = [[PRODUCTS_BUTTON, CONFIRM_BUTTON], [EXIT_BUTTON]]
    reply_markup = ReplyKeyboardMarkup(action_buttons, one_time_keyboard=False, resize_keyboard=True)
    return {'text': CART_BUTTON, 'reply_markup': reply_markup}
Example #28
0
def menu(update: Update, _: CallbackContext) -> int:
    logger.info(f"Menu selector. ({update.message.text})")

    keyboard = [
        [
            "💵 Current value",
        ],
        ["📈 Progress", "➗ Current ratios"],
        ["🔍 Check bot status", "⌛ Trade History"],
        ["🛠 Maintenance", "⚙️ Configurations"],
    ]

    config_keyboard = [
        ["▶ Start trade bot", "⏹ Stop trade bot"],
        ["📜 Read last log lines", "❌ Delete database"],
        ["⚙ Edit user.cfg", "👛 Edit coin list"],
        ["📤 Export database", "⬅️ Back"],
    ]

    maintenance_keyboard = [
        ["Update Telegram Bot"],
        ["Update Binance Trade Bot"],
        ["⬅️ Back"],
    ]

    reply_markup = ReplyKeyboardMarkup(keyboard, resize_keyboard=True)

    reply_markup_config = ReplyKeyboardMarkup(config_keyboard,
                                              resize_keyboard=True)

    reply_markup_maintenance = ReplyKeyboardMarkup(maintenance_keyboard,
                                                   resize_keyboard=True)

    if update.message.text in ["Begin", "⬅️ Back"]:
        message = "Please select one of the options."
        update.message.reply_text(message, reply_markup=reply_markup)

    elif update.message.text in ["Go back", "OK", "⚙️ Configurations"]:
        message = "Please select one of the options."
        update.message.reply_text(message, reply_markup=reply_markup_config)

    elif update.message.text in ["🛠 Maintenance", "Cancel update", "OK 👌"]:
        message = "Please select one of the options."
        update.message.reply_text(message,
                                  reply_markup=reply_markup_maintenance)

    elif update.message.text == "💵 Current value":
        for mes in buttons.current_value():
            update.message.reply_text(mes,
                                      reply_markup=reply_markup,
                                      parse_mode="MarkdownV2")

    elif update.message.text == "📈 Progress":
        for mes in buttons.check_progress():
            update.message.reply_text(mes,
                                      reply_markup=reply_markup,
                                      parse_mode="MarkdownV2")

    elif update.message.text == "➗ Current ratios":
        for mes in buttons.current_ratios():
            update.message.reply_text(mes,
                                      reply_markup=reply_markup,
                                      parse_mode="MarkdownV2")

    elif update.message.text == "🔍 Check bot status":
        update.message.reply_text(buttons.check_status(),
                                  reply_markup=reply_markup)

    elif update.message.text == "⌛ Trade History":
        for mes in buttons.trade_history():
            update.message.reply_text(mes,
                                      reply_markup=reply_markup,
                                      parse_mode="MarkdownV2")

    elif update.message.text == "▶ Start trade bot":
        update.message.reply_text(
            buttons.start_bot(),
            reply_markup=reply_markup_config,
            parse_mode="MarkdownV2",
        )

    elif update.message.text == "⏹ Stop trade bot":
        update.message.reply_text(buttons.stop_bot(),
                                  reply_markup=reply_markup_config)

    elif update.message.text == "📜 Read last log lines":
        update.message.reply_text(
            buttons.read_log(),
            reply_markup=reply_markup_config,
            parse_mode="MarkdownV2",
        )

    elif update.message.text == "❌ Delete database":
        re = buttons.delete_db()
        if re[1]:
            kb = [["⚠ Confirm", "Go back"]]
            update.message.reply_text(
                re[0],
                reply_markup=ReplyKeyboardMarkup(kb, resize_keyboard=True),
                parse_mode="MarkdownV2",
            )
            return DELETE_DB
        else:
            update.message.reply_text(re[0],
                                      reply_markup=reply_markup_config,
                                      parse_mode="MarkdownV2")

    elif update.message.text == "⚙ Edit user.cfg":
        re = buttons.edit_user_cfg()
        if re[1]:
            update.message.reply_text(re[0],
                                      reply_markup=ReplyKeyboardRemove(),
                                      parse_mode="MarkdownV2")
            return EDIT_USER_CONFIG
        else:
            update.message.reply_text(re[0],
                                      reply_markup=reply_markup_config,
                                      parse_mode="MarkdownV2")

    elif update.message.text == "👛 Edit coin list":
        re = buttons.edit_coin()
        if re[1]:
            update.message.reply_text(re[0],
                                      reply_markup=ReplyKeyboardRemove(),
                                      parse_mode="MarkdownV2")
            return EDIT_COIN_LIST
        else:
            update.message.reply_text(re[0],
                                      reply_markup=reply_markup_config,
                                      parse_mode="MarkdownV2")

    elif update.message.text == "📤 Export database":
        re = buttons.export_db()
        update.message.reply_text(re[0],
                                  reply_markup=reply_markup_config,
                                  parse_mode="MarkdownV2")
        if re[1] is not None:
            bot = Bot(settings.TOKEN)
            bot.send_document(
                chat_id=update.message.chat_id,
                document=re[1],
                filename="crypto_trading.db",
            )

    elif update.message.text == "Update Telegram Bot":
        re = buttons.update_tg_bot()
        if re[1]:
            kb = [["Update", "Cancel update"]]
            update.message.reply_text(
                re[0],
                reply_markup=ReplyKeyboardMarkup(kb, resize_keyboard=True),
                parse_mode="MarkdownV2",
            )
            return UPDATE_TG
        else:
            update.message.reply_text(
                re[0],
                reply_markup=reply_markup_maintenance,
                parse_mode="MarkdownV2",
            )

    elif update.message.text == "Update Binance Trade Bot":
        re = buttons.update_btb()
        if re[1]:
            kb = [["Update", "Cancel update"]]
            update.message.reply_text(
                re[0],
                reply_markup=ReplyKeyboardMarkup(kb, resize_keyboard=True),
                parse_mode="MarkdownV2",
            )
            return UPDATE_BTB
        else:
            update.message.reply_text(
                re[0],
                reply_markup=reply_markup_maintenance,
                parse_mode="MarkdownV2",
            )

    return MENU
Example #29
0
def markup_columns(keys: List[str], columns: int = 2) -> ReplyKeyboardMarkup:
    """ Make keyboard markup with specified number of columns """
    buttons = [KeyboardButton(text=key) for key in keys]
    keyboard = group_by(buttons, columns)
    markup = ReplyKeyboardMarkup(keyboard)
    return markup
Example #30
0
#!/usr/bin/env python
#https://github.com/tanzilli/digitalsign
#https://github.com/python-telegram-bot/python-telegram-bot#api

# Sergio Tanzilli - [email protected]
 
import logging
from telegram import Emoji, ForceReply, ReplyKeyboardMarkup, KeyboardButton
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters

import time
import os					

video_keyboard = ReplyKeyboardMarkup([["VIDEO1","VIDEO2","VIDEO3","VIDEO4"],["VIDEO5","VIDEO6","VIDEO7","VIDEO8"],["STOP"]])
video_keyboard.one_time_keyboard=False
video_keyboard.resize_keyboard=True

current_command="play"

screen = None
		
# Enable logging
logging.basicConfig(
		format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
		level=logging.INFO)

logger = logging.getLogger(__name__)

def cmd_start(bot, update):
	bot.sendMessage(update.message.chat_id, "Ciao %s ! Sei connesso con la tua insegna.\n" % ( update.message.from_user.first_name))
	bot.sendMessage(update.message.chat_id, text="Seleziona un video per farne il play ...", reply_markup=video_keyboard)
def on_set_language_button_pressed(update,context):
    update.effective_message.reply_text(strings.get(strings.choose_a_language,update),
                                        reply_markup=ReplyKeyboardMarkup(LANGUAGES))
    return WAITING_FOR_LANGUAGE