如何使用discord.py中的命令添加/创建角色

时间:2018-07-23 07:29:24

标签: python discord discord.py

因此,我试图让用户查看潜在的“角色”列表,并根据用户选择的内容(该角色当前是否存在),机器人将添加该角色给用户,或创建要添加到用户的新角色。目前,我一直收到错误消息,说未定义名称“ message”,但我不确定该怎么做。

这是我的代码

@client.command(pass_context = True)
async def classes():
class_list = ["English", "Math", "Science", "History", "Geography", "French","Technology", "Comp_Sci", "Business", "Music", "Art"]
entered_class = message.content
role = discord.utils.get(message.server.roles, name=entered_class)
roles = ["470082568163950612", "470082563696754708"]
if role is None:
    await client.create_role(name=entered_class, mentionable=True)
    await client.add_roles(message.author, role)
    msg = 'Successfully created and added role{0.author.mention}'.format(message)
    await client.send_message(message.channel, msg)
if role is True:
    await client.add_roles(message.author, role)
    await client.send_message(message.channel, msg)

这是我的进口货

import discord
from discord.utils import get
from discord.utils import find
from discord.ext import commands
from discord.ext.commands import Bot

TOKEN = 'NDcwMDYwMDc1MjgxODA5NDEw.DjQyZQ.j-YlOu5mZnDjpeUj32Nbc7wfbbs'


client = Bot(command_prefix = "Wood!")

任何帮助将不胜感激

1 个答案:

答案 0 :(得分:0)

错误消息name "message" is not defined告诉您,您正在尝试访问不存在的名为“ message”的变量。

查看您的代码,似乎在这里:

async def classes():
    class_list = ["English", "Math", "Science", "History", "Geography", "French","Technology", "Comp_Sci", "Business", "Music", "Art"]
    entered_class = HERE ---> message <--- .content

这是您需要的:

@client.command(pass_context = True)
async def classes(ctx): # note that we add a `ctx` argument here
    class_list = ["English", "Math", "Science", "History", "Geography", "French","Technology", "Comp_Sci", "Business", "Music", "Art"]
    entered_class = ctx.message.content # we get the message from the context here

但是实际上,这可能不是您想要的,因为它将包含命令名称和前缀以及参数。您正在使用discord.py的命令扩展名,因此您可能更喜欢这样做:

@client.command(pass_context = True)
async def classes(ctx, arg): # commands extension gets the argument for you!

,然后仅使用arg变量的值。

另外,从不,永远与任何人共享您的机器人令牌。返回不和谐页面,并立即重新生成它。这是因为有了该令牌,看到它的任何人都可以访问您的机器人并使其执行任何操作。