Reputation: 121
I am trying to use a command to give a specific role using DiscordPy, but every search I use brings me to the same answers, that don't help: 1, 2, 3.
Clearly, I'm missing a fundamental part, but i have no idea what. The documentation, covers that there is a add_roles command, but that doesn't give any explanation of how to use it for another user. In fact, trying await add_roles("Team Captain")
gives the error NameError: name 'add_roles' is not defined
.
What am I missing here? Why does add_roles
not exist when it's documented, and how do I use it against a different user.
This is (some of) what I have at the moment, but obviously, doesn't work:
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')
Upvotes: 1
Views: 357
Reputation: 6944
add_roles
is a method that belongs to the Member
object. This means that you'll need to get the target member, in your case message.mentions[0]
as message.mentions
returns a list of Members, and then stick .add_roles(..)
on the end of it.
Additionally, when adding a role, it accepts Role
objects, not just a name or ID. This means you'll need to fetch the role first, which can be done in a multitude of ways, but the one I'll use is utils.get()
(other methods such as Guild.get_role()
are also available)
This brings us to your code:
@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)
References:
utils.get()
Message.mentions
- message.mentions[0]
gets the first element of the list, which is the discord.Member
that was mentioned.Member.add_roles()
Guild.get_role()
- If you want to use this, you'll do:role = message.guild.get_role(112233445566778899)
112233445566778899
is the Team Captain
's role ID.Upvotes: 3