discord.py get member instance from name#discriminator - python-3.x

I have a string with the name of an user user = 'somename#1111' how can I mention him? (I get the name from google sheets that's why it's a string)
I tried with:
#client.command()
async def mention(ctx):
user : discord.Member = 'somename#1111'
await ctx.send(f"{user.mention} hello!")
But it doesn't work

Although this method is valid, I'd recommend switching to saving user IDs instead of usernames + discriminators, as user IDs are constant, but users are able to change their names and discriminators.
#client.command()
async def mention(ctx):
user = discord.utils.get(ctx.guild.members, name="somename", discriminator="1111")
await ctx.send(f"{user.mention} hello!")
And with the ID:
#client.command()
async def mention(ctx):
user = ctx.guild.get_member(112233445566778899) # replace user ID there
try:
await ctx.send(f"{user.mention} hello!")
except:
await ctx.send("Sorry, that user has left the server!")
References:
utils.get()
User.discriminator
Guild.get_member()
Guild.get_member_named() - "Returns the first member found that matches the name provided."

I haven't used user.mention, but what I do is I get the user's id, then mention them like this:
await ctx.send(f'<#!{user.id}> hello!')

Related

embed snipe message displays user id instead of the username discord bot python

My discord snipe feature but functions quite well however whenever it sends the embed of the deleted message, it displays the id number of the user who deleted the message instead of showing the actual username
#client.event
async def on_message_delete(message):
global snipe_message_content
global snipe_message_author
global snipe_message_id
snipe_message_content = message.content
snipe_message_author = message.author.id
snipe_message_id = message.id
embed = discord.Embed(description=f"{snipe_message_content}")
embed.set_author(name= f"<#{snipe_message_author}>")
channel = client.get_channel(795726497922809947)
await channel.send(embed=embed)
You assigned the author ID not the author name to snipe_message_author
snipe_message_author = message.author.name
Otherwise you could use str(message.author) which gives you the name#tag.
But I don't recommend that way. I'm using it myself because it is shorter than message.author.name + "#" + message.author.discriminator But yeah.

discord.py - How to send a private message to a server owner?

I am trying to make my bot dm the server owner whenever it joins a new server. I have tried this:
#client.event
async def on_guild_join(guild):
user = await client.fetch_user(guild.owner)
await client.send_message(user,"hi there!")
But it gives this error message:
In user_id: Value "myname" is not snowflake
I can't figure out how to get the user id of the guild owner, i looked through the documentation but i couldn't find anything.
Here is a solution. You can just call the owner argument on a Guild:
#client.event
async def on_guild_join(guild):
owner = guild.owner
await owner.send("hi there!")

How to create a portfolio command in discord.py?

So, I need to make a !vx portfolio command for my VX Helper Bot, I want it to send a link of the member of my team, example - !vx portfolio videro will send a link to videro's portfolios, I cant figure out how to do so, however, I know how to make !vx portfolio #Videro but I dont want the user to tag the member to get his/her portfolio, any help would be really appreciated.
Thanks!
I am using this but its not working-
async def portfolio(ctx, team_member):
videro="videro"
harxu="harxu"
team_member = [videro,harxu,]
videro_embed = discord.Embed(title=f"VX Videro", description=f"Here is Videro's Portfolio-"
f"\n:point_right: https://www.twitter.com/viderodzns", colour=0x40cc88)
while True:
if team_member=='videro':
await ctx.send(embed=videro_embed)
Here's one way to do it: we have two commands, register and portfolio. register saves a url, and portfolio will use those saves urls to create embeds.
from discord import Member, Embed
urls = {}
#bot.command()
async def register(ctx, member: Member, *, url):
urls[str(member.id)] = url
#bot.command()
async def portfolio(ctx, member: Member):
id = str(member.id)
if id not in urls:
await ctx.send(f"Unrecognized user {member.display_name}")
return
embed = Embed(title=f"VX {member.display_name}",
description=f"Here is {member.display_name}'s Portfolio-\n:point_right: {urls[id]}", colour=0x40cc88)
await ctx.send(embed=embed)

How do I make and assign roles using discord.py?

I'm trying to make a completly new role in discord (with discord.py) but everything I try, doesn't work. I allready tried
await guild.create_role(name("R3KT")) #NameError: name 'guild' not defined
and
author = ctx.message.author
await client.create_role(author.server, name="role name") #NameError: name 'ctx' not defined
I've tried changing ctx and guild to 'client' but it still didn't work. if needed I'll send the whole code (without the discord name and bot key)
here's the entire code:
import discord
token = "bot-key"
client = discord.Client()
#client.event
async def on_ready():
print("Bot is online and connected to Discord")
#client.event
async def on_message(message):
message.content = message.content.upper()
if message.author == client.user:
return
if message.content.startswith("AS HELLO"):
await message.channel.send("works")
elif message.content.startswith("AS CREATEROLE"):
if str(message.author) == "myDiscName#6969":
author = message.author
await discord.create_role(author.server, name="R3KT")
elif message.content.startswith("AS GIVEROLE"):
if str(message.author) == "myDiscName#6969":
print("give role")
client.run(token)
In the second example you provided, it looks like you're using a mish-mash between the old d.py (0.16.x) docs and d.py rewrite (1.x).
Make sure you have the most up-to-date version (rewrite) installed, as async is no longer being maintained.
Here's an example with the command decorator (usage: !newrole Member)
#client.command()
async def newrole(ctx, *, rolename=None):
if not rolename:
await ctx.send("You forgot to provide a name!")
else:
role = await ctx.guild.create_role(name=rolename, mentionable=True)
await ctx.author.add_roles(role)
await ctx.send(f"Successfully created and assigned {role.mention}!")
The mentionable kwarg isn't compulsory - it defaults to False if not specified - I just set it to True for the example. You're also able to write your own permissions for the role.
And another example using on_message - recommended to use command decorator instead, as args are easier to deal with
async def on_message(message):
args = message.content.split(" ")[2:] # 2: because prefix contains space
if message.content.lower().startswith("as createrole"):
role = await message.guild.create_role(name=" ".join(args))
await message.author.add_roles(role)
await message.channel.send(f"Successfully created and assigned {role.mention}!")
References:
discord.py Rewrite docs
Guild.create_role()
discord.Permissions
Member.add_roles()
discord.on_message()
You don't want to check by name and number (as you can change that if you have nitro), you should check by ID which is unique to every user and immutable.
Also note that server is referred to as guild in discord.py.
elif message.content.startswith("AS CREATEROLE"):
if message.author.id == YOUR_ID_GOES_HERE: # find your id by right clicking on yourself and selecting "copy id" at the bottom of the menu of options
author = message.author
# create a role named "R3KT" that has the permissions "Administrator" that has the color "white" that is not displayed separately and is not mentionable by everyone
await message.guild.create_role(name="R3KT", permissions=discord.Permissions(8), colour=discord.Colour.from_rgb(255, 255, 255), hoist=False, mentionable=False)
Permissions integer calculator
discord.Guild.create_role
With giving yourself a role:
elif message.content.startswith("AS GIVEROLE"):
if message.author.id == YOUR_ID_GOES_HERE:
user = message.author
await user.add_roles(message.guild.get_role(ROLE_ID_GOES_HERE), reason='Someone did a giverole bot command') # left click on the role and click "copy id"
discord.Member.add_roles
discord.Guild.get_role

How to get server details of a member

How to get details of a member using his UserID. like example i want to know in which server(name and ID) he is member of were ever my bot is added.
It's as simple as looping through all of the servers the bot has access to and trying to retrieve the Member object from each server for that ID.
from discord.ext import commands
bot = commands.Bot(command_prefix='!')
#bot.command(pass_context=True)
async def getUser(ctx, id):
# id = int(id) # On the rewrite branch, ids are ints
for server in bot.servers:
member = server.get_member(id)
if member:
await bot.say(f"Server Name: {server.name}")
await bot.say(f"Server ID: {server.id}")
bot.run("TOKEN")

Resources