How to how to convert username to discord ID? - python

I have a simple questions about discord. I am trying to create an economy system, and it works well, but I want to customize it a bit. I am using this person's module: https://github.com/Rapptz/discord.py
How do I convert a username to a discord ID. For example if I have a discord "command" to allow people to gift each other money, like: james#0243 types !give 100 bob#9413.
How can I convert bob#9413 to a discord id like 58492482649273613 because in my database, I have people's users stored as their ID rather than their actual username as people can change their username.

Use a converter to get the Member object of the target, which will include their id.
from discord import Member
from dicord.ext.commands import Bot
bot = Bot(command_prefix='!')
#bot.command()
async def getids(ctx, member: Member):
await ctx.send(f"Your id is {ctx.author.id}")
await ctx.send(f"{member.mention}'s id is {member.id}")
bot.run("token")
Converters are pretty flexible, so you can give names, nicknames, ids, or mentions.

on_message callback function is passed the message.
message is a discord.Message instance.
It has author and
mentions attributes which could be instances of discord.Member or discord.User depending on whether the message is sent in a private channel.
The discord.Member class subclasses the discord.User and the user id can be accessed there.

You could use get_member_named to do something like
#client.command(pass_context = True)
async def name_to_id(ctx, *, name):
server = ctx.message.server
user_id = server.get_member_named(name).id
The name can have an optional discriminator argument, e.g. “Jake#0001” or “Jake” will both do the lookup. However the former will give a more precise result.

prefix_choice = "!"
bot = commands.Bot(max_messages=10000, command_prefix=commands.when_mentioned_or(prefix_choice))
#bot.command()
async def membersLog(ctx):
for i, member in enumerate(ctx.message.server.members):
list_mem_num = (f'{i}')
list_mem_id = (f'{member.id}')
list_mem = (f'{member}')
list_mem_name = (f'{member.name}')
list_all = (f'Number: {list_mem_num} ID: {list_mem_id} Name: {list_mem} ({list_mem_name})\n')
print(list_all)
You can use this to collect all memberinfo of the server where the call comes from. This is the code I use for this.

Related

I am trying to make a discord bot in which I want that as soon as user type into command channel his/her discord id must be printed

if message.content.startswith('$register'):
await message.channel.send('You are registered successfully')
userk = print(client.user.id)
I am using Discord.py and Iam trying to get the Discord user id of a user when they type into a channel. But I am not able to find the specific command for that current api of discord is not saying anything about that.the above code is only printing my bot's id.
Get the author of the message
You need to look the id of the author.
API:
discord.on_message(message): Get a message, a Message,
class discord.Message: look for author attribute, a Member,
class discord.Member: look id attribute.
if message.content.startswith('$register'):
await message.channel.send('You are registered successfully')
print(message.author.id)
Maybe a possible answer here:
Discord-py When a user is typing, how to make the bot to follow the typing and when the user stop, the bot also stop typing in a specific channel?
EDIT:
enabling intents.typing and turning on the intents within the
Discord developer portal can access the on_typing event, you can
just enable all intents from your code like:
discord.Client(intents=intents) ```
The typing event can be called simply using an ``on_typing`` event,
``` #client.event async def on_typing(channel, user, when):
print(f"{user} is typing message in {channel} {when}")
Here is an example:
#client.event
async def on_typing(channel, user, when):
print(f"{user.id=}")
Check the discord.on_typing(channel, user, when) documentation.
user parameter can be a User or a Member, but either way, it have an id attribute.

Pythion Discord Bot #'ing people

I need when I run a command like /insult #name the bot #'s the person in the argument of the command and sends an image. I can do most of the rest but I can't seem to figure out of to have it #mention the person.
To mention a user in a command, you can use member: discord.Member. This helps you get a member object in the command itself. You can view more on how you can use a discord.Member object here. An example on how to use this in a command can also be found in the docs, view this: Discord Converters.
You can view how these can be incorporated below, including a None variable as a default to avoid errors in your console if the ctx.author does not mention a member.
#client.command() # or bot.command(), or whatever you're using
async def insult(ctx, member:discord.Member=None):
if member == None: # Happens if ctx.author does not mention a member..
member = ctx.author # ..so by default the member will be ctx.author
# You can use member.mention to mention/ ping/ # the person assigned as member
await ctx.send(f"Be insulted {member.mention}!")
# A not as good way to do it would be:
await ctx.send(f"Be insulted <#{member.id}>!")
# both methods work the same way, but member.mention is recommended

how to I get a mentioned user's ID in discord.py? [duplicate]

#bot.command()
async def id(ctx, a:str): #a = #user
how would I get the ID of a user mentioned in the command, and output it as:
await ctx.send(id)
Use a converter to get the User object:
#bot.command(name="id")
async def id_(ctx, user: discord.User):
await ctx.send(user.id)
Or to get the id of the author:
#bot.command(name="id")
async def id_(ctx):
await ctx.send(ctx.author.id)
Just realized that when you #someone and store it to the variable "a", it contains the user ID in the form of '<#userid>'. So a bit of clean up can get me the user ID
Here's the code:
#bot.command()
async def id(ctx, a:str):
a = a.replace("<","")
a = a.replace(">","")
a = a.replace("#","")
await ctx.send(a)
Since my command consists of "rev id #someone", the #someone gets stored in 'a' as the string '<#userid>' instead of '#someone'.
If you want to handle a mention within your function, you can get the mention from the context instead of passing the mention as a string argument.
#bot.command()
async def id(ctx):
# Loop through the list of mentioned users and print the id of each.
print(*(user_mentioned.id for user_mentioned in ctx.message.mentions), sep='\n')
ctx.message.mentions will return:
A list of Member that were mentioned. If the message is in a private
message then the list will be of User instead.
When you loop through ctx.message.mentions, each item is a mentioned member with attributes such as id, name, discriminator. Here's another example of looping through the mentioned list to handle each member who was mentioned:
for user_mentioned in ctx.message.mentions:
# Now we can use the .id attribute.
print(f"{user_mentioned}'s ID is {user_mentioned.id}")
It's up to you whether you want to require the argument a as shown in the question above. If you do need this, note that the string will sometimes include an exclamation in the mention depending on whether it is:
for a User or command was posted from mobile app: <#1234567890>
for a Nickname or command was posted from desktop app: <#!1234567890>
Which is why I prefer to get the id from a member/user attribute.

Is there a way to give roles without a command?

I have a database with discord id, seconds and more
A plugin from a game server is measuring player activity and feed it inside the database
I was wondering if there is a way to make my bot give a role to that specific discord id as long as his activity is bigger than some value
ive tried this way but it doesn't work
#tasks.loop(seconds=10)
async def checkDB():
delete_oldDate()
list = get_db_list('players_activity', '*')
for i in list:
if str(i[3]) != 'None' and int(i[2]) >= min_activity:
user = i[3]
role = discord.utils.get(user.guild.roles, giveawayRole_ID)
await client.add_role(user, role)
else:
print("")
any ideas?
Adding roles inside and outside of a command works the same way. client.add_role doesn't exist, which is why it doesn't work. The correct function is Member.add_roles(list_of_roles).
Going off of context, I'm gonna assume your user is already a discord.Member instance, as you're calling it's guild attribute. You can also use Guild.get_role(role_id) to get the discord.Role instance of the role.
user = i[3]
role = user.guild.get_role(giveawayRole_ID)
await user.add_roles([role])
EDIT:
Apparently your user was not a discord.Member instance yet, so you'll have to get that first. You should've gotten an error from that though, which you didn't mention. In case user is a string, user.guild shouldn't work at all either.
First of all, instead of storing their Discord ID as Mihái#8090, you should store their actual ID, which is a number. You can get this by using Member.id whenever they use a command (to put them in the database), or right-clicking them and using Copy ID in Discord.
Seeing as you always want to use the same Guild, you should already have the Guild's ID stored somewhere as well.
guild_id = 000000000000 # Whatever the ID of your Guild is
guild = client.get_guild(guild_id)
member = guild.get_member(int(i[3]))
role = guild.get_role(giveawayRole_ID)
await member.add_roles([role])
So first get the Guild instance, then the user's Member instance in that guild, then the Role instance, and then give the member the role.

How to get a mentioned user's avatar URL with discord.py?

How can I get a mentioned user's avatar?
I can get a mentioned user's ID, but I can't find out how to use it like message.author.avatar_url.
Can I make this into (Userid).author.avatar_url?
I already got the mentioned user's ID by slicing the message's content.
client = commands.Bot(command_prefix='-')
#client.command(name='avatar', help='fetch avatar of a user')
async def dp(ctx, *, member: discord.Member = None):
if not member:
member = ctx.message.author
userAvatar = member.avatar_url
await ctx.send(userAvatar)
The command will be something like => '-avatar' or '-avatar [user]'
P.s. Don't use [ ] after '-avatar' and before mentioning the user
If a user is not mentioned, it will fetch the avatar of the user sending the command
If you're using the commands extension, you can use a MemberConverter or UserConverter to get the Member or User object, respectively. Otherwise, you can use the Message.mentions attribute of the Message object to get a list of the Members that were mentioned in the message.
If you have the user ID already, you can use of the methods covered in the How do I get a specific model? section of the FAQ in the documentation to retrieve the Member or User object.
You can then use the avatar_url attribute of the Member or User object.
author = ctx.message.author
pfp = author.avatar_url
Author creates an object and can be used a string e.g username#0000
pfp (profile picture) is an asset that can be used in an embed for example
embed = discord.Embed()
embed.set_image(url=pfp)
await ctx.send(embed=embed)
You can use this:
author = message.author
await message.channel.send(author.avatar_url)
On use message args
If you're using discord.py v2 it is: message.author.avatar.
Check this: https://discordpy.readthedocs.io/en/master/api.html?highlight=member#discord.Member

Categories

Resources