Discord Python:向成员添加角色

时间:2020-07-23 19:27:43

标签: python discord.py

我的机器人检查每当有用户添加到Discord上的公会时,然后私下DM他们的电子邮件地址。然后,它将一次性代码发送到电子邮件地址,并要求用户在DM中输入该代码。所有这一切都已实现并起作用。但是,当用户回答该代码时,我似乎无法为该用户分配新角色。这是我当前拥有的(我删除了检查一次性代码的代码,等等,因为它可以工作,而且似乎不是问题的根源):

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

@client.event
async def on_message(message):
    # Check if message was sent by the bot
    if message.author == client.user:
        return

    # Check if the message was a DM
    if message.channel.type != discord.ChannelType.private:
        return

    user_code = 'some code sent via email'

    if message.content == user_code:
        member = message.author

        new_guild = client.get_guild(int(GUILD_ID))
        role = get(new_guild.roles, id=DISCORD_ROLE)
        await member.add_roles(role)

        response = "You can now use the Discord Server."
        await message.channel.send(response)

这是我收到的错误:

Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/discord/client.py", line 312, in _run_event
    await coro(*args, **kwargs)
  File "main.py", line 89, in on_message
    await member.add_roles(role)
AttributeError: 'User' object has no attribute 'add_roles'

1 个答案:

答案 0 :(得分:1)

为此,您需要将User对象转换为Member对象。这样,您可以调用add_roles方法。这是一种实现方法:

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

@client.event
async def on_message(message):
    # Check if message was sent by the bot
    if message.author == client.user:
        return

    # Check if the message was a DM
    if message.channel.type != discord.ChannelType.private:
        return

    user_code = "some code sent via email"

    if message.content == user_code:
        new_guild = client.get_guild(int(GUILD_ID))

        member = new_guild.get_member(message.author.id)
        role = new_guild.get_role(int(DISCORD_ROLE))
        await member.add_roles(role)

        response = "You can now use the Discord Server."
        await message.channel.send(response)