Commit c84e31bf authored by n0toose's avatar n0toose
Browse files

Merge branch 'refactor-dialogue' into 'main'

Refactor dialogue.py

See merge request !27
parents 1f019804 1ef2bf5a
Loading
Loading
Loading
Loading
+59 −19
Original line number Diff line number Diff line
@@ -107,17 +107,19 @@ async def send_language_menu(client: Client, chat_id: int, user_lang: str):
        await client.send_photo(
            chat_id=chat_id,
            photo=data["bot"]["language_photo"],
            caption=_(
                "<strong>Language selection</strong>\n\n" "Please select your language:"
            ),
            caption="<b>"
            + _("Language selection")
            + "</b>\n\n"
            + _("Please select your language:"),
            reply_markup=lang_markup,
        )
    except (WebpageCurlFailed, KeyError):
        await client.send_message(
            chat_id=chat_id,
            text=_(
                "<strong>Language selection</strong>\n\n" "Please select your language:"
            ),
            text="<b>"
            + _("Language selection")
            + "</b>\n\n"
            + _("Please select your language:"),
            reply_markup=lang_markup,
        )

@@ -158,37 +160,64 @@ async def send_welcome_message(client: Client, user_id: int, lang: str):

    await client.send_message(
        chat_id=user_id,
        text=_(
            "<strong>Welcome!</strong>\n\n"
            "Hi, welcome to {name}! "
            "What do you want me to do?"
        ).format(name=bot_name),
        text="<b>"
        + _("Welcome!")
        + "</b>\n\n"
        + _("Hi, welcome to {name}! ").format(name=bot_name)
        + _("What do you want me to do?"),
        reply_markup=InlineKeyboardMarkup(
            [
                [
                    InlineKeyboardButton(
                        _("Send me the Tor Browser"), "request_tor:" + lang
                    )
                ],
                [InlineKeyboardButton(change_lang_button_label, "change_lang:" + lang)],
                [InlineKeyboardButton(_("More..."), "send_faq:" + lang)],
            ]
        ),
    )


@Bot.on_callback_query(filters.regex("^send_faq:[^:]+$"))
async def send_faq(client: Client, callback: CallbackQuery):
    callback_data = callback.data.split(":")
    lang = callback_data[-1]
    _ = i18n.get_translation(lang)

    await client.send_message(
        chat_id=callback.from_user.id,
        text="<b>" + _("Questions") + "</b>\n\n" + _("What do you want to know?"),
        reply_markup=InlineKeyboardMarkup(
            [
                [
                    InlineKeyboardButton(
                        _("Send me Tor Browser through Telegram"), "request_tor:" + lang
                        _("Send me other mirrors for the Tor Browser"),
                        "request_tor_mirrors:" + lang,
                    )
                ],
                [
                    InlineKeyboardButton(
                        change_lang_button_label, "change_lang:" + lang
                        _("Send me Tor bridges."),
                        "request_tor_bridges:" + lang,
                    )
                ],
                [
                    InlineKeyboardButton(
                        _("Send me other mirrors for the Tor Browser"),
                        "request_tor_mirrors:" + lang,
                        _("Explain what Tor bridges are."),
                        "explain_bridges:" + lang,
                    )
                ],
                [
                    InlineKeyboardButton(
                        _("I want Tor bridges"), "request_tor_bridges:" + lang
                        _("Explain what Tor is."),
                        "explain_tor:" + lang
                    )
                ],
                [
                    InlineKeyboardButton(
                        _("Explain what Tor is"), "explain_tor:" + lang
                        _("I have other questions."),
                        "request_support:" + lang
                    )
                ],
            ]
@@ -230,7 +259,9 @@ async def request_tor(client: Client, callback: CallbackQuery):

    await client.send_message(
        callback.from_user.id,
        text=_("<strong>Download Tor from Telegram</strong>\n\n")
        text="<b>"
        + _("Download Tor from Telegram")
        + "</b>\n\n"
        + _("Which operating system are you using?"),
        reply_markup=platform_markup,
    )
@@ -367,8 +398,17 @@ Bot.on_callback_query(filters.regex("^request_tor_bridges:[^:]+$"))(
    dialogue.send_bridges
)

Bot.on_callback_query(filters.regex("^explain_tor:[^:]+$"))(dialogue.explain_tor)
Bot.on_callback_query(filters.regex("^explain_tor:[^:]+$"))(
    dialogue.explain_tor
)

Bot.on_callback_query(filters.regex("^explain_bridges:[^:]+$"))(
    dialogue.explain_bridges
)

Bot.on_callback_query(filters.regex("^request_support:[^:]+$"))(
    dialogue.send_support
)

async def main():
    global conn, curs, response
+15 −11
Original line number Diff line number Diff line
@@ -13,36 +13,40 @@ import aiosqlite


async def search_file_in_db(cursor: aiosqlite.Cursor, filename: str):
    return await (await cursor.execute(
        '''SELECT binary, binary_id, sig, sig_id FROM tor_releases WHERE (
    return await (
        await cursor.execute(
            """SELECT binary, binary_id, sig, sig_id FROM tor_releases WHERE (
             binary = ?
        );''',
        (filename,)
    )).fetchone()
        );""",
            (filename,),
        )
    ).fetchone()


async def create_empty_db(cursor: aiosqlite.Cursor, connection: aiosqlite.Connection):
    await cursor.execute(
        '''CREATE TABLE IF NOT EXISTS tor_releases (
        """CREATE TABLE IF NOT EXISTS tor_releases (
            binary TEXT, binary_id INTEGER, sig TEXT, sig_id INTEGER,
            UNIQUE(binary, binary_id, sig, sig_id)
        );'''
        );"""
    )

    return await connection.commit()


async def insert_new_release(
    cursor: aiosqlite.Cursor,
    connection: aiosqlite.Connection,
    name1: str,
    id1: int,
    name2: str,
    id2: int
    id2: int,
):
    await cursor.execute(
        '''INSERT INTO tor_releases VALUES (
        """INSERT INTO tor_releases VALUES (
             ?, ?, ?, ?
        );''',
        (name1, id1, name2, id2)
        );""",
        (name1, id1, name2, id2),
    )

    return await connection.commit()
+142 −20
Original line number Diff line number Diff line
@@ -26,7 +26,7 @@ async def send_mirrors(client: Client, callback: CallbackQuery):

    await client.send_message(
        chat_id=callback.from_user.id,
        text="<strong>" + _("Tor Browser Mirrors") + "</strong>\n\n"
        text="<b>" + _("Tor Browser Mirrors") + "</b>\n\n"
        "- EFF: https://tor.eff.org\n"
        "- Calyx Institute: https://tor.calyxinstitute.org\n"
        "- GitHub: https://github.com/torproject/torbrowser-releases/releases/\n"
@@ -36,7 +36,18 @@ async def send_mirrors(client: Client, callback: CallbackQuery):
        + _("(Make sure that your email provider is safe!)")
        + "\n",
        reply_markup=InlineKeyboardMarkup(
            [[InlineKeyboardButton(_("Main Menu"), "welcome:" + lang)]]
            [
                [
                    InlineKeyboardButton(
                        text=_("Go Back"), callback_data="send_faq:" + lang
                    )
                ],
                [
                    InlineKeyboardButton(
                        text=_("Main Menu"), callback_data="welcome:" + lang
                    )
                ],
            ]
        ),
    )

@@ -48,22 +59,36 @@ async def send_bridges(client: Client, callback: CallbackQuery):
    callback_data = callback.data.split(":")
    lang = callback_data[-1]
    _ = i18n.get_translation(lang)
    bridge_username = "@getbridgesbot"

    await client.send_message(
        chat_id=callback.from_user.id,
        text=_(
            "<strong>Tor Bridges</strong>\n\n"
            "Tor bridges are computers that can be very helpful when "
            "your internet provider has blocked you from using Tor, "
            "or if you just want to hide the fact that you are using Tor "
            "from anyone that could be monitoring your internet connection. "
            "That could be your internet provider, government, household "
            "members, school, workplace, among others.\n\n"
            "You can request a bridge from @getbridgesbot, but you should "
            "also configure the Tor Browser to use it."
        ),
        text="<b>"
        + _("Tor Bridges")
        + "</b>\n\n"
        + _("You can request a bridge from {username}. Please keep in mind "
            "that you will also have to configure the Tor Browser accordingly "
            "in order to use it."
        ).format(username=bridge_username),
        reply_markup=InlineKeyboardMarkup(
            [[InlineKeyboardButton(_("Main Menu"), "welcome:" + lang)]]
            [
                [
                    InlineKeyboardButton(
                        text=_("Wait, what are Tor bridges?"),
                        callback_data="explain_bridges:" + lang,
                    )
                ],
                [
                    InlineKeyboardButton(
                        text=_("Go Back"), callback_data="send_faq:" + lang
                    )
                ],
                [
                    InlineKeyboardButton(
                        text=_("Main Menu"), callback_data="welcome:" + lang
                    )
                ],
            ],
        ),
    )

@@ -78,17 +103,114 @@ async def explain_tor(client: Client, callback: CallbackQuery):

    await client.send_message(
        chat_id=callback.from_user.id,
        text=_(
            "<strong>What is Tor?</strong>\n\n"
            "Tor is a network that lets you anonymously connect to the Internet, "
        text="<b>"
        + _("What is Tor?")
        + "</b>\n\n"
        + _("Tor is a network that lets you anonymously connect to the Internet, "
            "while evading censorship, people monitoring of your Internet connection "
            "and ad tracking.\n\n"
            "The network is peer-to-peer and largely supported by volunteers, as "
            "and ad tracking."
        )
        + "\n\n"
        + _("The network is peer-to-peer and largely supported by volunteers, as "
            "well as The Tor Project Inc., a non-profit organization based "
            "in the United States."
        ),
        reply_markup=InlineKeyboardMarkup(
            [[InlineKeyboardButton(_("Main Menu"), "welcome:" + lang)]]
            [
                [
                    InlineKeyboardButton(
                        text=_("Go Back"), callback_data="send_faq:" + lang
                    )
                ],
                [
                    InlineKeyboardButton(
                        text=_("Main Menu"), callback_data="welcome:" + lang
                    )
                ],
            ]
        ),
    )

    await callback.answer()


# Example query: explain_bridges:en
async def explain_bridges(client: Client, callback: CallbackQuery):
    callback_data = callback.data.split(":")
    lang = callback_data[-1]
    _ = i18n.get_translation(lang)

    await client.send_message(
        chat_id=callback.from_user.id,
        text="<b>"
        + _("What are Tor bridges?")
        + "</b>\n\n"
        + _("Tor bridges are computers that can be very helpful when "
            "your internet provider has blocked you from using Tor, "
            "or if you just want to hide the fact that you are using Tor "
            "from anyone that could be monitoring your internet connection. "
            "That could be your internet provider, government, household "
            "members, school, workplace, among others.")
        + "\n\n"
        + _("If the Tor network is blocked in your country, you can use "
            "a bridge to gain access again. Bridges are also a good idea to "
            "use if you want to use Tor in a discrete manner."),
        reply_markup=InlineKeyboardMarkup(
            [
                [
                    InlineKeyboardButton(
                        text=_("Cool, how do I get one?"),
                        callback_data="request_tor_bridges:" + lang,
                    )
                ],
                [
                    InlineKeyboardButton(
                        text=_("Go Back"), callback_data="send_faq:" + lang
                    )
                ],
                [
                    InlineKeyboardButton(
                        text=_("Main Menu"), callback_data="welcome:" + lang
                    )
                ],
            ]
        ),
    )

    await callback.answer()


# Example query: request_support:en
async def send_support(client: Client, callback: CallbackQuery):
    callback_data = callback.data.split(":")
    lang = callback_data[-1]
    _ = i18n.get_translation(lang)
    support_username = "@TorProjectSupportBot"
    forum_link = "https://forum.torproject.net"

    await client.send_message(
        chat_id=callback.from_user.id,
        text="<b>"
        + _("Need support?")
        + "</b>\n\n"
        + _("If you need support with anything that has to do with Tor, the Tor "
            "user support team can be reached on Telegram: {username}.\n\n"
            "There's also a dedicated active forum where anyone can post "
            "a question, feedback, or concern: {link}"
        ).format(username=support_username, link=forum_link),
        reply_markup=InlineKeyboardMarkup(
            [
                [
                    InlineKeyboardButton(
                        text=_("Go Back"), callback_data="send_faq:" + lang
                    )
                ],
                [
                    InlineKeyboardButton(
                        text=_("Main Menu"), callback_data="welcome:" + lang
                    )
                ],
            ]
        ),
    )

+12 −10
Original line number Diff line number Diff line
@@ -119,18 +119,20 @@ async def progress(current: int, total: int, reply: Message, upload: bool, lang:
        percentage = (current / total) * 100.0
        eta = calculate_eta(current, total, start_time, current_time)

        text = ""
        text = "<b>" + _("We are preparing your download...") + "</b>\n\n"

        if upload:
            text = _(
                "<b>We are preparing your download...</b>\n\n"
                "We're now sending the file to Telegram, it will be ready in %s!\n"
            text += _(
                "We're now sending the file to Telegram, it will be ready in %s!"
            ) % duration(eta, lang)
        else:
            text = _(
                "<b>We are preparing your download...</b>\n\n"
                "You're the first person to request this file, so we have to download it first! Please wait...\n"
            text += _(
                "You're the first person to request this file, so we have to download it first! "
                "Please wait..."
            )
        text += f"\n<code>{generate_bar(current, total)} {percentage:.2f}% ({speed}/s)</code>"

        text += f"\n\n<code>{generate_bar(current, total)} {percentage:.2f}% ({speed}/s)</code>"

        if prevtext != text:
            try:
                await reply.edit(text)
+20 −19
Original line number Diff line number Diff line
@@ -45,7 +45,7 @@ async def file_send_notification(
    _ = get_translation(user_lang)

    return await client.send_message(
        callback.from_user.id, _("We are now uploading the program...")
        callback.from_user.id, _("We are now uploading the Tor Browser...")
    )


@@ -59,12 +59,12 @@ async def upload_succeeded(

    await client.send_message(
        chat_id=callback.from_user.id,
        text=_(
            "<strong>Success!</strong>\n\n"
            "Here's your Tor Browser **(%s)**. "
            "Stay safe!"
        )
        % (platform),
        text="<b>"
        + _("Success!")
        + "</b>\n\n"
        + _("Here's your Tor Browser")
        + f" <b>({platform}).</b> "
        + _("Stay safe!"),
        reply_markup=InlineKeyboardMarkup(
            [[InlineKeyboardButton(_("Main Menu"), "welcome:" + user_lang)]]
        ),
@@ -80,11 +80,12 @@ async def upload_already_done(

    await client.send_message(
        chat_id=callback.from_user.id,
        text=_(
            "<strong>Success!</strong>\n\n"
            "Here's your Tor Browser. "
            "Stay safe!"
        ),
        text="<b>"
        + _("Success!")
        + "</b>\n\n"
        + _("Here's your Tor Browser")
        + f" <b>({platform})</b>. "
        + _("Stay safe!"),
        reply_markup=InlineKeyboardMarkup(
            [[InlineKeyboardButton(_("Main Menu"), "welcome:" + user_lang)]]
        ),
@@ -99,6 +100,7 @@ async def upload_failed(
    platform: Optional[str] = None,
):
    _ = get_translation(lang)
    support_username = "@TorProjectSupportBot"

    """
    By default, we log a very limited amount of information that is normally enough to
@@ -115,17 +117,16 @@ async def upload_failed(

    download_info = ""
    if platform is not None:
        download_info = f"(<strong>{platform}</strong>)"
        download_info = f"(<b>{platform}</b>)"

    await client.send_message(
        chat_id=callback.from_user.id,
        text=_(
            "<strong>Failure!</strong>\n\n"
            "Something went wrong during the upload! "
            "Please try again later. "
        )
        text="<b>"
        + _("Failure!")
        + "</b>\n\n"
        + _("Something went wrong during the upload! " "Please try again later. ")
        + exception_text
        + "\n\n☎️: @TorProjectSupportBot "
        + "\n\n☎️: {username} ".format(username=support_username)
        + download_info,
        reply_markup=InlineKeyboardMarkup(
            [[InlineKeyboardButton(_("Main Menu"), "welcome:" + lang)]]
Loading