简体   繁体   English

Discord Python:向成员添加角色

[英]Discord Python: Adding a role to a member

My bot checks whenever a user is added to a guild on Discord and then privately DMs them for their email address.每当用户被添加到 Discord 上的公会时,我的机器人都会检查,然后私下向他们发送 email 地址。 It then sends a one-time code to the email address and asks the user to enter the code in the DM.然后它会向 email 地址发送一次性代码,并要求用户在 DM 中输入代码。 All this is implemented and works.所有这些都已实施并且有效。 However, when the user answers with the code, I cannot seems to be able to assign a new role to the user.但是,当用户使用代码回答时,我似乎无法为用户分配新角色。 Here is what I currently have (I removed the code that checks the one-time code, etc. as it works and does not seem to be the source of the problem):这是我目前拥有的(我删除了检查一次性代码等的代码,因为它可以工作并且似乎不是问题的根源):

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)

Here is the error I receive:这是我收到的错误:

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'

For that, you need to transform the User object into a Member object.为此,您需要将User object 转换为Member object。 That way, you can call the add_roles method.这样,您可以调用add_roles方法。 Here is one way of doing it:这是一种方法:

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM