首页 > 解决方案 > 如何让 Discord 机器人使用 Discord.py 制作和分配角色?

问题描述

我想制作一个机器人,为请求它的人制作并分配角色。我怎么做?我尝试了很多东西,但它们都不起作用。这是无效代码的副本。

import discord
import os
from discord.utils import get


client = discord.Client()

@client.event

async def on_ready():
  print ('we have logged in as {0.user}'.format(client))

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

  if message.content.startswith('~hello?'):
    await message.channel.send('YOU WILL NOW WISH YOU NEVER SUMMONED ME...')
    
client.run(os.environ['TOKEN'])

@client.event
async def on_message(message):
   if message.author == client.user:
        return
        
   if message.content == ('~begin?'):
        role = get(message.server.roles, name=('Admin'))
        await client.add_roles(message.author, role)

client.run(os.environ['TOKEN'])
    

第一部分有效(~hello?),但第二部分(~begin?)无效。你们中的一位仁慈的灵魂能否将我从这场无休止的调试和编码斗争中解救出来?

标签: pythondiscorddiscord.py

解决方案


您可以使用该@client.command功能添加命令,但首先您需要为`client添加一个前缀

client = commands.AutoShardedBot(commands.when_mentioned_or(*prefix*))

记得使用 from 导入命令discord.ext import commands

那么你现在的生活会很容易,如果你想添加一个命令就做

@client.command
async def add_role(ctx, member:discord.Member):
  role = get(ctx.guild.roles, name='*the role*')

  await member.add_roles(role)

所以调用命令只是说*prefix* add_role @*the user*


推荐阅读