本文整理汇总了Python中discord.ext.commands.command方法的典型用法代码示例。如果您正苦于以下问题:Python commands.command方法的具体用法?Python commands.command怎么用?Python commands.command使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类discord.ext.commands
的用法示例。
在下文中一共展示了commands.command方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: load
# 需要导入模块: from discord.ext import commands [as 别名]
# 或者: from discord.ext.commands import command [as 别名]
def load(self, ctx, save=None):
"""loads current team's save. defaults to most recent"""
server = ctx.message.server
author = ctx.message.author
channel = ctx.message.channel
try:
team = self.splayers[server.id][channel.id][author.id]
except:
team = None
await self.embark.callback(self, ctx, team, save)
# @adventure.command(pass_context=True)
# async def save(self, ctx, file):
# pass
# if no team and no save, if user doesn't have a save, new game. otherwise new game must specify team and save
示例2: tricklebot
# 需要导入模块: from discord.ext import commands [as 别名]
# 或者: from discord.ext.commands import command [as 别名]
def tricklebot(self, ctx):
"""Enables/disables trickling economy to the bot"""
sid = ctx.message.server.id
econ = self.bot.get_cog('Economy')
settings = self.settings[sid]
if econ.bank.account_exists(ctx.message.server.me):
settings["TRICKLE_BOT"] = not settings["TRICKLE_BOT"]
if self.settings[sid]["TRICKLE_BOT"]:
await self.bot.say("I will now get currency trickled to me.")
else:
await self.bot.say("I will stop getting currency "
"trickled to me.")
dataIO.save_json("data/economytrickle/settings.json", self.settings)
else:
await self.bot.say("I do not have an account registered with the "
"`Economy cog`. If you want currency to trickle"
" to me too, please use the `registerbot` "
"command to open an account for me, then try "
"again.")
示例3: close_command
# 需要导入模块: from discord.ext import commands [as 别名]
# 或者: from discord.ext.commands import command [as 别名]
def close_command(self, ctx: commands.Context) -> None:
"""
Make the current in-use help channel dormant.
Make the channel dormant if the user passes the `dormant_check`,
delete the message that invoked this,
and reset the send permissions cooldown for the user who started the session.
"""
log.trace("close command invoked; checking if the channel is in-use.")
if ctx.channel.category == self.in_use_category:
if await self.dormant_check(ctx):
# Remove the claimant and the cooldown role
await self.help_channel_claimants.delete(ctx.channel.id)
await self.remove_cooldown_role(ctx.author)
# Ignore missing task when cooldown has passed but the channel still isn't dormant.
self.cancel_task(ctx.author.id, ignore_missing=True)
await self.move_to_dormant(ctx.channel, "command")
self.cancel_task(ctx.channel.id)
else:
log.debug(f"{ctx.author} invoked command 'dormant' outside an in-use help channel")
示例4: user_info
# 需要导入模块: from discord.ext import commands [as 别名]
# 或者: from discord.ext.commands import command [as 别名]
def user_info(self, ctx: Context, user: Member = None) -> None:
"""Returns info about a user."""
if user is None:
user = ctx.author
# Do a role check if this is being executed on someone other than the caller
elif user != ctx.author and not with_role_check(ctx, *constants.MODERATION_ROLES):
await ctx.send("You may not use this command on users other than yourself.")
return
# Non-staff may only do this in #bot-commands
if not with_role_check(ctx, *constants.STAFF_ROLES):
if not ctx.channel.id == constants.Channels.bot_commands:
raise InWhitelistCheckFailure(constants.Channels.bot_commands)
embed = await self.create_user_embed(ctx, user)
await ctx.send(embed=embed)
示例5: time
# 需要导入模块: from discord.ext import commands [as 别名]
# 或者: from discord.ext.commands import command [as 别名]
def time(ctx: MtgContext, *, args: str) -> None:
"""Current time in location."""
if len(args) == 0:
await ctx.send('{author}: No location provided. Please type !time followed by the location you want the time for.'.format(author=ctx.author.mention))
return
try:
twentyfour = configuration.get_bool(f'{guild_or_channel_id(ctx.channel)}.use_24h') or configuration.get_bool(f'{ctx.channel.id}.use_24h')
ts = fetcher.time(args, twentyfour)
times_s = ''
for t, zones in ts.items():
cities = sorted(set(re.sub('.*/(.*)', '\\1', zone).replace('_', ' ') for zone in zones))
times_s += '{cities}: {t}\n'.format(cities=', '.join(cities), t=t)
await ctx.send(times_s)
except NotConfiguredException:
await ctx.send('The time command has not been configured.')
except TooFewItemsException:
logging.exception('Exception trying to get the time for %s.', args)
await ctx.send('{author}: Location not found.'.format(author=ctx.author.mention))
示例6: command_activity
# 需要导入模块: from discord.ext import commands [as 别名]
# 或者: from discord.ext.commands import command [as 别名]
def command_activity(self, ctx):
await self.increase_stat(ctx, "commands_used_life")
# log command lifetime stat
await self.bot.mdb.analytics_command_activity.update_one(
{"name": ctx.command.qualified_name},
{
"$inc": {"num_invocations": 1}, # yay, atomic operations
"$currentDate": {"last_invoked_time": True}
},
upsert=True
)
# log event
guild_id = 0 if ctx.guild is None else ctx.guild.id
await self.bot.mdb.analytics_command_events.insert_one(
{
"timestamp": datetime.datetime.utcnow(),
"command_name": ctx.command.qualified_name,
"user_id": ctx.author.id,
"guild_id": guild_id
}
)
示例7: prefix
# 需要导入模块: from discord.ext import commands [as 别名]
# 或者: from discord.ext.commands import command [as 别名]
def prefix(self, ctx, prefix: str = None):
"""Sets the bot's prefix for this server.
You must have Manage Server permissions or a role called "Bot Admin" to use this command.
Forgot the prefix? Reset it with "@Avrae#6944 prefix !".
"""
guild_id = str(ctx.guild.id)
if prefix is None:
current_prefix = await self.bot.get_server_prefix(ctx.message)
return await ctx.send(f"My current prefix is: `{current_prefix}`")
# insert into cache
self.bot.prefixes[guild_id] = prefix
# update db
await self.bot.mdb.prefixes.update_one(
{"guild_id": guild_id},
{"$set": {"prefix": prefix}},
upsert=True
)
await ctx.send("Prefix set to `{}` for this server.".format(prefix))
示例8: su
# 需要导入模块: from discord.ext import commands [as 别名]
# 或者: from discord.ext.commands import command [as 别名]
def su(self, ctx, member: discord.User, *, msg):
"""
Execute a command in place of another user
__Arguments__
**member**: The user (must be a member of this guild)
**msg**: The message, doesn't need to be a command
"""
if member.id == ctx.bot.owner_id:
raise cmd.CommandError("How about ... **no**?")
webhook = await ctx.channel.create_webhook(name="sudo")
await webhook.send(content=msg, username=member.name, avatar_url=member.avatar_url)
await webhook.delete()
await asyncio.sleep(1) # Webhooks are slow
message = ctx.message
message.author = member
message.content = msg
await self.bot.process_commands(message)
示例9: sudo
# 需要导入模块: from discord.ext import commands [as 别名]
# 或者: from discord.ext.commands import command [as 别名]
def sudo(self, ctx, *, command):
"""
Execute a command and bypass cooldown
__Arguments__
**command**: The command
"""
message = ctx.message
message.content = command
new_ctx = await self.bot.get_context(message, cls=context.Context)
new_ctx.command.reset_cooldown(new_ctx)
if isinstance(new_ctx.command, cmd.Group):
for command in new_ctx.command.all_commands.values():
command.reset_cooldown(new_ctx)
await self.bot.invoke(new_ctx)
示例10: loggingdb
# 需要导入模块: from discord.ext import commands [as 别名]
# 或者: from discord.ext.commands import command [as 别名]
def loggingdb(self, ctx, table, identifier):
"""Gets a list of the most recent errors from loggingdb"""
if table in [ "error", "errors", "bugs", "bug" ]:
table = loggingdb_spec.Error
filterer = lambda q: q.filter_by(message_id=identifier)
elif table in [ "message", "messages", "msg", "messages" ]:
table = loggingdb_spec.Message
filterer = lambda q: q.filter_by(id=identifier)
elif table in [ "command", "commands", "cmd", "cmds" ]:
table = loggingdb_spec.Command
filterer = lambda q: q.filter_by(message_id=identifier)
else:
raise UserError("Dont know what table you're talking about")
found = False
for obj in filterer(loggingdb.session.query(table)):
found = True
await ctx.send(embed=obj.to_embed(self))
if table == loggingdb_spec.Error:
chunks = obj.error_text_chunks()
for chunk in chunks:
await ctx.send(chunk)
if not found:
raise UserError("Couldn't find anything for that")
示例11: pokecry
# 需要导入模块: from discord.ext import commands [as 别名]
# 或者: from discord.ext.commands import command [as 别名]
def pokecry(self, ctx, *, pokemon):
"""Plays the pokemon's sound effect
Audio files for these pokemon cries were gotten from [Veekun](https://veekun.com/dex/downloads). Veekun does not have the cries for Generation VII yet, so I won't be able to play those.
Most pokemon have a new cry and an old cry. To get the old cry instead of the new one, add 'old' to the end of your command (see example below.)
**Example:**
`{cmdpfx}pokecry pikachu`
`{cmdpfx}pokecry bulbasaur old`"""
words = pokemon.split(" ")
old = "old" in words
if old:
words.remove("old")
pokemon = " ".join(words)
data, species_data = await self.get_pokemon_data(pokemon)
if data["id"] > 721:
raise UserError("Sorry, I don't have the cries for pokemon in Generation VII yet")
success = await self.play_pokecry(ctx, data["id"], pokemon, old=old)
if not success:
raise UserError(f"Couldn't find the cry for {data['localized_name']}")
示例12: hello
# 需要导入模块: from discord.ext import commands [as 别名]
# 或者: from discord.ext.commands import command [as 别名]
def hello(self, ctx):
"""Says hello
WHAT MORE DO YOU NEED TO KNOW!?!?!? IS 'Says hello' REALLY NOT CLEAR ENOUGH FOR YOU!?!!11?!!?11!!?!??"""
dota_hellos = [
"slark_attack_11",
"kunk_thanks_02",
"meepo_scepter_06",
"puck_ability_orb_03",
"tink_spawn_07",
"treant_ally_08",
"wraith_lasthit_02",
"timb_deny_08",
"tech_pain_39",
"meepo_attack_08",
"slark_lasthit_02"
]
dota_response = random.choice(dota_hellos)
response = session.query(Response).filter(Response.name == dota_response).first()
print("hello: " + response.name)
await self.play_response(response, ctx)
# Plays the correct command for the given keyphrase and hero, if a valid one is given
示例13: herotable
# 需要导入模块: from discord.ext import commands [as 别名]
# 或者: from discord.ext.commands import command [as 别名]
def herotable(self, ctx, *, table_args : HeroStatsTableArgs):
"""Displays a sorted table of heroes and their stats
Displays a table with computed hero stats showing which heroes have the highest values for the specified stat. To see the list of possible stats, try the `{cmdpfx}leveledstats` command
**Examples:**
`{cmdpfx}herotable dps`
`{cmdpfx}herotable health lvl 30`
`{cmdpfx}herotable attack speed level 21 descending`
"""
if table_args.stat is None:
raise UserError(f"Please select a stat to sort by. For a list of stats, see `{self.cmdpfx()}leveledstats`")
if table_args.hero_level < 1 or table_args.hero_level > 30:
raise UserError("Please select a hero level between 1 and 30")
if table_args.hero_count < 2 or table_args.hero_count > 40:
raise UserError("Please select a hero count between 2 and 40")
embed = discord.Embed()
image = discord.File(await drawdota.draw_herostatstable(table_args, self.hero_stat_categories, self.leveled_hero_stats), "herotable.png")
embed.set_image(url=f"attachment://{image.filename}")
embed.set_footer(text="The stats shown above do not account for talents, passives, or items")
await ctx.send(embed=embed, file=image)
示例14: lvlmsglock
# 需要导入模块: from discord.ext import commands [as 别名]
# 或者: from discord.ext.commands import command [as 别名]
def lvlmsglock(self, ctx):
'''Locks levelup messages to one channel. Disable command via locked channel.'''
channel = ctx.message.channel
server = ctx.message.server
if "lvl_msg_lock" not in self.settings.keys():
self.settings["lvl_msg_lock"] = {}
if server.id in self.settings["lvl_msg_lock"]:
if channel.id == self.settings["lvl_msg_lock"][server.id]:
del self.settings["lvl_msg_lock"][server.id]
await self.bot.say("**Level-up message lock disabled.**".format(channel.name))
else:
self.settings["lvl_msg_lock"][server.id] = channel.id
await self.bot.say("**Level-up message lock changed to `#{}`.**".format(channel.name))
else:
self.settings["lvl_msg_lock"][server.id] = channel.id
await self.bot.say("**Level-up messages locked to `#{}`**".format(channel.name))
fileIO('data/leveler/settings.json', "save", self.settings)
示例15: on_guild_join
# 需要导入模块: from discord.ext import commands [as 别名]
# 或者: from discord.ext.commands import command [as 别名]
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)