Esempio n. 1
0
class Cleaner(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    @slash_command(name='clear',
                   description="Чистит канал от сообщений ботов.")
    async def clear(
        self, ctx,
        channel: Option(discord.TextChannel,
                        'Выберите пользователя, которому выдаём Вотум',
                        required=False,
                        default=None),
        count: Option(int,
                      'Число последний сообщений, которые нужно удалить',
                      required=False,
                      default=10,
                      min_value=1,
                      max_value=500)):
        if not channel:
            channel = ctx.channel
        async for i in channel.history(limit=int(count)):
            if i.author.id == self.bot.user.id:
                await i.delete()
        return await ctx.send("Чат очищен успешно")

    @slash_command(name='purge',
                   description="Чистит канал от сообщений пользователей.",
                   default_permission=False,
                   permissions=[
                       permissions.CommandPermission(id="moderator",
                                                     type=8192,
                                                     permission=True)
                   ])
    async def purge(
        self, ctx,
        channel: Option(discord.TextChannel,
                        'Выберите пользователя, которому выдаём Вотум',
                        required=False,
                        default=None),
        count: Option(int,
                      'Число последний сообщений, которые нужно удалить',
                      required=False,
                      default=10,
                      min_value=1,
                      max_value=500)):
        if not channel:
            channel = ctx.channel
        async for i in channel.history(limit=int(count)):
            if i.author.id == self.bot.user.id:
                await i.delete()
        return await ctx.send("Чат очищен успешно")
Esempio n. 2
0
class VoiceRole(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    @commands.Cog.listener()
    async def on_voice_state_update(self, member, before, after):
        vc_roles = await voicerole.get_voice_roles_by_guild(member.guild.id)

        if after.channel is not None and before.channel is not None:
            if after.channel.id == before.channel.id:
                return
        if after.channel is not None:
            for vc_role in vc_roles:
                if after.channel.id == vc_role['voice_channel_id']:
                    role = discord.utils.get(
                        member.guild.roles, id=vc_role['role_id'])
                    await member.add_roles(role, reason='Joined voice channel.')
        if before.channel is not None:
            for vc_role in vc_roles:
                if before.channel.id == vc_role['voice_channel_id']:
                    role = discord.utils.get(
                        member.guild.roles, id=vc_role['role_id'])
                    await member.remove_roles(role, reason='Left voice channel.')
        return

    voicerole = discord.commands.SlashCommandGroup(
        "voicerole",
        "Commands for managing voice roles.",
        permissions=[permissions.CommandPermission(
            "owner", 2, True
        )
        ])

    @voicerole.command(name='create')
    async def vr_create(self, ctx, voice_channel: Option(discord.VoiceChannel, description="Voice channel to monitor."), role: Option(discord.Role, description="Role to assign to members in the voice channel.")):
        await voicerole.create_voice_role(ctx.guild.id, voice_channel.id, role.id)
        await ctx.respond(f"Created voice role mapping for {voice_channel.mention}", ephemeral=True)

    @voicerole.command(name='delete')
    async def vr_delete(self, ctx, role_id: int):
        await voicerole.delete_voice_role(ctx.guild.id, role_id)
        await ctx.respond(f"Deleted voice role mapping for {role_id}", ephemeral=True)
Esempio n. 3
0
class Config(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    guildconfig = discord.commands.SlashCommandGroup(
        "guildconfig",
        "Miscellaneous guild configuration commands for the bot's owner.",
        permissions=[
            permissions.CommandPermission(
                "owner", 2, True
            )
        ]
    )

    @guildconfig.command()
    async def set(self, ctx: ApplicationContext, parameter: Option(str), value: Option(str)):
        """
        Set a guild configuration parameter.
        """
        ctx.guild.config.set(parameter, value)
        await ctx.respond(f"Set {parameter} to {value}", ephemeral=True)

    @guildconfig.command()
    async def get(self, ctx: ApplicationContext):
        """
        Get a guild configuration parameter.
        """
        await ctx.respond(ctx.guild.config.dump(), ephemeral=True)

    @guildconfig.command()
    async def delete(self, ctx: ApplicationContext, parameter: Option(str)):
        """
        Delete a guild configuration parameter.
        """
        ctx.guild.config.delete(parameter)
        await ctx.respond(f"Deleted {parameter}", ephemeral=True)
Esempio n. 4
0
class Nickname(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    # @commands.command(
    #     help="Register your Twitch name with SahasrahBot."
    # )
    # async def twitch(self, ctx, twitch):
    #     await srlnick.insert_twitch_name(ctx.author.id, twitch)

    # @commands.command(
    #     help="Register your RaceTime.gg nick with SahasrahBot."
    # )
    # async def rtgg(self, ctx):
    #     await ctx.reply(f"Please visit <{APP_URL}/racetime/verification/initiate> to verify your RaceTime.gg ID!")

    # @commands.command(
    #     help="List the nicknames registered with SahasrahBot."
    # )
    # async def getnick(self, ctx):
    #     nick = await srlnick.get_nickname(ctx.author.id)
    #     if nick:
    #         await ctx.reply(f"Your currently registered nickname for Twitch is `{nick[0]['twitch_name']}`")
    #     else:
    #         await ctx.reply("You currently do not have any nicknames registered with this bot.  Use the command `$twitch yournick` to do that!")

    racetime_admin_group = discord.commands.SlashCommandGroup(
        "rtggadmin",
        "Miscellaneous administrative commands for RaceTime.gg",
        permissions=[permissions.CommandPermission("owner", 2, True)])

    @racetime_admin_group.command()
    @permissions.is_owner()
    async def blast(self, ctx: ApplicationContext,
                    role_name: Option(str,
                                      "Choose a role to blast",
                                      required=True,
                                      autocomplete=role_name_autocomplete)):
        """
        Used by Synack to blast requests to link your RaceTime.gg account to this bot.
        """
        role: discord.Role = discord.utils.get(ctx.guild._roles.values(),
                                               name=role_name)
        await ctx.defer()
        msg = []
        for member in role.members:
            result = await models.SRLNick.get_or_none(discord_user_id=member.id
                                                      )
            if result is None or result.rtgg_id is None:
                try:
                    await member.send((
                        f"Greetings {member.name}!  We have detected that you do not have a RaceTime.gg ID linked to SahasrahBot.\n"
                        f"Please visit <{APP_URL}/racetime/verification/initiate> to verify your RaceTime.gg ID!  We will need this info.\n\n"
                        "If you have any questions, please contact Synack.  Thank you!"
                    ))
                    msg.append(
                        f"Send DM to {member.name}#{member.discriminator}")
                except (discord.Forbidden, discord.HTTPException) as e:
                    msg.append(
                        f"Failed to send DM to {member.name}#{member.discriminator}.\n\n{str(e)}"
                    )

        if msg:
            await ctx.respond("\n".join(msg))
        else:
            await ctx.respond("No messages sent.")

    @racetime_admin_group.command()
    async def report(self, ctx: ApplicationContext,
                     role_name: Option(str,
                                       "Choose a role to report",
                                       required=True,
                                       autocomplete=role_name_autocomplete)):
        """
        Used by Synack to report users who have not linked their racetime account to SahasrahBot.
        """
        await ctx.defer()
        role: discord.Role = discord.utils.get(ctx.guild._roles.values(),
                                               name=role_name)
        msg = []
        for member in role.members:
            result = await models.SRLNick.get_or_none(discord_user_id=member.id
                                                      )
            if result is None or result.rtgg_id is None:
                msg.append(f"{member.name}#{member.discriminator}")

        if msg:
            await ctx.respond("\n".join(msg))

        else:
            await ctx.respond(
                "Everyone in this role is registered with the bot.")
Esempio n. 5
0
class DiscordServers(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    discordservers = discord.commands.SlashCommandGroup(
        "discordservers",
        "Commands for updating the discord server list.",
        permissions=[
            permissions.CommandPermission(
                "owner", 2, True
            )
        ]
    )

    category = discordservers.create_subgroup("category", "Manage catagories.")

    @category.command(name='add')
    async def category_add(self, ctx: ApplicationContext, channel: Option(discord.TextChannel, required=True), category_title: Option(str), category_description: Option(str, default=None), order=Option(int, default=0)):
        """
        Add a category to the discord server list.
        """
        await discord_server_lists.add_category(ctx.guild.id, channel.id, category_title=category_title, category_description=category_description, order=order)
        await ctx.respond(f"Added category {category_title} to {channel.mention}", ephemeral=True)

    @category.command(name='list')
    async def category_list(self, ctx: ApplicationContext):
        """
        List all categories in the server.
        """
        results = await discord_server_lists.get_categories(ctx.guild.id)
        if results:
            embed = discord.Embed(
                title="List of categories",
                color=discord.Colour.blue(),
            )
            for result in results:
                channel = ctx.guild.get_channel(result['channel_id'])
                embed.add_field(
                    name=result['category_title'],
                    value=f"_*Id:*_ {result['id']}\n_*Channel:*_ {channel.mention}",
                    inline=False
                )
            await ctx.respond(embed=embed)

    @category.command(name='remove')
    async def category_remove(self, ctx: ApplicationContext, category_id: Option(int, required=True)):
        await discord_server_lists.remove_category(ctx.guild.id, category_id)
        await ctx.respond(f"Removed category {category_id}", ephemeral=True)

    @category.command(name='update')
    async def category_update(self, ctx: ApplicationContext, category_id: Option(int, required=True), category_title: Option(str), category_description: Option(str, default=None), order=Option(int, default=0)):
        """
        Update a category.
        """
        await discord_server_lists.update_category(category_id, ctx.guild.id, category_title, category_description, order)
        await ctx.respond(f"Updated category {category_id}", ephemeral=True)

    server = discordservers.create_subgroup("server", "Manage servers in a category.")

    @server.command(name='add')
    async def server_add(self, ctx, category_id: Option(int, required=True), invite: discord.Invite, server_description: str):
        """
        Add a server to a category.
        """
        await discord_server_lists.add_server(ctx.guild.id, invite.id, category_id, server_description=server_description)
        await ctx.respond(f"Added server {invite.guild.name} to category {category_id}", ephemeral=True)

    @server.command(name='list')
    async def server_list(self, ctx: ApplicationContext, category_id: int):
        """
        List all servers in a category.
        """
        results = await discord_server_lists.get_servers_for_category(category_id)

        if results:
            embed = discord.Embed(
                title=f"Server list for category id {category_id}",
                color=discord.Colour.blue(),
            )
            for result in results:
                embed.add_field(
                    name=result['server_description'],
                    value=f"_*Id:*_ {result['id']}",
                    inline=False
                )
            await ctx.respond(embed=embed)

    @server.command(name='remove')
    async def server_remove(self, ctx, server_id: int):
        """
        Remove a server from the discord server list.
        """
        await discord_server_lists.remove_server(ctx.guild.id, server_id)
        await ctx.respond(f"Removed server {server_id}", ephemeral=True)

    @server.command(name='update')
    async def server_update(self, ctx, server_id: int, invite: discord.Invite, category_id: int, server_description: str = None):
        """
        Update a server in the discord server list.
        """
        await discord_server_lists.update_server(ctx.guild.id, server_id, invite.id, category_id, server_description)
        await ctx.respond(f"Updated server {server_id}", ephemeral=True)

    @discordservers.command()
    async def refresh(self, ctx):
        """
        Refresh the discord server list.
        """
        await ctx.defer()

        def is_me(m):
            return m.author == self.bot.user

        categories = await discord_server_lists.get_categories(ctx.guild.id)
        channels_to_update = list(set([c['channel_id'] for c in categories]))

        for c in channels_to_update:
            channel = discord.utils.get(ctx.guild.channels, id=c)
            await channel.purge(limit=100, check=is_me)

        for category in categories:
            server_list = await discord_server_lists.get_servers_for_category(category['id'])
            channel = discord.utils.get(
                ctx.guild.channels, id=category['channel_id'])

            list_of_servers = [server_list[i:i+10]
                               for i in range(0, len(server_list), 10)]

            for idx, servers in enumerate(list_of_servers):
                msgs = [
                    f"**__{category['category_title']}__**" if len(
                        list_of_servers) == 1 else f"**__{category['category_title']} - Part {idx+1}__**"
                ]
                msgs += [f"{s['server_description']}: https://discord.gg/{s['invite_id']}" for s in servers]
                await channel.send('\n'.join(msgs))

        await ctx.respond(f"Refreshed server list for {ctx.guild.name}", ephemeral=True)
Esempio n. 6
0
                            member = None

                        if member is None:
                            member = event_data.guild.get_member_named(
                                player.get('discordTag', ''))

                        if member is None:
                            messages.append(
                                f"Episode {episode['id']} - {event_slug} - {player['displayName']} could not be found"
                            )

        return messages

    @commands.slash_command(
        name='alttpr2022',
        permissions=[permissions.CommandPermission("owner", 2, True)])
    async def alttpr2022(self, ctx, player1: discord.Member,
                         player2: discord.Member):
        """
        Generate a randomizer seed for the ALTTPR Main Tournament 2022.
        """
        await ctx.defer()
        seed, preset, deck = await alttpr.roll_seed([player1, player2])

        embed = await seed.embed(emojis=self.bot.emojis)
        embed.insert_field_at(0, name="Preset", value=preset, inline=False)
        if deck:
            embed.insert_field_at(
                1,
                name="Deck",
                value="\n".join([f"**{p}**: {c}" for p, c in deck.items()]),