Example #1
0
def build_message(files, update):
    # נשמר למנוע חיפוש חוזר:
    #
    # מספר התוצאות (כמות הקבצים ברשימה)
    len_files = len(files)
    # הטקסט של ההודעה המקורית.
    message = get_message_text(update)
    # הID של ה CHAT.
    chat_id = get_message_chat_id(update)

    # אם יש תוצאות אבל החיפוש נעשה בקבוצה ולא בצ'אט פרטי..
    if chat_id < 0 < len_files:

        # אם יש את המילה "אקורדים" בהודעה, מדובר בחיפוש ולא סתם הודעה שרצה עם תוצאות במקרה.
        if "אקורדים" in message:
            # יוצר HASH ע"י השעה המדוייקת שנועד לשמור ולזהות את המקרה הספציפי הזה.
            time_hash = h1(str(time.time()).encode())

            # שומר לתוך מילון את תוצאות, המפתח הוא ה HASH (כשהמשתמש יחזור, נוכל לשלוף את התוצאות באמצעות ה HASH בלבד).
            saved[time_hash] = files

            # יוצר מקלדת מיוחדת, שמובילה לתוך הבוט.
            # הקישור המיוחד מראה כפתור "התחל" גם למשתמשים שהתחילו כבר, ומזין ערך מיוחד ל start_hash_handler.
            replay_markup = InlineKeyboardMarkup([[
                InlineKeyboardButton(
                    # ההודעה בקבוצה תהיה "אקורדים עבור ___", ועל הכתפור מתחת יהיה כתוב "לחץ פה".
                    text="לחץ פה",

                    # לחיצה תוביל לקישור - פותח את הבוט, יוצר התחלה חדשה עם ה time_hash המיוחד - וכך ה start_hash_handler יודע איזה קבצים להציג.
                    url=
                    f"https://t.me/Tab4usBot?start={str(time_hash)}andand{str(chat_id)}"
                )
            ]])

            # מסדר את כל הטקסט כדי לרשום את השם של השיר בצורה מדוייקת בהודעה החוזרת.
            data = message.replace("?", "")
            data = data.replace("לשיר ", "ל")
            data = data[data.index(" ל") + 2:]

            # שולח את ההודעה עם המקלדת.
            bot.sendMessage(text=f'אקורדים ל "{data.replace("אקורדים ", "")}"',
                            chat_id=chat_id,
                            reply_markup=replay_markup)

            # שומר לתוך רשימה מיוחדת איזו הודעה צריך למחוק ומאיפה.
            to_delete[time_hash] = [int(get_message_id(update))]

            # דגל שבודק אם ההודעה נמחקה.
            flags[time_hash] = False

            # יוצר לולאה שרצה ברקע ומוחקת את ההודעות בקבוצה אחרי שהמשתמש לחץ על הלינק (מונע הספמה)
            threading.Thread(target=delete, args=time_hash).start()
        return

    # אם אין תוצאות..
    if len_files == 0:

        # אם לא מדובר בקבוצה, שולחים הודעה אוטומטית שמדווחת על 0 תוצאות. בקבוצות לרוב ההודעות לא יהיו תוצאות, ולכן לא שולחים כלום.
        if chat_id > 0:
            # שולח למשתמש שלא נמצאו תוצאות.
            bot.sendMessage(chat_id=chat_id,
                            text="פאדיחה, לא מצאנו כלום.. נסה שילוב אחר!",
                            reply_markup=ReplyKeyboardRemove())
        return

    # אם יש כמה תוצאות (וזו לא קבוצה כי קבוצה שללנו למעלה)..
    if len_files > 1:

        # מכין מקלדת עם כל התוצאות.
        keyboard_values = sorted(list(map(replace_to_filename, files)))

        # הטקסט בהודעה הוא "בחר.."
        text = "בחר.."

        # אם יש מעל 100 תוצאות (וכפתור חזור אחד) מצמצמים ל100 תוצאות הראשונות - והמשתמש יצטרך לדייק את החיפוש שלו.
        if len(files) > 100:
            # חותכים את המקלדת ומשאירים רק את ה178 ערכים הראשונים.
            keyboard_values = keyboard_values[:100]

            # מדווחים למשתמש על עודף תוצאות.
            text = "החיפוש שלך כולל יותר מידי תוצאות, אז צמצמנו ל100 הראשונים.."

        # מוסיפים לתוצאות כפתור "חזור".
        keyboard_values.append("חזור")

        # יוצר מקלדת עם התוצאות המתאימות.
        keyboard = ReplyKeyboardMarkup(keyboard=[[i] for i in keyboard_values],
                                       resize_keyboard=True,
                                       one_time_keyboard=True)

        # שולחים למשתמש את ההודעה עם מקלדת התוצאות.
        bot.sendMessage(chat_id=chat_id, text=text, reply_markup=keyboard)
        return

    # אם מגיעים לפה, המשמעות היא שיר אחד בצ'אט פרטי.

    # מכניסים את הנתיב לשיר למשתנה fpath.
    fpath = files[0]

    # פותחים את הקובץ של השיר לקריאה.
    with open(fpath, "r") as song_file:

        # קוראים את כל הקובץ לתוך data.
        data = song_file.read()

        # אם השפה היא עברית, צריך להוסיף סימן מיוחד אחרי הכוכביות שימנע מהן להתהפך בכיוון.
        if data.split("\n")[5] == "HE":
            data = data.replace("#]", "#ᶥ")

        # מוחקים את כל הסוגריים שמסמנים אקורד מהטקסט.
        data = data.replace("[", "").replace("]", "")

        # מחלקים את הטקסט לשורות.
        data = data.split('\n')

        # מעתיק את הפתיחה הקבועה לעותק מקומי, כדי לשנות אותו בלי לפתוח מחדש את הצורך.
        intro = INTRO

        # מכניס את שם השיר למקום המתאים בפתיחה, מסיר תווים מיוחדים שלא קיימים בשם הקובץ.
        intro = intro.replace(
            "song", data[0].replace(" ", "_").replace('/', "").replace(
                '&', "").replace("'", "").replace(",", "_") +
            f"   \n{data[0]}")
        # מכניס את שם הזמר למקום המתאים בפתיחה, מסיר תווים מיוחדים שלא קיימים בשם הקובץ.
        intro = intro.replace(
            "singer", data[1].replace(" ", "_").replace('/', "").replace(
                '&', "").replace("'", "").replace(".", "_").replace(",", "_") +
            f"   \n{data[1]}")

        # אם בשורה השלישית כתוב "המערכת" ולא "גולש"..
        if "המערכת" == data[2]:
            # מוסיפים לשיר סימון של גרסה רשמית.
            intro = intro.replace("version", "⭐️ גרסה רשמית ⭐")
        # אם בשורה השלישית כתוב "גולש" ולא "המערכת""..
        else:
            # מוחקים את המיקום של הגרסה רשמית.
            intro = intro.replace("version", "")

        # השורה הרביעית בשיר מכילה את המספר של הגרסה הקלה - כמה צריך להזיז כדי להגיע אליה.
        # לא מכניסים את זה לפתיחה כי למשתמש זה לא יעיל, אלא מעבירים לפונקציה והיא מכניסה את זה לנתונים של כפתור "גרסה קלה".
        easy_key = data[3]

        # בשורה החמישית בשיר כתוב איפה לשים קאפו. אם הקאפו בשריג 0..
        if "0" == data[4]:
            # מסירים את הסימון של הקאפו. לא צריך לרשום 0.
            intro = intro.replace("capo", "")
        # אם הקאפו בשריג אחר..
        else:
            # רושמים במיקום המתאים איפה לשים את הקאפו.
            intro = intro.replace("capo", f"קאפו בשריג {data[4]}")

        # המידע בתחילת השיר (שמות, קאפו, גרסה קלה וכד') לא נשלח, רק מ - data[5] ואילך.
        # ולכן מוסיפים ל- data[5] את כל הפתיח הרשמי, והשיר נשלח משם ואילך.
        data[5] = intro

        # מוסיפים את הסיומת הקבועה (אין בה משתנים בכלל).
        data.append(ENDING)

        # שולחים את השיר למשתמש בעזרת הפונקציה הייעודית.
        send_data(data[5:], update, True, False, None, easy_key,
                  UPLOADED_LIST.index(fpath))
Example #2
0
def select_graph_host(bot, update, user_data):
    update.message.reply_text(
        text='Please enter hostname or ip.\nSend \end to end the conversation.',
        reply_markup=ReplyKeyboardRemove())

    return ZBX_GRAPH_HOST
Example #3
0
def display_mood(update: Update, user_data: Dict) -> None:
    update.message.reply_text(
        f"Your mood information:\n{facts_to_str(user_data)}\nUntil next time!",
        reply_markup=ReplyKeyboardRemove()
    )
def cancel(update, context):
    update.message.reply_text('Bye! I hope we can talk again some day.',
                              reply_markup=ReplyKeyboardRemove())
    # update.message.reply_text(about_message, reply_markup=kb_markup)
    return ConversationHandler.END
Example #5
0
def close_keyboard(update, context):
    update.message.reply_text("Ok", reply_markup=ReplyKeyboardRemove())
Example #6
0
def enter_address_subscribe(update, context):
    chat_id = update.message.chat.id  #NOT NEEDED HERE
    user = update.message.from_user
    update.message.reply_text('Please enter your operator address.',
                              reply_markup=ReplyKeyboardRemove())
    return SUBSCRIBE
Example #7
0
def anketa_start_cal(bot, update):
    bot.message.reply_text('Как Вас зовут?',
                           reply_markup=ReplyKeyboardRemove())
    return 'user_name'
Example #8
0
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters
from telegram import ReplyKeyboardMarkup, ReplyKeyboardRemove
import logging
import yaml
import actions as action
from imset import load_imsets
from objectdict import ObjectDict

no_keyboard = ReplyKeyboardRemove()
action_keyboard = ReplyKeyboardMarkup([['/make', '/guess']], resize_keyboard=True)

with open('config.yaml') as f:
  config = yaml.load(f, Loader=yaml.FullLoader)
  config['keyboard'] = {
    'action': action_keyboard,
    'empty': no_keyboard
  }
  config = ObjectDict(config)
  load_imsets(config)
action.use_config(config)

updater = Updater(token=config.token, use_context=True)
dispatcher = updater.dispatcher

logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
                     level=logging.INFO)
action_dict = {
  'start': action.start,
  'help': action.help,
  'team': action.team,
  'name': action.name,
Example #9
0
def cancel(update, context):
    user = update.message.from_user
    update.message.reply_text('Bye! I hope we can talk again some day.',
                              reply_markup=ReplyKeyboardRemove())

    return ConversationHandler.END  # Это будет в самом конце
Example #10
0
def post_news(update, context):
    update.message.reply_text(text=final_msg,
                              reply_markup=ReplyKeyboardRemove())
    context.bot.forward_message(channel_id, update.message.chat_id, update.message.message_id,\
                                    disable_notification=False, timeout=None)
    return POST_NEWS
Example #11
0
    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,
            CONF_TIMEOUT: None,
        }
        if data is not None:
            if ATTR_PARSER in data:
                params[ATTR_PARSER] = self._parsers.get(
                    data[ATTR_PARSER], self._parse_mode
                )
            if CONF_TIMEOUT in data:
                params[CONF_TIMEOUT] = data[CONF_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]
            # 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
def cancel(update, context):
    user = update.message.from_user
    logger.info("User %s canceled the conversation.", user.first_name)
    update.message.reply_text('Bye!', reply_markup=ReplyKeyboardRemove())

    return ConversationHandler.END
Example #13
0
def message_new(update: Update, context: CallbackContext, text: str) -> int:
    update.message.reply_text(
        text + '\n\n<b>Step 1 of 3</b>\nSend the news in one message',
        parse_mode=ParseMode.HTML,
        reply_markup=ReplyKeyboardRemove())
    return NEWS
Example #14
0
def send_data(data,
              update,
              is_song=False,
              is_converted=False,
              keyboard=None,
              easy_key=None,
              file_index=None):
    # יוצר את המקלדת כל פעם מחדש, כי הערך של "גרסה קלה" צריך להיות ב callback_data.
    if keyboard is None:
        # אם לא ביקשו מקלדת ספציפית, יוצר את המקלדת הרגילה עם הערכים של מספר השיר והגרסה קלה שלו.
        keyboard = default_keyboard(file_index, easy_key)

    # רשימה ריקה לתוכה תיכנס ההודעה, חתוכה לפי הגודל של הודעה מקסימלית ע"פ טלגרם (עד 4096 תווים להודעה).
    song = [""]

    # מונה - לכמה חלקים התחלקה ההודעה.
    counter = 0

    # עובר על השיר שורה שורה, מוסיף כל פעם את השורה עד שהגודל חורג, ואז פותח חלק שני.
    for line in data:

        # שומר את השורה הנוכחית יחד עם השורות שנשמרו כבר בחתיכה הנוכחית של song לתוך test כדי לבדוק אם אחרי ההוספה הגודל יחרוג.
        test = f"{song[counter]}%0A{line}{data[-1]}"

        # אם אחרי ההוספה הגודל חורג מ4096 בתים..
        if len(test) >= 4096:
            # מקדם את המונה ב1 כי מוסיפים חלק לשיר.
            counter += 1
            # פותח חתיכה חדשה ב song עבור המשך השיר.
            song.append("")

        # אחרי שנבדק לאיזו חתיכה צריכה להיכנס השורה הנוכחית, מוסיפים את השורה ל song[counter] (זו החתיכה המתאימה).
        if is_song:
            # אם מדובר בשיר, צריך להוסיף "אנטר" בין שורה לשורה.
            song[counter] += f"\n{line}"
        else:
            # אם לא מדובר בשיר, פשוט מוסיפים את השורה כמו שהיא.
            song[counter] += f"{line}"

    # עובר חתיכה חתיכה ושולח למשתמש.
    for part in song:
        # אם זו ההודעה האחרונה, מוסיף את המקלדת.
        if part == song[-1]:
            reply_markup = keyboard

        else:
            # אם זו לא ההודעה האחרונה, מסיר את המקלדת.
            reply_markup = ReplyKeyboardRemove()

        # ה -  ID של קבוצה תמיד יהיה במינוס.
        if get_message_chat_id(update) < 0:
            # אם זו הודעה בקבוצה, מסיר את המקלדת.
            reply_markup = ReplyKeyboardRemove()

        # שולח את ההודעה המסודרת למשתמש.
        bot.sendMessage(chat_id=get_message_chat_id(update),
                        text=part.replace(u'\xa0', u' '),
                        reply_markup=reply_markup)

    # סמיילי יד מצביע על ההודעה הראשונה כדי לדפדף אליה בקלות.
    # אם מדובר בהמרה, צריך לרדת עוד הודעה אחת למטה (ההודעה שהומרה, הודעת האצבע שלה, ואז ההודעה שנשלחה עכשיו).
    bot.sendMessage(chat_id=get_message_chat_id(update),
                    text=u'\u261d',
                    reply_to_message_id=get_message_id(update) + 1 +
                    int(is_converted))
Example #15
0
 def remove_button(self):
     return ReplyKeyboardRemove()
Example #16
0
def other(update, context):
    update.message.reply_text(
        'I see! Please send me a photo of yourself, '
        'so I know what you look like, or send /skip if you don\'t want to.',
        reply_markup=ReplyKeyboardRemove())
Example #17
0
def remove_keyboard(bot: Bot, update: Update):
    chat = update.effective_chat.id
    text = "Removing keyboards..."
    msg = bot.send_message(chat, text, reply_markup=ReplyKeyboardRemove(selective=False))
    msg.delete()
    bot.send_message(chat, "Done!")
Example #18
0
def test(update, context):
    update.message.reply_text('Keyboard', reply_markup=ReplyKeyboardRemove())
Example #19
0
def enter_address_remove(update, context):
    user = update.message.from_user
    update.message.reply_text('Please enter your operator address.',
                              reply_markup=ReplyKeyboardRemove())
    return REMOVE
Example #20
0
def list_framework(update, context):
    ReplyKeyboardRemove()
    update.message.reply_text('List them with comma(,) seperated.')

    return FRAMEWORK
Example #21
0
 def __button_help_handler(self, update: Update, context: CallbackContext):
     update.message.reply_text(
         text="Помощь",
         reply_markup=ReplyKeyboardRemove(),
     )
Example #22
0
def deleteKeyboard(bot, update):
    update.message.reply_text('deleted', reply_markup=ReplyKeyboardRemove())
Example #23
0
reply_keyboard = [['Sign up', 'Log in', 'Cancel']]
reply_keyboard_tryagain = [['Try again', 'Cancel']]
reply_keyboard_gender = [['Male', 'Female', 'Other'], ['Cancel Sign up']]
reply_keyboard_cancel_signup = [['Cancel Sign up']]
reply_keyboard_cancel = [['Cancel']]
reply_keyboard_logged = [["Show votings in which I'm registered to vote"],
                         ['Show all votings', 'Register in a census'],
                         ['Access to a voting', 'Log out']]
markup = ReplyKeyboardMarkup(reply_keyboard)
markup_tryagain = ReplyKeyboardMarkup(reply_keyboard_tryagain)
markup_gender = ReplyKeyboardMarkup(reply_keyboard_gender)
markup_cancel_signup = ReplyKeyboardMarkup(reply_keyboard_cancel_signup)
markup_cancel = ReplyKeyboardMarkup(reply_keyboard_cancel)
markup_logged = ReplyKeyboardMarkup(reply_keyboard_logged)
markup_quit = ReplyKeyboardRemove()

CHOOSING_NOT_LOGGED, CHOOSING_LOGGED, OPTION_VOTED, TYPING_USERNAME, TYPING_PASSWORD, TYPING_VOTING_ID, TYPING_USERNAME_SIGNUP, TYPING_PASSWORD_SINGUP, TYPING_CONFIRMATION_PASSWORD_SINGUP, TYPING_BIRTHDATE_SIGNUP, TYPING_GENDER_SINGUP, TYPING_VOTING_ID_CENSUS = range(
    12)


def start(bot, update):
    """Send welcome messages when the command /start is issued."""
    update.message.reply_text('Welcome!')
    update.message.reply_text(
        "I'm DecideLocasteBoothBot, the Telegram virtual booth assistant for Decide Locaste"
    )
    update.message.reply_text(
        "First of all, you need to sign up or to log in with your Decide Locaste credentials in order to access your votings",
        reply_markup=markup)
def MakeSure(update, context):
    user = update.message.from_user
    txt = "Now Please Send Your Picture , the better way is to send it as file "
    logger.info(" %s is  %s ,sure", user.first_name, update.message.text)
    update.message.reply_text(txt, reply_markup=ReplyKeyboardRemove())
    return PHOTO_RECIVING
Example #25
0
        InlineKeyboardButton('100 🐌', callback_data='altdown:100'),  # change alternative download speed
        InlineKeyboardButton('200 🐌', callback_data='altdown:200'),  # change alternative download speed
    ],
    [
        InlineKeyboardButton('✅🕑', callback_data='quick:schedon'),
        InlineKeyboardButton('❌🕑', callback_data='quick:schedoff'),
        InlineKeyboardButton('🔄 %', callback_data='quick:refresh:percentage'),
        InlineKeyboardButton('🔄 kb/s', callback_data='quick:refresh:dlspeed'),
    ]
])

SPEEDCAP_MENU = InlineKeyboardMarkup([[InlineKeyboardButton('toggle', callback_data='togglespeedcap')]])

REFRESH_ACTIVE = InlineKeyboardMarkup([[InlineKeyboardButton('refresh', callback_data='refreshactive')]])

REMOVE = ReplyKeyboardRemove()


def sort_markup(qbfilter, exclude_key='', row_width=2):
    markup = []
    sorting_keys_new = [e for e in SORTING_KEYS if e != exclude_key]
    for i in range(0, len(sorting_keys_new), row_width):
        row_keys = sorting_keys_new[i:i + row_width]
        row = [InlineKeyboardButton(row_key, callback_data='sort:{}:{}'.format(qbfilter, row_key)) for row_key in row_keys]
        markup.append(row)

    return InlineKeyboardMarkup(markup)


def actions_markup(torrent_hash):
    markup = [
Example #26
0
def cancel(bot, update):
    update.message.reply_text("Ладненько", reply_markup=ReplyKeyboardRemove())
    return ConversationHandler.END
Example #27
0
def end(bot, update):
    update.message.reply_text(text='conversation end.',
                              reply_markup=ReplyKeyboardRemove())

    return ConversationHandler.END
Example #28
0
def button2_handler(update: Update, context: CallbackContext):
    update.message.reply_text(
        text='Button two',
        reply_markup=ReplyKeyboardRemove(),
    )
Example #29
0
def cancel(update, context):
    update.message.reply_message("Bye! I hope we can talk again some day.",
                                 reply_markup=ReplyKeyboardRemove())

    return ConversationHandler.END
Example #30
0
def question(update, context):
    user = update.message.from_user
    cur_progress = db.search(query.id == user.id)[0]['progress']
    day = db.search(query.id == user.id)[0]['day']
    #Checking answer to the past question
    if cur_progress > 0:
        # wrong_ans=0
        # if users[user.id].get_progress() > 0:
        past_task = common_data['day_' + str(day)]['questions'][0]['group'][
            cur_progress - 1]['question']
        # past_task = common_data['day_'+str(day)]['questions'][0]['group'][users[user.id].get_progress()-1]['question']
        if past_task['type'] == 'buttons' or past_task['type'] == 'manual':
            if update.message.text.lower() in [
                    x.lower() for x in past_task['corr_answer']
            ]:
                update.message.reply_text(CORRECT[randrange(len(CORRECT))])
                db.update(
                    {'score': db.search(query.id == user.id)[0]['score'] + 1},
                    query.id == user.id)
                db.update({'wrong_ans': 0}, query.id == user.id)
            else:
                update.message.reply_text(INCORRECT[randrange(len(INCORRECT))])
                cur_progress -= 1
                db.update(
                    {
                        'wrong_ans':
                        db.search(query.id == user.id)[0]['wrong_ans'] + 1
                    }, query.id == user.id)
                # wrong_ans+=1
                if db.search(query.id == user.id)[0]['wrong_ans'] == 2:
                    update.message.reply_text(
                        'Correct answers are below.',
                        reply_markup=ReplyKeyboardMarkup(
                            list_to_matrix(past_task['corr_answer']),
                            one_time_keyboard=False,
                            resize_keyboard=True))
                    db.update({'wrong_ans': 0}, query.id == user.id)
                    # wrong_ans = 0
                return QUESTION
        elif past_task['type'] == 'number':
            tmp = ''
            for i in update.message.text:
                if i.isdigit():
                    tmp += i
            if tmp in past_task['corr_answer']:
                update.message.reply_text(CORRECT[randrange(len(CORRECT))])
                db.update(
                    {'score': db.search(query.id == user.id)[0]['score'] + 1},
                    query.id == user.id)
                db.update({'wrong_ans': 0}, query.id == user.id)
            else:
                update.message.reply_text(INCORRECT[randrange(len(INCORRECT))])
                cur_progress -= 1
                # wrong_ans+=1
                db.update(
                    {
                        'wrong_ans':
                        db.search(query.id == user.id)[0]['wrong_ans'] + 1
                    }, query.id == user.id)
                if db.search(query.id == user.id)[0]['wrong_ans'] == 2:
                    update.message.reply_text(
                        'Correct answers are below.',
                        reply_markup=ReplyKeyboardMarkup(
                            list_to_matrix(past_task['corr_answer']),
                            one_time_keyboard=False,
                            resize_keyboard=True,
                        ))
                return QUESTION
        elif past_task['type'] == 'user':
            context.bot.forward_message(chat_id=ADMIN_ID,
                                        from_chat_id=user.id,
                                        message_id=update.message.message_id)

    if cur_progress < len(
            common_data['day_' + str(day)]['questions'][0]['group']):
        # if users[user.id].progress < len(common_data['day_'+str(day)]['questions'][0]['group']):
        task = common_data[
            'day_' +
            str(day)]['questions'][0]['group'][cur_progress]['question']
        # task = common_data['day_'+str(day)]['questions'][0]['group'][users[user.id].get_progress()]['question']

        # if cur_progress < len(common_data['day_'+str(day)]['questions'][0]['group']):
        # if users[user.id].progress < len(common_data['day_'+str(day)]['questions'][0]['group']):

        #Asking new question
        if task['type'] == 'buttons':
            if 'meta' in task:
                if task['meta']['type'] == 'image':
                    update.message.reply_photo(
                        photo=open('./images/' + task['meta']['path'], 'rb'),
                        caption=task['value'],
                        reply_markup=ReplyKeyboardMarkup(
                            list_to_matrix(task['variations']),
                            resize_keyboard=True,
                            one_time_keyboard=False))
                elif task['meta']['type'] == 'audio':
                    update.message.reply_audio(
                        audio=open('./audio/' + task['meta']['path'], 'rb'),
                        caption=task['value'],
                        reply_markup=ReplyKeyboardMarkup(
                            list_to_matrix(task['variations']),
                            resize_keyboard=True,
                            one_time_keyboard=False))
            else:
                # reply_keyboard = task['variations']
                update.message.reply_text(task['value'],
                                          reply_markup=ReplyKeyboardMarkup(
                                              list_to_matrix(
                                                  task['variations']),
                                              resize_keyboard=True,
                                              one_time_keyboard=False))
        elif task['type'] == 'manual' or task['type'] == 'user' or task[
                'type'] == 'info' or task['type'] == 'number':
            if 'meta' in task:
                if task['type'] == 'info':
                    if task['meta']['type'] == 'image':
                        update.message.reply_photo(
                            photo=open('./images/' + task['meta']['path'],
                                       'rb'),
                            caption=task['value'],
                            reply_markup=ReplyKeyboardMarkup(
                                [['Okay!']],
                                resize_keyboard=True,
                                one_time_keyboard=False))
                    elif task['meta']['type'] == 'audio':
                        update.message.reply_audio(
                            audio=open('./audio/' + task['meta']['path'],
                                       'rb'),
                            caption=task['value'],
                            reply_markup=ReplyKeyboardMarkup(
                                [['Okay!']],
                                resize_keyboard=True,
                                one_time_keyboard=False))
                    elif task['meta']['type'] == 'pdf':
                        update.message.reply_document(
                            document=open('./pdf/' + task['meta']['path'],
                                          'rb'),
                            caption=task['value'],
                            reply_markup=ReplyKeyboardMarkup(
                                [['Okay!']],
                                resize_keyboard=True,
                                one_time_keyboard=False))
                else:
                    if task['meta']['type'] == 'image':
                        update.message.reply_photo(photo=open(
                            './images/' + task['meta']['path'], 'rb'),
                                                   caption=task['value'])
                    elif task['meta']['type'] == 'audio':
                        update.message.reply_audio(audio=open(
                            './audio/' + task['meta']['path'], 'rb'),
                                                   caption=task['value'])
            else:
                if task['type'] == 'info':
                    update.message.reply_text(task['value'],
                                              reply_markup=ReplyKeyboardMarkup(
                                                  [['Okay!']],
                                                  resize_keyboard=True,
                                                  one_time_keyboard=False))
                else:
                    update.message.reply_text(
                        task['value'], reply_markup=ReplyKeyboardRemove())

    db.update({'progress': cur_progress + 1}, query.id == user.id)
    # users[user.id].inc_progress()

    if cur_progress == len(common_data['day_' +
                                       str(day)]['questions'][0]['group']):
        # if users[user.id].get_progress() == 1+len(common_data['day_'+str(day)]['questions'][0]['group']):
        db.update({'wrong_ans': 0}, query.id == user.id)
        update.message.reply_text(
            common_data['day_' + str(day)]['text']['outro'],
            reply_markup=ReplyKeyboardMarkup([['Bye!!']],
                                             resize_keyboard=True,
                                             one_time_keyboard=False))
        if day == 31:
            return ConversationHandler.END
        else:
            db.update({'day': day + 1}, query.id == user.id)
            db.update({'progress': 0}, query.id == user.id)
            return QUESTION
    else:
        return QUESTION