【问题标题】:How can my bot give a user a role through a command我的机器人如何通过命令赋予用户角色
【发布时间】:2021-01-16 11:30:38
【问题描述】:

例如,如果我输入 !Cuff @user,我希望该用户获得 cuff 的角色。有谁知道怎么做?

if message.content.startswith('!cuff'):
    args = message.content.split(' ')
    if len(args) == 2:
        member: Member = discord.utils.find(lambda m: args[1] in m.name, message.guild.members)
        if member:
            role = get(message.server.roles, name='Cuff')
            await client.add_roles('{}'.format(member.name))

【问题讨论】:

  • 到目前为止你有什么尝试?
  • 您可以编辑您的帖子以在其中插入您的代码。
  • 你能用你的代码编辑你的帖子吗?
  • 不,总是写得这么扭曲
  • 我的意思是你的问题。您的问题下方有一个Edit 按钮。

标签: python python-3.x discord.py


【解决方案1】:

如果要发出命令,则应使用discord.ext.commands 而不是on_message 事件。然后,您可以通过传递参数轻松获取discord.Member 对象。

另外,client 对象没有属性add_roles。您应该使用discord.Member.add_roles(role)message 对象没有属性server,而是使用guild

from discord.ext import commands

client = commands.Bot(command_prefix="!")

@client.command()
async def cuff(ctx, member: discord.Member=None):
    if not member:
        return # or you can send message to the channel that says "you have to pass member argument"
    role = get(ctx.guild.roles, name='Cuff')
    await member.add_roles(role)

【讨论】:

  • AttributeError: 模块 'discord.message' 没有属性 'guild'
  • 您使用的是什么版本的 discord.py?
  • Python 版本 3.7.4
  • 我的意思是你使用 repl.itrewrite 版本的 discord.py。如果重写,那么您使用什么版本的重写(1.4.x、1.5.x 等)?
  • 我觉得应该是ctx.guild.rolesmessage没有定义
猜你喜欢
  • 2021-04-12
  • 1970-01-01
  • 2017-07-07
  • 2020-10-07
  • 2018-10-11
  • 2021-09-20
  • 2020-11-16
  • 2022-01-10
  • 1970-01-01
相关资源
最近更新 更多