コード例 #1
0
class Config(commands.Cog):
    """Bot configuration commands for Magoji."""
    def __init__(self, bot: Bot):
        self.bot = bot

    @commands.command(name="prefix")
    @commands.check_any(commands.has_permissions(manage_guild=True),
                        commands.is_owner())
    @commands.cooldown(rate=1, per=15, type=commands.BucketType.guild)
    async def prefix(self, ctx: Context, *, p: Optional[str]) -> None:
        """Change Magoji's perfix per guild"""
        if not p:
            await ctx.send_help(ctx.invoked_with)
            return

        if len(p) >= 255:
            await ctx.send("That's an invalid prefix!")
            return

        await self.bot.db.update_guild_prefix(ctx.guild.id, p)
        await ctx.send(f"Your prefix for this guild has been set to: `{p}`")

    @commands.command(name="log_channel", aliases=("logchannel", ))
    @commands.check_any(commands.has_permissions(manage_guild=True),
                        commands.is_owner())
    @commands.cooldown(rate=1, per=15, type=commands.BucketType.guild)
    async def _log_channel(self, ctx: Context,
                           channel: discord.TextChannel) -> None:
        """Sets the logging channel for your server."""

        await ctx.update_guild_config(log_channel=channel.id)
        embed = EmbedHelper(
            description=
            f"**✅ Logging channel has been set to {channel.mention}.**")
        await ctx.send(embed=embed)
コード例 #2
0
class Administrator(commands.Cog):
    @commands.command(brief="Reloads a module.")
    @commands.check(commands.is_owner())
    async def reload(self, ctx: commands.Context, module: str):
        discord_logger.info("{:s} issued command to reload module {:s}".format(
            str(ctx.message.author), module))
        try:
            ctx.bot.reload_extension("package." + module)
            await ctx.send("Reloaded extension {:s}.".format(module))
        except commands.ExtensionNotFound:
            await ctx.send(
                "Failed to reload extension {:s}: Not found.".format(module))
        except commands.ExtensionFailed:
            await ctx.send(
                "Failed to reload extension {:s}: Failed to set up.".format(
                    module))
        except commands.ExtensionNotLoaded:
            await ctx.send(
                "Failed to reload extension {:s}: Not loaded yet. Please use load command to load extension first."
                .format(module))

    @commands.command(brief="Unloads a module.")
    @commands.check(commands.is_owner())
    async def unload(self, ctx: commands.Context, module: str):
        discord_logger.info("{:s} issued command to unload module {:s}".format(
            str(ctx.message.author), module))
        try:
            ctx.bot.unload_extension("package." + module)
        except commands.ExtensionNotLoaded:
            await ctx.send(
                "Failed to unload extension {:s}: Not loaded yet. Please use load command to load extension first."
                .format(module))

    @commands.command(brief="Loads a module.")
    @commands.check(commands.is_owner())
    async def load(self, ctx: commands.Context, module: str):
        discord_logger.info("{:s} issued command to load module {:s}".format(
            str(ctx.message.author), module))
        try:
            ctx.bot.load_extension(module)
        except commands.ExtensionNotFound:
            await ctx.send(
                "Failed to load extension {:s}: Not found.".format(module))
        except commands.ExtensionAlreadyLoaded:
            await ctx.send(
                "Failed to load extension {0:s}: {0:s} was already loaded.".
                format(module))
        except commands.ExtensionFailed:
            await ctx.send(
                "Failed to load extension {0:s}: {0:s} errored in its entry function."
                .format(module))
コード例 #3
0
class Index(commands.Cog):

  def __init__(self, client):
    self.client = client

  @commands.check_any(commands.is_owner(), commands.has_permissions(administrator=True))       
  @commands.command(brief="Get topic index", description="Gets the index of the next question in the list. Useful for debugging. Only for use by the bot owner.")
  async def getindex(self, ctx):
    index = get_index(ctx.guild)
    await ctx.reply(f"Current index: **{index}**")

  @commands.check_any(commands.is_owner(), commands.has_permissions(administrator=True))       
  @commands.command(brief="Restart question cycle", description="Starts the question cycle from beginning by setting the topic index to 0. Next time a topic is requested the first one in the cycle will be returned. Useful for debugging. Only for use by the bot owner.")
  async def resetindex(self, ctx):
    reset_index(ctx.guild)
コード例 #4
0
class Config(commands.Cog):
    """Change the bot config."""
    def __init__(self, bot: Bot):
        self.bot = bot

    @commands.command(name="prefix")
    @commands.check_any(commands.is_owner(),
                        commands.has_guild_permissions(manage_guild=True))
    async def prefix(self, ctx: Context, *, new: str = None):
        """Set or get the guild prefix."""

        if not new:
            guild = await self.bot.db.fetch_guild(ctx.guild.id,
                                                  ctx.guild.owner_id)
            return await ctx.reply(
                f"The prefix in this server is `{guild['prefix']}`")

        if len(new) > 16:
            return await ctx.reply("Prefixes should be 16 characters or fewer."
                                   )

        await self.bot.db.set_guild_prefix(ctx.guild.id, new)
        await ctx.reply(f"Changed this server's prefix to `{new}`")

        del self.bot.prefixes[ctx.guild.id]
コード例 #5
0
 async def skip(self, ctx):
     queue = self.getQueue(ctx)
     if not ctx.voice_client:
         await ctx.send("Nobu not in voice channel.")
         return
     if commands.is_owner():
         queue.voice_client.stop()
         await ctx.send("Song skipped by developer.")
     elif ctx.author == queue.current_song.requested:
         queue.voice_client.stop()
         await ctx.send("Song skipped by requested.")
     else:
         needed = 2
         voice_members = len([
             member for member in queue.voice_client.channel.members
             if not member.bot
         ])
         if voice_members <= needed:
             needed = voice_members - 1
         if ctx.author.id not in queue.votes:
             queue.votes.append(ctx.author.id)
         else:
             await ctx.send("Duplicate vote!")
             return
         if len(queue.votes) >= needed:
             queue.voice_client.stop()
             await ctx.send("Song being skipped.")
         else:
             await ctx.send("{} votes to skip. {} needed in total.".format(
                 len.queue.votes, needed))
コード例 #6
0
async def goodbye(ctx):
    if commands.is_owner():
        await ctx.send("so long world, see you again soon! :wave:")
        await bot.change_presence(status=discord.Status.offline)
        await bot.logout()
    else:
        await ctx.send("You can't control me :triumph:")
コード例 #7
0
    async def predicate(ctx: custom.Context) -> Literal[True]:

        unwrapped = [
            wrapped.predicate for wrapped in  # type: ignore
            [
                commands.is_owner(),
                checks.is_guild_owner(),
                checks.has_any_permissions(
                    manage_channels=True,
                    manage_roles=True,
                    manage_guild=True,
                    kick_members=True,
                    ban_members=True,
                    administrator=True,
                ),
            ]
        ]
        errors = []

        for func in unwrapped:
            try:
                value = await func(ctx)
            except commands.CheckFailure as e:
                errors.append(e)
            else:
                if value:
                    return True

        raise commands.CheckAnyFailure(unwrapped, errors)  # type: ignore
コード例 #8
0
ファイル: Moderation.py プロジェクト: Dalwy/Ayame
 async def Ban(self, ctx, member: discord.Member, *, reason=''):
     """Aliases: 'b', 'ban'. Example: Ayame ban @user#0001 Being Disrespectful"""
     if commands.is_owner():
         return await ctx.send("Cant do that")
     db = sqlite3.connect('Main.sqlite')
     cursor = db.cursor()
     cursor.execute(
         "SELECT user_id, KickedOrBanned, guild_id FROM Moderation WHERE user_id = ? AND guild_id = ?",
         (
             member.id,
             member.guild.id,
         ))
     print(member.guild.id)
     print(member.id)
     result = cursor.fetchone()
     if result is None:
         sql = (
             f"INSERT OR IGNORE INTO Moderation (user_id, KickedOrBanned, reason, Staff, guild_id) "
             f"VALUES (?, ?, ?, ?, ?)")
         val = (member.id, "Banned", reason, ctx.author.id, member.guild.id)
         cursor.execute(sql, val)
         result = cursor.fetchone()
         print(result)
         db.commit()
     user = member
     embed = discord.Embed(title="Banned",
                           description="Reason: " + str(reason))
     embed.add_field(name='User Banned: ', value=str(member.mention))
     embed.add_field(name='Banned by: ', value=str(ctx.author.mention))
     embed.set_footer(text=str(user) + ' UID: ' + str(user.id))
     await ctx.send(embed=embed)
     await member.ban(reason=reason)
     msg = ctx.message
     await msg.delete()
コード例 #9
0
ファイル: tapir.py プロジェクト: RossSmyth/tapir-bot
class Tapir(commands.Cog):
    """the tapir command(s)"""

    def __init__(self, bot):
        self.bot = bot
        self.config = config.Config('tapirs.json', loop=bot.loop)

    @commands.command()
    @commands.cooldown(1, 10, commands.BucketType.channel)
    async def tapir(self, ctx):
        """The wonderful tapir command that outputs a random tapir"""
        tapir_list = self.config.get('tapirs', [])
        tapir = tapir_list[random.randrange(len(tapir_list))]

        embed = discord.Embed(colour=discord.Colour(0xa07553))
        embed.set_image(url="{}".format(tapir))

        await ctx.send(embed=embed)

    @commands.command(hidden=True)
    @commands.check(commands.is_owner())
    async def save_tapir(self, ctx, *, tapir_link):
        """allows the saving of a tapirs"""
        tapir_list = self.config.get('tapirs', [])
        tapir_list.append(tapir_link)
        await self.config.put('tapirs', tapir_list)
        await ctx.send('\N{OK HAND SIGN}')
コード例 #10
0
ファイル: moderation.py プロジェクト: ioistired/BotBot
class Moderation(commands.Cog):

    def __init__(self, bot: BotBase):
        self.bot = bot

    @commands.command(name='cleanup')
    @commands.check_any(commands.has_guild_permissions(manage_messages=True), commands.is_owner())
    async def cleanup(self, ctx: Context, limit: int = 50):
        """Deletes messages related to bot commands from the channel.

        `limit`: the number of messages to process, can be a maximum of 100 messages.
        """
        to_delete = []

        if not 0 < limit <= 100:
            raise commands.BadArgument('You can only delete between 1 and 100 messages.')

        async for message in ctx.channel.history(limit=limit):

            context = await self.bot.get_context(message)
            if message.author == self.bot.user:
                to_delete.append(message)

            if ctx.me.permissions_in(ctx.channel).manage_messages and context.command is not None:
                to_delete.append(message)

        await ctx.send(f'Deleted {len(to_delete)} messages', delete_after=5)

        if ctx.me.permissions_in(ctx.channel).manage_messages:
            await ctx.channel.delete_messages(to_delete)
        else:
            for message in to_delete:
                await message.delete(silent=True)
コード例 #11
0
ファイル: Ctrl.py プロジェクト: LT-bot/bot
 async def cog_check(self, context: commands.Context) -> bool:
     """
     Only bot owner and people with bot ctrl role can do this.
     """
     return await commands.check_any(
         commands.is_owner(),
         commands.has_role(int(
             conf["Roles"]["bot ctrl"]))).predicate(context)
コード例 #12
0
    async def command_callback(self,
                               ctx: Context,
                               *,
                               command: Optional[str] = None):
        # ignores the command for those who are neither the bot owner or a guild moderator

        if await commands.check_any(commands.is_owner(),
                                    is_guild_moderator()).predicate(ctx):
            return await super().command_callback(ctx, command=command)
コード例 #13
0
def bot_owner_or_in_guild(*guilds: discord.Object):
    """A check that determines if a user is the bot owner or in a particular guild"""

    is_owner = commands.is_owner().predicate

    async def predicate(ctx: Context) -> bool:
        return (ctx.guild and ctx.guild.id in guilds) or await is_owner(ctx)

    return commands.check(predicate)
コード例 #14
0
ファイル: fun.py プロジェクト: Thecoder3281F/Twenty-one
class Fun(commands.Cog):
    """weird commands for fun"""
    def __init__(self, bot):
        self.bot = bot

    # events
    @commands.Cog.listener()
    async def on_ready(self):
        print('Cog Fun is working.')

    # Commands
    @commands.command()
    async def ping(self, ctx):
        """latency"""
        await ctx.send(f'Pong! {round(self.bot.latency * 1000)} ms')

    @commands.command(aliases=['8ball'])
    async def _8ball(self, ctx, *, question):
        """the 8 ball command. """
        responses = [
            "It is certain.", "It is decidedly so.", "Without a doubt.",
            "Yes - definitely.", "You may rely on it.", "As I see it, yes.",
            "Most likely.", "Outlook good.", "Yes.", "Signs point to yes.",
            "Reply hazy, try again.", "Ask again later.",
            "Better not tell you now.", "Cannot predict now.",
            "Concentrate and ask again.", "Don't count on it.",
            "My reply is no.", "My sources say no.", "Outlook not so good.",
            "Very doubtful."
        ]
        await ctx.send(
            f'Question: {question}\nAnswer: {random.choice(responses)}')

    @commands.command(aliases=['randomfact'])
    async def random_fact(self, ctx):
        """random fact. self explanatory"""
        responses2 = [
            "9+10=21.", "I like 21", "hello", "um...",
            "Algodoo should have an update.", "hi", "good job!"
        ]
        await ctx.send(f'{random.choice(responses2)}')

    @commands.command(aliases=['dice'])
    async def roll_dice(self, ctx):
        """roll a dice from 1 to 6"""
        await ctx.send(f':game_die: {random.randint(1, 6)}')

    @commands.command(aliases=['repeat'])
    async def copy(self, ctx, *, statement):
        """repeats what you say"""
        await ctx.send(statement)

    @commands.command(aliases=['swap'])
    @commands.check_any(commands.is_owner())
    async def replace(self, ctx, *, statement):
        """replaces what you say"""
        await ctx.channel.purge(limit=1)
        await ctx.send(statement)
コード例 #15
0
class Utilities(commands.Cog):
    def __init__(self, client):
        self.client = client
        print("Utilities Loaded")

    @commands.command()
    @commands.check_any(commands.has_permissions(administrator=True),
                        commands.has_role('Moderator'))
    async def lock(self, ctx):
        pass

    @commands.command()
    @commands.check_any(commands.has_permissions(administrator=True),
                        commands.has_role('Moderator'))
    async def unlock(self, ctx):
        pass

    @commands.command()
    @commands.check_any(commands.is_owner(),
                        commands.has_permissions(administrator=True))
    async def echo(self,
                   ctx,
                   channel: typing.Optional[discord.TextChannel] = None,
                   *,
                   message):
        channel = ctx.channel if not channel else channel
        files = [
            await attachment.to_file()
            for attachment in ctx.message.attachments
        ] if ctx.message.attachments != [] else None
        await channel.send(message, files=files)

    @commands.command()
    @commands.has_permissions(administrator=True)
    async def dm(self, ctx, user: discord.Member, *, message):
        files = [
            await attachment.to_file()
            for attachment in ctx.message.attachments
        ] if ctx.message.attachments != [] else None
        await user.send(message, files=files)

    @commands.command(aliases=['sm', 'slowmode'])
    @commands.check_any(commands.has_permissions(administrator=True),
                        commands.has_role('Moderator'))
    async def slowmo(self,
                     ctx,
                     channel: typing.Optional[discord.TextChannel] = None,
                     *,
                     seconds: int):
        await channel.edit(slowmode_delay=seconds)
        if seconds == 0:
            await ctx.send(f"Slowmode disabled for {channel.mention}")
        else:
            await ctx.send(
                f"Channel {channel.mention} slowmode set to {seconds} seconds."
            )
コード例 #16
0
class Moderation(commands.Cog):
    def __init__(self, client):
        self.client = client

    @commands.command()
    @commands.check_any(commands.is_owner(),
                        commands.has_permissions(manage_messages=True))
    async def clear(self, ctx, amount=1):
        deleted_msgs = await ctx.channel.purge(limit=amount + 1)
        num_of_msgs = len(deleted_msgs) - 1
        message = await ctx.send(content=str(num_of_msgs) +
                                 " messages were deleted",
                                 delete_after=2)

    @commands.command()
    @commands.check_any(commands.is_owner(),
                        commands.has_permissions(kick_members=True))
    async def kick(self, ctx, member: discord.Member, *, reason=None):
        await member.kick(reason=reason)
        await ctx.send(str(member) + " was kicked")

    @commands.command()
    @commands.check_any(commands.is_owner(),
                        commands.has_permissions(ban_members=True))
    async def ban(self, ctx, member: discord.Member, *, reason=None):
        await member.ban(reason=reason)
        await ctx.send(str(member) + " was banned")

    @commands.command()
    @commands.check_any(commands.is_owner(),
                        commands.has_permissions(ban_members=True))
    async def unban(self, ctx, *, member):
        bannedUsers = await ctx.guild.bans()
        memberName, memberDiscriminator = member.split("#")

        for banEntry in bannedUsers:
            user = banEntry.user

            if (user.name, user.discriminator) == (memberName,
                                                   memberDiscriminator):
                await ctx.guild.unban(user)
                await ctx.send(str(user) + " was unbanned")
                return
コード例 #17
0
def bot_owner_or_permissions(**perms):
    """A check that determines if a user is the bot owner or if the author has specific permissions"""

    has_perms = commands.has_permissions(**perms).predicate
    is_owner = commands.is_owner().predicate

    async def predicate(ctx: Context) -> bool:
        return await has_perms(ctx) or await is_owner(ctx)

    return commands.check(predicate)
コード例 #18
0
def bot_owner_or_guild_moderator():
    """A check that determines if a user is the bot owner or if the bot owner is a guild moderator"""

    is_mod = is_guild_moderator().predicate
    is_owner = commands.is_owner().predicate

    async def predicate(ctx: Context) -> bool:
        return await is_mod(ctx) or await is_owner(ctx)

    return commands.check(predicate)
コード例 #19
0
ファイル: BotControl.py プロジェクト: leduythuccs/potd
class BotControl(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    # @commands.Cog.listener()
    # async def on_ready(self):
    #     pass

    # from TLE bot.
    @commands.command(brief="Check if bot is still alive.")
    async def ping(self, ctx):
        """Replies to a ping."""
        start = time.perf_counter()
        message = await ctx.send('<:pingreee:665243570655199246>')
        end = time.perf_counter()
        duration = (end - start) * 1000
        await message.edit(
            content=
            f'<:pingreee:665243570655199246>\nREST API latency: {int(duration)}ms\n'
            f'Gateway API latency: {int(self.bot.latency * 1000)}ms')

    @commands.command(brief="Kill bot. ")
    @commands.check_any(commands.is_owner(),
                        commands.has_any_role('Admin', 'Mod VNOI'))
    async def kill(self, ctx):
        """Kill bot"""
        await ctx.send("Dying")
        exit(0)

    @commands.command(brief='Restart bot')
    @commands.check_any(commands.is_owner(),
                        commands.has_any_role('Admin', 'Mod VNOI'))
    async def restart(self, ctx):
        await ctx.send('Restarting...')
        os.execv(sys.executable, [sys.executable] + sys.argv)

    @commands.command(brief='Get database')
    @commands.check_any(commands.is_owner(),
                        commands.has_any_role('Admin', 'Mod VNOI'))
    async def db(self, ctx):
        await ctx.send(
            file=discord.File('database/potd.db', filename='potd.db'))
コード例 #20
0
ファイル: bans.py プロジェクト: elenawinters/Stitch
class Moderation(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    @commands.command(aliases=['ban', 'hban'])
    @commands.has_permissions(ban_members=True)
    @core.checks.is_banned()  # Simple hackban
    async def hackban(self, ctx, snowflake, *, reason='User was hackbanned'):
        try:
            await ctx.guild.ban(tls.Snowflake(snowflake), delete_message_days=0, reason=reason)
            await ctx.send(f'Hackbanned <@!{snowflake}> with reason `{reason}`.')
        except discord.Forbidden as err:
            await funcs.respond(ctx, err)
        except discord.HTTPException as err:
            await funcs.respond(ctx, err)
        except Exception as err:
            log.exception(err)

    @commands.command(aliases=['gban'])
    @core.checks.is_banned()  # To globally ban an account. (complicated D: )
    @commands.check_any(commands.is_owner(), core.checks.ban_assitant())
    async def globalban(self, ctx, snowflake, *, reason='User was globally banned'):
        ban = data.base['bans'].find_one(id=snowflake)
        if not ban:  # If None, ban
            gban = dict(
                id=snowflake,
                reason=f'{reason} (Global Ban)',
                by=ctx.author.id,
                date=datetime.datetime.utcnow()
            )
            data.base['bans'].upsert(gban, ['id'])
            await ban_sweep(self)
            await ctx.send(f'<@!{ctx.author.id}> globally banned <@!{snowflake}> with reason `{reason}`.')
        else:
            await ctx.send(f"<@!{snowflake}> was already globally banned by <@!{ban['by']}> with reason `{ban['reason']}` at `{ban['date']} (UTC)`")

    @commands.Cog.listener()  # Attempt kickban on join
    async def on_member_join(self, member):
        await ban_attempt(self, member.guild, member.id)

    @commands.Cog.listener()  # Reban if unbanned
    async def on_member_unban(self, guild, user):
        await ban_attempt(self, guild, user.id)

    @commands.Cog.listener()  # Initial sweep on ready
    async def on_ready(self):
        await ban_sweep(self)

    @commands.Cog.listener()  # Sweep every 5 minutes based on member updates, which are quite frequent
    async def on_member_update(self, before, after):  # This should be called constantly, hopefully. At least once a minute
        global rate
        if time.time.diff(rate, datetime.datetime.utcnow()).seconds >= 300:  # 5 minute rate limit
            rate = datetime.datetime.utcnow()
            await ban_sweep(self)
コード例 #21
0
ファイル: internal.py プロジェクト: Kronifer/bot
    def __init__(self, bot: Bot):
        self.bot = bot
        self.env = {}
        self.ln = 0
        self.stdout = StringIO()

        self.socket_since = arrow.utcnow()
        self.socket_event_total = 0
        self.socket_events = Counter()

        if DEBUG_MODE:
            self.eval.add_check(is_owner().predicate)
コード例 #22
0
class Admin(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    @commands.check_any(commands.is_owner(), commands.has_role('Admin'))
    @commands.command(name='purge',
                      brief='Purges [X] amount of messages from the chat')
    async def purge(self, ctx, amount=0):
        await ctx.channel.purge(limit=amount + 1)

    @commands.check_any(commands.is_owner())
    @commands.command(name='prune',
                      brief='Purges inactive members from the Discord server')
    async def prune(self, ctx):
        prune_count = await ctx.guild.prune_members(
            days=30,
            compute_prune_count=True,
            roles=ctx.guild.roles or None,
            reason='Pruned for inactivity')
        await ctx.send(
            f'Pruned {prune_count} inactive members from the server.')
コード例 #23
0
class RandomCommands(commands.Cog):
    def __init__(self, client):
        self.client = client
        self.thumbnail_url = "https://cdn.discordapp.com/icons/694003889506091100/a_c40ba19cfcfbb9db5f5060e85f6539cf.png?size=128"
        self.map_embed = discord.Embed(
            title="Map du Projet BTE",
            colour=discord.Colour(0x00FF00),
            description="https://buildtheearth.net/map")
        self.youtube_embed = discord.Embed(
            title="YouTube de BTE: France",
            colour=discord.Colour(0xFF0000),
            description=
            "https://www.youtube.com/channel/UCZwaYbXg_umFjI0knBV5PhA")
        self.twitter_embed = discord.Embed(
            title="Twitter de BTE: France",
            colour=discord.Colour(0x0000FF),
            description="https://twitter.com/BuildFr")
        self.instagram_embed = discord.Embed(
            title="Instagram de BTE: France",
            colour=discord.Colour(0xFFFF00),
            description="https://www.instagram.com/bte_france/")
        self.map_embed.set_thumbnail(url=self.thumbnail_url)
        self.youtube_embed.set_thumbnail(url=self.thumbnail_url)
        self.twitter_embed.set_thumbnail(url=self.thumbnail_url)
        self.instagram_embed.set_thumbnail(url=self.thumbnail_url)

    @commands.command(brief='Donne la latence du bot')
    async def ping(self, ctx):
        await ctx.send(f'Pong! {round(self.client.latency*1000)}ms')

    @commands.command(aliases=['purge'],
                      brief='Supprime les x derniers messages')
    @commands.check_any(commands.is_owner(),
                        commands.has_permissions(manage_roles=True,
                                                 manage_channels=True))
    async def clear(self, ctx, number=1):
        await ctx.channel.purge(limit=number + 1)

    @commands.command(brief='Lien de la Map BTE')
    async def map(self, ctx):
        await ctx.send(embed=self.map_embed)

    @commands.command(brief='Lien YouTube', aliases=['ytb', 'yt'])
    async def youtube(self, ctx):
        await ctx.send(embed=self.youtube_embed)

    @commands.command(brief='Lien Twitter', aliases=['twi'])
    async def twitter(self, ctx):
        await ctx.send(embed=self.twitter_embed)

    @commands.command(brief='Lien Instagram', aliases=['insta'])
    async def instagram(self, ctx):
        await ctx.send(embed=self.instagram_embed)
コード例 #24
0
ファイル: manage.py プロジェクト: jtexeira/WALL-E
class Manage(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    @commands.command(
        name='castigo',
        brief='Punish someone for their sins. [ADMIN ONLY]',
        help='This command gives the role "castigo" to the specified user(s).',
        usage='user1[, user2[, ...]] [reason]')
    @commands.check_any(commands.is_owner(),
                        commands.has_permissions(administrator=True))
    async def castigo(self, ctx: commands.Context):
        castigo = [x for x in ctx.guild.roles
                   if x.name.lower() == "castigo"][0]
        for member in ctx.message.mentions:
            await member.add_roles(castigo,
                                   reason=(' '.join([
                                       x
                                       for x in ctx.message.content.split()[2:]
                                       if '<@!' not in x
                                   ])))

    @commands.command(
        name='perdoar',
        brief='Forgive someone for their sins. [ADMIN ONLY]',
        help=
        'This command removes the role "castigo" from the specified user(s).',
        usage='user1[, user2[, ...]] [reason]')
    @commands.check_any(commands.is_owner(),
                        commands.has_permissions(administrator=True))
    async def perdoar(self, ctx: commands.Context):
        castigo = [x for x in ctx.guild.roles
                   if x.name.lower() == "castigo"][0]
        for member in ctx.message.mentions:
            await member.remove_roles(
                castigo,
                reason=(' '.join([
                    x for x in ctx.message.content.split()[2:]
                    if '<@!' not in x
                ])))
コード例 #25
0
class MTwowAdministrator(commands.Cog):
    @commands.command(brief="Initialises database.")
    @commands.check(commands.is_owner())
    async def init(self, ctx: commands.Context):
        sqlutils.init(conn)

    @commands.command(brief="Wipes database.")
    @commands.check(commands.is_owner())
    async def wipe(self, ctx: commands.Context):
        sqlutils.wipe(conn)

    @commands.command(brief="Starts signups.")
    @commands.check(commands.is_owner())
    async def start_signups(self, ctx: commands.Context, time: parse_time):
        if time[0] == 0:
            ret = admin.start_signups(conn, time[1])
            if ret is not None:
                await ctx.send("Error: " + ret[1])
            else:
                await ctx.send("Started signups!")
        else:
            await ctx.send("Error: " + time[1])
コード例 #26
0
class HelpBuilding(commands.Cog):
    def __init__(self, client):
        self.client = client

    async def add_emojis(self, message, node):
        for child in node.children:
            try:
                await message.add_reaction(child.emoji)
            except discord.errors.HTTPException:
                print(f"Emoji {child.emoji} not found!")

    @commands.command(brief='[WIP] Aide type FAQ en cours de création')
    @commands.check_any(commands.is_owner())
    async def build(self, ctx):
        if ctx.channel.type != discord.ChannelType.private:
            await ctx.send(f"{ctx.author.mention}, regarde tes MPs! :mailbox:")
        message = await ctx.author.send(embed=discord.Embed(
            description=root.question))
        await self.add_emojis(message, root)

    @commands.command(brief='Trouve le nom d\'une emoji')
    @commands.check_any(commands.is_owner())
    async def emojiname(self, ctx, emoji):
        await ctx.author.send(emoji.encode('ascii', 'namereplace'))

    @commands.Cog.listener()
    async def on_reaction_add(self, reaction, user):
        if reaction.message.channel.type == discord.ChannelType.private and not user.bot:
            try:
                node = root.get_node(reaction.message.embeds[0].description)
            except Exception:
                return
            for child in node.children:
                if child.emoji == reaction.emoji:
                    message = await reaction.message.channel.send(
                        embed=discord.Embed(type='rich',
                                            description=child.question))
                    await self.add_emojis(message, child)
                    break
コード例 #27
0
class Admin(Cog):
    def __init__(self, client):
        self.client = client

    # Command to load a cog (also called 'extension' or 'module')
    @check_any(has_permissions(administrator=True), is_owner())
    @command(name='load', hidden=True)
    async def load(self, context, extension):
        try:
            self.client.load_extension(self.client.COGS_FOLDER + extension)
            print('Successfully loaded extension \'{}\''.format(extension))
        except Exception as error:
            print('Extension \'{}\' cannot be loaded. [Reason: {}]'.format(
                extension, error))

    # Command to unload a cog (also called 'extension' or 'module')
    @check_any(has_permissions(administrator=True), is_owner())
    @command(name='unload', hidden=True)
    async def unload(self, context, extension):
        if extension != "admin" and extension != "debug":
            try:
                self.client.unload_extension(self.client.COGS_FOLDER +
                                             extension)
                print(
                    'Successfully unloaded extension \'{}\''.format(extension))
            except Exception as error:
                print(
                    'Extension \'{}\' cannot be unloaded. [Reason: {}]'.format(
                        extension, error))
        else:
            print(
                'Access denied: You cannot EVER unload extensions \'admin\' or \'debug\'.'
            )

    @check_any(has_permissions(administrator=True), is_owner())
    @command(nam='adminhelp', hidden=True, aliases=['admincommands'])
    async def adminhelp(self, context):
        await get_hidden_commands(self.client, dirname(__file__))
コード例 #28
0
class Moderation(commands.Cog):
    """Obviously in progress"""
    def __init__(self, bot):
        self.bot = bot

    @commands.Cog.listener()
    async def on_ready(self):
        print('Cog Moderation is working.')

    @commands.command()
    @commands.check_any(commands.is_owner())
    async def kick(self, ctx, member: discord.Member, *, reason=None):
        """self explanatory. Mention member"""
        await member.kick(reason=reason)
        await ctx.send(f'Kicked {member.mention}')

    @commands.command()
    @commands.check_any(commands.is_owner())
    async def ban(self, ctx, member: discord.Member, *, reason=None):
        """self explanatory. Mention member"""
        await member.ban(reason=reason)
        await ctx.send(f'Banned {member.mention}')

    @commands.command()
    @commands.check_any(commands.is_owner())
    async def unban(self, ctx, *, member):
        """self explanatory. Type member's user and discriminator"""
        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.send(f'Unbanned {user.mention}')
                return
コード例 #29
0
ファイル: BombBot.py プロジェクト: KxC954/DiscCountdown
async def blow(ctx):
    global x, m, h
    if commands.is_owner():
        if x == 0:
            while x < 12 * h:
                x = x + 1
                time.sleep(1)
                if x == 6 * h:
                    await ctx.send("@everyone 6 HOURS REMAINING.")

                if x < 60:
                    await ctx.send("{} seconds remaining.".format(60 - x))
            await ctx.send("Boom.")
        if x > 0:
            await ctx.send("Bomb already ticking !")
コード例 #30
0
ファイル: whitelist.py プロジェクト: Daggy1234/BotBot
class Whitelist(Cog):
    def __init__(self, bot: BotBase):
        self.bot = bot
        bot.loop.create_task(self.add_users())

    @commands.group(aliases=["vww"])
    @commands.check_any(commands.is_owner(), is_dpy_mod())
    async def voice_woes_whitelist(self, ctx: Context):
        """Voice woes whitelist management commands."""
        if ctx.invoked_subcommand is not None:
            return

        paginator = EmbedPaginator(
            colour=discord.Colour.orange(),
            title="Voice Woes Whitelist",
            max_description=512,
        )
        paginator.set_footer(text="user (bb)vww add, and (bb)vww remove to manage the whitelist.")

        for user_id in self.bot.whitelisted_users:
            paginator.add_line(f"<@{user_id}>")

        menu = menus.MenuPages(paginator)
        await menu.start(ctx)

    @voice_woes_whitelist.command(name="add")
    async def voice_woes_whiitelist_add(self, ctx: Context, member: discord.User):
        """Add a user to the voice woes whitelist."""
        async with ctx.db as connection:
            await VoiceWoesWhitelist.insert(connection, user_id=member.id)
        self.bot.whitelisted_users.add(member.id)
        await ctx.tick()

    @voice_woes_whitelist.command(name="remove")
    async def voice_woes_whiitelist_remove(self, ctx: Context, member: discord.User):
        """Remove a user from the voice woes whitelist."""
        async with ctx.db as connection:
            await VoiceWoesWhitelist.delete(connection, user_id=member.id)
        self.bot.whitelisted_users.remove(member.id)
        await ctx.tick()

    async def add_users(self):
        await self.bot.wait_until_ready()

        async with MaybeAcquire(pool=self.bot.pool) as connection:
            for record in await VoiceWoesWhitelist.fetch(connection):
                self.bot.whitelisted_users.add(record["user_id"])