示例#1
0
    async def on_command_error(self, ctx: Context,
                               error: Exception) -> NoReturn:
        """If an unexpected error occurs, it displays an... error message?

        Attributes:
        -----------
        - `error` - error information

        """
        s = await Settings(ctx.guild.id)
        lang = await s.get_field("locale", CONFIG["default_locale"])
        STRINGS = Strings(lang)
        COMMANDS = Commands(lang)

        if isinstance(error, commands.CommandNotFound):
            return
        await ctx.message.add_reaction(CONFIG["no_emoji"])

        if isinstance(error, commands.MissingRequiredArgument):
            prefix = await s.get_field("prefix", CONFIG["default_prefix"])

            if ctx.command.cog.name != "Jishaku":
                embed = Utils.error_embed(STRINGS["etc"]["usage"].format(
                    COMMANDS[ctx.command.cog.name]["commands"][
                        ctx.command.name]["usage"].format(prefix)))
        elif isinstance(error, commands.MissingPermissions):
            embed = Utils.error_embed(STRINGS["error"]["missing_perms"])

        elif isinstance(error, commands.BotMissingPermissions):
            embed = Utils.error_embed(
                STRINGS["error"]["missing_bot_perms"].format(" ".join(
                    "+ " + STRINGS["etc"]["permissions"][f"{perm}"]
                    for perm in error.missing_perms)))

        elif isinstance(error, commands.CommandOnCooldown):
            embed = Utils.error_embed(STRINGS["error"]["cooldown"].format(
                error.retry_after))

        elif isinstance(error, commands.errors.NSFWChannelRequired):
            embed = discord.Embed(
                title=STRINGS["error"]["nsfwerrortitle"],
                description=STRINGS["error"]["nsfwnotcorrectspot"],
                color=0xFF0000,
            )
            embed.add_field(
                name=STRINGS["error"]["nsfwlogerror"],
                value=STRINGS["error"]["nsfwtraceback"].format(str(error)),
                inline=False,
            )

        else:
            embed = discord.Embed(color=0xDD0000)
            embed.title = STRINGS["error"]["on_error_title"]
            embed.description = STRINGS["error"]["on_error_text"].format(
                str(error))
            Logger.warn(str(error))

        msg = await ctx.send(embed=embed)
        await asyncio.sleep(20)
        await msg.delete()
示例#2
0
    async def mute(
        self, ctx: Context, member: discord.Member, *, reason: str = "N/A"
    ) -> NoReturn:
        s = await Settings(ctx.guild.id)
        lang = await s.get_field("locale", CONFIG["default_locale"])
        STRINGS = Strings(lang)
        mute_role_id = await s.get_field("mute_role_id")

        if (
            mute_role_id is None
            or discord.utils.get(ctx.guild.roles, id=mute_role_id) is None
        ):
            embed = Utils.done_embed(STRINGS["moderation"]["on_mute_role_create"])
            await ctx.send(embed=embed)
            mute_role = await ctx.guild.create_role(name="OpenMod - Muted")

            await s.set_field("mute_role_id", mute_role.id)
            mute_role_id = await s.get_field("mute_role_id")

        else:
            mute_role = discord.utils.get(ctx.guild.roles, id=mute_role_id)

            for user_role in member.roles:
                if user_role == mute_role:
                    embed = Utils.error_embed(STRINGS["error"]["already_muted"])
                    await ctx.send(embed=embed)
                    return

        for channel in ctx.guild.text_channels:
            await channel.set_permissions(
                mute_role, read_messages=True, send_messages=False, speak=False
            )

        await member.add_roles(mute_role)
        await ctx.message.add_reaction(CONFIG["yes_emoji"])
示例#3
0
    async def unban(self, ctx: Context, *, member: Member) -> NoReturn:
        """Unbans the user.

        Attributes:
        -----------
        - `member` - user tag. Example: `name#1234`

        """
        s = await Settings(ctx.guild.id)
        lang = await s.get_field("locale", CONFIG["default_locale"])
        STRINGS = Strings(lang)

        banned_users = await ctx.guild.bans()
        member_name, member_discriminator = member.split("#")

        for ban_entry in banned_users:
            user = ban_entry.user
            if (user.name, user.discriminator) == (member_name, member_discriminator):
                await ctx.guild.unban(user)
                await ctx.message.add_reaction(CONFIG["yes_emoji"])
                return

        await ctx.message.add_reaction(CONFIG["no_emoji"])
        embed = Utils.error_embed(STRINGS["error"]["user_not_found"])
        await ctx.send(embed=embed)
示例#4
0
    async def locale(self, ctx: Context, locale: str) -> NoReturn:
        """Sets bot language. If not found, it throws an error.

        Attributes:
        -----------
        - `locale` - new locale

        """
        s = await Settings(ctx.guild.id)
        lang = await s.get_field("locale", CONFIG["default_locale"])
        STRINGS = Strings(lang)
        locales = Utils.get_locales_list()

        for _locale in locales:
            if _locale == locale:
                await s.set_field("locale", locale)

                await ctx.message.add_reaction(CONFIG["yes_emoji"])
                return

        # FIXME
        embed = discord.Embed(
            title=STRINGS["error"]["on_error_title"],
            description=STRINGS["error"]["localeerrortext"],
            color=0xFF0000,
        )
        embed.add_field(
            name=STRINGS["error"]["generictracebackthing"],
            value=STRINGS["error"]["localerrrorstring"],
            inline=False,
        )
        print(f"Wrong localization given on {ctx.message.guild}")
        await ctx.send(embed=embed)
示例#5
0
    async def setname(self, ctx: Context, member: Member, *,
                      name: str) -> NoReturn:
        s = await Settings(ctx.guild.id)
        lang = await s.get_field("locale", CONFIG["default_locale"])
        STRINGS = Strings(lang)

        if len(name) > 32:
            embed = Utils.error_embed(STRINGS["error"]["too_long_name"])
            await ctx.send(embed=embed)
        elif (ctx.message.author.guild_permissions.manage_nicknames
              or member == ctx.message.author):
            await member.edit(nick=name)
            await ctx.message.add_reaction(CONFIG["yes_emoji"])
        else:
            embed = Utils.error_embed(STRINGS["error"]["missing_perms"])
            await ctx.send(embed=embed)
示例#6
0
    async def kick(self,
                   ctx: Context,
                   member: Member,
                   *,
                   reason: str = "N/A") -> NoReturn:
        """Kicks the user.

        Attributes:
        -----------
        - `member` - user
        - `reason` - kick reason

        """
        s = await Settings(ctx.guild.id)
        lang = await s.get_field("locale", CONFIG["default_locale"])
        STRINGS = Strings(lang)

        select_components = [[
            Button(style=ButtonStyle.green, label="✓"),
            Button(style=ButtonStyle.red, label="X"),
        ]]
        done_components = [[
            Button(style=ButtonStyle.grey, label="·", disabled=True),
        ]]

        embedconfirm = discord.Embed(
            title="Kick Command",
            description="```Do you want to kick this member?```",
        )
        await ctx.send(embed=embedconfirm, components=select_components)
        response = await self.bot.wait_for(
            "button_click", check=lambda message: message.author == ctx.author)
        if response.component.label == "✓":
            await response.respond(
                type=7,
                embed=discord.Embed(
                    title="Action Completed",
                    description=f"Kicked {member} for {reason}",
                    color=0xDD2E44,
                ),
                components=done_components,
            )
            if not member.bot:
                embed = Utils.error_embed(
                    STRINGS["moderation"]["dm_kick"].format(ctx.guild, reason))
                await member.send(embed=embed)
            await asyncio.sleep(5)
            await member.kick()
            await ctx.message.add_reaction(CONFIG["yes_emoji"])
        else:
            await response.respond(
                type=7,
                embed=discord.Embed(
                    title="Action Aborted",
                    description="The action was aborted by clicking the no button",
                    color=0xDD2E44,
                ),
                components=done_components,
            )
            return
示例#7
0
    async def multiban(self,
                       ctx: Context,
                       members: Greedy[Member],
                       *,
                       reason: str = "N/A") -> NoReturn:
        """Bans multiple users.

        Attributes:
        -----------
        - `member` - user
        - `reason` - ban reason

        """
        s = await Settings(ctx.guild.id)
        lang = await s.get_field("locale", CONFIG["default_locale"])
        STRINGS = Strings(lang)
        not_banned_members = []

        for member in members:
            try:
                await member.ban(reason=reason)
                await ctx.send("Members banned")

            except discord.Forbidden:
                not_banned_members.append(member.mention)

            else:
                try:
                    embed = Utils.error_embed(
                        STRINGS["moderation"]["dm_ban"].format(
                            ctx.guild.name, reason))
                    await member.send(embed=embed)
                except:
                    pass

        if not not_banned_members:
            await ctx.message.add_reaction(CONFIG["yes_emoji"])
        else:
            await ctx.message.add_reaction(CONFIG["warn_emoji"])
            msg = await ctx.send(
                Utils.warn_embed(
                    STRINGS["moderation"]["on_not_full_multiban"].format(
                        ", ".join(not_banned_members))))
            await asyncio.sleep(30)
            await msg.delete()
示例#8
0
    async def ping(self, ctx: Context) -> NoReturn:
        """Shows host latency."""
        s = await Settings(ctx.guild.id)
        lang = await s.get_field("locale", CONFIG["default_locale"])
        STRINGS = Strings(lang)
        latency = int(round(self.bot.latency * 100, 1))

        embed = Utils.done_embed(STRINGS["other"]["pong"].format(str(latency)))
        await ctx.send(embed=embed)
示例#9
0
 async def unmute(
     self, ctx: Context, member: discord.Member, *, reason: str = "N/A"
 ) -> NoReturn:
     mute_role = discord.utils.get(
         ctx.guild.roles, id=Utils.get_mute_role(None, ctx.message)
     )
     if mute_role is None:
         # FIXME
         await ctx.send("нету роли мута ок да\n\n\nок")
     else:
         await member.remove_roles(mute_role)
         await ctx.message.add_reaction(CONFIG["yes_emoji"])
示例#10
0
    async def ban(
        self, ctx: Context, member: discord.Member, *, reason: str = "N/A"
    ) -> NoReturn:
        """Bans the user.

        Attributes:
        -----------
        - `member` - user
        - `reason` - ban reason

        """
        s = await Settings(ctx.guild.id)
        lang = await s.get_field("locale", CONFIG["default_locale"])
        STRINGS = Strings(lang)

        try:
            embed = Utils.error_embed(
                STRINGS["moderation"]["dm_ban"].format(ctx.guild.name, reason)
            )
            await member.send(embed=embed)
            await asyncio.sleep(5)
            await member.ban(reason=reason)

        except discord.Forbidden:
            await ctx.message.add_reaction(CONFIG["no_emoji"])
            embed = Utils.error_embed(STRINGS["error"]["ban_fail"])
            msg = await ctx.send(embed=embed)
            await asyncio.sleep(5)
            await msg.delete()

        else:
            try:
                embed = Utils.error_embed(
                    STRINGS["moderation"]["dm_ban"].format(ctx.guild.name, reason)
                )
                await member.send(embed=embed)
            except:
                pass

            await ctx.message.add_reaction(CONFIG["yes_emoji"])
示例#11
0
    async def _reload(self, ctx: Context, *, module: str) -> NoReturn:
        """Loads a module (cog). If the module is not found
            or an error is found in its code, it will throw an error.

        Attributes:
        -----------
        - `module` - the module to load

        """
        try:
            self.bot.reload_extension(f"cogs.{module}")
        except Exception as e:
            await ctx.message.add_reaction(CONFIG["no_emoji"])
            embed = Utils.error_embed("`{}`: {}".format(type(e).__name__, e))
            await ctx.send(embed=embed)
        else:
            await ctx.message.add_reaction(CONFIG["yes_emoji"])
示例#12
0
    async def purge(self, ctx: Context, number: int) -> NoReturn:
        """Deletes a specified number of messages in the current channel.

        Attributes:
        -----------
        - `number` - The number of messages to be deleted.

        """
        s = await Settings(ctx.guild.id)
        lang = await s.get_field("locale", CONFIG["default_locale"])
        STRINGS = Strings(lang)

        deleted = await ctx.channel.purge(limit=number + 1)

        embed = Utils.done_embed(STRINGS["moderation"]["on_clear"].format(len(deleted)))
        msg = await ctx.send(embed=embed)
        await asyncio.sleep(10)
        await msg.delete()
示例#13
0
    async def locale(self, ctx: Context, locale: str) -> NoReturn:
        """Sets bot language. If not found, it throws an error.

        Attributes:
        -----------
        - `locale` - new locale

        """
        s = await Settings(ctx.guild.id)
        locales = Utils.get_locales_list()

        for _locale in locales:
            if _locale == locale:
                await s.set_field("locale", locale)

                await ctx.message.add_reaction(CONFIG["yes_emoji"])
                return

        # FIXME
        await ctx.send("нет такой локали какбы")
示例#14
0
    async def kick(
        self, ctx: Context, member: discord.Member, *, reason: str = "N/A"
    ) -> NoReturn:
        """Kicks the user.

        Attributes:
        -----------
        - `member` - user
        - `reason` - kick reason

        """
        s = await Settings(ctx.guild.id)
        lang = await s.get_field("locale", CONFIG["default_locale"])
        STRINGS = Strings(lang)

        embed = Utils.error_embed(
            STRINGS["moderation"]["dm_kick"].format(ctx.guild, reason)
        )
        await member.send(embed=embed)
        await asyncio.sleep(5)
        await member.kick()
        await ctx.message.add_reaction(CONFIG["yes_emoji"])
示例#15
0
    async def unban(self, ctx, *, member) -> NoReturn:
        """Unbans the user.

        Attributes:
        -----------
        - `member` - user tag. Example: `name#1234`

        """
        s = await Settings(ctx.guild.id)
        lang = await s.get_field("locale", CONFIG["default_locale"])
        STRINGS = Strings(lang)

        select_components = [[
            Button(style=ButtonStyle.green, label="✓"),
            Button(style=ButtonStyle.red, label="X"),
        ]]
        done_components = [[
            Button(style=ButtonStyle.grey, label="·", disabled=True),
        ]]

        embedconfirm = discord.Embed(
            title="Unban Command",
            description="```Do you want to unban this member?```",
        )
        await ctx.send(embed=embedconfirm, components=select_components)
        response = await self.bot.wait_for(
            "button_click", check=lambda message: message.author == ctx.author)

        if "#" in ctx.message.content and response.component.label == "✓":
            banned_users = await ctx.guild.bans()
            for ban_entry in banned_users:
                member_name, member_discriminator = member.split("#")
                user = ban_entry.user
                if (user.name, user.discriminator) == (
                        member_name,
                        member_discriminator,
                ):
                    await ctx.guild.unban(user)
                    await response.respond(
                        type=7,
                        embed=discord.Embed(
                            title="Action confirmed",
                            description=f"Unbanned {user}",
                            color=0xFF8000,
                        ),
                        components=done_components,
                    )

            return
        elif response.component.label == "✓":
            member = await self.client.fetch_user(int(member))
            await ctx.guild.unban(member)
            await response.respond(
                type=7,
                embed=discord.Embed(
                    title="Action confirmed",
                    description=f"Unbanned {member}",
                    color=0xFF8000,
                ),
                components=done_components,
            )
        else:
            await response.respond(
                type=7,
                embed=discord.Embed(
                    title="Action Aborted",
                    description="The action was aborted by clicking the no button",
                    color=0xDD2E44,
                ),
                components=done_components,
            )

        await ctx.message.add_reaction(CONFIG["no_emoji"])
        embed = Utils.error_embed(STRINGS["error"]["user_not_found"])
        await ctx.send(embed=embed)
示例#16
0
    async def help(self, ctx: Context, command: str = None) -> NoReturn:
        """Shows help for a specific command, or displays a complete list of commands.

        Attributes:
        -----------
        - `command` - the command to display help for.
            If `command` is empty, displays a complete list of commands.
            If the command does not exist, writes that the command was not found.

        """
        s = await Settings(ctx.guild.id)
        lang = await s.get_field("locale", CONFIG["default_locale"])
        prefix = await s.get_field("prefix", CONFIG["default_prefix"])
        STRINGS = Strings(lang)
        COMMANDS = Commands(lang)

        if command is None:
            embed = discord.Embed(
                title=STRINGS["general"]["commands_list"],
                description=STRINGS["general"]["help_list_description"].format(
                    prefix),
                color=0xEF940B,
            )
            for i in COMMANDS:
                title = COMMANDS[i]["title"]

                description = ", ".join(f"`{j}`"
                                        for j in COMMANDS[i]["commands"])

                if self.bot.get_cog(i) is not None:
                    embed.add_field(name=title,
                                    value=description,
                                    inline=False)
            embed.set_footer(text=self.bot.user.name,
                             icon_url=self.bot.user.avatar_url)
            await ctx.send(embed=embed)

        elif command != "":
            for i in COMMANDS:
                for j in COMMANDS[i]["commands"]:
                    if command == j:
                        embed = discord.Embed(
                            title=STRINGS["general"]["helpsystemtitle"].format(
                                f"`{prefix}{j}`"),
                            color=0xEF940B,
                        )

                        embed.add_field(
                            name=STRINGS["general"]["description"],
                            value=COMMANDS[i]["commands"][j]["description"],
                            inline=False,
                        )

                        embed.add_field(
                            name=STRINGS["general"]["usage"],
                            value=COMMANDS[i]["commands"][j]["usage"].format(
                                prefix),
                            inline=False,
                        )

                        if len(COMMANDS[i]["commands"][j]["aliases"]) > 0:
                            aliases = ", ".join(f"`{alias}`"
                                                for alias in COMMANDS[i]
                                                ["commands"][j]["aliases"])

                            embed.add_field(
                                name=STRINGS["general"]["aliases"],
                                value=aliases,
                                inline=False,
                            )

                        embed.set_footer(text=self.bot.user.name,
                                         icon_url=self.bot.user.avatar_url)

                        await ctx.send(embed=embed)
                        return
            else:
                await ctx.send(embed=Utils.error_embed(STRINGS["error"]
                                                       ["command_not_found"]))
示例#17
0
from cogs.trivia import Trivia
from cogs.admin import Admin

intents = nextcord.Intents()
intents.members = True  # Join/Leave messages
intents.guild_messages = True  # Trivia
intents.bans = True  # Ban messages
intents.guilds = True  # Docs says so
intents.guild_reactions = True  # For roles

db = sqlite3.connect('data/malcolm.db')
cur = db.cursor()

logging.basicConfig(level=logging.WARN)
bot = Malcolm(command_prefix=',', intents=intents, configpath=sys.argv[1])


@bot.event
async def on_ready():
    logging.info('Malcolm-next has started')


bot.add_cog(JoinLeave(bot))
bot.add_cog(Trivia(bot, db, cur))
bot.add_cog(Utils(bot))
bot.add_cog(Roles(bot, db, cur))
bot.add_cog(Admin(bot))
bot.add_cog(Fun(bot))

bot.run()
示例#18
0
dirname = os.path.dirname(__file__)

cloud_config = {
    'secure_connect_bundle':
    os.path.join(dirname, '../secure-connect-giraffe-time.zip')
}
auth_provider = PlainTextAuthProvider(os.getenv('DB_USERNAME'),
                                      os.getenv('DB_PASSWORD'))
cluster = Cluster(cloud=cloud_config, auth_provider=auth_provider)
session = cluster.connect()

from discord.ext import commands
from cogs.fun import Fun
from cogs.utils import Utils
from cogs.reminder import Reminder
from cogs.roles import Roles

intent = discord.Intents.all()
client = discord.Client(intents=intent)

bot = commands.Bot(command_prefix='/', intents=intent)

# Add cogs here
bot.add_cog(Fun(bot, session))
bot.add_cog(Utils(bot, session))
bot.add_cog(Reminder(bot, session))
bot.add_cog(Roles(bot, session))

bot.run(os.getenv('DISCORD_TOKEN'))