Esempio n. 1
0
def button_th(bot, update):
    query = update.callback_query
    if query.data == str(Languages.en.value):
        AnkiGenDB().update_language(query.message.chat_id, Languages.en)
        bot.editMessageText(text="Success! Language updated.",
                chat_id=query.message.chat_id,
                message_id=query.message.message_id)
        return
    elif query.data == str(Languages.es.value):
        AnkiGenDB().update_language(query.message.chat_id, Languages.es)
        bot.editMessageText(text="Success! Language updated.",
                chat_id=query.message.chat_id,
                message_id=query.message.message_id)
        return
    elif query.data == str(Languages.fr.value):
        AnkiGenDB().update_language(query.message.chat_id, Languages.fr)
        bot.editMessageText(text="Success! Language updated.",
                chat_id=query.message.chat_id,
                message_id=query.message.message_id)
        return
    try:
        if query.data != '-1':
            bot.editMessageText(text="{}\n*Uploading card to your anki deck*".format(query.message.text),
                    parse_mode='Markdown',
                    chat_id=query.message.chat_id,
                    message_id=query.message.message_id)
            try:
                db = AnkiGenDB()
                username, password, deck = db.get_data(query.message.chat_id)
                if username is None or password is None or deck is None:
                    bot.editMessageText(text="I can't send your data because I don't have your credentials or deck name",
                        chat_id=query.message.chat_id,
                        message_id=query.message.message_id)
                    return
                front = query.message.text
                back = query.data.lower()
                if db.is_order_reversed(query.message.chat_id) == 1: # Reverse
                    CardSender(username, password).send_card(back, front, deck)
                else: # Don't reverse
                    CardSender(username, password).send_card(front, back, deck)
            except Exception:
                bot.editMessageText(text="Could not connect to ankiweb. Is your username and password correct? Check if you can access https://ankiweb.net/ with your credentials",
                        chat_id=query.message.chat_id,
                        message_id=query.message.message_id)
                return
            bot.editMessageText(text="{}\n".format(query.message.text) + u"\u2705",
                    chat_id=query.message.chat_id,
                    message_id=query.message.message_id)
        else:
            bot.editMessageText(text=query.message.text + '\n' + u"\u274C",
                    chat_id=query.message.chat_id,
                    message_id=query.message.message_id)
    except:
        bot.editMessageText(text="Sorry, the message was too old",
                chat_id=query.message.chat_id,
                message_id=query.message.message_id)
Esempio n. 2
0
def button_th(bot, update):
    query = update.callback_query
    language_codes = [str(lang.value) for lang in dict_state_to_lang.values()]
    if query.data in language_codes:
        AnkiGenDB().update_language(query.message.chat_id, int(query.data))
        bot.editMessageText(text="Success! Language updated.",
                            chat_id=query.message.chat_id,
                            message_id=query.message.message_id)
        return
    if query.data[:4] == 'deck' and (query.data[4:] == '-1'
                                     or query.data[4:] in language_codes):
        if query.data[4:] == '-1':
            bot.editMessageText(text="No deck name was changed.",
                                chat_id=query.message.chat_id,
                                message_id=query.message.message_id)
            return
        state = None
        for st, lang in dict_state_to_lang.items():
            if str(lang.value) == query.data[4:]:
                state = st
                break
        AnkiGenDB().update_state(query.message.chat_id, state)
        bot.editMessageText(text="Send me the deck name for {}.".format(
            Languages(int(query.data[4:])).name),
                            chat_id=query.message.chat_id,
                            message_id=query.message.message_id)
        return
    try:
        if query.data != '-1':
            db = AnkiGenDB()
            spl = query.data.split('|', 1)[0]
            deck = None
            if spl in language_codes:
                deck = db.get_deck_name(query.message.chat_id, spl)
            if deck is None:
                deck = default_deck_name
            bot.editMessageText(
                text="{}\n*Uploading card to your anki deck*".format(
                    query.message.text),
                parse_mode='Markdown',
                chat_id=query.message.chat_id,
                message_id=query.message.message_id)
            try:
                username, password = db.get_data(query.message.chat_id)
                if username is None or password is None or deck is None:
                    bot.editMessageText(
                        text=
                        "I can't send your data because I don't have your credentials",
                        chat_id=query.message.chat_id,
                        message_id=query.message.message_id)
                    return
                front = query.message.text
                if '|' in query.data:
                    back = query.data.split('|', 1)[1]
                else:
                    back = query.data.lower()
                if db.get_if_add_phonetics(
                        query.message.chat_id) != 0 and db.get_language(
                            query.message.chat_id) == Languages.English.value:
                    ipa = to_ipa(back)
                    if ipa != back:  # ipa translation found
                        back = "{} /{}/".format(back, ipa)
                with lock_card_senders:
                    try:
                        card_sender = card_senders[query.message.chat_id]
                        card_sender.last_access = time.time()
                    except KeyError:
                        card_sender = CardSender(username, password)
                        card_senders[query.message.chat_id] = card_sender

                    Timer(delay, delete_card_sender,
                          [query.message.chat_id]).start()

                    if db.is_order_reversed(
                            query.message.chat_id) == 1:  # Reverse
                        card_sender.send_card(back, front, deck)
                    else:  # Don't reverse
                        card_sender.send_card(front, back, deck)
            except Exception:
                print(traceback.format_exc())
                bot.editMessageText(
                    text=
                    "Could not connect to ankiweb. Is your username and password correct? Check if you can access https://ankiweb.net/ with your credentials",
                    chat_id=query.message.chat_id,
                    message_id=query.message.message_id)
                return
            bot.editMessageText(text="{}\n{}".format(query.message.text,
                                                     u"\u2705"),
                                chat_id=query.message.chat_id,
                                message_id=query.message.message_id)
        else:
            bot.editMessageText(text="{}\n{}".format(query.message.text,
                                                     u"\u274C"),
                                chat_id=query.message.chat_id,
                                message_id=query.message.message_id)
    except TimedOut:
        bot.editMessageText(text="Telegram timed out, try again later.",
                            chat_id=query.message.chat_id,
                            message_id=query.message.message_id)
        print("Telegram timed out")
        print(traceback.format_exc())
    except:
        bot.editMessageText(text="Sorry, the message was too old",
                            chat_id=query.message.chat_id,
                            message_id=query.message.message_id)
        print("Sorry, the message was too old")
        print(traceback.format_exc())
        raise
Esempio n. 3
0
def button_th(bot, update):
    query = update.callback_query
    if query.data == str(Languages.en.value):
        AnkiGenDB().update_language(query.message.chat_id, Languages.en)
        bot.editMessageText(text="Success! Language updated.",
                            chat_id=query.message.chat_id,
                            message_id=query.message.message_id)
        return
    elif query.data == str(Languages.es.value):
        AnkiGenDB().update_language(query.message.chat_id, Languages.es)
        bot.editMessageText(text="Success! Language updated.",
                            chat_id=query.message.chat_id,
                            message_id=query.message.message_id)
        return
    elif query.data == str(Languages.fr.value):
        AnkiGenDB().update_language(query.message.chat_id, Languages.fr)
        bot.editMessageText(text="Success! Language updated.",
                            chat_id=query.message.chat_id,
                            message_id=query.message.message_id)
        return
    try:
        if query.data != '-1':
            bot.editMessageText(
                text="{}\n*Uploading card to your anki deck*".format(
                    query.message.text),
                parse_mode='Markdown',
                chat_id=query.message.chat_id,
                message_id=query.message.message_id)
            try:
                db = AnkiGenDB()
                username, password, deck = db.get_data(query.message.chat_id)
                if username is None or password is None or deck is None:
                    bot.editMessageText(
                        text=
                        "I can't send your data because I don't have your credentials or deck name",
                        chat_id=query.message.chat_id,
                        message_id=query.message.message_id)
                    return
                front = query.message.text
                back = query.data.lower()
                if db.get_if_add_phonetics(query.message.chat_id) != 0:
                    ipa = to_ipa(back)
                    if ipa != back:  # ipa translation found
                        back = "{} /{}/".format(back, ipa)
                with lock_card_senders:
                    try:
                        card_sender = card_senders[query.message.chat_id]
                        card_sender.last_access = time.time()
                    except KeyError:
                        card_sender = CardSender(username, password)
                        card_senders[query.message.chat_id] = card_sender

                    Timer(delay, delete_card_sender,
                          [query.message.chat_id]).start()

                    if db.is_order_reversed(
                            query.message.chat_id) == 1:  # Reverse
                        card_sender.send_card(back, front, deck)
                    else:  # Don't reverse
                        card_sender.send_card(front, back, deck)
            except Exception:
                print(traceback.format_exc())
                bot.editMessageText(
                    text=
                    "Could not connect to ankiweb. Is your username and password correct? Check if you can access https://ankiweb.net/ with your credentials",
                    chat_id=query.message.chat_id,
                    message_id=query.message.message_id)
                return
            bot.editMessageText(text="{}\n{}".format(query.message.text,
                                                     u"\u2705"),
                                chat_id=query.message.chat_id,
                                message_id=query.message.message_id)
        else:
            bot.editMessageText(text="{}\n{}".format(query.message.text,
                                                     u"\u274C"),
                                chat_id=query.message.chat_id,
                                message_id=query.message.message_id)
    except TimedOut:
        bot.editMessageText(text="Telegram timed out, try again later.",
                            chat_id=query.message.chat_id,
                            message_id=query.message.message_id)
        print("Telegram timed out")
        print(traceback.format_exc())
    except:
        bot.editMessageText(text="Sorry, the message was too old",
                            chat_id=query.message.chat_id,
                            message_id=query.message.message_id)
        print("Sorry, the message was too old")
        print(traceback.format_exc())
        raise
Esempio n. 4
0
def button_th(update, context):
    query = update.callback_query
    language_codes = [str(lang.value) for lang in dict_state_to_lang.values()]
    if query.data in language_codes:
        AnkiGenDB().update_language(query.message.chat_id, int(query.data))
        context.bot.editMessageText(text="Success! Language updated.",
                                    chat_id=query.message.chat_id,
                                    message_id=query.message.message_id)
        return
    if query.data[:4] == 'deck' and (query.data[4:] == '-1'
                                     or query.data[4:] in language_codes):
        if query.data[4:] == '-1':
            context.bot.editMessageText(text="No deck name was changed.",
                                        chat_id=query.message.chat_id,
                                        message_id=query.message.message_id)
            return
        state = None
        for st, lang in dict_state_to_lang.items():
            if str(lang.value) == query.data[4:]:
                state = st
                break
        AnkiGenDB().update_state(query.message.chat_id, state)
        context.bot.editMessageText(
            text="Send me the deck name for {}.".format(
                Languages(int(query.data[4:])).name),
            chat_id=query.message.chat_id,
            message_id=query.message.message_id)
        return
    if query.data[:5] == 'fromd' and (query.data[5:] == '-1'
                                      or query.data[5:] in language_codes):
        if query.data[5:] == '-1':
            context.bot.editMessageText(text="No changes were made.",
                                        chat_id=query.message.chat_id,
                                        message_id=query.message.message_id)
            return

        for st, lang in dict_state_to_lang_defi.items():
            if str(lang.value) == query.data[5:]:
                state = st
                break
        db = AnkiGenDB()
        db.update_state(query.message.chat_id, state)
        langs = sorted(list(dict_state_to_lang.values()),
                       key=lambda x: x.value)

        keyboard = [[
            InlineKeyboardButton("{}".format(lang.name),
                                 callback_data="tod{}".format(lang.value))
        ] for lang in langs if lang.value != int(query.data[5:])]
        if db.get_def_lang(query.message.chat_id, int(query.data[5:])):
            keyboard.append([
                InlineKeyboardButton('Disable {} translation'.format(
                    Languages(int(query.data[5:])).name),
                                     callback_data="tod{}".format(-2))
            ])
        keyboard.append(
            [InlineKeyboardButton('Cancel', callback_data="tod{}".format(-1))])

        context.bot.editMessageText(text='\nMake the definition for cards in {} be in another language B. Note the translation is automatic and can be innacurate sometimes\n*Now select language B*\nYou can press a button or write a valid language code from [this list](https://telegra.ph/Language-codes-07-26)'\
                                        .format(Languages(int(query.data[5:])).name),
                                    chat_id=query.message.chat_id,
                                    reply_markup=InlineKeyboardMarkup(keyboard),
                                    parse_mode='Markdown',
                                    message_id=query.message.message_id)
        return
    if query.data[:3] == 'tod' and (query.data[3:]
                                    in language_codes + ['-1', '-2']):
        db = AnkiGenDB()
        if query.data[3:] == '-1':
            context.bot.editMessageText(text="No changes were made.",
                                        chat_id=query.message.chat_id,
                                        message_id=query.message.message_id)
            AnkiGenDB().update_state(query.message.chat_id, State.normal)
            return

        state = State(db.get_state(query.message.chat_id))
        if state not in dict_state_to_lang_defi:
            return
        from_lang = dict_state_to_lang_defi[state]
        db.update_state(query.message.chat_id, State.normal)
        if query.data[3:] == '-2':
            AnkiGenDB().remove_def_lang(query.message.chat_id, from_lang)
            context.bot.editMessageText(
                text='Ok! I will not translate the definition of the {} cards.'
                .format(from_lang.name),
                chat_id=query.message.chat_id,
                message_id=query.message.message_id)
            return
        to_lang = int(query.data[3:])
        db.update_def_lang(
            query.message.chat_id, from_lang,
            language_translate_shell_codes[Languages(to_lang).name])
        context.bot.editMessageText(
            text='Ok! I will translate the definitions of {} cards into {}'.
            format(from_lang.name,
                   Languages(to_lang).name),
            chat_id=query.message.chat_id,
            message_id=query.message.message_id)
        return
    if query.data[:5] == 'fromw' and (query.data[5:] == '-1'
                                      or query.data[5:] in language_codes):
        if query.data[5:] == '-1':
            context.bot.editMessageText(text="No changes were made.",
                                        chat_id=query.message.chat_id,
                                        message_id=query.message.message_id)
            return

        for st, lang in dict_state_to_lang_word.items():
            if str(lang.value) == query.data[5:]:
                state = st
                break
        db = AnkiGenDB()
        db.update_state(query.message.chat_id, state)
        langs = sorted(list(dict_state_to_lang_word.values()),
                       key=lambda x: x.value)

        keyboard = [[
            InlineKeyboardButton("{}".format(lang.name),
                                 callback_data="tow{}".format(lang.value))
        ] for lang in langs if lang.value != int(query.data[5:])]

        if db.get_def_lang(query.message.chat_id, int(query.data[5:])):
            keyboard.append([
                InlineKeyboardButton('Disable {} translation'.format(
                    Languages(int(query.data[5:])).name),
                                     callback_data="tow{}".format(-2))
            ])
        keyboard.append(
            [InlineKeyboardButton('Cancel', callback_data="tow{}".format(-1))])
        context.bot.editMessageText(text='\nFor cards in {}, add a translation of the concept to the language you will now select. Note the translations are automatic and can be innacurate sometimes\n**Now select language B**' \
                                    .format(Languages(int(query.data[5:])).name),
                                    chat_id=query.message.chat_id,
                                    reply_markup=InlineKeyboardMarkup(keyboard),
                                    parse_mode='Markdown',
                                    message_id=query.message.message_id)
        return
    if query.data[:3] == 'tow' and (query.data[3:]
                                    in language_codes + ['-1', '-2']):
        db = AnkiGenDB()
        if query.data[3:] == '-1':
            context.bot.editMessageText(text="No changes were made.",
                                        chat_id=query.message.chat_id,
                                        message_id=query.message.message_id)
            AnkiGenDB().update_state(query.message.chat_id, State.normal)
            return

        state = State(db.get_state(query.message.chat_id))
        if state not in dict_state_to_lang_word:
            return
        from_lang = dict_state_to_lang_word[state]
        if query.data[3:] == '-2':
            AnkiGenDB().remove_word_lang(query.message.chat_id, from_lang)
            context.bot.editMessageText(
                text="Word translation has been disabled for {}".format(
                    from_lang.name),
                chat_id=query.message.chat_id,
                message_id=query.message.message_id)
            return
        to_lang = int(query.data[3:])
        db.update_word_lang(
            query.message.chat_id, from_lang,
            language_translate_shell_codes[Languages(to_lang).name])
        context.bot.editMessageText(text='Ok! Cards for {} words will be translated into {} and you will be asked whether you want to add a translation into the card.' \
                                    .format(from_lang.name, Languages(to_lang).name),
                                    chat_id=query.message.chat_id,
                                    message_id=query.message.message_id)
        return
    if query.data[:4] == 'tags' and (query.data[4:] == '-1'
                                     or query.data[4:] in language_codes):
        if query.data[4:] == '-1':
            context.bot.editMessageText(text="No tags were changed.",
                                        chat_id=query.message.chat_id,
                                        message_id=query.message.message_id)
            return
        state = None
        for st, lang in dict_state_to_lang_tags.items():
            if str(lang.value) == query.data[4:]:
                state = st
                break
        AnkiGenDB().update_state(query.message.chat_id, state)
        context.bot.editMessageText(
            text=
            "Send me the tags for {} (words separated by spaces). Or send /tags again to delete all tags for this language."
            .format(Languages(int(query.data[4:])).name),
            chat_id=query.message.chat_id,
            message_id=query.message.message_id)
        return
    try:
        if query.data != '-1':
            db = AnkiGenDB()
            spl = query.data.split('|', 1)[0]
            deck = None
            if spl in language_codes:
                deck = db.get_deck_name(query.message.chat_id, spl)
                tags = db.get_tags(query.message.chat_id, spl)
            if deck is None:
                context.bot.editMessageText(
                    text=
                    "You need to specify the name of an existing deck with /deck"
                    .format(query.message.text),
                    parse_mode='Markdown',
                    chat_id=query.message.chat_id,
                    message_id=query.message.message_id)
                return
            try:
                username, password, card_type = db.get_data(
                    query.message.chat_id)
                if username is None or password is None or deck is None:
                    context.bot.editMessageText(
                        text=
                        "I can't send your data because I don't have your credentials",
                        chat_id=query.message.chat_id,
                        message_id=query.message.message_id)
                    return
                front = query.message.text
                display_front = front
                if '|' in query.data:
                    data = query.data.split('|', 2)
                    back = data[1]
                    if len(data) > 2:
                        display_front = "{}\n{}".format(
                            query.message.reply_markup.inline_keyboard[int(
                                data[2])][0].text, front)
                        front = "{}\n\n{}".format(
                            query.message.reply_markup.inline_keyboard[int(
                                data[2])][0].text, front)

                        #if front[0] == '(':
                        #    idx = front.find(')')
                        #    front = '{} ({}){}'.format(front[: idx+ 1 ], query.message.reply_markup.inline_keyboard[int(data[2])][0].text, front[idx + 1: ] )
                        #else:
                        #    front = "({}) {}".format(query.message.reply_markup.inline_keyboard[int(data[2])][0].text, front)
                else:
                    back = query.data.lower()
                if db.get_if_add_phonetics(
                        query.message.chat_id) != 0 and db.get_language(
                            query.message.chat_id) == Languages.English.value:
                    ipa = to_ipa(back)
                    if ipa != back:  # ipa translation found
                        back = "{} /{}/".format(back, ipa)

                if db.is_order_reversed(
                        query.message.chat_id) == 1:  # Reverse if we have to
                    front, back = back, front
                    display_front, back = back, display_front
                context.bot.editMessageText(
                    text="{}\n---\n{}\n*Uploading card to your anki deck*".
                    format(display_front, back),
                    parse_mode='Markdown',
                    chat_id=query.message.chat_id,
                    message_id=query.message.message_id)
                with lock_card_senders:
                    try:
                        card_sender = card_senders[query.message.chat_id]
                        card_sender.last_access = time.time()
                    except KeyError:
                        card_sender = CardSender(username, password, card_type)
                        card_senders[query.message.chat_id] = card_sender

                    Timer(delay, delete_card_sender,
                          [query.message.chat_id]).start()

                    ret = card_sender.send_card(front, back, deck, tags)
                    if ret:
                        context.bot.sendMessage(query.message.chat_id,
                                                text=escape_markdown(ret),
                                                parse_mode='Markdown')
            except NoDeckFoundError as e:
                print(traceback.format_exc())
                context.bot.editMessageText(
                    text=
                    "Could not find the deck \"{}\". Check it exists or use /deck to change the name of the deck I should use for this language"
                    .format(e.deck),
                    chat_id=query.message.chat_id,
                    message_id=query.message.message_id)
                return
            except Exception:
                print(traceback.format_exc())
                context.bot.editMessageText(
                    text=
                    "Could not connect to ankiweb. Is your username and password correct? Check if you can access https://ankiweb.net/ with your credentials",
                    chat_id=query.message.chat_id,
                    message_id=query.message.message_id)
                return
            context.bot.editMessageText(text="{}\n---\n{}\n{}".format(
                display_front, back, u"\u2705"),
                                        chat_id=query.message.chat_id,
                                        message_id=query.message.message_id)
        else:
            context.bot.editMessageText(text="{}\n{}".format(
                query.message.text, u"\u274C"),
                                        chat_id=query.message.chat_id,
                                        message_id=query.message.message_id)
    except TimedOut:
        context.bot.editMessageText(
            text="Telegram timed out, try again later.",
            chat_id=query.message.chat_id,
            message_id=query.message.message_id)
        print("Telegram timed out")
        print(traceback.format_exc())
    except:
        context.bot.editMessageText(text="Sorry, the message was too old",
                                    chat_id=query.message.chat_id,
                                    message_id=query.message.message_id)
        print("Sorry, the message was too old")
        print(traceback.format_exc())
        raise