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)
python类command()的实例源码
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)
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.')
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)
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))
def setcookie(self, ctx):
"""Cookie settings group command"""
if ctx.invoked_subcommand is None:
await send_cmd_help(ctx)
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)
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.")
def shop(self, ctx):
"""Shop Commands. Use !help Shop for other command groups"""
if ctx.invoked_subcommand is None:
await send_cmd_help(ctx)
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)
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."))
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."))
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)
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")
def __unload(self):
for command, parent_name in self.search_subcommands:
utilities.remove_as_subcommand(self, parent_name, "search")
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"
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)
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)
def test(self):
'''Basic test command'''
await self.bot.say("Hello, World!")
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)
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
def add_as_subcommand(cog, command, parent_name, subcommand_name, *, aliases = []):
if isinstance(parent_name, commands.Command):
parent = parent_name
# parent_cog = cog.bot.get_cog(parent.cog_name)
parent_cog = parent.instance
parent_command_name = parent.name
else:
parent_cog_name, parent_command_name = parent_name.split('.')
parent_cog = cog.bot.get_cog(parent_cog_name)
parent = getattr(parent_cog, parent_command_name, None)
if not parent: return
subcommand = copy.copy(command)
subcommand.name = subcommand_name
subcommand.aliases = aliases
# async def wrapper(*args, **kwargs):
# async def wrapper(*args, command = command, **kwargs):
# await command.callback(cog, *args, **kwargs)
# subcommand.callback = wrapper
# subcommand.params = inspect.signature(subcommand.callback).parameters.copy()
setattr(parent_cog, "{}_{}".format(parent_command_name, subcommand_name), subcommand)
parent.add_command(subcommand)
def format_help_for(self, context, command_or_bot):
"""Formats the help page and handles the actual heavy lifting of how
the help command looks like. To change the behaviour, override the
:meth:`format` method.
Parameters
-----------
context : :class:`Context`
The context of the invoked help command.
command_or_bot : :class:`Command` or :class:`Bot`
The bot or command that we are getting the help of.
Returns
--------
list
A paginated output of the help command.
"""
self.context = context
return await self.format(command_or_bot)
def _help(self, ctx, *, command: str = None):
"""Shows help about a command or the bot"""
try:
if command is None:
p = await HelpPaginator.from_bot(ctx)
else:
entity = self.bot.get_cog(command) or self.bot.get_command(command)
if entity is None:
return await ctx.send(f'Command "{command}" not found.')
elif isinstance(entity, commands.Command):
p = await HelpPaginator.from_command(ctx, entity)
else:
p = await HelpPaginator.from_cog(ctx, entity)
await p.paginate()
except CannotPaginate as e:
await ctx.send(e)
def add_phrase(self, phrase):
if(not isinstance(phrase, Phrase)):
raise TypeError("{} not instance of Phrase.".format(phrase))
## Manually build command to be added
command = commands.Command(
phrase.name,
self._create_phrase_callback(phrase.message, phrase.is_music),
**phrase.kwargs,
**self.command_kwargs
)
## _phrase_callback doesn't have an instance linked to it,
## (not technically a method of Phrases?) so manually insert the correct instance anyway.
## This also fixes the broken category label in the help page.
command.instance = self
self.bot.add_command(command)
## Build a dynamic callback to invoke the bot's say method
def _help(self, ctx, *, command: str = None):
"""Shows help about a command or the bot"""
try:
if command is None:
p = await HelpPaginator.from_bot(ctx)
else:
entity = self.bot.get_cog(command) or self.bot.get_command(command)
if entity is None:
clean = command.replace('@', '@\u200b')
return await ctx.send(f'Command or category "{clean}" not found.')
elif isinstance(entity, commands.Command):
p = await HelpPaginator.from_command(ctx, entity)
else:
p = await HelpPaginator.from_cog(ctx, entity)
await p.paginate()
except Exception as e:
await ctx.send(e)
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")
def __init__(self, bot):
self.bot = bot
self.players = {}
for name, command in inspect.getmembers(self):
if isinstance(command, commands.Command) and command.parent is None and name != "audio":
self.bot.add_command(command)
self.audio.add_command(command)
def process_commands(self, message):
_internal_channel = message.channel
_internal_author = message.author
view = StringView(message.content)
if self._skip_check(message.author, self.user):
return
prefix = await self._get_prefix(message)
invoked_prefix = prefix
if not isinstance(prefix, (tuple, list)):
if not view.skip_string(prefix):
return
else:
invoked_prefix = discord.utils.find(view.skip_string, prefix)
if invoked_prefix is None:
return
invoker = view.get_word().lower() # case-insensitive commands
tmp = {'bot': self, 'invoked_with': invoker, 'message': message, 'view': view, 'prefix': invoked_prefix}
ctx = Context(**tmp)
del tmp
if invoker in self.commands:
command = self.commands[invoker]
self.dispatch('command', command, ctx)
try:
await command.invoke(ctx)
except CommandError as e:
ctx.command.dispatch_error(e, ctx)
else:
self.dispatch('command_completion', command, ctx)
elif invoker:
exc = CommandNotFound('Command "{}" is not found'.format(invoker))
self.dispatch('command_error', exc, ctx)
# Make Subcommands Case-Insensitive
def command_ancestry(command):
if isinstance(command, Command):
cmd = command
while cmd is not None:
yield cmd.qualified_name
cmd = cmd.parent
if command.instance:
yield '_' + command.cog_name.casefold()
elif command != '_all':
yield '_' + type(command).__name__.casefold()
yield '_all'