Exemplo n.º 1
0
    async def on_message(self, raw):
        await self.wait_until_ready()

        sender = raw.author
        identifier = sender.name + "#" + sender.discriminator
        channel = raw.channel
        message = raw.content
        guild = None

        if config["BibleBot"]["devMode"] == "True":
            if str(sender.id) != config["BibleBot"]["owner"]:
                return

        if sender == self.user:
            return

        if central.is_optout(str(sender.id)):
            return

        language = languages.get_language(sender)

        if hasattr(channel, "guild"):
            guild = channel.guild

            if language is None:
                language = languages.get_guild_language(guild)

            if hasattr(channel.guild, "name"):
                source = channel.guild.name + "#" + channel.name
            else:
                source = "unknown (direct messages?)"

            if "Discord Bot" in channel.guild.name:
                if sender.id != config["BibleBot"]["owner"]:
                    return
        else:
            source = "unknown (direct messages?)"

        if guild is None:
            shard = 1
        else:
            shard = guild.shard_id + 1

        if language is None:
            language = "english_us"

        embed_or_reaction_not_allowed = False

        if guild is not None:
            try:
                perms = channel.permissions_for(guild.me)

                if perms is not None:
                    if not perms.send_messages or not perms.read_messages:
                        return

                    if not perms.embed_links:
                        embed_or_reaction_not_allowed = True

                    if not perms.add_reactions:
                        embed_or_reaction_not_allowed = True

                    if not perms.manage_messages or not perms.read_message_history:
                        embed_or_reaction_not_allowed = True
            except AttributeError:
                pass

        if message.startswith(config["BibleBot"]["commandPrefix"]):
            command = message[1:].split(" ")[0]
            args = message.split(" ")

            if not isinstance(args.pop(0), str):
                args = None

            raw_language = getattr(central.languages, language).raw_object

            cmd_handler = CommandHandler()

            res = cmd_handler.process_command(bot, command, language, sender,
                                              guild, channel, args)

            original_command = ""
            self.current_page = 1

            if res is None:
                return

            if res is not None:
                if "leave" in res:
                    if res["leave"] == "this":
                        if guild is not None:
                            await guild.leave()
                    else:
                        for item in bot.guilds:
                            if str(item.id) == res["leave"]:
                                await item.leave()
                                await channel.send("Left " + str(item.name))

                    central.log_message("info", shard, identifier, source,
                                        "+leave")
                    return

                if "isError" not in res:
                    if guild is not None:
                        is_banned, reason = central.is_banned(str(guild.id))

                        if is_banned:
                            await channel.send(
                                "This server has been banned from using BibleBot. Reason: `"
                                + reason + "`.")
                            await channel.send(
                                "If this is invalid, the server owner may appeal by contacting "
                                + "vypr#0001.")

                            central.log_message("err", shard, identifier,
                                                source, "Server is banned.")
                            return

                    is_banned, reason = central.is_banned(str(sender.id))
                    if is_banned:
                        await channel.send(
                            sender.mention +
                            " You have been banned from using BibleBot. " +
                            "Reason: `" + reason + "`.")
                        await channel.send(
                            "You may appeal by contacting vypr#0001.")

                        central.log_message("err", shard, identifier, source,
                                            "User is banned.")
                        return

                    if embed_or_reaction_not_allowed:
                        await channel.send(
                            "I need 'Embed Links', 'Read Message History', " +
                            "'Manage Messages', and 'Add Reactions' permissions!"
                        )
                        return

                    if "announcement" not in res:
                        if "twoMessages" in res:
                            await channel.send(res["firstMessage"])
                            await channel.send(res["secondMessage"])
                        elif "paged" in res:
                            self.total_pages = len(res["pages"])

                            msg = await channel.send(embed=res["pages"][0])

                            await msg.add_reaction("⬅")
                            await msg.add_reaction("➡")

                            def check(r, u):
                                if r.message.id == msg.id:
                                    if str(r.emoji) == "⬅":
                                        if u.id != bot.user.id:
                                            if self.current_page != 1:
                                                self.current_page -= 1
                                                return True
                                    elif str(r.emoji) == "➡":
                                        if u.id != bot.user.id:
                                            if self.current_page != self.total_pages:
                                                self.current_page += 1
                                                return True

                            continue_paging = True

                            try:
                                while continue_paging:
                                    reaction, user = await bot.wait_for(
                                        'reaction_add',
                                        timeout=120.0,
                                        check=check)
                                    await reaction.message.edit(
                                        embed=res["pages"][self.current_page -
                                                           1])

                                    reaction, user = await bot.wait_for(
                                        'reaction_remove',
                                        timeout=120.0,
                                        check=check)
                                    await reaction.message.edit(
                                        embed=res["pages"][self.current_page -
                                                           1])

                            except (asyncio.TimeoutError, IndexError):
                                await msg.clear_reactions()
                        else:
                            if "reference" not in res and "text" not in res:
                                # noinspection PyBroadException
                                try:
                                    await channel.send(embed=res["message"])
                                except Exception:
                                    pass
                            else:
                                if res["message"] is not None:
                                    await channel.send(res["message"])
                                else:
                                    await channel.send("Done.")

                        for original_command_name in raw_language[
                                "commands"].keys():
                            untranslated = [
                                "setlanguage", "userid", "ban", "unban",
                                "reason", "optout", "unoptout", "eval",
                                "jepekula", "joseph", "tiger"
                            ]

                            if raw_language["commands"][
                                    original_command_name] == command:
                                original_command = original_command_name
                            elif command in untranslated:
                                original_command = command
                    else:
                        for original_command_name in raw_language[
                                "commands"].keys():
                            if raw_language["commands"][
                                    original_command_name] == command:
                                original_command = original_command_name

                        count = 1
                        total = len(bot.guilds)

                        for item in bot.guilds:
                            announce_tuple = misc.get_guild_announcements(
                                item, False)

                            # noinspection PyBroadException
                            try:
                                if "Discord Bot" not in item.name:
                                    if announce_tuple is not None:
                                        chan, setting = announce_tuple
                                    else:
                                        chan = "preferred"
                                        setting = True

                                    preferred = [
                                        "misc", "bots", "meta", "hangout",
                                        "fellowship", "lounge", "congregation",
                                        "general", "bot-spam", "staff"
                                    ]

                                    if chan != "preferred" and setting:
                                        ch = self.get_channel(chan)
                                        perm = ch.permissions_for(item.me)

                                        if perm.read_messages and perm.send_messages:
                                            await channel.send(
                                                str(count) + "/" + str(total) +
                                                " - " + item.name +
                                                " :white_check_mark:")

                                            if perm.embed_links:
                                                await ch.send(
                                                    embed=res["message"])
                                            else:
                                                await ch.send(res["message"].
                                                              fields[0].value)
                                        else:
                                            await channel.send(
                                                str(count) + "/" + str(total) +
                                                " - " + item.name +
                                                " :regional_indicator_x:")
                                    elif chan == "preferred" and setting:
                                        sent = False

                                        for ch in item.text_channels:
                                            try:
                                                if not sent:
                                                    for name in preferred:
                                                        if ch.name == name:
                                                            perm = ch.permissions_for(
                                                                item.me)

                                                            if perm.read_messages and perm.send_messages:
                                                                await channel.send(
                                                                    str(count)
                                                                    + "/" +
                                                                    str(total)
                                                                    + " - " +
                                                                    item.name +
                                                                    " :white_check_mark:"
                                                                )
                                                                if perm.embed_links:
                                                                    await ch.send(
                                                                        embed=
                                                                        res["message"]
                                                                    )
                                                                else:
                                                                    await ch.send(
                                                                        res["message"]
                                                                        .
                                                                        fields[
                                                                            0].
                                                                        value)
                                                            else:
                                                                await channel.send(
                                                                    str(count)
                                                                    + "/" +
                                                                    str(total)
                                                                    + " - " +
                                                                    item.name +
                                                                    " :regional_indicator_x:"
                                                                )

                                                            sent = True
                                            except (AttributeError,
                                                    IndexError):
                                                sent = True
                                    else:
                                        await channel.send(
                                            str(count) + "/" + str(total) +
                                            " - " + item.name +
                                            " :regional_indicator_x:")
                            except Exception:
                                pass

                            count += 1

                        await channel.send("Done.")

                    clean_args = str(args).replace(",", " ").replace(
                        "[", "").replace("]", "")
                    clean_args = clean_args.replace("\"", "").replace(
                        "'", "").replace("  ", " ")
                    clean_args = clean_args.replace("\n", "").strip()

                    if original_command == "puppet":
                        clean_args = ""
                    elif original_command == "eval":
                        clean_args = ""
                    elif original_command == "announce":
                        clean_args = ""

                    central.log_message(
                        res["level"], shard, identifier, source,
                        "+" + original_command + " " + clean_args)
                else:
                    # noinspection PyBroadException
                    try:
                        await channel.send(embed=res["return"])
                    except Exception:
                        pass
        else:
            verse_handler = VerseHandler()

            result = verse_handler.process_raw_message(raw, sender, language,
                                                       guild)

            if result is not None:
                if "invalid" not in result and "spam" not in result:
                    for item in result:
                        try:
                            if "twoMessages" in item:
                                if guild is not None:
                                    is_banned, reason = central.is_banned(
                                        str(guild.id))
                                    if is_banned:
                                        await channel.send(
                                            "This server has been banned from using BibleBot. "
                                            + "Reason: `" + reason + "`.")
                                        await channel.send(
                                            "If this is invalid, the server owner may appeal by contacting "
                                            + "vypr#0001.")

                                        central.log_message(
                                            "err", shard, identifier, source,
                                            "Server is banned.")
                                        return

                                is_banned, reason = central.is_banned(
                                    str(sender.id))
                                if is_banned:
                                    await channel.send(
                                        sender.mention +
                                        " You have been banned from using BibleBot. "
                                        + "Reason: `" + reason + "`.")
                                    await channel.send(
                                        "You may appeal by contacting vypr#0001."
                                    )

                                    central.log_message(
                                        "err", shard, identifier, source,
                                        "User is banned.")
                                    return

                                if embed_or_reaction_not_allowed:
                                    await channel.send(
                                        "I need 'Embed Links', 'Read Message History', "
                                        +
                                        "'Manage Messages', and 'Add Reactions' permissions!"
                                    )
                                    return
                                await channel.send(item["firstMessage"])
                                await channel.send(item["secondMessage"])
                            elif "message" in item:
                                if guild is not None:
                                    is_banned, reason = central.is_banned(
                                        str(guild.id))
                                    if is_banned:
                                        await channel.send(
                                            "This server has been banned from using BibleBot. "
                                            + "Reason: `" + reason + "`.")
                                        await channel.send(
                                            "If this is invalid, the server owner may appeal by contacting "
                                            + "vypr#0001.")

                                        central.log_message(
                                            "err", shard, identifier, source,
                                            "Server is banned.")
                                        return

                                is_banned, reason = central.is_banned(
                                    str(sender.id))
                                if is_banned:
                                    await channel.send(
                                        sender.mention +
                                        " You have been banned from using BibleBot. "
                                        + "Reason: `" + reason + "`.")
                                    await channel.send(
                                        "You may appeal by contacting vypr#0001."
                                    )

                                    central.log_message(
                                        "err", shard, identifier, source,
                                        "User is banned.")
                                    return

                                if embed_or_reaction_not_allowed:
                                    await channel.send(
                                        "I need 'Embed Links', 'Read Message History', "
                                        +
                                        "'Manage Messages', and 'Add Reactions' permissions!"
                                    )
                                    return
                                await channel.send(item["message"])
                        except KeyError:
                            pass

                        if "reference" in item:
                            central.log_message(item["level"], shard,
                                                identifier, source,
                                                item["reference"])
                else:
                    if "spam" in result:
                        await channel.send(result["spam"])
Exemplo n.º 2
0
    async def on_message(self, raw):
        sender = raw.author
        identifier = sender.name + "#" + sender.discriminator
        channel = raw.channel
        message = raw.content
        guild = None

        if (config["BibleBot"]["devMode"] == "True"):
            if str(sender.id) != config["BibleBot"]["owner"]:
                return

        if sender == self.user:
            return

        language = languages.getLanguage(sender)

        if language is None:
            language = "english_us"

        if hasattr(channel, "guild"):
            guild = channel.guild
            if hasattr(channel.guild, "name"):
                source = channel.guild.name + "#" + channel.name
            else:
                source = "unknown (direct messages?)"

            if "Discord Bot" in channel.guild.name:
                if sender.id != config["BibleBot"]["owner"]:
                    return
        else:
            source = "unknown (direct messages?)"

        embedOrReactionNotAllowed = False

        if guild is not None:
            perms = channel.permissions_for(guild.me)

            if not perms.send_messages or not perms.read_messages:
                return

            if not perms.embed_links:
                embedOrReactionNotAllowed = True

            if not perms.add_reactions:
                embedOrReactionNotAllowed = True

        if message.startswith(config["BibleBot"]["commandPrefix"]):
            if embedOrReactionNotAllowed:
                await channel.send("I need 'Embed Links'" +
                                   " and 'Add Reactions' permissions!")
                return

            command = message[1:].split(" ")[0]
            args = message.split(" ")

            if not isinstance(args.pop(0), str):
                args = None

            rawLanguage = eval(
                "central.languages." + str(language))
            rawLanguage = rawLanguage.rawObject

            cmdHandler = CommandHandler()

            res = cmdHandler.processCommand(
                bot, command, language, sender, args)

            originalCommand = ""
            self.currentPage = 1

            if res is None:
                return

            if res is not None:
                if guild is not None:
                    if central.isBanned(str(guild.id)):
                        await channel.send("This server has been banned" +
                                           " from using BibleBot.")
                        await channel.send("If this is invalid, the server " +
                                           "owner may appeal by contacting " +
                                           "null#3464.")
                        central.logMessage(
                            "err", shard, identifier, source, "Server is " +
                            "banned.")
                        return

            if central.isBanned(str(sender.id)):
                await channel.send(sender.mention +
                                   " You have been banned from " +
                                   "using BibleBot.")
                await channel.send("You may appeal by " +
                                   "contacting null#3464.")
                central.logMessage("err", shard, identifier,
                                   source, "User is banned.")
                return

            if "leave" in res:
                if res["leave"] == "this":
                    if guild is not None:
                        await guild.leave()
                else:
                    for item in bot.guilds:
                        if str(item.id) == res["leave"]:
                            await item.leave()
                            await channel.send("Left " + str(item.name))

                central.logMessage("info", shard, identifier, source, "+leave")
                return

            if "isError" not in res:
                if "announcement" not in res:
                    if "twoMessages" in res:
                        await channel.send(res["firstMessage"])
                        await channel.send(res["secondMessage"])
                    elif "paged" in res:
                        self.totalPages = len(res["pages"])

                        msg = await channel.send(
                            embed=res["pages"][0])
                        await msg.add_reaction("⬅")
                        await msg.add_reaction("➡")

                        def check(reaction, user):
                            if reaction.message.id == msg.id:
                                if str(reaction.emoji) == "⬅":
                                    if user.id != bot.user.id:
                                        if self.currentPage != 1:
                                            self.currentPage -= 1
                                            return True
                                elif str(reaction.emoji) == "➡":
                                    if user.id != bot.user.id:
                                        if self.currentPage != self.totalPages:
                                            self.currentPage += 1
                                            return True

                        continuePaging = True

                        try:
                            while continuePaging:
                                reaction, user = await bot.wait_for(
                                    'reaction_add', timeout=120.0, check=check)
                                await reaction.message.edit(
                                    embed=res["pages"][self.currentPage - 1])
                                reaction, user = await bot.wait_for(
                                    'reaction_remove', timeout=120.0,
                                    check=check)
                                await reaction.message.edit(
                                    embed=res["pages"][self.currentPage - 1])

                        except (asyncio.TimeoutError, IndexError):
                            continuePaging = False
                    else:
                        if "reference" not in res and "text" not in res:
                            await channel.send(embed=res["message"])
                        else:
                            if res["message"] is not None:
                                await channel.send(res["message"])
                            else:
                                await channel.send("Done.")

                    for originalCommandName in rawLanguage["commands"].keys():
                        if rawLanguage["commands"][originalCommandName] == command:  # noqa: E501
                            originalCommand = originalCommandName
                        elif command == "setlanguage":
                            originalCommand = "setlanguage"
                        elif command == "ban":
                            originalCommand = "ban"
                        elif command == "unban":
                            originalCommand = "unban"
                        elif command == "eval":
                            originalCommand = "eval"
                        elif command == "jepekula":
                            originalCommand = "jepekula"
                        elif command == "joseph":
                            originalCommand = "joseph"
                        elif command == "tiger":
                            originalCommand = "tiger"
                else:
                    for originalCommandName in rawLanguage["commands"].keys():
                        if rawLanguage["commands"][originalCommandName] == command:  # noqa: E501
                            originalCommand = originalCommandName

                    count = 1
                    total = len(bot.guilds)

                    for item in bot.guilds:
                        if "Discord Bot" not in item.name:
                            if str(item.id) != "362503610006765568":
                                sent = False

                                preferred = ["misc", "bots", "meta", "hangout",
                                             "fellowship", "lounge",
                                             "congregation", "general",
                                             "taffer", "family_text", "staff"]

                                for ch in item.text_channels:
                                    try:
                                        if not sent:
                                            for name in preferred:
                                                if ch.name == name:
                                                    if not sent:
                                                        perm = ch.permissions_for(  # noqa: E501
                                                            item.me)

                                                        if perm.read_messages:
                                                            if perm.send_messages:  # noqa: E501
                                                                await channel.send(str(count) +  # noqa: E501
                                                                                "/" + str(total) + " - " +  # noqa: E501
                                                                                item.name + " :white_check_mark:")  # noqa: E501
                                                                if perm.embed_links:  # noqa: E501
                                                                    await ch.send(  # noqa: E501
                                                                        embed=res["message"])  # noqa: E501
                                                                else:
                                                                    await ch.send(res["message"].fields[0].value)  # noqa: E501
                                                            else:
                                                                await channel.send(str(count) +  # noqa: E501
                                                                                "/" + str(total) + " - " +  # noqa: E501
                                                                                item.name + " :regional_indicator_x:")  # noqa: E501
                                                            count += 1
                                                            sent = True
                                    except Exception:
                                        sent = False
                            else:
                                for ch in item.text_channels:
                                    if ch.name == "announcements":
                                        await ch.send(embed=res["message"])

                    await channel.send("Done.")

                cleanArgs = str(args).replace(
                    ",", " ").replace("[", "").replace(
                        "]", "").replace("\"", "").replace(
                            "'", "").replace(
                                "  ", " ")

                if originalCommand == "puppet":
                    cleanArgs = ""
                elif originalCommand == "eval":
                    cleanArgs = ""
                elif originalCommand == "announce":
                    cleanArgs = ""

                central.logMessage(res["level"], shard, identifier,
                                   source, "+" + originalCommand +
                                   " " + cleanArgs)
            else:
                await channel.send(embed=res["return"])
        else:
            verseHandler = VerseHandler()

            result = verseHandler.processRawMessage(
                shard, raw, sender, language)

            if result is not None:
                if embedOrReactionNotAllowed:
                    await channel.send("I need 'Embed Links'" +
                                       " and 'Add Reactions' permissions!")
                    return

                if guild is not None:
                    if central.isBanned(str(guild.id)):
                        await channel.send("This server has been banned " +
                                           "from using BibleBot.")
                        await channel.send("If this is invalid, the server " +
                                           "owner may appeal by contacting " +
                                           "null#3464.")
                        central.logMessage(
                            "err", shard, identifier,
                            source, "Server is banned.")
                        return

                if central.isBanned(str(sender.id)):
                    await channel.send(sender.mention +
                                       " You have been banned from " +
                                       "using BibleBot.")
                    await channel.send("You may appeal by " +
                                       "contacting null#3464.")
                    central.logMessage(
                        "err", shard, identifier, source, "User is banned.")
                    return

                if "invalid" not in result and "spam" not in result:
                    for item in result:
                        if "twoMessages" in item:
                            await channel.send(item["firstMessage"])
                            await channel.send(item["secondMessage"])
                        elif "message" in item:
                            await channel.send(item["message"])

                        if "reference" in item:
                            central.logMessage(item["level"], shard,
                                               identifier, source,
                                               item["reference"])
                else:
                    if "spam" in result:
                        await channel.send(result["spam"])
Exemplo n.º 3
0
    async def on_message(self, raw):
        owner_id = config["BibleBot"]["owner"]
        await self.wait_until_ready()

        if ":" not in raw.content:
            if config["BibleBot"]["commandPrefix"] not in raw.content:
                return

        ctx = {
            "self": bot,
            "author": raw.author,
            "identifier": f"{raw.author.id}",
            "channel": raw.channel,
            "message": raw.content,
            "raw": raw,
            "guild": None,
            "language": None
        }

        is_self = ctx["author"] == self.user
        is_optout = central.is_optout(str(ctx["author"].id))
        if is_self or is_optout:
            return

        is_owner = ctx["identifier"] == owner_id
        if is_owner:
            ctx["identifier"] = "owner"

        language = languages.get_language(ctx["author"])

        if hasattr(ctx["channel"], "guild"):
            ctx["guild"] = ctx["channel"].guild

            if language is None:
                language = languages.get_guild_language(ctx["guild"])

            guild_id = str(ctx["channel"].guild.id)
            chan_id = str(ctx["channel"].id)

            source = f"{guild_id}#{chan_id}"

            if "Discord Bot" in ctx["channel"].guild.name:
                if not is_owner:
                    return
        else:
            source = "unknown (direct messages?)"

        if ctx["guild"] is None:
            shard = 1
        else:
            shard = ctx["guild"].shard_id + 1

        if language is None or language in ["english_us", "english_uk"]:
            language = "english"

        if config["BibleBot"]["devMode"] == "True":
            # more often than not, new things are added that aren't filtered
            # through crowdin yet so we do this to avoid having to deal with
            # missing values
            language = "default"

            if not is_owner:
                return

        ctx["language"] = central.get_raw_language(language)

        if ctx["message"].startswith(config["BibleBot"]["commandPrefix"]):
            command = ctx["message"][1:].split(" ")[0]
            remainder = " ".join(ctx["message"].split(" ")[1:])

            cmd_handler = CommandHandler()

            res = await cmd_handler.process_command(ctx, command, remainder)

            original_command = ""

            if res is None:
                return

            if "announcement" in res:
                central.log_message("info", 0, "owner", "global",
                                    "Announcement starting.")
                await bot_extensions.send_announcement(ctx, res)
                central.log_message("info", 0, "owner", "global",
                                    "Announcement finished.")
                return

            if "isError" not in res:
                if "twoMessages" in res:
                    await ctx["channel"].send(res["firstMessage"])
                    await ctx["channel"].send(res["secondMessage"])
                elif "paged" in res:
                    msg = await ctx["channel"].send(embed=res["pages"][0])

                    self.current_page[msg.id] = 1
                    self.total_pages[msg.id] = len(res["pages"])

                    await msg.add_reaction("⬅")
                    await msg.add_reaction("➡")

                    def check(r, u):
                        if r.message.id == msg.id:
                            if str(r.emoji) == "⬅":
                                if u.id != bot.user.id:
                                    if self.current_page[msg.id] != 1:
                                        self.current_page[msg.id] -= 1
                                        return True
                            elif str(r.emoji) == "➡":
                                if u.id != bot.user.id:
                                    if self.current_page[
                                            msg.id] != self.total_pages[
                                                msg.id]:
                                        self.current_page[msg.id] += 1
                                        return True

                    self.continue_paging[msg.id] = True

                    try:
                        while self.continue_paging[msg.id]:
                            reaction, _ = await asyncio.ensure_future(
                                bot.wait_for('reaction_add',
                                             timeout=60.0,
                                             check=check))
                            await reaction.message.edit(
                                embed=res["pages"][self.current_page[msg.id] -
                                                   1])

                            reaction, _ = await asyncio.ensure_future(
                                bot.wait_for('reaction_remove',
                                             timeout=60.0,
                                             check=check))
                            await reaction.message.edit(
                                embed=res["pages"][self.current_page[msg.id] -
                                                   1])
                    except (asyncio.TimeoutError, IndexError):
                        try:
                            self.current_page.pop(msg.id)
                            self.total_pages.pop(msg.id)
                            self.continue_paging.pop(msg.id)

                            await msg.clear_reactions()
                        except (discord.errors.Forbidden,
                                discord.errors.NotFound):
                            pass
                elif "embed" in res:
                    try:
                        await ctx["channel"].send(embed=res["embed"])
                    except discord.errors.Forbidden:
                        await ctx["channel"].send(
                            "Unable to send embed, please verify permissions.")
                else:
                    if "reference" not in res and "text" not in res:
                        await ctx["channel"].send(embed=res["message"])
                    else:
                        await ctx["channel"].send(res["message"])

                lang = central.get_raw_language(language)
                for original_command_name in lang["commands"].keys():
                    untranslated = [
                        "setlanguage", "userid", "ban", "unban", "reason",
                        "optout", "unoptout", "eval", "jepekula", "joseph",
                        "tiger", "rose", "lsc", "heidelberg", "ccc", "quit"
                    ]

                    if lang["commands"][original_command_name] == command:
                        original_command = original_command_name
                    elif command in untranslated:
                        original_command = command

                clean_args = remainder.replace("\"", "").replace("'",
                                                                 "").replace(
                                                                     "  ", " ")
                clean_args = clean_args.replace("\n", "").strip()

                ignore_arg_commands = ["puppet", "eval", "announce"]

                if original_command in ignore_arg_commands:
                    clean_args = ""

                central.log_message(res["level"], shard, ctx["identifier"],
                                    source,
                                    f"+{original_command} {clean_args}")
            else:
                await ctx["channel"].send(embed=res["message"])
        else:
            verse_handler = VerseHandler()

            result = await verse_handler.process_raw_message(
                raw, ctx["author"], ctx["language"], ctx["guild"])

            if result is not None:
                if "invalid" not in result and "spam" not in result:
                    for item in result:
                        try:
                            if "twoMessages" in item:
                                await ctx["channel"].send(item["firstMessage"])
                                await ctx["channel"].send(item["secondMessage"]
                                                          )
                            elif "message" in item:
                                await ctx["channel"].send(item["message"])
                            elif "embed" in item:
                                await ctx["channel"].send(embed=item["embed"])

                            if "reference" in item:
                                central.log_message(item["level"], shard,
                                                    ctx["identifier"], source,
                                                    item["reference"])
                        except (KeyError, TypeError):
                            pass
                elif "spam" in result:
                    central.log_message("warn", shard, ctx["identifier"],
                                        source, "Too many verses at once.")
                    await ctx["channel"].send(result["spam"])
Exemplo n.º 4
0
    async def on_message(self, raw):
        await self.wait_until_ready()

        sender = raw.author
        identifier = sender.name + "#" + sender.discriminator
        channel = raw.channel
        message = raw.content
        guild = None

        if config["OrthoBot"]["devMode"] == "True":
            if str(sender.id) != config["OrthoBot"]["owner"]:
                return

        if sender == self.user:
            return

        if hasattr(channel, "guild"):
            guild = channel.guild

            if hasattr(channel.guild, "name"):
                source = channel.guild.name + "#" + channel.name
            else:
                source = "unknown (direct messages?)"

            if "Discord Bot" in channel.guild.name:
                if sender.id != config["OrthoBot"]["owner"]:
                    return
        else:
            source = "unknown (direct messages?)"

        if guild is None:
            shard = 1
        else:
            shard = guild.shard_id + 1

        embed_or_reaction_not_allowed = False

        if guild is not None:
            try:
                perms = channel.permissions_for(guild.me)

                if perms is not None:
                    if not perms.send_messages or not perms.read_messages:
                        return

                    if not perms.embed_links:
                        embed_or_reaction_not_allowed = True

                    if not perms.add_reactions:
                        embed_or_reaction_not_allowed = True

                    if not perms.manage_messages or not perms.read_message_history:
                        embed_or_reaction_not_allowed = True
            except AttributeError:
                pass

        if message.startswith(config["OrthoBot"]["commandPrefix"]):
            command = message[1:].split(" ")[0]
            args = message.split(" ")

            if not isinstance(args.pop(0), str):
                args = None

            cmd_handler = CommandHandler()

            res = cmd_handler.process_command(bot, command, sender, guild, channel, args)

            self.current_page = 1

            if res is None:
                return

            if res is not None:
                if "leave" in res:
                    if res["leave"] == "this":
                        if guild is not None:
                            await guild.leave()
                    else:
                        for item in bot.guilds:
                            if str(item.id) == res["leave"]:
                                await item.leave()
                                await channel.send("Left " + str(item.name))

                    central.log_message("info", shard, identifier, source, "+leave")
                    return

                if "isError" not in res:
                    if guild is not None:
                        is_banned, reason = central.is_banned(str(guild.id))

                        if is_banned:
                            await channel.send("This server has been banned from using OrthoBot. Reason: `" +
                                               reason + "`.")
                            await channel.send("If this is invalid, the server owner may appeal by contacting " +
                                               "vypr#0001.")

                            central.log_message("err", shard, identifier, source, "Server is banned.")
                            return

                    is_banned, reason = central.is_banned(str(sender.id))
                    if is_banned:
                        await channel.send(sender.mention + " You have been banned from using OrthoBot. " +
                                           "Reason: `" + reason + "`.")
                        await channel.send("You may appeal by contacting vypr#0001.")

                        central.log_message("err", shard, identifier, source, "User is banned.")
                        return

                    if embed_or_reaction_not_allowed:
                        await channel.send("I need 'Embed Links', 'Read Message History', "
                                           + "'Manage Messages', and 'Add Reactions' permissions!")
                        return

                    if "twoMessages" in res:
                        await channel.send(res["firstMessage"])
                        await channel.send(res["secondMessage"])
                    elif "paged" in res:
                        self.total_pages = len(res["pages"])

                        msg = await channel.send(embed=res["pages"][0])

                        await msg.add_reaction("⬅")
                        await msg.add_reaction("➡")

                        def check(r, u):
                            if r.message.id == msg.id:
                                if str(r.emoji) == "⬅":
                                    if u.id != bot.user.id:
                                        if self.current_page != 1:
                                            self.current_page -= 1
                                            return True
                                elif str(r.emoji) == "➡":
                                    if u.id != bot.user.id:
                                        if self.current_page != self.total_pages:
                                            self.current_page += 1
                                            return True

                        continue_paging = True

                        try:
                            while continue_paging:
                                reaction, user = await bot.wait_for('reaction_add', timeout=120.0, check=check)
                                await reaction.message.edit(embed=res["pages"][self.current_page - 1])

                                reaction, user = await bot.wait_for('reaction_remove', timeout=120.0, check=check)
                                await reaction.message.edit(embed=res["pages"][self.current_page - 1])

                        except (asyncio.TimeoutError, IndexError):
                            await msg.clear_reactions()
                    else:
                        if "reference" not in res and "text" not in res:
                            await channel.send(embed=res["message"])
                        else:
                            if res["message"] is not None:
                                await channel.send(res["message"])
                            else:
                                await channel.send("Done.")

                    clean_args = str(args).replace(",", " ").replace("[", "").replace("]", "")
                    clean_args = clean_args.replace("\"", "").replace("'", "").replace("  ", " ")
                    clean_args = clean_args.replace("\n", "").strip()

                    ignore_arg_commands = ["puppet", "eval"]

                    if command in ignore_arg_commands:
                        clean_args = ""

                    central.log_message(res["level"], shard, identifier, source, config["OrthoBot"]["commandPrefix"]
                                        + command + " " + clean_args)
                else:
                    if "return" in res:
                        await channel.send(embed=res["return"])