Перейти к содержимому

Как получить пользователя по id discord py

  • автор:

Как получить объект Member, зная id?

phaggi

Вы пытаетесь взять слово «Сервер», и получить конкретного участника из определения «Сервер», не конкретного сервера.

Но в данном случае всё может быть намного проще, не нужно изобретать велосипед, достаточно разок почитать документацию, а не устаревшие туториалы (привет pass_context): https://discordpy.readthedocs.io/en/stable/ext/com.

В discord.py существует понятие «конвертеры», которые значительно упрощают написание команд:

Это, к слову, позволит вызывать команду не только по упоминанию пользователя, но и по его никнейму, ID, и полному тегу: https://discordpy.readthedocs.io/en/stable/ext/com.
9rL1N4x.png

Получать объект пользователя (User) нет смысла в данном случае, так как класс Member все методы класса User путём наследования.

Discord.py: Get user object with id

I have a bot which only saves the id of a user (it’s better working like that). Now I want to get the user-object from that id.

I tried following which doesn’t work for me, maybe I have made something wrong..

Here is the code:

Executing this, it will only print "Top rank entered" but not the user or "Top rank end" However, I did not get an error message. The method just stops there (The bot is running on Heroku). Thanks in advance!

Discord.py get user object from id/tag

I’m using the discord.py library to build a discord bot. I’m trying to get a User object from an id or tag, however, I am using a user account not a bot account, so I can’t use get_user_info(). Is there any way to do this on a user account?

TheOneMusic's user avatar

9 Answers 9

If you know the user id, I suggest using bot.get_user(user_id) instead.

TheOneMusic's user avatar

If you’re using commands , you can use a converter:

Other wise, you can use Client.get_all_members to get all Member objects you can see.

Patrick Haugh's user avatar

This will return you a discord.Member object.

Mahesh Mahi's user avatar

This also will return your user object, but not your member object. If you want the member object, please follow AJ Lee’s answer

I couldn’t write a comment to the previous answer (because of reputation) but make sure that id is int type here.

Yalchin Mammadli's user avatar

If you already have the id, call user = await ctx.bot.fetch_user(user_id) . No messing about with permissions.

If you only have the username and tag, you can use:

Note you’ll also need to turn the Members intent on in your code and the Discord Developer Portal in order to call fetch_members()

Name already in use

discord-api-docs / docs / resources / User.md

  • Go to file T
  • Go to line L
  • Copy path
  • Copy permalink

55 contributors

Users who have contributed to this file

  • Open with Desktop
  • View raw
  • Copy raw contents Copy raw contents

Copy raw contents

Copy raw contents

Users in Discord are generally considered the base entity. Users can spawn across the entire platform, be members of guilds, participate in text and voice chat, and much more. Users are separated by a distinction of «bot» vs «normal.» Although they are similar, bot users are automated users that are «owned» by another user. Unlike normal users, bot users do not have a limitation on the number of Guilds they can be a part of.

Usernames and Nicknames

Discord enforces the following restrictions for usernames and nicknames:

  1. Names can contain most valid unicode characters. We limit some zero-width and non-rendering characters.
  2. Usernames must be between 2 and 32 characters long.
  3. Nicknames must be between 1 and 32 characters long.
  4. Names are sanitized and trimmed of leading, trailing, and excessive internal whitespace.

The following restrictions are additionally enforced for usernames:

  1. Usernames cannot contain the following substrings: @ , # , : , «` , discord
  2. Usernames cannot be: everyone , here

There are other rules and restrictions not shared here for the sake of spam and abuse mitigation, but the majority of users won’t encounter them. It’s important to properly handle all error messages returned by Discord when editing or updating names.

Field Type Description Required OAuth2 Scope
id snowflake the user’s id identify
username string the user’s username, not unique across the platform identify
discriminator string the user’s 4-digit discord-tag identify
avatar ?string the user’s avatar hash identify
bot? boolean whether the user belongs to an OAuth2 application identify
system? boolean whether the user is an Official Discord System user (part of the urgent message system) identify
mfa_enabled? boolean whether the user has two factor enabled on their account identify
banner? ?string the user’s banner hash identify
accent_color? ?integer the user’s banner color encoded as an integer representation of hexadecimal color code identify
locale? string the user’s chosen language option identify
verified? boolean whether the email on this account has been verified email
email? ?string the user’s email email
flags? integer the flags on a user’s account identify
premium_type? integer the type of Nitro subscription on a user’s account identify
public_flags? integer the public flags on a user’s account identify
Value Name Description
1 << 0 STAFF Discord Employee
1 << 1 PARTNER Partnered Server Owner
1 << 2 HYPESQUAD HypeSquad Events Member
1 << 3 BUG_HUNTER_LEVEL_1 Bug Hunter Level 1
1 << 6 HYPESQUAD_ONLINE_HOUSE_1 House Bravery Member
1 << 7 HYPESQUAD_ONLINE_HOUSE_2 House Brilliance Member
1 << 8 HYPESQUAD_ONLINE_HOUSE_3 House Balance Member
1 << 9 PREMIUM_EARLY_SUPPORTER Early Nitro Supporter
1 << 10 TEAM_PSEUDO_USER User is a team
1 << 14 BUG_HUNTER_LEVEL_2 Bug Hunter Level 2
1 << 16 VERIFIED_BOT Verified Bot
1 << 17 VERIFIED_DEVELOPER Early Verified Bot Developer
1 << 18 CERTIFIED_MODERATOR Moderator Programs Alumni
1 << 19 BOT_HTTP_INTERACTIONS Bot uses only HTTP interactions and is shown in the online member list
1 << 22 ACTIVE_DEVELOPER User is an Active Developer

Premium types denote the level of premium a user has. Visit the Nitro page to learn more about the premium plans we currently offer.

Value Name
0 None
1 Nitro Classic
2 Nitro
3 Nitro Basic

The connection object that the user has attached.

Field Type Description
id string id of the connection account
name string the username of the connection account
type string the service of this connection
revoked? boolean whether the connection is revoked
integrations? array an array of partial server integrations
verified boolean whether the connection is verified
friend_sync boolean whether friend sync is enabled for this connection
show_activity boolean whether activities related to this connection will be shown in presence updates
two_way_link boolean whether this connection has a corresponding third party OAuth2 token
visibility integer visibility of this connection
Value Name
battlenet Battle.net
ebay eBay
epicgames Epic Games
facebook Facebook
github GitHub
instagram Instagram
leagueoflegends League of Legends
paypal PayPal
playstation PlayStation Network
reddit Reddit
riotgames Riot Games
spotify Spotify
skype * Skype
steam Steam
tiktok TikTok
twitch Twitch
twitter Twitter
xbox Xbox
youtube YouTube

* Service can no longer be added by users

Value Name Description
0 None invisible to everyone except the user themselves
1 Everyone visible to everyone

Application Role Connection Object

The role connection object that an application has attached to a user.

Application Role Connection Structure

Field Type Description
platform_name ?string the vanity name of the platform a bot has connected (max 50 characters)
platform_username ?string the username on the platform a bot has connected (max 100 characters)
metadata object object mapping application role connection metadata keys to their string -ified value (max 100 characters) for the user on the platform a bot has connected

Get Current User % GET /users/@me

Returns the user object of the requester’s account. For OAuth2, this requires the identify scope, which will return the object without an email, and optionally the email scope, which returns the object with an email.

Returns a user object for a given user ID.

Modify Current User % PATCH /users/@me

Modify the requester’s user account settings. Returns a user object on success. Fires a User Update Gateway event.

info All parameters to this endpoint are optional.

Field Type Description
username string user’s username, if changed may cause the user’s discriminator to be randomized.
avatar ?image data if passed, modifies the user’s avatar

Get Current User Guilds % GET /users/@me/guilds

Returns a list of partial guild objects the current user is a member of. Requires the guilds OAuth2 scope.

Example Partial Guild

info This endpoint returns 200 guilds by default, which is the maximum number of guilds a non-bot user can join. Therefore, pagination is not needed for integrations that need to get a list of the users’ guilds.

Query String Params

Field Type Description Required Default
before snowflake get guilds before this guild ID false absent
after snowflake get guilds after this guild ID false absent
limit integer max number of guilds to return (1-200) false 200

Returns a guild member object for the current user. Requires the guilds.members.read OAuth2 scope.

Leave a guild. Returns a 204 empty response on success. Fires a Guild Delete Gateway event and a Guild Member Remove Gateway event.

Create DM % POST /users/@me/channels

Create a new DM channel with a user. Returns a DM channel object (if one already exists, it will be returned instead).

warn You should not use this endpoint to DM everyone in a server about something. DMs should generally be initiated by a user action. If you open a significant amount of DMs too quickly, your bot may be rate limited or blocked from opening new ones.

Field Type Description
recipient_id snowflake the recipient to open a DM channel with

Create Group DM % POST /users/@me/channels

Create a new group DM channel with multiple users. Returns a DM channel object. This endpoint was intended to be used with the now-deprecated GameBridge SDK. Fires a Channel Create Gateway event.

warn This endpoint is limited to 10 active group DMs.

Field Type Description
access_tokens array of strings access tokens of users that have granted your app the gdm.join scope
nicks dict a dictionary of user ids to their respective nicknames

Get User Connections % GET /users/@me/connections

Returns a list of connection objects. Requires the connections OAuth2 scope.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *