예제 #1
0
def include_word_translation(update, context):
    word_langs = AnkiGenDB().get_all_word_langs(update.message.chat_id)
    word_langs_text = ''
    if word_langs:
        current_settings = [
            '\n- *{}*: {}'.format(
                Languages(language).name,
                supported_language_codes.get(word_lang, ""))
            for (word_lang, language) in word_langs if word_lang
        ]
        word_langs_text = '\n\nCurrent settings are:{}'.format(
            ''.join(current_settings
                    ) if current_settings else "") if current_settings else ""

    langs = sorted(list(dict_state_to_lang.values()), key=lambda x: x.value)
    keyboard = [[
        InlineKeyboardButton("{}".format(lang.name),
                             callback_data="fromw{}".format(lang.value))
    ] for lang in langs]
    keyboard.append(
        [InlineKeyboardButton('Cancel', callback_data="fromw{}".format(-1))])
    reply_markup = InlineKeyboardMarkup(keyboard)
    update.message.reply_text(
        'Make me include with the card of a word in language A, the translation of the word in language B. Every time, you will pick which translation you want to use.\n*Select language A*{}'
        .format(word_langs_text),
        reply_markup=reply_markup,
        parse_mode='Markdown')
예제 #2
0
def definition_language(update, context):
    def_langs = AnkiGenDB().get_all_def_langs(update.message.chat_id)
    def_langs_text = ''
    if def_langs:
        current_settings = [
            '\n- *{}*: {}'.format(
                Languages(language).name,
                supported_language_codes.get(def_lang, ""))
            for (def_lang, language) in def_langs if def_lang
        ]
        def_langs_text = '\n\nCurrent settings are:{}'.format(
            ''.join(current_settings
                    ) if current_settings else "") if current_settings else ""

    langs = sorted(list(dict_state_to_lang.values()), key=lambda x: x.value)
    keyboard = [[
        InlineKeyboardButton("{}".format(lang.name),
                             callback_data="fromd{}".format(lang.value))
    ] for lang in langs]
    keyboard.append(
        [InlineKeyboardButton('Cancel', callback_data="fromd{}".format(-1))])
    reply_markup = InlineKeyboardMarkup(keyboard)
    update.message.reply_text(
        'Make the definition of a word in language A be in another language B. Note the translation is automatic and can be innacurate.\n*Select language A*{}'
        .format(def_langs_text),
        reply_markup=reply_markup,
        parse_mode='Markdown')
예제 #3
0
def tags(update, context):
    db = AnkiGenDB()
    state = State(db.get_state(update.message.chat_id))
    if state in dict_state_to_lang_tags:
        db.update_tags(update.message.chat_id,
                       tags="",
                       lang=dict_state_to_lang_tags[state])
        update.message.reply_text("Ok! I deleted all the tags for {}.".format(
            dict_state_to_lang_tags[state].name),
                                  parse_mode='Markdown')
    else:
        langs = sorted(list(dict_state_to_lang.values()),
                       key=lambda x: x.value)
        keyboard = [[
            InlineKeyboardButton(lang.name,
                                 callback_data="tags{}".format(lang.value))
        ] for lang in langs]
        keyboard.append([
            InlineKeyboardButton('Cancel', callback_data="tags{}".format(-1))
        ])
        reply_markup = InlineKeyboardMarkup(keyboard)

        tags = db.get_all_tags(update.message.chat_id)
        if tags is None:
            tags = ''
        else:
            tags = '\nCurrent tags are:\n' + \
                         ''.join(['\n- *{}*: {}'.format(Languages(language).name, escape_markdown(lang_tags) if tags else "") for lang_tags, language in tags])
        text = 'Select a language to set tags for that language.{}'.format(
            tags)
        update.message.reply_text(text,
                                  reply_markup=reply_markup,
                                  parse_mode='Markdown')
예제 #4
0
def deck(update, context):
    langs = sorted(list(dict_state_to_lang.values()), key=lambda x: x.value)
    keyboard = [[
        InlineKeyboardButton(lang.name,
                             callback_data="deck{}".format(lang.value))
    ] for lang in langs]
    keyboard.append(
        [InlineKeyboardButton('Cancel', callback_data="deck{}".format(-1))])
    reply_markup = InlineKeyboardMarkup(keyboard)

    deck_names = AnkiGenDB().get_all_deck_names(update.message.chat_id)
    if deck_names is None:
        deck_names = ''
    else:
        deck_names = '\nCurrent deck names are:\n' + ''.join([
            '\n- *{}*: {}'.format(
                Languages(language).name,
                escape_markdown(deck_name) if deck_name else "")
            for deck_name, language in deck_names
        ])
    text = 'Select a language to set a deck name for that language.{}'.format(
        deck_names)
    update.message.reply_text(text,
                              reply_markup=reply_markup,
                              parse_mode='Markdown')
예제 #5
0
def language(bot, update):
    langs = sorted(list(dict_state_to_lang.values()), key=lambda x: x.value)
    keyboard = [[
        InlineKeyboardButton(lang.name, callback_data="{}".format(lang.value))
    ] for lang in langs]
    reply_markup = InlineKeyboardMarkup(keyboard)
    lang = AnkiGenDB().get_language(update.message.chat_id)
    reminder_interface = '\nYou can always use /en /es /fr /de or /it before a word for words in a language that is not the default one. Examples:\n/es amigo\n/en friend'
    update.message.reply_text(
        'Pick a new default language. Current is *{}*.{}'.format(
            Languages(lang).name, reminder_interface),
        reply_markup=reply_markup,
        parse_mode='Markdown')
예제 #6
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
예제 #7
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