猿问

Discord Python:向成员添加角色

我的机器人会检查何时将用户添加到 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'


郎朗坤
浏览 158回答 1
1回答

蝴蝶不菲

为此,您需要将User对象转换为Member对象。这样,您就可以调用该add_roles方法。这是一种方法:import discordfrom discord.ext import commandsfrom discord.utils import get@client.eventasync 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)
随时随地看视频慕课网APP

相关分类

Python
我要回答