Discord.py add roles - python

I am trying to add roles in discord.py but I can't really make it work.
#bot.command(brief="Report member")
async def member(ctx):
if ctx.author.id != 783430063076147210:
await ctx.send("Mention the member you want to report")
message = await bot.wait_for('message', check=lambda message: ctx.author == ctx.author)
msg = message.content.replace("<","")
msg = msg.replace(">","")
msg = msg.replace("#","")
msg = msg.replace("!","")
#try:
msg = int(msg)
user = bot.get_user(msg)
await ctx.send('Are you sure you want to report ' + user.mention + "?")
message = await bot.wait_for('message', check=lambda message: ctx.author == ctx.author)
if message.content.lower() == "yes" or message.content.lower() == "y":
member = ctx.message.author
role = get(member.guild.roles, name="Reported")
user = ctx.guild.get_member(msg)
await bot.add_roles(user, role)
await ctx.send(user.mention + " was reported by " + member.mention + ".")
else:
await ctx.send("User was not reported!")
#except:
await ctx.send("Oops! That was not a user!")
I'm getting an AttributeError: 'Bot' object has no attribute 'add_roles', and the same with the other way
await user.add_roles(role)
returns AttributeError: 'NoneType' object has no attribute 'add_roles'
Is there something I'm missing?

Two ways of making this work:
1.
#bot.command()
async def role(ctx, member:commands.MemberConverter, role:commands.RoleConverter):
await member.add_roles(role)
^^ This method uses a role converter that accepts role ID, name, or mention.
I also use commands.MemberConverter because it accepts more methods of referencing a user than discord.Member, and the same thing for discord.Role.
2.
#bot.command()
async def role(ctx, member:commands.MemberConverter, role):
role = discord.utils.get(ctx.guild.roles, name=role)
await member.add_roles(role)
^^ This method uses discord.utils.get to get a guild role. From my knowledge, it only accepts role names and not role IDs or mentions.

bot.get_user() will return a User object, to which you cannot add roles, as no guild is specified. You could do ctx.guild.get_member(id) to get the Member object then add roles to that, but you'd be better of getting the member from the mentions attribute of a Message. Docs: https://discordpy.readthedocs.io/en/latest/api.html?highlight=mentions#discord.Message.mentions

Try something like this:
#bot.command()
async def role(ctx):
test = ctx.author
role = discord.utils.get(test.guild.roles, name="Name")
if role in test.roles:
await ctx.send("you already have a role")
else:
await test.add_roles(role)

Your line
await bot.add_roles(user, role)
needs to be replaced by
await user.add_roles(role)

these are my addrole and remouverole commands:
#bot.command()
#commands.has_permissions(administrator=True)
async def addrole(ctx, member : discord.Member, role : discord.Role):
await member.add_roles(role)
await ctx.send(f"{role} is added to {member}.")
#bot.command()
#commands.has_permissions(administrator=True)
async def removerole(ctx, member : discord.Member, role : discord.Role):
await member.remove_roles(role)
await ctx.send(f"{role} is removed from {member}.")

Related

role react bot discord python

I'm trying to create a react role on a message that my bot would have sent, how can I do it?
here is my code debut:
#bot.command(name = 'role_react_1')
async def role_react_1(ctx):
del = await ctx.channel.history(limit=1).flatten()
for each_messages in del:
await each_messages.delete()
message = await ctx.send("for have the role : evil : :smiling_imp: \nwhat role you want ?")
await message.add_reaction("????")
def checkEmoji(reaction):
return message.id == reaction.message.id and str(reaction.emoji) == ":evil:"
reaction = await bot.wait_for("reaction_add", check=checkEmoji)
if reaction.emoji == ":evil:":
role = discord.utils.get(ctx.guild.roles, name="evil")
await ctx.author.add_roles(role)
await ctx.send(f"the role {role} was assigned")
I've been told about 'on_raw_reaction_add' but I don't know how to use it. how to do it
if someone want a answer, it need a bot.event with reaction_add

Discord.py get_member with on_ready

We have a bot command on a server !verifyme1
Which adds a member to a role.
async def verfiyme1(ctx):
user=ctx.message.author
#user=ctx.guild.get_member(536147700115308545)
print(user)
channel = bot.get_channel(858993936932274196)
print(client)
await user.send('Welcome to the Member Club!')
role= discord.utils.get(user.guild.roles, name="Holder Club")
if role in user.roles:
await channel.send(f"You are already a member of the holder club!")
#exit()
else:
await user.add_roles(role)
await channel.send(f"Congrats {user.mention} You are now a member of the Holder Club!")
#exit()
We need to change the command so it isn't triggered by a user but by us triggering the script (so we can do some extra verification checks) ie loading members.py triggers it to add the role to the chosen member then exits.
Looking at the docs i need to use on_ready()
async def on_ready():
#user=ctx.message.author
print("this is a test")
channel = bot.get_channel(858993936932274196)
print(channel)
user=ctx.guild.get_member([we will pass this ID in])
print(user)
await user.send('Welcome to the Member Club!')
role= discord.utils.get(user.guild.roles, name="Holder Club")
if role in user.roles:
await channel.send(f"You are already a member of the holder club!")
#exit()
else:
await user.add_roles(role)
await channel.send(f"Congrats {user.mention} You are now a member of the Holder Club!")
#exit()
bot.run(DISCORD_TOKEN)
But the issue with this is you can't use ctx with on_ready thus ctx.guild.get_member returns an error. Is there any alternative to guild.get.member that would work?
You can get the guild, just like you get the channel
guild = bot.get_guild(guild_id)
Found in the docs.
#bot.event
async def on_ready():
guild = bot.get_guild(guild_id)
if guild == None:
guild = await bot.fetch_guild(guild_id) # if guild not in cache
user = guild.get_member(536147700115308545)
channel = guild.get_channel(858993936932274196)
await user.send('Welcome to the Member Club!')
role = discord.utils.get(guild.roles, name="Holder Club")
if role in user.roles:
await channel.send(f"You are already a member of the holder club!")
#exit()
else:
await user.add_roles(role)
await channel.send(f"Congrats {user.mention} You are now a member of the Holder Club!")
#exit()

I want to send message with embed at ban command (Discord.py)

at 4. and 5. lines i need help.it doesn't send embed.
#Bot.command()
#has_permissions(ban_members=True)
async def ban(ctx, member : discord.Member=None, reason=None):
if member == None or member == ctx.message.author:
embed1 = discord.Embed(title="ERROR:", description="You can not ban yourself.", color=0x00ff00)
await ctx.send(embed=embed1)
return
if reason == None:
reason = 'Nothing.'
await ctx.guild.ban(member, reason=reason)
await ctx.channel.send(f"{ctx.message.author} banned {member} from server. Reason:{reason}")```
await ctx.guild.ban(member, reason=reason)
Expects a user to ban, not a member.
Try
await member.ban(reason=reason)
like documented here.
#Bot.command()
#has_permissions(ban_members=True)
async def ban(ctx, member : discord.Member=None, reason=None):
if member == None or member == ctx.message.author:
embed1 = discord.Embed(title="ERROR:", description="You can not ban yourself.", color=0x00ff00)
await ctx.send(embed=embed1)
return
if reason == None:
reason = 'Nothing.'
await member.ban(reason=reason)
await ctx.channel.send(f"{ctx.message.author} banned {member} from server. Reason:{reason}")

Remove all member roles and return them back some time later

I need to remove all member roles and return them back later, I had started working on it but when I had executed this function (just writing command to Discord chat), I got following message: discord.errors.NotFound: 404 Not Found (error code: 10011): Unknown Role
And here's the code I executed:
import asyncio
import discord
from discord.ext import commands
from discord.utils import get
TOKEN = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
bot = commands.Bot(command_prefix='e!')
bot.remove_command("help")
#bot.command()
async def hardmute(ctx, time : str, member : discord.Member = None):
if time[-1]=='s':
tme = int(time[:-1])
elif time[-1]=='m':
tme = int(time[:-1])*60
elif time[-1]=='h':
tme = int(time[:-1])*60*60
elif time[-1]=='d':
tme = int(time[:-1])*60*60*60*24
else:
tme = False
permissionrole = get(ctx.guild.roles, id=544069068777324579)
hardmutedrole = get(ctx.guild.roles, id=717877658259554396)
if member is None and tme and not ctx.author.roles[-1] >= ctx.guild.me.roles[-1]:
await ctx.channel.send('{}, you're going to be hardmuted for {}'.format(ctx.author.mention, time))
roles = ctx.author.roles
await asyncio.sleep(3)
await ctx.author.remove_roles(*ctx.author.roles)
await ctx.author.add_roles(hardmutedrole)
await asyncio.sleep(tme)
await ctx.author.remove_roles(hardmutedrole)
await ctx.author.add_roles(*roles)
await ctx.channel.send('{} came back from hardmute!'.format(ctx.author.mention))
elif member is not None and tme and not member.roles[-1] >= member.guild.me.roles[-1]:
if permissionrole in ctx.author.roles:
await ctx.channel.send('{}, you're going to be hardmuted for {}'.format(member.mention, time))
roles = member.roles
await asyncio.sleep(3)
await member.remove_roles(*ctx.author.roles)
await member.add_roles(hardmutedrole)
await asyncio.sleep(tme)
await member.remove_roles(hardmutedrole)
await member.add_roles(*roles)
await ctx.channel.send('{} came back from hardmute!'.format(member.mention))
else:
await ctx.channel.send('You dont have permission role')
elif ctx.author.roles[-1] >= ctx.guild.me.roles[-1] and member is None:
await ctx.channel.send('{}, you have a role "{}", that is high or equal in role hierarchy than "{}"'.format(ctx.author.mention, ctx.author.roles[-1].name, ctx.guild.me.roles[-1].name))
elif ctx.author.roles[-1] >= member.guild.me.roles[-1]:
await ctx.channel.send('User {} have role "{}", that is high or equal in role hierarchy than "{}"'.format(member.name, member.roles[-1].name, ctx.guild.me.roles[-1].name))
bot.run(TOKEN)
I'm not pretty sure but ctx.author.roles returns a list, and you tried to remove role from list, you can try this instead:
roles = member.roles
await asyncio.sleep(3)
for role in ctx.author.roles:
await member.remove_roles(role)
await member.add_roles(hardmutedrole)
await asyncio.sleep(tme)
await member.remove_roles(hardmutedrole)
for role in roles:
await member.add_roles(role)

how do I check if a user has a specific role in discord

This should check if the specific person does or doesn't have the mute role
#bot.command(pass_context=True)
#commands.has_role("Admin")
async def unmute(ctx, user: discord.Member):
role = discord.utils.find(lambda r: r.name == 'Member',
ctx.message.server.roles)
if user.has_role(role):
await bot.say("{} is not muted".format(user))
else:
await bot.add_roles(user, role)
This error is thrown
Command raised an exception: AttributeError: 'Member' object has no attribute 'has_role'
I don't know how to do it so i would really appreciate every help I can get
Member does not have a .has_role() method, you can however get a list of all their roles using .roles.
To see if a user has a given role we can use role in user.roles.
#bot.command(pass_context=True)
#commands.has_role("Admin")
async def unmute(ctx, user: discord.Member):
role = discord.utils.find(lambda r: r.name == 'Member', ctx.message.guild.roles)
if role in user.roles:
await bot.say("{} is not muted".format(user))
else:
await bot.add_roles(user, role)
Docs for reference: https://discordpy.readthedocs.io/en/latest/api.html#member
Note: ctx.message.guild.roles use to be ctx.message.server.roles. Updated due to API change.
Personally I use this:
#bot.command(pass_context=True)
#commands.has_role("Admin")
async def unmute (ctx,user:discord.Member):
role = discord.utils.get(ctx.guild.roles, name="Muted")
if role in user.roles:
await user.remove_roles(role)
await user.add_roles(role)
embed = discord.Embed(title="Unmuute Members", description=f"{user.mention} has been unmuted" , color = discord.Color.blue())
embed.add_field(name='Unmuted by:' , value = f"{ctx.author.mention}")
await user.remove_roles(role)
await ctx.send(embed=embed)
else:
await ctx.send("Invalid Argumnets or The user is not muted.")
So as you can see
role = discord.utils.get(ctx.guild.roles, name="Muted") this variable locates the Muted role in the server
if role in user.roles:
await user.remove_roles(role)
and this will remove the role from the user

Categories

Resources