Discord.py Get all roles from mentioned member - python

is there a way to send all of the mentioned person's roles to a channel?
Start of my code:
#client.command()
#commands.has_role("Enhanced Permissions")
async def softban(ctx, user : discord.Member,
Not sure what to do next

roles = user.roles
roles = [role.name for role in roles]
await ctx.send(f"```{','.join(roles)}```"
This will fetch the roles belonging to user and print them within codeblocks.

Related

How to check if the player has a role when the bot starts and sends the message "on_ready"

Blockquote
I have a bug, I created a bot that issues a role when entering the members server, but sometimes the bot is offline and cannot issue a role
Therefore, I wanted the bot to display a role when the bot is started if the member does not have a role, and to do nothing if the member already has a role
I tried it but it doesn't work and yes I work because of the cogenter image description here
#commands.Cog.listener()
async def on_ready(self, guild: discord.Guild):
role = discord.utils.get(guild.roles, id=775777298111791104)
for m in guild.members:
for r in role.guild.members:
if m.guild.roles != r.get_role(775777298111791104):
print("Ok")
await m.add_roles(role)
=======================================================================
async def setup(bot):
await bot.add_cog(JoinMemberMessages(bot))
I think there's a few fundamental issues with your code.
You're looping over the guild members and then for each guild member you're starting another loop where you're looping over the guild members again? Then you're checking if all the server's role is equal to one particular role?
Additionally, the on_ready event doesn't take guild as a parameter
Your code doesn't quite do what you suggest it's trying to do.
async def on_ready(self):
# if your client/bot is instantiated as another var - then change this
# perhaps if it's `client` or `self.bot` or whatever
guild = await bot.fetch_guild(YOUR_GUILD_ID)
role = discord.utils.get(guild.roles, id=MY_ROLE_ID)
for member in guild.members:
member_roles = member.roles
member_role_ids = [role.id for role in member_roles]
if MY_ROLE_ID in member_roles_ids:
# user already has our role
continue
await member.add_roles(role)
print(f"Given {member.name} the {role.name} role")
Replace CAPITAL_VARIABLES with yours or the relevant magic numbers.
Here, we loop over the members and check they don't have the existing role ID; and assign it to them if they don't.
Perhaps check the docs:
on_ready
discord.Guild
discord.Member

How to explicitly add role to a user in discord bot

I'm relatively new to programming and am trying to code a bot for a server I'm in. I'd ideally like to assign a user to a specific role based on them sending a message containing 'gm' or 'good morning'. Right now, the bot can read the message and send a reply. But I'm a bit lost trying to figure out how to actually add the role to a user once the 'gm' message is read.
`#client.event
async def on_ready():
print(f'We have logged in as {client.user}')
async def addRole(user : discord.Member, role : discord.Role = BagChaser):
if role in user.roles:
return
else: await user.add_roles(role)
#client.event
async def on_message(message):
if message.author == client.user:
return
msg = message.content.lower()
words_list = ['gm', 'good morning']
if any(word in msg for word in words_list):
# await addRole(message.author, BagChaser)
await message.channel.send(f'Lets get this bag, {message.author}')
await message.author.add_roles(BagChaser)`
the commented line and the last line were some ideas of how to add the role 'BagChaser' to the author of the message. I tried setting the role parameter in the addRole function to BagChaser since that will never change, but this seems incorrect. The role is already made in my server, but I'm not sure how I can make the bot aware of that role in the code. Any help would be greatly appreciated!
I tried explicitly calling out my role but i can't get it recognized.
You need a role object, and to do that, you need a guild object, which you can get with message.author.guild.
From this, you can get the Role object:
role = await message.author.guild.get_role(ROLE_ID)
Note that you need to get the role ID yourself. The easiest method to do so is to go into Discord and enable Developer settings, then right click the role on someone's profile and click "Copy ID". Once you have this role object, you can just apply it with message.author.add_roles(role).
Complete code:
role_id = ...
author = message.author;
role = await author.guild.get_role(role_id)
await author.add_roles(role)
Make sure your bot has the Manage Roles permission

How to add role hierarchy in discord.User cog?

I have a ban command which uses discord.User cog as to ban members who are not in the guild, but I want to add role hierarchy but when I checked the docs there was no attribute for it, is there a way to do both? Have role hierarchy and be able to ban users who are not in the guild
You can iterate through the roles of the user and check if he has a role in a list. I prefer to use the role IDs since it can't be changed.
Use typing.Union to either get a member, or the id if the user is not in the server
from typing import Union
#client.command()
#commands.bot_has_permissions(ban_members=True)
#commands.has_permissions(ban_members=True)
async def ban(ctx, user: Union[discord.Member, int]):
if isinstance(user, int):
# user is not in guild -> ban him by id
pass
else:
whitelisted_roles = [123456, 456789, 789012] # List of Mod roles
for role in user.roles:
if role.id in whitelisted_roles:
return await ctx.send("You can't ban this user! He is a moderator!")
else:
pass
# ban the member
Welcome to StackOwerflow!
Yes, it's possible to check role hierarchy as well as ban users with their user_ids.
I recommend taking a looking into the answer by Guddi.
First and formost:
You need a check role heirarchy.
To do that, here's the code:
if not (user.guild_permissions.administrator and user.top_role.position > ctx.me.top_role.position and user.top_role.position > ctx.author.top_role.position):
user.ban()
To ban the user who is not in the guild,
if isinstance(user, int):
user = await bot.fetch_user(user)
await ctx.guild.ban(user)
I hope this is helpful.

Discord.py Server Roles Command, Roles Starting From Down

Hi I do a server roles command and it working perfectly but the top role is showing in the down. My code is this:
#bot.command(pass_context=True)
async def roles(ctx):
guild = ctx.guild
roles = [role for role in guild.roles if role != ctx.guild.default_role]
embed = discord.Embed(title="Server Roles", description=f"\n \n".join([role.mention for role in roles]))
await ctx.send(embed=embed)
I want the top role to start form the top not down, how can I do that?
I will be very happy if someone help me :)
list type has a reverse method. So if you write roles.reverse(), top role will be the first one.

Discord.py rewrite - looking to see if a member is server muted, no info found on API Reference

How do I go about looking to see if a Member object is server muted? I can use the edit() function to mute them, but I want to retrieve a list of all members of a server that are muted. But I can't do that if I can't make a check to see if the Member object is muted.
Also how do I change a user's permission so they can't send messages (a mute function)
if ctx.author.is_muted(): # <<< Goal :) Not a real function
await ctx.author.edit(mute=False) # Is a real function, only works on voice connection.
else:
pass
As you said (and as I know), there is no way to mute a server member properly using a function that is provided by the discord.py API. You can mute a member in the voice chat but not in text channels.
The only way to avoid a user to send messages is to create a mute role and change all the channels perms.
Here are some examples of what you can do to answer your question :
Mute role :
So we wan't to create a role called "muted" if it doesn't exist each time we call the command mute #user :
import discord, asyncio
from discord.utils import get
async def create_mute_role(guild):
'''
`guild` : must be :class:`discord.Guild`
'''
role_name = "muted"
mute_role = get(guild.roles, name = role_name) # allows us to check if the role exists or not
# if the role doesn't exist, we create it
if mute_role is None:
await guild.create_role(name = role_name)
mute_role = get(guild.roles, name = role_name) # retrieves the created role
# set channels permissions
for channel in guild.text_channels:
await asyncio.sleep(0)
mute_permissions = discord.PermissionsOverwrite()
mute_permissions.send_messages = False
await channel.set_permissions(mute_role, overwrite = mute_permissions)
return(mute_role)
Your mute #user command will do something like :
#commands.command()
async def mute(self, ctx, member: discord.Member):
guild = ctx.message.guild
mute_role = await create_mute_role(guild)
await member.add_roles(mute_role)
await ctx.send(f"{member.name} has been muted !")
return
Get the muted members :
To get a list of your server muted members, you want to use role.members.
So doing :
muted_list = mute_role.members
print(len(muted_list))
Will display the amount of muted members, you can walk through this list with :
for member in muted_list:
Hope it helped !

Categories