Discord bot检查用户是否为管理员
问题内容:
您好,我是使用Discord进行python编码的新手,我试图制作一个命令来告诉用户他们是否是管理员,但是很好…它丝毫没有作用
@client.command(name="whoami",description="who are you?")
async def whoami():
if message.author == client.user:
return
if context.message.author.mention == discord.Permissions.administrator:
msg = "You're an admin {0.author.mention}".format(message)
await client.send_message(message.channel, msg)
else:
msg = "You're an average joe {0.author.mention}".format(message)
await client.send_message(message.channel, msg)
然后当我尝试键入whoami时我得到了这个
Ignoring exception in command whoami
Traceback (most recent call last):
File "/home/python/.local/lib/python3.6/site-packages/discord/ext/commands/core.py", line 50, in wrapped
ret = yield from coro(*args, **kwargs)
File "<stdin>", line 3, in whoami
NameError: name 'message' is not defined
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/python/.local/lib/python3.6/site-packages/discord/ext/commands/bot.py", line 846, in process_commands
yield from command.invoke(ctx)
File "/home/python/.local/lib/python3.6/site-packages/discord/ext/commands/core.py", line 374, in invoke
yield from injected(*ctx.args, **ctx.kwargs)
File "/home/python/.local/lib/python3.6/site-packages/discord/ext/commands/core.py", line 54, in wrapped
raise CommandInvokeError(e) from e
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: NameError: name 'message' is not defined
问题答案:
更改
@client.command(name="whoami",description="who are you?")
async def whoami():
至
@client.command(pass_context=True)
async def whoami(ctx):
然后,您可以ctx
用来获取各种内容,例如编写它的用户,消息内容等等。
要查看aUser
是否为管理员
if ctx.message.author.server_permissions.administrator:
,True
如果用户为administrator则应返回
您的代码应如下所示:
import discord
import asyncio
from discord.ext.commands import Bot
client = Bot(description="My Cool Bot", command_prefix="!", pm_help = False, )
@client.event
async def on_ready():
print("Bot is ready!")
return await client.change_presence(game=discord.Game(name='My bot'))
@client.command(pass_context = True)
async def whoami(ctx):
if ctx.message.author.server_permissions.administrator:
msg = "You're an admin {0.author.mention}".format(ctx.message)
await client.send_message(ctx.message.channel, msg)
else:
msg = "You're an average joe {0.author.mention}".format(ctx.message)
await client.send_message(ctx.message.channel, msg)
client.run('Your_Bot_Token')