python - 如何让 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?)无效。你们中的一位仁慈的灵魂能否将我从这场无休止的调试和编码斗争中解救出来?
解决方案
您可以使用该@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*
推荐阅读
- c# - 将对象属性(包括具有私有 setter 的属性)深度复制到另一个相同类型的对象
- c# - How to P/Invoke os_log?
- python - 函数中的常量,而不是单独的文件
- javascript - 在 moment.js 中获取从现在开始的时间差异
- c++ - 该程序的输出说明:
- php - PHP中关联数组中的三元
- excel - 工作中使用 excel 的船员轮换板
- java - Cucumber JVM 4.0.0 和 Junit 测试运行程序不会发生并行执行
- c# - 在某些调用中不使用 httpClient.BaseAddress 会导致创建新客户端吗?
- java - 尝试使用 listFiles() 函数,但文件数组为空,Java,Andriod Studio