问题
I wanted to create a command, like !iknow @user . A normal verification bot I think. Here's my code, I only pasted the important parts:
import discord
from discord.ext import commands
@client.command(pass_context=True)
async def iknow(ctx, arg):
await ctx.send(arg)
unknownrole = discord.utils.get(ctx.guild.roles, name = "Unknown")
await client.remove_roles(arg, unknownrole)
knownrole = discord.utils.get(ctx.guild.roles, name = "Verified")
await client.add_roles(arg, knownrole)
(The Unknown role is automatically passed when a user joins the server.)
The problem is: I get an error on line 6 (and I think I will get on line 9, too).
File "/home/archit/.local/lib/python3.7/site-packages/discord/ext/commands/core.py", line 83, in wrapped
ret = await coro(*args, **kwargs) File "mainbot.py", line 6, in iknow await client.remove_roles(arg, unknownrole) AttributeError: 'Bot' object has no attribute 'remove_roles'
I just started learning python, so please don't bully me!
回答1:
You're looking for Member.remove_roles and Member.add_roles.
You can also specify that arg
must be of type discord.Member
, which will automatically resolve your mention into the proper Member
object.
Side note, it's no longer needed to specify pass_context=True
when creating commands. This is done automatically, and context
is always the first variable in the command coroutine.
import discord
from discord.ext import commands
client = commands.Bot(command_prefix='!')
@client.command()
async def iknow(ctx, arg: discord.Member):
await ctx.send(arg)
unknownrole = discord.utils.get(ctx.guild.roles, name="Unknown")
await arg.remove_roles(unknownrole)
knownrole = discord.utils.get(ctx.guild.roles, name="Verified")
await arg.add_roles(knownrole)
client.run('token')
来源:https://stackoverflow.com/questions/61008770/discord-py-passing-an-argument-role-functions