How to get member object from Id discord.py - discord

I have a user's id however I want to be able to convert this into a member object.
my bot has a leader board and stores uses the users discord id as a key. I want to be able to use these id's to get a member object. I want to be able to access this even if that user is not in the server.
Is this possible, if so how can I do it

You can do this in one line of code:
member_obj = ctx.guild.get_member(user_id)
So for example, this is how you could use it in a function:
import discord
from discord.ext import commands
#client.command()
async def id_to_name(ctx, *, id):
member_obj = ctx.guild.get_member(user_id)
await ctx.send(f'ID to name: {member_obj.display_name}')

You could do either of two things.
If you want to use ctx:
ctx.author.mention
#If you want to use the member thing.
#Bot.command()
async def example(ctx, member : discord.Member):
await ctx.send(f"name{member.mention or ctx.authour.mention}

Related

Command that allows you to make a role

I wanted to make a command that allows you to make a role, along with the permissions, colors, and whether it's hoisted or not.
I've put the command inside a cog.
#commands.command(aliases=['make_role'])
#commands.has_permissions(manage_roles=True)
async def createrole(self, ctx, *, name):
guild = ctx.guild
await guild.create_role(name=name)
await ctx.send(f'Role `{name}` has been created')
What else do I need to change so that I can add permissions, colors and hoist status upon making the role?
You can apply these parameters to the create_role method that you ran in your code. Here's an example that fills these parameters:
import discord
from discord.ext import commands
#commands.command(aliases=['make_role'])
#commands.has_permissions(manage_roles=True)
async def create_role(self, ctx, *, name):
guild = ctx.guild
await guild.create_role(name=name,
permissions=discord.Permissions.membership(),
color=discord.Color.default(),
hoist=True)
await ctx.send(f'Role `{name}` has been created')
With that example, you can change the initializing values of Permissions and Color.

If I want to remove an ID-specified role within a function, how can I do that?

If I want to remove an ID-specified role within a function, how can I do that?
#bot.command()
async def aa(ctx,member:discord.Member):
role_muted = discord.utils.get(ctx.guild.roles, name='test01')
await member.remove_roles(role_muted)
What I want is to specify an ID in a function like this.
#bot.command()
async def aa(ctx):
member = 414087251992117211 #ID User
role_muted = discord.utils.get(ctx.guild.roles, name='test01')
await member.remove_roles(role_muted)
how can i do it The reason I have to do this is because I will continue to develop such as When you receive this Role within 3 days if not online it will remove your Role.
Use Guild.get_member(id) to get a member by their ID. You can get the Guild either from the ctx if you want it to run in the guild where you call the command, or from a Guild ID that you store somewhere using Bot.get_guild(id).
If you want to pass the ID in as an argument to the function and have it convert to a member automatically, use a Converter.
Can you give an example? I tried to do as you said. but an error occurred
#bot.command()
async def aa(ctx):
member = discord.Guild.get_member(414087251992117211)
role_muted = discord.utils.get(ctx.guild.roles, name='test01')
await member.remove_roles(role_muted)
Error
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'remove_roles'
#UpFeR Pattamin, please comment on a reply instead of posting a new one. You're getting this error because you're not specifying which guild you are talking about. If you want to get the one that the command was executed in, I'm pretty sure you need to do ctx.guild.get_member().

How can I allow people to only kick members lower than their role with discord.py?

I'm trying to make a kick command using Python and the discord.py library, though I cannot figure out how to allow people to only be able to kick members lower than their role, so Moderators wouldn't be able to kick Admins.
enter image description here
You can compare the Member object with a function called top_role
An example code would be:
#client.command()
#commands.has_permissions(kick_members=True)
async def kick(ctx, member: discord.Member, *, reason=None):
if member.top_role >= ctx.author.top_role: # Check if the role is below the authors role
await ctx.send("You can only kick users with a lower role!")
return
else:
await member.kick(reason=reason)
await ctx.send(f"{member.id} got kicked with the reason: {reason}.")
Add all the moderators to a list and regular users to another list.
Like this;
string[] moderator = all moderators.
string[] regularUsers = all regular users.

guild.get_member_named(name) is returning 'NoneType' inspite of existence of such member

I have enabled intents all through my code and developer portal;got necessary permissions for the bot to 'see' the other members but still the method returns NoneType for almost all users(only exception is Dyno)
Now I need a complete check through my program and the permissions and settings
if it doesn't get sorted after the check then the question topic gets adjusted accordingly
import discord
import os
from discord.ext import commands
intents = discord.Intents.default()
intents.members = True
bot = commands.Bot(command_prefix='!',intents=intents)
#bot.event
async def on_ready():
print('We have logged in as {0.user}'.format(bot))
#bot.command()
async def ping(ctx,args1):
guild = bot.get_guild(ServerID)
member = guild.get_member_named(args1) #getting NoneType here
await ctx.send('member.mention') #Assuming the existence of member coz I know there is such one
bot.run(os.getenv('TOKEN'))
Try using
discord.utils.get(guild.members, name='theusernamehere') #replace"theusernamehere" with the person username
To get by id use this
discord.utils.get(guild.members, id='idhere') #replace "idhere" with the person id
or you can just use arg1: discord.Member

Discord.py - Tag a random user

I recently started working with Discord.py.
My question is: How can I tag a random user, for example if you write !tag in the chat? I haven't found an answer yet.
if message.content.startswith('+best'):
userid = '<# # A RANDOM ID #>'
yield from client.send_message(message.channel, ' : %s is the best ' % userid)
ThankĀ“s
Here's how I'd do it:
Generate a list of users in your server
Use random.choice to select a random user from the list
Mention that user using the API (or if you'd like, do it manually) along with your message
Here's the implementation:
from random import choice
if message.content.startswith('+best'):
user = choice(message.channel.guild.members)
yield from client.send_message(message.channel, ' : %s is the best ' % user.mention)
Elaborating on aeshthetic's answer, you can do something like this:
import random
if message.content.startswith('+best'):
channel = message.channel
randomMember = random.choice(channel.guild.members)
await channel.send(f'{randomMember.mention} is the best')
Please note that the code is in the rewrite version of discord.py and not the async version - if you're using the async version, I'd recommend you migrate to rewrite as support for the async version of discord.py has ceased. To learn more about that, refer to the migrating documentation found here.
Let me know if you need help - happy coding!
I was playing around a bit and got this to work, you can try it.
#client.command(pass_context=True)
async def hug(ctx):
user = choice(ctx.message.channel.guild.members)
await ctx.send(f'{ctx.message.author.mention} hugged {user.mention}')
First of all, I suggest you install discord.py-rewrite, as it is more advanced.
Then, I suggest you create bot commands using the #client.command() decorator, like this:
#client.command()
async def testcommand(ctx):
pass
Now that you have done both things, there are several ways to do it. For example, if you don't want the bot to mention the command invoker or other bots, you can write:
from random import choice
from discord.ext import commands
#client.command()
#commands.guild_only()
async def tag(ctx):
try:
await ctx.send(choice(tuple(member.mention for member in ctx.guild.members if not member.bot and member!=ctx.author)))
except IndexError:
await ctx.send("You are the only human member on it!")
If you don't want the bot to mention other bots, but it can mention the command invoker, use:
from random import choice
from discord.ext import commands
#client.command()
#commands.guild_only()
async def tag(ctx):
await ctx.send(choice(tuple(member.mention for member in ctx.guild.members if not member.bot)))
If you want the bot to mention any guild member, human or bot, use:
from random import choice
from discord.ext import commands
#client.command()
#commands.guild_only()
async def tag(ctx):
await ctx.send(choice(tuple(member.mention for member in ctx.guild.members)))

Resources