Python discord.ext.commands 模块,command() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用discord.ext.commands.command()

项目:Jumper-Cogs    作者:Redjumpman    | 项目源码 | 文件源码
def code_clear(self, settings, server, user, number):
        userid = [subdict for subdict in settings["Pending"]
                  if number in settings["Pending"][subdict]]
        if userid:
            mobj = server.get_member(userid[0])
            await self.bot.say("Do you want to clear this pending item for {}?".format(mobj.name))
            response = await self.bot.wait_for_message(timeout=15, author=user)
            if response is None:
                msg = "Timeout response, cancelling clear command."
            elif response.content.title() == "No":
                msg = "Cancelling clear command."
            elif response.content.title() == "Yes":
                settings["Pending"][mobj.id].pop(number, None)
                msg = "Pending item {}, cleared for user {}".format(number, mobj.name)
            else:
                msg = "Incorrect response, cancelling clear command."
        else:
            msg = "The confirmation code provided could not be found."
        await self.bot.say(msg)
项目:Jumper-Cogs    作者:Redjumpman    | 项目源码 | 文件源码
def _xferlimit_setcasino(self, ctx, limit: int):
        """This is the limit of chips a player can transfer at one time.

        Remember, that without a cooldown, a player can still use this command
        over and over. This is just to prevent a transfer of outrageous amounts.

        """
        author = ctx.message.author
        settings = super().check_server_settings(author.server)

        if limit > 0:
            settings["System Config"]["Transfer Limit"] = limit
            msg = _("{} set transfer limit to {}.").format(author.name, limit)
            logger.info("SETTINGS CHANGED {}({}) {}".format(author.name, author.id, msg))
            super().save_system()
        else:
            msg = _("Limit must be higher than 0.")

        await self.bot.say(msg)
项目:CorpBot.py    作者:corpnewt    | 项目源码 | 文件源码
def recheckrole(self, ctx, *, user : discord.Member = None):
        """Re-iterate through all members and assign the proper roles based on their xp (admin only)."""

        author  = ctx.message.author
        server  = ctx.message.server
        channel = ctx.message.channel

        isAdmin = author.permissions_in(channel).administrator

        # Only allow admins to change server stats
        if not isAdmin:
            await self.bot.send_message(channel, 'You do not have sufficient privileges to access this command.')
            return

        if not user:
            user = author

        # Now we check for promotions
        if await CheckRoles.checkroles(user, channel, self.settings, self.bot):
            await self.bot.send_message(channel, 'Done checking roles.\n\n*{}* was updated.'.format(DisplayName.name(user)))
        else:
            await self.bot.send_message(channel, 'Done checking roles.\n\n*{}* was not updated.'.format(DisplayName.name(user)))
项目:discordbot.py    作者:rauenzi    | 项目源码 | 文件源码
def on_command_error(self, error, ctx):
        ignored = (commands.NoPrivateMessage, commands.DisabledCommand, commands.CheckFailure,
                   commands.CommandNotFound, commands.UserInputError, discord.HTTPException)
        error = getattr(error, 'original', error)

        if isinstance(error, ignored):
            return

        if ctx.message.server:
            fmt = 'Channel: {0} (ID: {0.id})\nGuild: {1} (ID: {1.id})'
        else:
            fmt = 'Channel: {0} (ID: {0.id})'

        exc = traceback.format_exception(type(error), error, error.__traceback__, chain=False)
        description = '```py\n%s\n```' % ''.join(exc)
        time = datetime.datetime.utcnow()

        name = ctx.command.qualified_name
        author = '{0} (ID: {0.id})'.format(ctx.message.author)
        location = fmt.format(ctx.message.channel, ctx.message.server)

        message = '{0} at {1}: Called by: {2} in {3}. More info: {4}'.format(name, time, author, location, description)

        self.bot.logs['discord'].critical(message)
项目:Jumper-Cogs    作者:Redjumpman    | 项目源码 | 文件源码
def notify_handler(self, settings, ctx, itemname, user, confirmation):
        role = settings["Config"]["Shop Role"]
        if "Role" not in settings["Users"][user.id]["Inventory"][itemname]:
            if settings["Config"]["Shop Notify"] and role is not None:
                msg = ("{} was added to the pending list by {}.\nConfirmation#: {}.\nUser ID: "
                       "{}".format(itemname, user.name, confirmation, user.id))
                names = self.role_check(role, ctx)
                destinations = [m for m in ctx.message.server.members if m.name in names]
                for destination in destinations:
                    await self.bot.send_message(destination, msg)
            await self.bot.say("```{} has been added to pending list. Your confirmation number is "
                               "{}.\nTo check the status of your pending items, use the command "
                               "{}pending check```".format(itemname, confirmation, ctx.prefix))
        else:
            await self.bot.say("{} just received the {} role!".format(user.name, itemname))
        quantity = 1
        self.user_remove_item(settings, user, itemname, quantity)
项目:Jumper-Cogs    作者:Redjumpman    | 项目源码 | 文件源码
def blackjack(self, ctx, bet: int):
        """Modified Blackjack."""

        # Declare variables for the game.
        user = ctx.message.author
        settings = super().check_server_settings(user.server)

        # Run a logic check to determine if the user can play the game
        check = self.game_checks(settings, ctx.prefix, user, bet, "Blackjack", 1, [1])
        if check:
            msg = check
        else:  # Run the game when the checks return None
            super().withdraw_chips(user, bet)
            settings["Players"][user.id]["Played"]["Blackjack"] += 1
            deck = main_deck[:]  # Make a copy of the deck so we can remove cards that are drawn
            dhand = self.dealer(deck)
            ph, dh, amt = await self.blackjack_game(dhand, user, bet, deck)
            msg = self.blackjack_results(settings, user, amt, ph, dh)
        # Send a message telling the user the outcome of this command
        await self.bot.say(msg)
项目:Harmonbot    作者:Harmon758    | 项目源码 | 文件源码
def gofish_start(self, ctx, *players : str):
        '''WIP'''
        self.gofish_channel = ctx.message.channel
        if ctx.message.server:
            for member in ctx.message.server.members:
                if member.name in players:
                    self.gofish_players.append(member)
                    break
        else:
            await self.bot.embed_reply(":no_entry: Please use that command in a server")
            pass
        gofish.start(len(players))
        gofish_players_string = ""
        for player in self.gofish_players:
            gofish_players_string += player.name + " and "
        await self.bot.embed_reply("{} has started a game of Go Fish between {}!".format(message.author.display_name, gofish_players_string[:-5]))
项目:Harmonbot    作者:Harmon758    | 项目源码 | 文件源码
def __init__(self, bot):
        self.bot = bot
        # Add commands as random subcommands
        for name, command in inspect.getmembers(self):
            if isinstance(command, commands.Command) and command.parent is None and name != "random":
                self.bot.add_command(command)
                self.random.add_command(command)
        # Add fact subcommands as subcommands of corresponding commands
        for command, parent in ((self.fact_cat, self.cat), (self.fact_date, self.date), (self.fact_number, self.number)):
            utilities.add_as_subcommand(self, command, parent, "fact")
        # Add random subcommands as subcommands of corresponding commands
        self.random_subcommands = ((self.color, "Resources.color"), (self.giphy, "Resources.giphy"), (self.map, "Resources.map"), (self.streetview, "Resources.streetview"), (self.uesp, "Search.uesp"), (self.wikipedia, "Search.wikipedia"), (self.xkcd, "Resources.xkcd"))
        for command, parent_name in self.random_subcommands:
            utilities.add_as_subcommand(self, command, parent_name, "random")
        # Import jokes
        self.jokes = []
        try:
            with open("data/jokes.csv", newline = "") as jokes_file:
                jokes_reader = csv.reader(jokes_file)
                for row in jokes_reader:
                    self.jokes.append(row[0])
        except FileNotFoundError:
            pass
项目:Harmonbot    作者:Harmon758    | 项目源码 | 文件源码
def discriminator(self, ctx, *, name : str = ""):
        '''
        Get a discriminator
        Your own or someone else's discriminator
        '''
        if not name:
            await self.bot.embed_reply("Your discriminator: #" + ctx.message.author.discriminator)
            return
        if not ctx.message.server:
            await self.bot.embed_reply(":no_entry: Please use that command in a server")
            return
        flag = True
        for member in ctx.message.server.members:
            if member.name == name:
                embed = discord.Embed(description = name + "'s discriminator: #" + member.discriminator, color = clients.bot_color)
                avatar = member.default_avatar_url if not member.avatar else member.avatar_url
                embed.set_author(name = str(member), icon_url = avatar)
                await self.bot.reply("", embed = embed)
                flag = False
        if flag and name:
            await self.bot.embed_reply(name + " was not found on this server")
项目:CorpBot.py    作者:corpnewt    | 项目源码 | 文件源码
def setwelcome(self, ctx, *, message = None):
        """Sets the welcome message for your server (bot-admin only). [[user]] = user name, [[atuser]] = user mention, [[server]] = server name"""

        isAdmin = ctx.message.author.permissions_in(ctx.message.channel).administrator
        if not isAdmin:
            checkAdmin = self.settings.getServerStat(ctx.message.server, "AdminArray")
            for role in ctx.message.author.roles:
                for aRole in checkAdmin:
                    # Get the role that corresponds to the id
                    if aRole['ID'] == role.id:
                        isAdmin = True
        # Only allow admins to change server stats
        if not isAdmin:
            await self.bot.send_message(ctx.message.channel, 'You do not have sufficient privileges to access this command.')
            return

        if message == None:
            self.settings.setServerStat(ctx.message.server, "Welcome", None)
            await self.bot.send_message(ctx.message.channel, 'Welcome message removed!')
            return

        self.settings.setServerStat(ctx.message.server, "Welcome", message)
        await self.bot.send_message(ctx.message.channel, 'Welcome message updated!\n\nHere\'s a preview:')
        await self._welcome(ctx.message.author, ctx.message.server, ctx.message.channel)
项目:CorpBot.py    作者:corpnewt    | 项目源码 | 文件源码
def setgoodbye(self, ctx, *, message = None):
        """Sets the goodbye message for your server (bot-admin only). [[user]] = user name, [[atuser]] = user mention, [[server]] = server name"""

        isAdmin = ctx.message.author.permissions_in(ctx.message.channel).administrator
        if not isAdmin:
            checkAdmin = self.settings.getServerStat(ctx.message.server, "AdminArray")
            for role in ctx.message.author.roles:
                for aRole in checkAdmin:
                    # Get the role that corresponds to the id
                    if aRole['ID'] == role.id:
                        isAdmin = True
        # Only allow admins to change server stats
        if not isAdmin:
            await self.bot.send_message(ctx.message.channel, 'You do not have sufficient privileges to access this command.')
            return

        if message == None:
            self.settings.setServerStat(ctx.message.server, "Goodbye", None)
            await self.bot.send_message(ctx.message.channel, 'Goodbye message removed!')
            return

        self.settings.setServerStat(ctx.message.server, "Goodbye", message)
        await self.bot.send_message(ctx.message.channel, 'Goodbye message updated!\n\nHere\'s a preview:')
        await self._goodbye(ctx.message.author, ctx.message.server, ctx.message.channel)
项目:CorpBot.py    作者:corpnewt    | 项目源码 | 文件源码
def setrules(self, ctx, *, rules : str = None):
        """Set the server's rules (admin only)."""

        isAdmin = ctx.message.author.permissions_in(ctx.message.channel).administrator
        # Only allow admins to change server stats
        if not isAdmin:
            await self.bot.send_message(ctx.message.channel, 'You do not have sufficient privileges to access this command.')
            return

        if rules == None:
            rules = ""

        self.settings.setServerStat(ctx.message.server, "Rules", rules)
        msg = 'Rules now set to:\n{}'.format(rules)

        await self.bot.send_message(ctx.message.channel, msg)
项目:CorpBot.py    作者:corpnewt    | 项目源码 | 文件源码
def setsstat(self, ctx, stat : str = None, value : str = None):
        """Sets a server stat (admin only)."""

        author  = ctx.message.author
        server  = ctx.message.server
        channel = ctx.message.channel

        isAdmin = author.permissions_in(ctx.message.channel).administrator
        # Only allow admins to change server stats
        if not isAdmin:
            await self.bot.send_message(channel, 'You do not have sufficient privileges to access this command.')
            return

        if stat == None or value == None:
            msg = 'Usage: `{}setsstat Stat Value`'.format(ctx.prefix)
            await self.bot.send_message(channel, msg)
            return

        self.setServerStat(server, stat, value)

        msg = '**{}** set to *{}!*'.format(stat, value)
        await self.bot.send_message(channel, msg)
项目:CorpBot.py    作者:corpnewt    | 项目源码 | 文件源码
def recheckroles(self, ctx):
        """Re-iterate through all members and assign the proper roles based on their xp (admin only)."""

        author  = ctx.message.author
        server  = ctx.message.server
        channel = ctx.message.channel

        isAdmin = author.permissions_in(channel).administrator

        # Only allow admins to change server stats
        if not isAdmin:
            await self.bot.send_message(channel, 'You do not have sufficient privileges to access this command.')
            return

        changeCount = 0
        for member in server.members:
            # Now we check for promotions
            if await CheckRoles.checkroles(member, channel, self.settings, self.bot, True):
                changeCount += 1

        if changeCount == 1:
            await self.bot.send_message(channel, 'Done checking roles.\n\n*1 user* updated.')
        else:
            await self.bot.send_message(channel, 'Done checking roles.\n\n*{} users* updated.'.format(changeCount))
项目:CorpBot.py    作者:corpnewt    | 项目源码 | 文件源码
def setchatchannel(self, ctx, *, channel : discord.Channel = None):
        """Sets the channel for bot chatter."""
        isAdmin = ctx.message.author.permissions_in(ctx.message.channel).administrator
        # Only allow admins to change server stats
        if not isAdmin:
            await self.bot.send_message(ctx.message.channel, 'You do not have sufficient privileges to access this command.')
            return

        if channel == None:
            self.settings.setServerStat(ctx.message.server, "ChatChannel", "")
            msg = 'Chat channel removed - must use the `{}chat [message]` command to chat.'.format(ctx.prefix)
            await self.bot.send_message(ctx.message.channel, msg)
            return

        # If we made it this far - then we can add it
        self.settings.setServerStat(ctx.message.server, "ChatChannel", channel.id)
        msg = 'Chat channel set to **{}**.'.format(channel.name)
        await self.bot.send_message(ctx.message.channel, msg)
项目:CorpBot.py    作者:corpnewt    | 项目源码 | 文件源码
def setbotparts(self, ctx, *, parts : str = None):
        """Set the bot's parts - can be a url, formatted text, or nothing to clear."""

        isAdmin = ctx.message.author.permissions_in(ctx.message.channel).administrator
        # Only allow admins to change server stats
        if not isAdmin:
            await self.bot.send_message(ctx.message.channel, 'You do not have sufficient privileges to access this command.')
            return

        channel = ctx.message.channel
        author  = ctx.message.author
        server  = ctx.message.server

        if not parts:
            parts = ""

        self.settings.setUserStat(self.bot.user, server, "Parts", parts)
        msg = '*{}\'s* parts have been set to:\n{}'.format(DisplayName.serverNick(self.bot.user, server), parts)
        await self.bot.send_message(channel, msg)
项目:Sitryk-Cogs    作者:Sitryk    | 项目源码 | 文件源码
def addcommand(self, ctx, *, command):
        """Restricts all co-owners from using [command] """

        confirm = await self._confirm_owner(ctx)
        if not confirm:
            return

        AliasCog = self.bot.get_cog('Alias')
        if AliasCog:
            alias_loaded = False
        else:
            alias_loaded = True
        server = ctx.message.server
        t = True if self.bot.get_command(command) else False
        if not t and alias_loaded:
            t = True if command in AliasCog.aliases[server.id] else False
        if t and command not in self.settings["RESTRICTED"]:
            await self.bot.say("**All owners will be restricted from using**: {}".format(command))
            self.settings["RESTRICTED"].append(command)
            dataIO.save_json(self.path, self.settings)
        elif command in self.settings["RESTRICTED"]:
            await self.bot.say("{} is already a restricted command".format(command))
        else:
            await self.bot.say("{} is not a valid command.".format(command))
项目:spirit    作者:jgayfer    | 项目源码 | 文件源码
def get_command_signature(self, prefix, cmd):
        """Create a user friendly command signature"""
        result = []
        params = cmd.clean_params
        parent = cmd.full_parent_name
        name = prefix + cmd.name if not parent else prefix + parent + ' ' + cmd.name
        result.append(name)

        # Format arguments to display which are required and which are optional
        if len(params) > 0:
            for name, param in params.items():
                if param.default is not param.empty:
                    result.append('[{}]'.format(name))
                elif param.kind == param.VAR_POSITIONAL:
                    result.append('[{}...]'.format(name))
                else:
                    result.append('<{}>'.format(name))
        return(' '.join(result))
项目:spirit    作者:jgayfer    | 项目源码 | 文件源码
def on_guild_join(self, guild):
        """Send welcome message to the server owner"""
        message = ("Greetings! My name is **{}**, and my sole responsibility is to help you and "
                   "your group kick ass in Destiny 2! You're receiving this message because you "
                   "or one of your trusted associates has added me to **{}**.\n\n"
                   "**Command Prefix**\n\n"
                   "My default prefix is **!**, but you can also just mention me with **@{}**. "
                   "If another bot is already using the **!** prefix, you can choose a different prefix "
                   "for your server with **!settings setprefix <new_prefix>** (don't include the brackets).\n\n"
                   "For a list of all available commands, use the **!help** command. If you want more "
                   "information on a command, use **!help <command_name>**.\n\n"
                   "If you have any feedback, you can use my **!feedback** command to send "
                   "a message to my developer! If you want to request a feature, report a bug, "
                   "stay up to date with new features, or just want some extra help, check out the official "
                   "{} Support server! (https://discord.gg/GXCFpkr)"
                   ).format(self.bot.user.name, guild.name, self.bot.user.name,
                            self.bot.user.name, self.bot.user.name)
        await guild.owner.send(message)
项目:PTSCogs    作者:PlanetTeamSpeakk    | 项目源码 | 文件源码
def spam(self, ctx, user : discord.Member, spamtext, number : int=0):
        """Spams x times, default is 4."""
        if user.id == "96987941519237120":
            await self.bot.say("Hell nah, I ain't spamming him.")
            return
        if user.id == settings.owner:
            await self.bot.say("Hell nah, I ain't spamming him. If you want to spam my owner use the `suggest` command!")
            return
        if number >> 8:
            await self.bot.say("Hell nah, not past 8 for fck sakes.")
            return
        if number == 0:
            number = 4
        counter = 0
        while counter < number:
            try:
                await self.bot.send_message(user, "{}, sent by **{}**".format(spamtext, ctx.message.author))
            except discord.Forbidden:
                await self.bot.say("{} blocked me :sob:".format(user.mention))
                return
            counter = counter + 1
            if counter == 1:
                await self.bot.say("Hehe, {} got spammed {} time!".format(user.mention, counter))
            else:
                await self.bot.say("Hehe, {} got spammed {} time!".format(user.mention, counter))
项目:lagbot    作者:mikevb1    | 项目源码 | 文件源码
def nostalgia(self, ctx, date: date = None, *, channel: discord.TextChannel = None):
        """Pins an old message from a specific date.

        If a date is not given, then pins first message from the channel.
        If a channel is not given, then pins from the channel the
        command was ran on.

        The format of the date must be either YYYY-MM-DD or YYYY/MM/DD.
        """

        if channel is None:
            channel = ctx.channel
        if date is None:
            date = channel.created_at

        async for m in ctx.history(after=date, limit=1):
            try:
                await m.pin()
            except:
                await ctx.send('\N{THUMBS DOWN SIGN} Could not pin message.')
项目:lagbot    作者:mikevb1    | 项目源码 | 文件源码
def on_member_join(self, member):
        """Automatically assign roles if guild has a role set through `newrole` command."""
        if not member.guild.me.guild_permissions.manage_roles:
            return
        async with self.bot.db_pool.acquire() as con:
            role_id = await con.fetchval('''
                SELECT role_id FROM newrole WHERE guild_id = $1
                ''', member.guild.id)
            if role_id is None:
                return
            role = discord.utils.get(member.guild.roles, id=role_id)
            if role is None:
                async with con.transaction():
                    await con.execute('''
                        DELETE FROM newrole WHERE guild_id = $1
                        ''', member.guild.id)
                return
        await member.add_roles(role, reason='New Member')
项目:Luna    作者:Moonlington    | 项目源码 | 文件源码
def rquote(self, ctx):
        """From a list of random quotes, it says one."""
        quotes = [
            'YOU THOUGHT THIS COMMENT WOULD MENTION [name] BUT IT WAS I, DIO!',
            'Even [name] didn\'t understand the usage of this command, However, [name] knew the truth! This command existed in order to be fun! The quotes that fueled the fun made this command exist! This command makes appear a random quote! he said.',
            'DID YOU QUOTE THIS TOO, [name]!? TELL ME!?\nWhat are you even asking? i settled this quote and you walked right into it!',
            'Even a bastard like me spot true evil when it sees it, true evil are those who use the weak for their own gain! Especially a innocent woman! And that is exactly what you\'ve done, isnt it [name]?!, thats why... I\'ll judge you myself!',
            'What is a [name]? A miserable little pile of secrets. But enough talk.',
            'Thank you [name]! But our Princess is in another castle!',
            'This is your fault. I\'m going to kill you. And all the [name] is gone. You don\'t even care, do you?',
            'The right man in the wrong place can make all the difference in the [name].',
            'I am the great mighty [name], and Im going to throw my shit at you.',
            'Why, that\'s the second biggest [name] head I\'ve ever seen!',
            'Look behind you, a three headed [name]!',
            'In the year 200x a super robot named [name] was created.',
            '[name] has been kidnapped by ninjas. Are you a bad enough dude to rescue the president?',
            'You were almost a [name] sandwich!',
            'All your [name] are belong to us.']
        i = random.randrange(len(quotes))
        quote = quotes[i]
        x = random.randrange(len(ctx.message.server.members))
        user = list(ctx.message.server.members)[x]
        fquote = quote.replace('[name]', user.name)
        await self.bot.say(fquote)
项目:PomodoroBot    作者:VicenteRD    | 项目源码 | 文件源码
def timer(self, ctx):
        """ Controls the channel's timer. Do '!help timer' for sub-commands.
            None of the sub-commands will really work without using `setup`
            first.
        """

        if ctx.invoked_subcommand is None:
            sect = ctx.message.content.split(' ')
            if len(sect) < 2 or sect[1] is None:
                log = "{} invoked an incomplete timer command."

                send = "Timers are allowed here. Now what?"
            else:
                log = "{} invoked an invalid timer command."
                send = "Invalid timer sub-command."
        else:
            return

        lib.log(log.format(lib.get_author_name(ctx)),
                channel_id=lib.get_channel_id(ctx))
        await self.bot.say(send, delete_after=self.bot.ans_lifespan)
项目:Godavaru    作者:Godavaru    | 项目源码 | 文件源码
def kill(self, ctx):
        """Attempt to kill people. Has a chance of failing. Also, you may only kill one user at a time, so this command does not (and will never) have multi mention support.

        **Usage:** `g_kill <user>`

        **Permission:** User"""
        killmsg = ["**"+ctx.message.mentions[0].display_name+"** was stabbed by **"+ctx.message.author.display_name+"**", "You tried to kill **"+ctx.message.mentions[0].display_name+"**, but you got caught by the police :<", "**"+ctx.message.mentions[0].display_name+"** disintegrated.", "While trying to kill **"+ctx.message.mentions[0].display_name+"**, **"+ctx.message.author.display_name+"** accidentally killed themselves.", "**"+ctx.message.mentions[0].display_name+"** drowned.", "Hahahaha nice try. You just tried to kill a cop. You're in jail now.", "While trying to kill **"+ctx.message.mentions[0].display_name+"**, you accidentally pinged b1nzy. Ouch.", "You pushed **"+ctx.message.mentions[0].display_name+"** into a river with crocodiles.", "You made **"+ctx.message.mentions[0].display_name+"** listen to KidzBop, so they bled out of their ears and died.", "Meh. I don't feel like helping a murder today. Try again.", "**"+ctx.message.mentions[0].display_name+"** was thrown into a pit of snakes.", "**"+ctx.message.author.display_name+"** threw **"+ctx.message.mentions[0].display_name+"** into a pit of snakes, but fell in as well.", "**"+ctx.message.mentions[0].display_name+"** was given the death sentence after **"+ctx.message.author.display_name+"** framed them for murder.", "**"+ctx.message.mentions[0].display_name+"** was forced to use Kotlin by **"+ctx.message.author.display_name+"**, so they died.", "**"+ctx.message.author.display_name+"** tried to kill someone, but found their way into Mantaro Hub and gave into the memes.", "**"+ctx.message.mentions[0].display_name+"** was killed by a sentient robot... Why are you looking at me? I didn't do it...", "**"+ctx.message.author.display_name+"** tried to kill someone and got away from the police. However, the FBI jailed them.", "You don't have a weapon. Oops. Was I supposed to bring it? I think I was...", "When **"+ctx.message.author.display_name+"** tried to kill **"+ctx.message.mentions[0].display_name+"**, they were disappointed to find they were already dead.", "**"+ctx.message.mentions[0].display_name+"** took an arrow to the knee! Well, actually it was a gunshot. And it was actually to the heart."]
        var = int(random.random() * len(killmsg))

        if len(ctx.message.mentions) == 0:
            await ctx.send(":x: You must mention a user!")
        elif len(ctx.message.mentions) > 0:
            if ctx.message.mentions[0].id == ctx.message.author.id:
                await ctx.send("Don't kill yourself! I love you!")
            elif ctx.message.mentions[0].id == ctx.message.guild.me.id:
                await ctx.send("You tried to kill me, but you realised I'm a bot. So I killed you instead.")
            else:
                await ctx.send(killmsg[var])
        else:
            await ctx.send("An unexpected error occurred. Please report this to Desiree#3658 on the support guild, link found in g!about.") # just in case. You never know shrug
项目:Inkxbot    作者:InkxtheSquid    | 项目源码 | 文件源码
def __init__(self, bot):
        self.bot = bot
        #self.loop = AbstractEventLoop.run_in_executor()

        """def get_cards(self):
        #You can change for fitting your language deDE, enUS, esES, esMX,
        #frFR, itIT, jaJP, koKR, plPL, ptBR, ruRU, thTH, zhCN, zhTW
        response = requests.get('https://api.hearthstonejson.com/v1/12574/enUS/cards.collectible.json')#, 'https://api.hearthstonejson.com/v1/13619/enUS/cards.collectible.json', 'https://api.hearthstonejson.com/v1/15181/enUS/cards.collectible.json', 'https://api.hearthstonejson.com/v1/15300/enUS/cards.collectible.json')#
        data = response.json()
        return data


        @commands.command()
        async def hearthcard(self, args):
        data = get_cards()
        cardname = data['"name": 'args]
        attack = data['"attack": ']
        if data["type": "MINION"] == True:
            await self.bot.say('**{0}** \n' +
            """
项目:Brick    作者:T3CHNOLOG1C    | 项目源码 | 文件源码
def concern(self, ctx):
        """MEMES?"""
        await ctx.send("https://i.imgur.com/cWXBb5g.png")

## Ill finish this later

##    @commands.cooldown(rate=1, per=10.0, type=commands.BucketType.channel)
##    @commands.command()
##    async def dongroder(self, ctx, variant=""):
##    """MEMES?!?
##    This meme has multiple variants : piter, swotch.
##    If no variant is specified, it will defautlt to piter."""
##        if variant == "piter":
##            await ctx.send(
##                "I'm so sorry, I was a fucking retard for saying words that would get me in touble and anger lots of people who are transgender or who are dating a transgender person. " +
##                "I didn't think before I spoke a word so it just came out as something totally wrong, I don't hate anybody who is transgender, just the community. I like Aurora, just not the trans community. I'm sorry for all of this. All I'm asking for is a apology is all. I should have been thinking before I spoke."
##            )
##        elif variant == "swotch":
##            await ctx.send(
##                "I'm so sorry, I was a fucking retard for saying words that would get me in touble and anger lots of people who are bees or who are dating a bee. I didn't think before I spoke a word so it just came out as something totally wrong, I don't hate anybody who is a bee, just the hive. " +
##                "I like bees, just not the beehive. I'm sorry for all of this. All I'm asking for is a apology is all. I should have been thinking before I spoke."
##            )
项目:aryas    作者:lattkkthxbbye    | 项目源码 | 文件源码
def clear(self, ctx: commands.Context, number: int, member: discord.Member = None) -> None:
        """
        Purges messages from the channel
        :param ctx: The message context
        :param number: The number of messages to purge
        :param member: The member whose messages will be cleared
        """

        if number < 1:
            await command_error(ctx, "You must attempt to purge at least 1 message!")
            return

        def predicate(msg: discord.Message) -> bool:
            return msg == ctx.message or member is None or msg.author == member

        if number <= 100:
            #  Add 1 to limit to include command message, subtract 1 from the return to not count it.
            msgs = await self.bot.purge_from(ctx.message.channel, limit=number + 1, check=predicate)
            send(self.bot, '{} message{} cleared.'.format(len(msgs) - 1, "s" if len(msgs) - 1 != 1 else ""),
                 ctx.message.channel, True)
        else:
            await command_error(ctx, 'Cannot delete more than 100 messages at a time.')
项目:kitsuchan-2    作者:n303p4    | 项目源码 | 文件源码
def help(self, ctx, *cmds: str):
        """Help command.

        * command_or_cog - The name of a command or cog.
        """
        if not cmds:
            commands_list = []
            for command in ctx.bot.commands:
                if command.hidden:
                    continue
                try:
                    can_run = await command.can_run(ctx)
                except Exception:
                    continue
                if can_run:
                    commands_list.append(command.name)
            commands_list.sort()
            help_text = f'```{", ".join(commands_list)}```'
            help_text += f"\nRun **help command** for more details on a command."
            help_text = "**List of commands:**\n" + help_text
            await ctx.send(help_text)
        else:
            # This is awful, haha
            await ctx.bot.all_commands["old_help"].callback(ctx, *cmds)
项目:kitsuchan-2    作者:n303p4    | 项目源码 | 文件源码
def sh(self, ctx, *, command):
        """Execute a system command. Bot owner only."""
        command = command.split(" ")
        process = subprocess.Popen(command,
                                   universal_newlines=True,
                                   stdout=subprocess.PIPE,
                                   stderr=subprocess.PIPE)
        try:
            output, errors = process.communicate(timeout=8)
            output = output.split("\n")
            process.terminate()
        except subprocess.TimeoutExpired:
            process.kill()
            output = ["Command timed out. x.x"]
        paginator = commands.Paginator(prefix="```bash")
        for line in output:
            paginator.add_line(line)
        for page in paginator.pages:
            await ctx.send(page)
项目:discordbot.py    作者:rauenzi    | 项目源码 | 文件源码
def on_command(self, command, ctx):
        message = ctx.message
        if message.channel.is_private:
            id = ctx.message.author.id
            destination = 'Private Message'
        else:
            id = ctx.message.server.id
            destination = '#{0.channel.name} ({0.server.name})'.format(message)

        self.bot.logs['stats'].info('{0.timestamp}: {0.author.name} in {1}: {0.content}'.format(message, destination))

        data = self.config.get('data', {})
        server_data = data.get(id, {})
        server_data[ctx.command.qualified_name] = server_data.get(ctx.command.qualified_name, 0) + 1
        data[id] = server_data
        await self.config.put('data', data)
项目:discordbot.py    作者:rauenzi    | 项目源码 | 文件源码
def disable(self, ctx, *, command: str):
        """Disables a command for this server.

        You must have Manage Server permissions or the
        Bot Admin role to use this command.
        """
        command = command.lower()

        if command in ('enable', 'disable'):
            return await self.bot.responses.failure(message='Cannot disable that command.')

        if command not in self.bot.commands:
            return await self.bot.responses.failure(message='Command "{}" was not found.'.format(command))

        guild_id = ctx.message.server.id
        cmds = self.config.get('commands', {})
        entries = cmds.get(guild_id, [])
        entries.append(command)
        cmds[guild_id] = entries
        await self.config.put('commands', cmds)
        await self.bot.responses.success(message='"%s" command disabled in this server.' % command)
项目:discordbot.py    作者:rauenzi    | 项目源码 | 文件源码
def _all(self, ctx):
        """Ignores every channel in the server from being processed.

        This works by adding every channel that the server currently has into
        the ignore list. If more channels are added then they will have to be
        ignored by using the ignore command.

        To use this command you must have Manage Server permissions along with
        Manage Channels permissions. You could also have the Bot Admin role.
        """

        ignored = self.config.get('ignored', [])
        channels = ctx.message.server.channels
        ignored.extend(c.id for c in channels if c.type == discord.ChannelType.text)
        await self.config.put('ignored', list(set(ignored))) # make unique
        await self.bot.responses.success(message='All channels ignored.')
项目:discordbot.py    作者:rauenzi    | 项目源码 | 文件源码
def plonk(self, ctx, *, member: discord.Member):
        """Bans a user from using the bot.

        This bans a person from using the bot in the current server.
        There is no concept of a global ban. This ban can be bypassed
        by having the Manage Server permission.

        To use this command you must have the Manage Server permission
        or have a Bot Admin role.
        """

        plonks = self.config.get('plonks', {})
        guild_id = ctx.message.server.id
        db = plonks.get(guild_id, [])

        if member.id in db:
            await self.bot.responses.failure(message='That user is already bot banned in this server.')
            return

        db.append(member.id)
        plonks[guild_id] = db
        await self.config.put('plonks', plonks)
        await self.bot.responses.success(message='%s has been banned from using the bot in this server.' % member)
项目:calebj-cogs    作者:calebj    | 项目源码 | 文件源码
def quote(self, ctx, *, author_or_num: str = None):
        """Say a stored quote!

        Without any arguments, this command randomly selects from all stored
        quotes. If you supply an author name, it randomly selects from among
        that author's quotes. Finally, if given a number, that specific quote
        will be said, assuming it exists. Use [p]lsquotes to show all quotes.
        """

        sid = ctx.message.server.id
        if sid not in self.quotes or len(self.quotes[sid]) == 0:
            await self.bot.say("There are no quotes in this server!")
            return

        try:
            quote = self._get_quote(ctx, author_or_num)
        except commands.BadArgument:
            if author_or_num.lower().strip() in ['me', 'myself', 'self']:
                quote = self._get_quote(ctx, ctx.message.author)
            else:
                raise
        await self.bot.say(self._format_quote(ctx, quote))
项目:Jumper-Cogs    作者:Redjumpman    | 项目源码 | 文件源码
def setcookie(self, ctx):
        """Cookie settings group command"""

        if ctx.invoked_subcommand is None:
            await send_cmd_help(ctx)
项目:Jumper-Cogs    作者:Redjumpman    | 项目源码 | 文件源码
def _cookiecd_heist(self, ctx, cooldown: int):
        """Set the cooldown for cookie command"""
        server = ctx.message.server
        settings = self.check_server_settings(server)
        if cooldown >= 0:
            settings["Config"]["Cookie CD"] = cooldown
            dataIO.save_json(self.file_path, self.system)
            msg = "Cooldown for cookie set to {}".format(cooldown)
        else:
            msg = "Cooldown needs to be higher than 0."
        await self.bot.say(msg)
项目:Jumper-Cogs    作者:Redjumpman    | 项目源码 | 文件源码
def resetrr(self, ctx):
        """Reset command if game is stuck."""
        server = ctx.message.server
        settings = self.check_server_settings(server)
        self.reset_game(settings)
        await self.bot.say("Russian Roulette system has been reset.")
项目:Jumper-Cogs    作者:Redjumpman    | 项目源码 | 文件源码
def shop(self, ctx):
        """Shop Commands. Use !help Shop for other command groups"""

        if ctx.invoked_subcommand is None:
            await send_cmd_help(ctx)
项目:Jumper-Cogs    作者:Redjumpman    | 项目源码 | 文件源码
def long_message(output, truncate=False, max_lines=15):
    output = output.strip()
    return ["\n".join(output.split("\n")[:max_lines]) +
            "\n... *Search results truncated. " +
            "Send me a command over PM to show more!*"] \
        if truncate and output.count("\n") > max_lines \
        else split_every(output, 2000)
项目:Jumper-Cogs    作者:Redjumpman    | 项目源码 | 文件源码
def _purge_casino(self, ctx):
        """Removes all servers that the bot is no longer on.
        If your JSON file is getting rather large, utilize this
        command. It is possible that if your bot is on a ton of
        servers, there are many that it is no longer running on.
        This will remove them from the JSON file.
        """
        author = ctx.message.author
        servers = super().get_all_servers()
        purge_list = [x for x in servers if self.bot.get_server(x) is None]
        if not purge_list:
            return await self.bot.say("There are no servers for me to purge at this time.")
        await self.bot.say(_("I found {} server(s) I am no longer on. Would you like for me to "
                             "delete their casino data?").format(len(purge_list)))
        response = await self.bot.wait_for_message(timeout=15, author=author)

        if response is None:
            return await self.bot.say(_("You took too long to answer. Canceling purge."))

        if response.content.title() == _("Yes"):
            for x in purge_list:
                servers.pop(x)
            super().save_system()
            await self.bot.say(_("{} server entries have been erased.").format(len(purge_list)))
        else:
            return await self.bot.say(_("Incorrect response. This is a yes or no question."))
项目:Jumper-Cogs    作者:Redjumpman    | 项目源码 | 文件源码
def _forceupdate_casino(self, ctx):
        """Force applies older patches
        This command will attempt to update your JSON with the
        new dictionary keys. If you are having issues with your JSON
        having a lot of key errors, namely Cooldown, then try using
        this command. THIS DOES NOT UPDATE CASINO
        """

        server = ctx.message.server
        settings = super().check_server_settings(server)
        super().casino_patcher(settings, force=True)
        super().save_system()
        await self.bot.say(_("Force applied several data updates. Please reload casino."))
项目:Jumper-Cogs    作者:Redjumpman    | 项目源码 | 文件源码
def allin(self, ctx, multiplier: int):
        """It's all or nothing. Bets everything you have."""

        # Declare variables for the game.
        user = ctx.message.author
        settings = super().check_server_settings(user.server)
        chip_name = settings["System Config"]["Chip Name"]

        if not super().membership_exists(user):
            return await self.bot.say(_("You need to register. Type "
                                        "{}casino join.").format(ctx.prefix))

        # Run a logic check to determine if the user can play the game.
        check = self.game_checks(settings, ctx.prefix, user, 0, "Allin", 1, [1])
        if check:
            msg = check
        else:  # Run the game when the checks return None.
            # Setup the game to determine an outcome.
            settings["Players"][user.id]["Played"]["Allin"] += 1
            amount = int(round(multiplier * settings["Players"][user.id]["Chips"]))
            balance = super().chip_balance(user)
            outcome = random.randint(0, multiplier + 1)
            super().withdraw_chips(user, balance)
            await self.bot.say(_("You put all your chips into the machine and pull the lever..."))
            await asyncio.sleep(3)

            # Begin game logic to determine a win or loss.
            if outcome == 0:
                super().deposit_chips(user, amount)
                msg = _("```Python\nJackpot!! You just won {} {} "
                        "chips!!```").format(amount, chip_name)
                settings["Players"][user.id]["Won"]["Allin"] += 1
            else:
                msg = (_("Sorry! Your all or nothing gamble failed and you lost "
                         "all your {} chips.").format(chip_name))
            # Save the results of the game
            super().save_system()
        # Send a message telling the user the outcome of this command
        await self.bot.say(msg)
项目:Harmonbot    作者:Harmon758    | 项目源码 | 文件源码
def __init__(self, bot):
        self.bot = bot
        # Add commands as search subcommands
        for name, command in inspect.getmembers(self):
            if isinstance(command, commands.Command) and command.parent is None and name != "search":
                self.bot.add_command(command)
                self.search.add_command(command)
        # Add search subcommands as subcommands of corresponding commands
        self.search_subcommands = ((self.imgur, "Resources.imgur"), (self.youtube, "Audio.audio"))
        for command, parent_name in self.search_subcommands:
            utilities.add_as_subcommand(self, command, parent_name, "search")
项目:Harmonbot    作者:Harmon758    | 项目源码 | 文件源码
def __unload(self):
        for command, parent_name in self.search_subcommands:
            utilities.remove_as_subcommand(self, parent_name, "search")
项目:Harmonbot    作者:Harmon758    | 项目源码 | 文件源码
def __init__(self, bot):
        self.bot = bot
        utilities.create_file("stats", content = {"uptime" : 0, "restarts" : 0, "cogs_reloaded" : 0, "commands_executed" : 0, "commands_usage": {}, "reaction_responses": 0})
        self.command_not_found = "No command called `{}` found"
项目:Harmonbot    作者:Harmon758    | 项目源码 | 文件源码
def disable(self, ctx, command : str):
        '''Disable a command'''
        self.bot.commands[command].enabled = False
        await self.bot.embed_reply("`{}{}` has been disabled".format(ctx.prefix, command))
        await self.bot.delete_message(ctx.message)
项目:Harmonbot    作者:Harmon758    | 项目源码 | 文件源码
def enable(self, ctx, command : str):
        '''Enable a command'''
        self.bot.commands[command].enabled = True
        await self.bot.embed_reply("`{}{}` has been enabled".format(ctx.prefix, command))
        await self.bot.delete_message(ctx.message)
项目:Harmonbot    作者:Harmon758    | 项目源码 | 文件源码
def test(self):
        '''Basic test command'''
        await self.bot.say("Hello, World!")
项目:Harmonbot    作者:Harmon758    | 项目源码 | 文件源码
def do(self, ctx, times : int, *, command):
        '''Repeats a command a specified number of times'''
        msg = copy.copy(ctx.message)
        msg.content = command
        for _ in range(times):
            await self.bot.process_commands(msg)