Exemplo n.º 1
0
def check_verification_email(bot, message):
    if message.content_type == 'text':
        (ver_code, chance) = additional_info.split(':')
        chance = int(chance) + 1
        db_connector.put_user_operation(message.from_user.id,
                                        operation=opRegister,
                                        status=status,
                                        additional_info=ver_code + ':' +
                                        str(chance))
        if chance <= 10:
            if message.text == ver_code:
                finish_reg(bot, message)
            else:
                bot.send_message(message.chat.id,
                                 'Неверный код. Попробуйте ещё раз.',
                                 reply_markup=types.ReplyKeyboardHide())
        else:
            bot.send_message(
                message.chat.id,
                'Многократный неверный ввод. Аккаунт заблокировн. Для разблокировки пишите на админа.',
                reply_markup=types.ReplyKeyboardHide())
            bot.send_message(
                config['BASE']['Admin_id'],
                'Заблокирован пользователь {}'.format(message.from_user.id))
    else:
        bot.send_message(message.chat.id,
                         'Введите код',
                         reply_markup=types.ReplyKeyboardHide())
Exemplo n.º 2
0
def give_quest():
    """Отправка квеста.

    @Написано, тестируется
    Предполагается с кнопкой "начать" - нуно чтобы дать пользователь возможность выйти на исходную позицию, если надо.
    Можно заменить  пока на выдачу первого вопроса сразу.
    """
    global status, additional_info
    quest_id = additional_info.get('buttons-quest_id',
                                   {}).get(message.text, None)
    additional_info.pop('buttons-quest_id', None)
    if not quest_id:
        #@обработка ошибки. Сообщение об ошибке и редирект на show_quest_list
        db_connector.save_to_log(
            'system',
            message=message,
            comment_text='Не удалось найти код квеста по кнопке')
        bot.send_message(message.chat.id,
                         'Нужно выбрать квест кнопкой',
                         reply_markup=types.ReplyKeyboardHide())
        show_quest_list()
    else:
        additional_info['quest_id'] = quest_id
        bot.send_message(message.chat.id,
                         'Ваш квест начинается. Удачи!',
                         reply_markup=types.ReplyKeyboardHide())
        give_question(next_q=True)
Exemplo n.º 3
0
def confirm_match_choose(message):
    if (message.text == 'cancel' or message.text == 'Cancel'):
        markup = types.ReplyKeyboardHide()
        bot.send_message(message.chat.id,
                         _('Action cancelled.'),
                         reply_markup=markup)
        userStep[message.from_user.id] = None
        return
    chat_id = message.chat.id
    markup = types.ReplyKeyboardHide()
    bot.send_message(chat_id,
                     _('Match selected correctly.'),
                     reply_markup=markup)
    mid = message.text.split(' ')
    query = get_matches()
    match = query.filter(Match.id == int(mid[0])).one()
    to_winner[message.from_user.id] = {
        'id': match.id,
        'team1': match.team1,
        'team2': match.team2
    }
    markup = types.ForceReply(selective=False)
    bot.send_message(chat_id,
                     match.team1 + ' ' + _('Score:'),
                     reply_markup=markup)
    userStep[message.from_user.id] = 32
Exemplo n.º 4
0
def resolve_resolution(message):
    chatState[message.chat.id]['state'] = 'resolve_resolution'

    if message.text.lower() in ['y', 'yes', 'correct', 'right']:
        outcome = True
    elif message.text.lower() in ['n', 'no', 'incorrect']:
        outcome = False
    else:
        if message.text.lower() != 'cancel':
            bot.send_message(message.chat.id, "Cannot interpret your answer",
                             reply_markup=types.ReplyKeyboardHide())
        cancel(message)
        return

    chatState[message.chat.id]['prediction_outcome'] = outcome
    try:
        make_request_to_server(
            chatState[message.chat.id]['prediction_id'],
            method="PATCH",
            data={'outcome': outcome})
    except RequestException:
        bot.send_message(message.chat.id, "Something went wrong.",
                         reply_markup=types.ReplyKeyboardHide())
        cancel(message)
        return

    bot.send_message(message.chat.id, "Ok, we saved that. Good luck next time",
                     reply_markup=types.ReplyKeyboardHide())
Exemplo n.º 5
0
def give_question(next_q=True):
    """Выслать вопрос

    @Написано, тестируется
    Типы вопросов
    text
    dig
    geo - выслать кнопку запроса координат.
    """
    global status, additional_info
    quest_id = additional_info.get('quest_id')
    last_question_id = additional_info.get('question_id')
    if not quest_id:
        db_connector.save_to_log(
            'system',
            message=message,
            comment_text='Не удалось найти код квеста в additional_info')
        bot.send_message(message.chat.id,
                         'Что-то пошло не так...',
                         reply_markup=types.ReplyKeyboardHide())
        show_quest_list()
    else:
        if next_q:
            next_quest = db_connector.get_next_question(
                quest_id=quest_id, question_id=last_question_id)
        else:
            next_quest = db_connector.get_question(
                question_id=last_question_id)
        if next_quest:
            #Структура ID, description, answer_type, correct_answer
            (question_id, description, photo, answer_type,
             correct_answer) = next_quest
            if answer_type == 'geo':
                markup = types.ReplyKeyboardMarkup(resize_keyboard=True,
                                                   one_time_keyboard=True)
                markup.add(
                    types.KeyboardButton(text=r'Вышел на точку!',
                                         request_location=True))
            else:
                markup = types.ReplyKeyboardHide()
            additional_info['question_id'] = question_id
            status = 'need_answer'
            put_operations()
            bot.send_message(message.chat.id, description, reply_markup=markup)
            if photo:
                bot.send_photo(message.chat.id, photo, reply_markup=markup)
        elif next_q:
            finish_quest()
        else:
            db_connector.save_to_log('system',
                                     message=message,
                                     comment_text='Вопрос где-то потерялся')
            bot.send_message(message.chat.id,
                             'Что-то пошло не так...',
                             reply_markup=types.ReplyKeyboardHide())
            show_quest_list()
Exemplo n.º 6
0
def ask(message):
    global usid
    global inQuestion
    if message.text == "/start":
        usid = message.chat.id
        markup = types.ReplyKeyboardMarkup(row_width=1)
        markup.add(whynot)
        bot.send_message(message.chat.id, greeting, reply_markup=markup)
    elif inQuestion:
        res = t.validate_answer(int(message.text) - 1)
        markup = types.ReplyKeyboardHide(selective=False)
        markup = types.ReplyKeyboardMarkup(row_width=1)
        markup.add(nextOne)
        markup.add(killBot)
        if res['right']:
            bot.send_message(message.chat.id, rightAnswer, reply_markup=markup)
        else:
            bot.send_message(message.chat.id,
                             wrongAnswer + res['right_answer'],
                             reply_markup=markup)
        inQuestion = False
    elif message.text == killBot:
        markup = types.ReplyKeyboardHide(selective=False)
        keyboard = types.InlineKeyboardMarkup(row_width=3)
        url_button1 = types.InlineKeyboardButton(
            text="iOS",
            url="https://itunes.apple.com/ru/app/moj-univer/id656335236?mt=8")
        url_button2 = types.InlineKeyboardButton(
            text="WP",
            url=
            r"https://www.microsoft.com/en-us/store/p/%D0%9C%D0%BE%D0%B9-%D0%A3%D0%BD%D0%B8%D0%B2%D0%B5%D1%80/9wzdncrdkknr"
        )
        url_button3 = types.InlineKeyboardButton(
            text="Android",
            url=
            "https://play.google.com/store/apps/details?id=ru.etemplarsoft.mu.main.pro"
        )
        keyboard.add(url_button1, url_button2, url_button3)
        bot.send_message(message.chat.id, addvert, reply_markup=markup)
        bot.send_message(message.chat.id, addvertMore, reply_markup=keyboard)
        time.sleep(10)
        dailik()
    elif message.text == noDaily:
        markup = types.ReplyKeyboardHide(selective=False)
        bot.send_message(message.chat.id, finalAddvert, reply_markup=markup)
    else:
        markup = types.ReplyKeyboardMarkup(row_width=2)
        markup.add('1', '2', "3", '4')
        questions = t.get_next_question()
        final_string = ''
        final_string += questions.question_text + '\n\n'
        for i, k in enumerate(questions.answer_strings):
            final_string += str(i + 1) + ") " + k + "\n"
        bot.send_message(message.chat.id, final_string, reply_markup=markup)
        inQuestion = True
Exemplo n.º 7
0
def repeat_all_messages(message):
    user_id = message.from_user.id
    db = Db(db_dir)
    user = db.get_user_by_id(user_id)
    if user:
        if user[1]:
            if message.text in ['1', '2', '3', '4', '5', '6', '7', '8', '9']:
                pos = int(message.text)
                user_game = db.get_game(user_id)
                if '0' == user_game[2][pos]:
                    field = db.set_step(user_id, pos)
                    winner = who_win(field)
                    if winner:
                        markup = types.ReplyKeyboardHide()
                        field = draw_field(field)
                        bot.send_message(user_id,
                                         field + "\n" + winner,
                                         reply_markup=markup,
                                         parse_mode='HTML')
                        db.set_type_to_user(user_id, None)
                        if 'Ничья' == winner:
                            db.user_draw(user_id)
                        else:
                            db.user_win(user_id)
                        db.end_game(user_id)
                        return True
                    field = bot_step(user_id, field)
                    winner = who_win(field)
                    if winner:
                        markup = types.ReplyKeyboardHide()
                        field = draw_field(field)
                        bot.send_message(user_id,
                                         field + "\n" + winner,
                                         reply_markup=markup,
                                         parse_mode='HTML')
                        db.set_type_to_user(user_id, None)
                        if 'Ничья' == winner:
                            db.user_draw(user_id)
                        else:
                            db.user_lose(user_id)
                        db.end_game(user_id)
                        return True
                    field = draw_field(field)
                    bot.send_message(user_id, field, parse_mode='HTML')
                else:
                    bot.send_message(user_id, 'Так сходить нельзя')
            else:
                markup = types.ReplyKeyboardHide()
                if message.text in ['X', 'O']:
                    db.set_type_to_user(user_id, message.text)
                    bot.send_message(user_id,
                                     'Вы выбрали ' + str(message.text) + '!',
                                     reply_markup=markup)
                db.create_game(user_id)
                cmd_game(message)
Exemplo n.º 8
0
def check_phone(bot, message):
    if message.content_type == 'contact':
        if message.contact.user_id == message.from_user.id:
            db_connector.register_user(message.from_user.id, phone=message.contact.phone_number)
            next_step(bot, message)
        else:
            bot.send_message(message.chat.id, "Неверный телефон", reply_markup=types.ReplyKeyboardHide())
            ask_phone(bot, message)
    else:
        bot.send_message(message.chat.id,
                         'Необходимо нажать кнопки "разрешить" и во всплывшем окне ок. \n Если вы нажали кнопку, а окно не всплыло, то, скорее всего у вас старая версия Telegram. Обновите приложение через Google Play Market или AppStore. Или же зарегистрируйтесь через барузер. Версии выпущенные до апреля 2016го года не поддерживают многие функции.',
                         reply_markup=types.ReplyKeyboardHide())
        ask_phone(bot, message)
Exemplo n.º 9
0
def take_quest_name():
    global status, additional_info
    if message.content_type != 'text':
        bot.send_message(message.chat.id,
                         'Введите название квсета или нажмите /cancel',
                         reply_markup=types.ReplyKeyboardHide())
        return

    additional_info['quest_name'] = message.text
    bot.send_message(message.chat.id,
                     'Введите описание квеста.',
                     reply_markup=types.ReplyKeyboardHide())
    status = 'need_quest_desc'
    put_operations()
Exemplo n.º 10
0
def take_quest_desc():
    global status, additional_info
    if message.content_type != 'text':
        bot.send_message(message.chat.id,
                         'Введите описание квеста или нажмите /cancel',
                         reply_markup=types.ReplyKeyboardHide())
        return

    additional_info['quest_desc'] = message.text
    bot.send_message(
        message.chat.id,
        'Приложите фото квеста или нажмите /skip - квест без фото.',
        reply_markup=types.ReplyKeyboardHide())
    status = 'need_quest_photo'
    put_operations()
Exemplo n.º 11
0
def command_theme(m):
    cid = m.chat.id
    user = str(m.from_user.id)
    text = m.text
    exist = settings.settings_exist(cid)
    if exist:
        theme = text.split("/theme")[1].replace(" ", "")
        if not theme in THEMES:
            markup = types.ReplyKeyboardMarkup(row_width=2)
            for key in THEMES.keys():
                markup.add("/theme " + key)
            current = game.get_info(cid)['theme']
            bot.send_message(cid,
                             "Choose one option:\n <b>Current: </b>" + current,
                             reply_markup=markup,
                             parse_mode="HTML",
                             disable_notification=True)

        else:
            markup = types.ReplyKeyboardHide(selective=False)
            bot.send_message(cid,
                             "Succesful!",
                             reply_markup=markup,
                             disable_notification=True)
            settings.update_settings(cid, theme=theme)
            playing = tools.game_exist(cid)
            if playing:
                game.update_info(cid, theme=theme)
                caption = tools.get_last_from_pgn(cid)
                tools.send_board_image(bot, cid, caption, silent=True)
def listener(messages):
    for m in messages:
        if m.content_type == 'text' and m.text == '/subscribe':
            choose_groups(m.chat.id, True)
        if m.content_type == 'text' and m.text == '/unsubscribe':
            choose_groups(m.chat.id, False)
        if m.text.startswith('/group'):
            if '+' in m.text and m.chat.id in list_users_to_subscribe:
                utils.add_user_to_list_of_subscribers(m.chat.id,
                                                      m.text[m.text.find(':') + 2:].strip())
                # list_users_to_subscribe.remove(m.chat.id)
                send_message_with_hide_keyboard(m.chat.id, 'Вы подписались на категорию '
                                                + m.text[m.text.find(':') + 2:].strip())
            if '-' in m.text and m.chat.id in list_users_to_unsibscribe:
                utils.delete_user_from_list_of_subscribers(m.chat.id,
                                                           m.text[m.text.find(':') + 2:].strip())
                # list_users_to_unsibscribe.remove(m.chat.id)
                send_message_with_hide_keyboard(m.chat.id, 'Вы отписались от категории '
                                                + m.text[m.text.find(':') + 2:].strip())
        if m.text == '/0:Закрыть':
            hider = types.ReplyKeyboardHide()
            tb.send_message(m.chat.id, 'Готово!', reply_markup=hider)
            try:
                list_users_to_unsibscribe.remove(m.chat.id)
                list_users_to_subscribe.remove(m.chat.id)
            except:
                pass
Exemplo n.º 13
0
 def wrapped(message):
     result = fn(message)
     msg = 'Stored' if result else 'Failed to store'
     bot.send_message(message.chat.id,
                      msg,
                      reply_markup=types.ReplyKeyboardHide(selective=True))
     return result
Exemplo n.º 14
0
def command_engine(m):
    cid = m.chat.id
    user = str(m.from_user.id)
    text = m.text
    exist = settings.settings_exist(cid)
    playing = tools.game_exist(cid)
    if exist and (not playing):
        engine = text.split("/engine")[1].replace(" ", "")
        if not engine in ENGINES:
            markup = types.ReplyKeyboardMarkup(row_width=2)
            for key in ENGINES:
                markup.add("/engine " + key)
            current = settings.get_settings(cid)['engine']
            bot.send_message(cid,
                             "Choose one option:\n <b>Current: </b>" + current,
                             reply_markup=markup,
                             parse_mode="HTML",
                             disable_notification=True)

        else:
            markup = types.ReplyKeyboardHide(selective=False)
            bot.send_message(cid,
                             "Succesful!",
                             reply_markup=markup,
                             disable_notification=True)
            settings.update_settings(cid, engine=engine)
Exemplo n.º 15
0
def act(message):
    markup = types.ReplyKeyboardHide()

    status_codes = []

    msg = {
        200: "You are successfully authorized.",
        201: "URL has been successfully added.",
        403: "Invalid username or password. Please try again: /auth.",
        500: "The service encountered an error. Please try again later."
    }

    if message.text == 'Auth':
        status_codes.append(instapaper.auth(*data))

    else:
        for url in data:
            status_codes.append(instapaper.add(url))

    data.clear()

    for status_code in status_codes:
        bot.send_message(message.chat.id,
                         msg[status_code],
                         reply_markup=markup)
Exemplo n.º 16
0
def ask_for_url(message):
    global instapaper
    instapaper = Instapaper(message.chat.id) if not instapaper else instapaper

    data.clear()

    global command
    command = message.text

    if not instapaper.is_authorized():
        bot.send_message(message.chat.id,
                         messages.auth_requirement,
                         parse_mode='Markdown',
                         reply_markup=types.ReplyKeyboardHide())

        return None

    markup = types.ReplyKeyboardMarkup(resize_keyboard=True)

    btn = types.KeyboardButton('Add')

    markup.add(btn)

    text = "Send me *URL*:"
    bot.send_message(message.chat.id,
                     text,
                     parse_mode='Markdown',
                     reply_markup=markup)
Exemplo n.º 17
0
def ask_for_data(message):
    global instapaper
    instapaper = Instapaper(message.chat.id) if not instapaper else instapaper

    data.clear()

    global command
    command = message.text

    if instapaper.is_authorized():
        bot.send_message(message.chat.id,
                         messages.auth_warning,
                         parse_mode='Markdown',
                         reply_markup=types.ReplyKeyboardHide())

    markup = types.ReplyKeyboardMarkup(resize_keyboard=True)

    btn = types.KeyboardButton('Auth')

    markup.add(btn)

    text = "Send me your *Email* or *Username* and *Password, if you have one*:"
    bot.send_message(message.chat.id,
                     text,
                     parse_mode='Markdown',
                     reply_markup=markup)
Exemplo n.º 18
0
def set_bet_db(message):
    chat_id = message.chat.id
    markup = types.ReplyKeyboardHide()
    bot.send_message(chat_id,
                     _('Winner correctly selected.'),
                     reply_markup=markup)
    query = get_matches()
    match = query.filter(
        Match.id == to_winner[message.from_user.id]['id']).first()
    match.score1 = to_winner[message.from_user.id]['score1']
    match.score2 = message.text

    update()
    query = get_bets()
    bets = query.filter(
        Bet.match == to_winner[message.from_user.id]['id']).all()
    for b in bets:
        query = get_ranking()
        ranking = query.filter(Ranking.player_id == b.player_id).first()
        if not ranking:
            ranking = Ranking(player_id=b.player_id)
            add(ranking)
        ranking.total += 1
        winner = ('team1' if int(message.text) < int(
            to_winner[message.from_user.id]['score1']) else 'team2')
        if to_winner[message.from_user.id][winner] == b.bet:
            ranking.wins += 1
        update()
    userStep[message.from_user.id] = None
Exemplo n.º 19
0
def ask_email(bot, message):
    text = 'Укажите ваш  email.'
    if config['REGISTRATION']['Verification_email']:
        text += ' На него будет выслан код для активации.'
    bot.send_message(message.chat.id,
                     text,
                     reply_markup=types.ReplyKeyboardHide())
Exemplo n.º 20
0
def ask_question_desk():
    global status, additional_info
    bot.send_message(message.chat.id,
                     'Введите текст задания',
                     reply_markup=types.ReplyKeyboardHide())
    status = 'need_question_desc'
    put_operations()
Exemplo n.º 21
0
def add_task_enter(message):
    """
    Enters into 'Task adding' state.
    """
    markup = types.ReplyKeyboardHide(selective=False)
    bot.send_message(message.chat.id, ADD_TASK_MESSAGE, reply_markup=markup)
    user_actions[message.from_user.id] = 'Task adding'
Exemplo n.º 22
0
def handle_start_help(message):
    game = math_game.MathGame()
    my_bot.busy = True
    my_bot.playing = True
    my_bot.bot.send_message(message.chat.id, config.game_intro)
    sleep(4)
    while True:
        round = game.getNextRound()
        my_bot.bot.send_message(message.chat.id, round[0],
                                reply_markup=round[1])
        while my_bot.answer == "":
            pass
        if my_bot.answer == config.stop_playing_request.lower():
            my_bot.bot.send_message(message.chat.id,
                                    config.stop_playing_answer,
                                    reply_markup=types.ReplyKeyboardHide())
            break
        else:
            result = game.checkAnswer(round[0], my_bot.answer)
            my_bot.bot.send_message(message.chat.id, 
                                    config.game_answer[result])
        my_bot.answer = ""
    my_bot.bot.send_message(message.chat.id,
                            "You answered " + str(game.answered_all) +
                            " times. " + str(game.answered_right) +
                            " of them were correct.")
    my_bot.busy = False
    my_bot.playing = False
    my_bot.answer = ""
def send_message_with_hide_keyboard(chat_id, text, hide_keyboard=False):
    message_length = 2000
    if hide_keyboard:
        keyboard = types.ReplyKeyboardHide()
    else:
        keyboard = None
    for msg_part in utils.string_splitter(text, message_length):
        tb.send_message(chat_id, msg_part, disable_web_page_preview=True, reply_markup=keyboard)
Exemplo n.º 24
0
def msg_add_match_date(message):
    chat_id = message.chat.id
    markup = types.ReplyKeyboardHide()
    bot.send_message(chat_id, _('Date set correctly.'), reply_markup=markup)
    markup = types.ForceReply(selective=False)
    to_add[message.from_user.id]['date'] = message.text
    bot.send_message(message.chat.id, _('Match hour:'), reply_markup=markup)
    userStep[message.from_user.id] = 24
Exemplo n.º 25
0
Arquivo: run.py Projeto: GTejik/laba
def set_nd_matrix(message):
    markup = types.ReplyKeyboardHide(selective=False)
    matrix = '0 1\n-a a,b c 0\n-b e c 1\nc e a,c 1\ne e e 0'
    f = open('input.txt', 'w')
    f.write(matrix)
    bot.send_message(message.chat.id,
                     'матрица:\n' + matrix,
                     reply_markup=markup)
Exemplo n.º 26
0
def generate_markup(state):
    if not state.get('options'):
        return types.ReplyKeyboardHide(selective=False)

    markup = types.ReplyKeyboardMarkup()
    for option in state['options']:
        markup.row(option)
    return markup
Exemplo n.º 27
0
def ask_quest_name():
    global status, additional_info
    bot.send_message(
        message.chat.id,
        'Вы собираетесь добавить новый квест. Введите его название.',
        reply_markup=types.ReplyKeyboardHide())
    status = 'need_quest_name'
    put_operations()
Exemplo n.º 28
0
def account_chosen(message):
    BOT.register_next_step_handler(message, amount_given)
    account = message.text
    user_id = message.from_user.id
    redis_helpers.store_transaction_from(account, user_id)
    BOT.send_message(user_id,
                     'Give amount:',
                     reply_markup=types.ReplyKeyboardHide())
Exemplo n.º 29
0
def votar(m):
    cid = m.chat.id
    if m.text in encuesta['respuestas']:
        markup = types.ReplyKeyboardHide()
        mensaje = str(m.from_user.first_name) + " (@" + str(m.from_user.username) + ")"
        votaciones[mensaje] = m.text
        bot.send_message( cid, "Voto añadido/actualizado", reply_markup=markup)
        bot.send_message( admin, mensaje + " ha votado.")
Exemplo n.º 30
0
def repeat_all_messages(message):
    #bot.send_message(message.chat.id, message.text)

    if message.text == "a":
        types.ReplyKeyboardHide()
        bot.send_message(message.chat.id, "You've typed 'a' on virtual keyboard")
    else:
        bot.reply_to(message, phrases[random.randint(0, 7)])