为了账号安全,请及时绑定邮箱和手机立即绑定

Discord Python:向成员添加角色

Discord Python:向成员添加角色

郎朗坤 2023-03-30 10:12:48
我的机器人会检查何时将用户添加到 Discord 上的公会,然后私下向他们发送 DM 以获取他们的电子邮件地址。然后它会向电子邮件地址发送一个一次性代码,并要求用户在 DM 中输入该代码。所有这些都已实施并有效。但是,当用户回答代码时,我似乎无法为用户分配新角色。这是我目前拥有的(我删除了检查一次性代码等的代码,因为它可以工作并且似乎不是问题的根源):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:        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 回答

?
蝴蝶不菲

TA贡献1810条经验 获得超4个赞

为此,您需要将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)


查看完整回答
反对 回复 2023-03-30
  • 1 回答
  • 0 关注
  • 157 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信