【问题标题】:Giving a role to another user with DiscordPy使用 DiscordPy 将角色分配给另一个用户
【发布时间】:2020-06-14 23:43:52
【问题描述】:

我正在尝试使用命令来使用 DiscordPy 赋予特定角色,但我使用的每个 search 都会给我带来相同的答案,但无济于事:123

显然,我遗漏了一个基本部分,但我不知道是什么。 documentation 涵盖了有一个add_roles 命令,但这并没有说明如何将它用于其他用户。事实上,尝试await add_roles("Team Captain") 会给出错误NameError: name 'add_roles' is not defined

我在这里缺少什么?为什么add_roles 在记录时不存在,以及如何针对不同的用户使用它。

这是我目前拥有的(部分),但显然不起作用:

import discord, discord.utils, random, os, re, json
from discord.ext import commands
from discord.utils import get
from dotenv import load_dotenv

client = discord.Client()

load_dotenv()
key = os.getenv('DISCORD_KEY')

@client.event
async def on_message(message):
    if message.author == client.user:
        return

    print('Message from {0.author}: {0.content}'.format(message))

    #Want these commands in the right channel
    if str(message.channel).lower().startswith("bot"):
        if message.content.lower().startswith("$addcaptain"):
            if len(message.mentions) == 0:
                await message.channel.send("Needs a user to give Team Captain role.")
                return
            else:
                await add_roles("Team Captain") #Doesn't work, and I assume would be against the user who sent the message, not the mentioned one

client.run(key)
key = os.getenv('DISCORD_KEY')

【问题讨论】:

    标签: python-3.x discord.py


    【解决方案1】:

    add_roles 是属于Member 对象的方法。这意味着您需要获取目标成员,在您的情况下为message.mentions[0],因为message.mentions 返回成员列表,然后在其末尾粘贴.add_roles(..)

    此外,添加角色时,它接受Role 对象,而不仅仅是名称或ID。这意味着您需要先获取角色,这可以通过多种方式完成,但我将使用utils.get()(也可以使用其他方法,例如Guild.get_role()

    这将我们带到您的代码:

    @client.event
    async def on_message(message):
        # code
        if str(message.channel).lower().startswith("bot"):
            if message.content.lower().startswith("$addcaptain"):
                if len(message.mentions) == 0:
                    await message.channel.send("Needs a user to give Team Captain role.")
                    return
                else:
                    role = discord.utils.get(message.guild.roles, name="Team Captain")
                    await message.mentions[0].add_roles(role)
    

    参考资料:

    【讨论】:

    • 很好的解释,Diggy,谢谢。抱歉,我也不能投票,需要 15 个代表。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-01
    • 2021-09-16
    • 2022-12-17
    • 1970-01-01
    • 2023-02-14
    相关资源
    最近更新 更多