Oauth2 application does not have a bot ошибка

Opcodes and Status Codes

Gateway

All gateway events in Discord are tagged with an opcode that denotes the payload type. Your connection to our gateway may also sometimes close. When it does, you will receive a close code that tells you what happened.

Gateway Opcodes
Code Name Client Action Description
0 Dispatch Receive An event was dispatched.
1 Heartbeat Send/Receive Fired periodically by the client to keep the connection alive.
2 Identify Send Starts a new session during the initial handshake.
3 Presence Update Send Update the client’s presence.
4 Voice State Update Send Used to join/leave or move between voice channels.
6 Resume Send Resume a previous session that was disconnected.
7 Reconnect Receive You should attempt to reconnect and resume immediately.
8 Request Guild Members Send Request information about offline guild members in a large guild.
9 Invalid Session Receive The session has been invalidated. You should reconnect and identify/resume accordingly.
10 Hello Receive Sent immediately after connecting, contains the heartbeat_interval to use.
11 Heartbeat ACK Receive Sent in response to receiving a heartbeat to acknowledge that it has been received.
Gateway Close Event Codes

In order to prevent broken reconnect loops, you should consider some close codes as a signal to stop reconnecting. This can be because your token expired, or your identification is invalid. This table explains what the application defined close codes for the gateway are, and which close codes you should not attempt to reconnect.

Code Description Explanation Reconnect
4000 Unknown error We’re not sure what went wrong. Try reconnecting? true
4001 Unknown opcode You sent an invalid Gateway opcode or an invalid payload for an opcode. Don’t do that! true
4002 Decode error You sent an invalid payload to Discord. Don’t do that! true
4003 Not authenticated You sent us a payload prior to identifying. true
4004 Authentication failed The account token sent with your identify payload is incorrect. false
4005 Already authenticated You sent more than one identify payload. Don’t do that! true
4007 Invalid seq The sequence sent when resuming the session was invalid. Reconnect and start a new session. true
4008 Rate limited Woah nelly! You’re sending payloads to us too quickly. Slow it down! You will be disconnected on receiving this. true
4009 Session timed out Your session timed out. Reconnect and start a new one. true
4010 Invalid shard You sent us an invalid shard when identifying. false
4011 Sharding required The session would have handled too many guilds — you are required to shard your connection in order to connect. false
4012 Invalid API version You sent an invalid version for the gateway. false
4013 Invalid intent(s) You sent an invalid intent for a Gateway Intent. You may have incorrectly calculated the bitwise value. false
4014 Disallowed intent(s) You sent a disallowed intent for a Gateway Intent. You may have tried to specify an intent that you have not enabled or are not approved for. false

Voice

Our voice gateways have their own set of opcodes and close codes.

Voice Opcodes
Code Name Sent By Description
0 Identify client Begin a voice websocket connection.
1 Select Protocol client Select the voice protocol.
2 Ready server Complete the websocket handshake.
3 Heartbeat client Keep the websocket connection alive.
4 Session Description server Describe the session.
5 Speaking client and server Indicate which users are speaking.
6 Heartbeat ACK server Sent to acknowledge a received client heartbeat.
7 Resume client Resume a connection.
8 Hello server Time to wait between sending heartbeats in milliseconds.
9 Resumed server Acknowledge a successful session resume.
13 Client Disconnect server A client has disconnected from the voice channel
Voice Close Event Codes
Code Description Explanation
4001 Unknown opcode You sent an invalid opcode.
4002 Failed to decode payload You sent an invalid payload in your identifying to the Gateway.
4003 Not authenticated You sent a payload before identifying with the Gateway.
4004 Authentication failed The token you sent in your identify payload is incorrect.
4005 Already authenticated You sent more than one identify payload. Stahp.
4006 Session no longer valid Your session is no longer valid.
4009 Session timeout Your session has timed out.
4011 Server not found We can’t find the server you’re trying to connect to.
4012 Unknown protocol We didn’t recognize the protocol you sent.
4014 Disconnected Channel was deleted, you were kicked, voice server changed, or the main gateway session was dropped. Should not reconnect.
4015 Voice server crashed The server crashed. Our bad! Try resuming.
4016 Unknown encryption mode We didn’t recognize your encryption.

HTTP

Our API will return semantically valid HTTP response codes based on the success of your request. The following table can be used as a reference for response codes it will return.

HTTP Response Codes
Code Meaning
200 (OK) The request completed successfully.
201 (CREATED) The entity was created successfully.
204 (NO CONTENT) The request completed successfully but returned no content.
304 (NOT MODIFIED) The entity was not modified (no action was taken).
400 (BAD REQUEST) The request was improperly formatted, or the server couldn’t understand it.
401 (UNAUTHORIZED) The Authorization header was missing or invalid.
403 (FORBIDDEN) The Authorization token you passed did not have permission to the resource.
404 (NOT FOUND) The resource at the location specified doesn’t exist.
405 (METHOD NOT ALLOWED) The HTTP method used is not valid for the location specified.
429 (TOO MANY REQUESTS) You are being rate limited, see Rate Limits.
502 (GATEWAY UNAVAILABLE) There was not a gateway available to process your request. Wait a bit and retry.
5xx (SERVER ERROR) The server had an error processing your request (these are rare).

JSON

Along with the HTTP error code, our API can also return more detailed error codes through a code key in the JSON error response. The response will also contain a message key containing a more friendly error string. Some of these errors may include additional details in the form of Error Messages provided by an errors object.

JSON Error Codes
Code Meaning
0 General error (such as a malformed request body, amongst other things)
10001 Unknown account
10002 Unknown application
10003 Unknown channel
10004 Unknown guild
10005 Unknown integration
10006 Unknown invite
10007 Unknown member
10008 Unknown message
10009 Unknown permission overwrite
10010 Unknown provider
10011 Unknown role
10012 Unknown token
10013 Unknown user
10014 Unknown emoji
10015 Unknown webhook
10016 Unknown webhook service
10020 Unknown session
10026 Unknown ban
10027 Unknown SKU
10028 Unknown Store Listing
10029 Unknown entitlement
10030 Unknown build
10031 Unknown lobby
10032 Unknown branch
10033 Unknown store directory layout
10036 Unknown redistributable
10038 Unknown gift code
10049 Unknown stream
10050 Unknown premium server subscribe cooldown
10057 Unknown guild template
10059 Unknown discoverable server category
10060 Unknown sticker
10062 Unknown interaction
10063 Unknown application command
10065 Unknown voice state
10066 Unknown application command permissions
10067 Unknown Stage Instance
10068 Unknown Guild Member Verification Form
10069 Unknown Guild Welcome Screen
10070 Unknown Guild Scheduled Event
10071 Unknown Guild Scheduled Event User
10087 Unknown Tag
20001 Bots cannot use this endpoint
20002 Only bots can use this endpoint
20009 Explicit content cannot be sent to the desired recipient(s)
20012 You are not authorized to perform this action on this application
20016 This action cannot be performed due to slowmode rate limit
20018 Only the owner of this account can perform this action
20022 This message cannot be edited due to announcement rate limits
20024 Under minimum age
20028 The channel you are writing has hit the write rate limit
20029 The write action you are performing on the server has hit the write rate limit
20031 Your Stage topic, server name, server description, or channel names contain words that are not allowed
20035 Guild premium subscription level too low
30001 Maximum number of guilds reached (100)
30002 Maximum number of friends reached (1000)
30003 Maximum number of pins reached for the channel (50)
30004 Maximum number of recipients reached (10)
30005 Maximum number of guild roles reached (250)
30007 Maximum number of webhooks reached (15)
30008 Maximum number of emojis reached
30010 Maximum number of reactions reached (20)
30011 Maximum number of group DMs reached (10)
30013 Maximum number of guild channels reached (500)
30015 Maximum number of attachments in a message reached (10)
30016 Maximum number of invites reached (1000)
30018 Maximum number of animated emojis reached
30019 Maximum number of server members reached
30030 Maximum number of server categories has been reached (5)
30031 Guild already has a template
30032 Maximum number of application commands reached
30033 Max number of thread participants has been reached (1000)
30034 Max number of daily application command creates has been reached (200)
30035 Maximum number of bans for non-guild members have been exceeded
30037 Maximum number of bans fetches has been reached
30038 Maximum number of uncompleted guild scheduled events reached (100)
30039 Maximum number of stickers reached
30040 Maximum number of prune requests has been reached. Try again later
30042 Maximum number of guild widget settings updates has been reached. Try again later
30046 Maximum number of edits to messages older than 1 hour reached. Try again later
30047 Maximum number of pinned threads in a forum channel has been reached
30048 Maximum number of tags in a forum channel has been reached
30052 Bitrate is too high for channel of this type
30056 Maximum number of premium emojis reached (25)
30058 Maximum number of webhooks per guild reached (1000)
30060 Maximum number of channel permission overwrites reached (1000)
30061 The channels for this guild are too large
40001 Unauthorized. Provide a valid token and try again
40002 You need to verify your account in order to perform this action
40003 You are opening direct messages too fast
40004 Send messages has been temporarily disabled
40005 Request entity too large. Try sending something smaller in size
40006 This feature has been temporarily disabled server-side
40007 The user is banned from this guild
40012 Connection has been revoked
40032 Target user is not connected to voice
40033 This message has already been crossposted
40041 An application command with that name already exists
40043 Application interaction failed to send
40058 Cannot send a message in a forum channel
40060 Interaction has already been acknowledged
40061 Tag names must be unique
40062 Service resource is being rate limited
40066 There are no tags available that can be set by non-moderators
40067 A tag is required to create a forum post in this channel
50001 Missing access
50002 Invalid account type
50003 Cannot execute action on a DM channel
50004 Guild widget disabled
50005 Cannot edit a message authored by another user
50006 Cannot send an empty message
50007 Cannot send messages to this user
50008 Cannot send messages in a non-text channel
50009 Channel verification level is too high for you to gain access
50010 OAuth2 application does not have a bot
50011 OAuth2 application limit reached
50012 Invalid OAuth2 state
50013 You lack permissions to perform that action
50014 Invalid authentication token provided
50015 Note was too long
50016 Provided too few or too many messages to delete. Must provide at least 2 and fewer than 100 messages to delete
50017 Invalid MFA Level
50019 A message can only be pinned to the channel it was sent in
50020 Invite code was either invalid or taken
50021 Cannot execute action on a system message
50024 Cannot execute action on this channel type
50025 Invalid OAuth2 access token provided
50026 Missing required OAuth2 scope
50027 Invalid webhook token provided
50028 Invalid role
50033 Invalid Recipient(s)
50034 A message provided was too old to bulk delete
50035 Invalid form body (returned for both application/json and multipart/form-data bodies), or invalid Content-Type provided
50036 An invite was accepted to a guild the application’s bot is not in
50039 Invalid Activity Action
50041 Invalid API version provided
50045 File uploaded exceeds the maximum size
50046 Invalid file uploaded
50054 Cannot self-redeem this gift
50055 Invalid Guild
50067 Invalid request origin
50068 Invalid message type
50070 Payment source required to redeem gift
50073 Cannot modify a system webhook
50074 Cannot delete a channel required for Community guilds
50080 Cannot edit stickers within a message
50081 Invalid sticker sent
50083 Tried to perform an operation on an archived thread, such as editing a message or adding a user to the thread
50084 Invalid thread notification settings
50085 before value is earlier than the thread creation date
50086 Community server channels must be text channels
50091 The entity type of the event is different from the entity you are trying to start the event for
50095 This server is not available in your location
50097 This server needs monetization enabled in order to perform this action
50101 This server needs more boosts to perform this action
50109 The request body contains invalid JSON.
50131 Owner cannot be pending member
50132 Ownership cannot be transferred to a bot user
50138 Failed to resize asset below the maximum size: 262144
50144 Cannot mix subscription and non subscription roles for an emoji
50145 Cannot convert between premium emoji and normal emoji
50146 Uploaded file not found.
50163 Cannot delete guild subscription integration
50159 Voice messages do not support additional content.
50160 Voice messages must have a single audio attachment.
50161 Voice messages must have supporting metadata.
50162 Voice messages cannot be edited.
50173 You cannot send voice messages in this channel.
50178 The user account must first be verified
50600 You do not have permission to send this sticker.
60003 Two factor is required for this operation
80004 No users with DiscordTag exist
90001 Reaction was blocked
110001 Application not yet available. Try again later
130000 API resource is currently overloaded. Try again a little later
150006 The Stage is already open
160002 Cannot reply without permission to read message history
160004 A thread has already been created for this message
160005 Thread is locked
160006 Maximum number of active threads reached
160007 Maximum number of active announcement threads reached
170001 Invalid JSON for uploaded Lottie file
170002 Uploaded Lotties cannot contain rasterized images such as PNG or JPEG
170003 Sticker maximum framerate exceeded
170004 Sticker frame count exceeds maximum of 1000 frames
170005 Lottie animation maximum dimensions exceeded
170006 Sticker frame rate is either too small or too large
170007 Sticker animation duration exceeds maximum of 5 seconds
180000 Cannot update a finished event
180002 Failed to create stage needed for stage event
200000 Message was blocked by automatic moderation
200001 Title was blocked by automatic moderation
220001 Webhooks posted to forum channels must have a thread_name or thread_id
220002 Webhooks posted to forum channels cannot have both a thread_name and thread_id
220003 Webhooks can only create threads in forum channels
220004 Webhook services cannot be used in forum channels
240000 Message blocked by harmful links filter
Example JSON Error Response
{
  "message": "Invalid authentication token",
  "code": 50014
}

RPC

RPC is the local Discord server running on localhost. Access to the RPC server requires approval from Discord.

RPC Error Codes
Code Name Description
1000 Unknown error An unknown error occurred.
4000 Invalid payload You sent an invalid payload.
4002 Invalid command Invalid command name specified.
4003 Invalid guild Invalid guild ID specified.
4004 Invalid event Invalid event name specified.
4005 Invalid channel Invalid channel ID specified.
4006 Invalid permissions You lack permissions to access the given resource.
4007 Invalid client ID An invalid OAuth2 application ID was used to authorize or authenticate with.
4008 Invalid origin An invalid OAuth2 application origin was used to authorize or authenticate with.
4009 Invalid token An invalid OAuth2 token was used to authorize or authenticate with.
4010 Invalid user The specified user ID was invalid.
5000 OAuth2 error A standard OAuth2 error occurred; check the data object for the OAuth2 error details.
5001 Select channel timed out An asynchronous SELECT_TEXT_CHANNEL/SELECT_VOICE_CHANNEL command timed out.
5002 GET_GUILD timed out An asynchronous GET_GUILD command timed out.
5003 Select voice force required You tried to join a user to a voice channel but the user was already in one.
5004 Capture shortcut already listening You tried to capture more than one shortcut key at once.
RPC Close Event Codes
Code Name Description
4000 Invalid client ID You connected to the RPC server with an invalid client ID.
4001 Invalid origin You connected to the RPC server with an invalid origin.
4002 Rate limited You are being rate limited.
4003 Token revoked The OAuth2 token associated with a connection was revoked, get a new one!
4004 Invalid version The RPC Server version specified in the connection string was not valid.
4005 Invalid encoding The encoding specified in the connection string was not valid.

Содержание

  1. Discord API errors Elevated и Latency в Discord инструкции как исправить
  2. API Errors в Discord – какие бывают и почему возникают?
  3. Произошла ошибка API – что делать?
  4. Что означает сбой API в Discord и как это исправить?
  5. # Errors
  6. # Types of Errors
  7. # API Errors
  8. # discord.js errors
  9. # JavaScript errors
  10. # WebSocket and Network errors
  11. # How to diagnose API errors
  12. # Message
  13. # Method
  14. # Common discord.js and API errors
  15. # An invalid token was provided.
  16. # Request to use token, but token was unavailable to the client.
  17. # EmbedBuilder field values may not be empty.
  18. # The messages must be an Array, Collection, or number.
  19. # Members didn’t arrive in time.
  20. # MaxListenersExceededWarning: Possible EventEmitter memory leak detected.
  21. # Cannot send messages to this user.
  22. # Common miscellaneous errors
  23. # code ENOENT. syscall spawn git.
  24. # code ELIFECYCLE
  25. Name already in use
  26. discord-api-docs / docs / topics / Opcodes_and_Status_Codes.md

Discord API errors Elevated и Latency в Discord инструкции как исправить

API Errors Discord – это достаточно распространенная категория ошибок, возникающих во время авторизации в приложении мессенджера. И в основном они связаны со сбоем, произошедшем на стороне разработчиков и серверов. Как правило, вины пользователей в подобных неполадках нет, а появляться они могут по разным причинам. Например, из-за слишком большой нагрузки, технических работ и попросту случайного бага. Но, как показывает статистика, программисты Дискорда быстро принимают меры для устранения ошибок и возвращают сервису былую работоспособность. Однако предлагаем ознакомиться с основными проблемами и способами их решения.

API Errors в Discord – какие бывают и почему возникают?

По доступной в интернете информации становится понятно, что API Errors – это ошибки, которые возникают во время авторизации в приложении мессенджера. И, что самое интересное, столкнуться с ними можно как на компьютере, так и на мобильном устройстве.

На самом деле существует несколько категорий багов, но наиболее часто встречаются только две:

Именно их мы и будем рассматривать, а также разбираться, как исправить ситуацию и пофиксить баг. И в любом случае, когда произошла API Errors в Дискорд, рекомендуем перейти по следующей ссылке – https://discordstatus.com/. Это официальный сайт, который используется для отслеживания сбоев. Если они имеются, то вы увидите соответствующую информацию.

Произошла ошибка API – что делать?

И первым делом нужно отметить, что самостоятельно устранить API Errors в Discord практически невозможно – от вас они попросту не зависят.

А если во время авторизации вы видите уведомление о проблеме, то нужно всего лишь дождаться ее решения. Как правило, глобальные сбои разработчики устраняют в кратчайшие сроки, но иногда на это уходит несколько часов. Но наиболее часто пользователи задают вопрос: Elevated API Errors в Дискорд – как исправить?

Мы рекомендуем следовать алгоритму, показывающему неплохие результаты (но только, если произошел не глобальный сбой):

  1. Пытаемся выполнить авторизацию в учетной записи посредством официального сайта, а не программы.
  2. Если ситуация не изменилась, то устанавливаем на смартфон мобильное приложение Discord. При его наличии и авторизации выполняем удаление программы, а затем повторную установку. Открываем приложение и входим в свой аккаунт.
  3. Если все работает, то авторизуемся и на компьютере. В противном случае, когда ничего не помогло, рекомендуем в настройках изменить сервер. Например, остановившись на наиболее ближайшем варианте.

Дискорд API Errors latency – что это? А под этим понимается очередная ошибка, связанная с авторизацией в приложении мессенджера. И ее уже никак не получится устранить самостоятельно – остается только ждать, пока разработчики примут меры. Если у вас не заходит в Дискорд, то API Errors latency наблюдается у многих пользователей.

Таким образом, мы рассмотрели основные Discord API Errors, встречающиеся в программе мессенджера. И, как правило, они связаны со сбоями на стороне разработчиков. Есть дополнительные вопросы по теме материала? Мы готовы на них ответить в комментариях!

Источник

Что означает сбой API в Discord и как это исправить?

Хотя Discord обычно может отправлять и доставлять сообщения в течение нескольких секунд, бывают ошибки, которые либо блокируют этот процесс, либо может даже помешать пользователям войти в систему. Это включает в себя печально известный сбой API, который является результатом потери соединения. Однако эта конкретная ошибка не является ошибкой пользователя или его собственного интернет-соединения.

Сбой API в Discord, по сути, означает, что его основной интерфейс нельзя использовать из-за проблемы с сервером на стороне Discord. . Таким образом, проблема в основном не в ваших руках. Если вам стало известно о сбое в работе API, крайне важно сначала проверить специальный сайт статуса Discord. На этой странице не только показано точное время начала сбоя, но и подробно описан план Discord по возвращению пользователей в сеть.

Важно проверять страницу время от времени, так как Discord начнет отключаться. медленно разрешите пользователям вернуться на платформу, как только проблема будет решена. Если на странице действительно отображается обновление, сообщающее о том, что пользователи могут снова войти в систему, мы рекомендуем вам закрыть и перезапустить приложение, так как в противном случае оно может не позволить вам войти в свою учетную запись.

Наконец, если на сайте нет намеков на сбой API, вам может потребоваться отправить запрос в службу поддержки Discord. В большинстве случаев служба поддержки ответит на запрос по электронной почте, чтобы помочь вам снова запустить и запустить приложение.

По теме: Как исправить Discord не удалось ошибка загрузки сообщений

Источник

# Errors

There is no doubt that you have encountered errors while making bots. While errors are instrumental at warning you of what is going wrong, many people are stumped by them and how to track them down and fix them, but don’t worry, we have you covered. This section will be all about diagnosing errors, identifying where they are coming from, and fixing them.

# Types of Errors

# API Errors

API Errors or DiscordAPIErrors are thrown by the Discord API when an invalid request carries out. API Errors can be mostly diagnosed using the message that is given. You can further examine errors by inspecting the HTTP method and path used. We will explore tracking these errors down in the next section.

Example: DiscordAPIError: Cannot send an empty message

# discord.js errors

discord.js errors are thrown by the library itself. They can usually be easily tracked down using the stack trace and error message.

Example: The messages must be an Array, Collection, or number.

# JavaScript errors

JavaScript errors are thrown by node itself or by discord.js. These errors can easily be fixed by looking at the type of error and the stack trace. You can find a full list of types here

open in new window And a list of common js errors here

Example: ReferenceError: «x» is not defined , Cannot read properties of null(reading ‘something’)

# WebSocket and Network errors

WebSocket and Network errors are common system errors thrown by Node in response to something wrong with the WebSocket connection. Unfortunately, these errors do not have a concrete solution and can be (usually) fixed by getting a better, more stable, and more robust connection. discord.js will automatically try to reconnect to the WebSocket if an error occurs.

In version 12, WebSocket errors are handled internally, meaning your process should never crash from them. If you want to log these errors, should they happen, you can listen to the shardError event as shown below.

The commonly thrown codes for these errors are:

  • ECONNRESET — The connection was forcibly closed by a peer, thrown by the loss of connection to a WebSocket due to timeout or reboot.
  • ETIMEDOUT — A connect or send request failed because the receiving party did not respond after some time.
  • EPIPE — The remote side of the stream being written to has been closed.
  • ENOTFOUND — The domain being accessed is unavailable, usually caused by a lack of internet, can be thrown by the WebSocket and HTTP API.
  • ECONNREFUSED — The target machine refused the connection; check your ports and firewall.

# How to diagnose API errors

API Errors can be tracked down by adding an event listener for unhandled rejections and looking at the extra info. This can be done by adding this to your main file.

The next time you get the error it will show info along the bottom of the error which will look something like this for example:

All of this information can help you track down what caused the error and how to fix it. In this section, we will run through what each property means.

# Message

The most important part of the error is the message. It tells you what went wrong, which can help you track down where it originates. You can find a full list of messages here

open in new window in the Discord API documentation.

Another helpful piece of information is the path, which tells you what API endpoint the error occurred on. We cannot possibly cover all endpoints, but they are usually very descriptive.

In the above example, the path tells you that the action was executed in the /channels/ scope. The number you see next is the channel’s id. Next, you can spot the message/ scope. The number is again the object’s id. Combined with the method GET you can conclude, that the bot tried to fetch the message with the id [object Object] from the channel with the id 638200642359525387 .

As the error message tells you [object Object] is not a valid id, so you now know where to look for an error! Find out where you pass an object as an id when trying to fetch a message and fix your code in that location.

The code is another partial representation of the message, in this case, Invalid Form Body . You can find a full list of codes here

The code is also handy if you want only to handle a specific error. Say you’re trying to delete a message which may or may not be there, and wanted to ignore unknown message errors. This can be done by checking the code, either manually or using discord.js constants.

Or using Constants:

You can find a list of constants here

# Method

The final piece of information can tell you a lot about what you tried to do to the path. There are a set of predefined keywords that describe our actions on the path.

In this particular example, you can see you are trying to access a piece of data, specifically, a message.

# Common discord.js and API errors

# An invalid token was provided.

This is a prevalent error; it originates from a wrong token being passed into client.login() . The most common causes of this error are:

  • Not importing the config or env file correctly
  • Copying the client secret instead of the bot token (the token is alphanumerical and three parts delimited by a period while the client secret is significantly smaller and one part only)
  • Not updating the token after resetting it

Before the release of version 12, there used to be an issue where the token was not prefixed correctly, which resulted in valid tokens being marked as invalid. If you have verified that all of the above is not the case, make sure you have updated discord.js to the current stable version.

# Request to use token, but token was unavailable to the client.

This error originates from the client attempting to execute an action that requires the token but the token not being available. This is most commonly caused by destroying the client and then trying to perform an action.

This error is also caused by attempting to use a client that has not logged in. Both of the examples below will throw errors.

# EmbedBuilder field values may not be empty.

This error originates from calling EmbedBuilder#addFields() with a field object’s name property as an empty string. If you would like the title to be empty for a reason, you should use a zero width space, which can be input as u200b .

In conjunction with the previous error, this error results from calling EmbedBuilder#addFields() with a field object’s value property as an empty string. You can use a zero-width space if you would like this blank.

# The messages must be an Array, Collection, or number.

This error originates from an invalid call to bulkDelete() . Make sure you are inputting a valid Array or Collection of messages or a valid number.

# Members didn’t arrive in time.

This error happens when fetching multiple members via GuildMemberManager#fetch() and:

  • The GuildMembers intent is not specified or enabled in the dev dashboard
  • The internet connection is somewhat bad
  • The amount of members fetched is large (about 50 thousand and upwards)

You can specify the time to wait for with the time option in the .fetch() call. Another solution could be to move your bot to a faster infrastructure, if available.

# MaxListenersExceededWarning: Possible EventEmitter memory leak detected.

This error is caused by spawning a large number of event listeners, usually for the client. The most common cause of this is nesting your event listeners instead of separating them. The way to fix this error is to make sure you do not nest your listeners; it is not to use emitter.setMaxListeners() as the error suggests.

You can debug these messages in different ways:

open in new window : node —trace-warnings index.js
Through the process#warning event

# Cannot send messages to this user.

This error throws when the bot attempts to send a DM message to a user but cannot do so. A variety of reasons causes this:

  • The bot and the user do not share a guild (often, people attempt to DM the user after kicking or banning them).
  • The bot tries to DM another bot.
  • The user has blocked the bot.
  • The user has disabled DMs in the privacy settings.

In the case of the last two reasons, the error is not preventable, as the Discord API does not provide a way to check if you can send a user a DM until you attempt to send one. The best way to handle this error is to add a .catch() where you try to DM the user and either ignore the rejected Promise or do what you want because of it.

# Common miscellaneous errors

# code ENOENT. syscall spawn git.

This error is commonly thrown by your system due to it not finding git . You need to install git or update your path if git is already installed. Here are the download links for it:

  • Ubuntu/Debian: sudo apt-get install git
  • Windows: git-scm

# code ELIFECYCLE

This error is commonly thrown by your system in response to the process unexpectedly closing. Cleaning the npm cache and deleting node_modules can usually fix it. The instructions for doing that are as such:

Источник

Name already in use

discord-api-docs / docs / topics / Opcodes_and_Status_Codes.md

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

Copy raw contents

Copy raw contents

Opcodes and Status Codes

All gateway events in Discord are tagged with an opcode that denotes the payload type. Your connection to our gateway may also sometimes close. When it does, you will receive a close code that tells you what happened.

Code Name Client Action Description
Dispatch Receive An event was dispatched.
1 Heartbeat Send/Receive Fired periodically by the client to keep the connection alive.
2 Identify Send Starts a new session during the initial handshake.
3 Presence Update Send Update the client’s presence.
4 Voice State Update Send Used to join/leave or move between voice channels.
6 Resume Send Resume a previous session that was disconnected.
7 Reconnect Receive You should attempt to reconnect and resume immediately.
8 Request Guild Members Send Request information about offline guild members in a large guild.
9 Invalid Session Receive The session has been invalidated. You should reconnect and identify/resume accordingly.
10 Hello Receive Sent immediately after connecting, contains the heartbeat_interval to use.
11 Heartbeat ACK Receive Sent in response to receiving a heartbeat to acknowledge that it has been received.

Gateway Close Event Codes

In order to prevent broken reconnect loops, you should consider some close codes as a signal to stop reconnecting. This can be because your token expired, or your identification is invalid. This table explains what the application defined close codes for the gateway are, and which close codes you should not attempt to reconnect.

Code Description Explanation Reconnect
4000 Unknown error We’re not sure what went wrong. Try reconnecting? true
4001 Unknown opcode You sent an invalid Gateway opcode or an invalid payload for an opcode. Don’t do that! true
4002 Decode error You sent an invalid payload to Discord. Don’t do that! true
4003 Not authenticated You sent us a payload prior to identifying. true
4004 Authentication failed The account token sent with your identify payload is incorrect. false
4005 Already authenticated You sent more than one identify payload. Don’t do that! true
4007 Invalid seq The sequence sent when resuming the session was invalid. Reconnect and start a new session. true
4008 Rate limited Woah nelly! You’re sending payloads to us too quickly. Slow it down! You will be disconnected on receiving this. true
4009 Session timed out Your session timed out. Reconnect and start a new one. true
4010 Invalid shard You sent us an invalid shard when identifying. false
4011 Sharding required The session would have handled too many guilds — you are required to shard your connection in order to connect. false
4012 Invalid API version You sent an invalid version for the gateway. false
4013 Invalid intent(s) You sent an invalid intent for a Gateway Intent. You may have incorrectly calculated the bitwise value. false
4014 Disallowed intent(s) You sent a disallowed intent for a Gateway Intent. You may have tried to specify an intent that you have not enabled or are not approved for. false

Our voice gateways have their own set of opcodes and close codes.

Code Name Sent By Description
Identify client Begin a voice websocket connection.
1 Select Protocol client Select the voice protocol.
2 Ready server Complete the websocket handshake.
3 Heartbeat client Keep the websocket connection alive.
4 Session Description server Describe the session.
5 Speaking client and server Indicate which users are speaking.
6 Heartbeat ACK server Sent to acknowledge a received client heartbeat.
7 Resume client Resume a connection.
8 Hello server Time to wait between sending heartbeats in milliseconds.
9 Resumed server Acknowledge a successful session resume.
13 Client Disconnect server A client has disconnected from the voice channel

Voice Close Event Codes

Code Description Explanation
4001 Unknown opcode You sent an invalid opcode.
4002 Failed to decode payload You sent an invalid payload in your identifying to the Gateway.
4003 Not authenticated You sent a payload before identifying with the Gateway.
4004 Authentication failed The token you sent in your identify payload is incorrect.
4005 Already authenticated You sent more than one identify payload. Stahp.
4006 Session no longer valid Your session is no longer valid.
4009 Session timeout Your session has timed out.
4011 Server not found We can’t find the server you’re trying to connect to.
4012 Unknown protocol We didn’t recognize the protocol you sent.
4014 Disconnected Channel was deleted, you were kicked, voice server changed, or the main gateway session was dropped. Should not reconnect.
4015 Voice server crashed The server crashed. Our bad! Try resuming.
4016 Unknown encryption mode We didn’t recognize your encryption.

Our API will return semantically valid HTTP response codes based on the success of your request. The following table can be used as a reference for response codes it will return.

HTTP Response Codes

Code Meaning
200 (OK) The request completed successfully.
201 (CREATED) The entity was created successfully.
204 (NO CONTENT) The request completed successfully but returned no content.
304 (NOT MODIFIED) The entity was not modified (no action was taken).
400 (BAD REQUEST) The request was improperly formatted, or the server couldn’t understand it.
401 (UNAUTHORIZED) The Authorization header was missing or invalid.
403 (FORBIDDEN) The Authorization token you passed did not have permission to the resource.
404 (NOT FOUND) The resource at the location specified doesn’t exist.
405 (METHOD NOT ALLOWED) The HTTP method used is not valid for the location specified.
429 (TOO MANY REQUESTS) You are being rate limited, see Rate Limits.
502 (GATEWAY UNAVAILABLE) There was not a gateway available to process your request. Wait a bit and retry.
5xx (SERVER ERROR) The server had an error processing your request (these are rare).

Along with the HTTP error code, our API can also return more detailed error codes through a code key in the JSON error response. The response will also contain a message key containing a more friendly error string. Some of these errors may include additional details in the form of Error Messages provided by an errors object.

JSON Error Codes

Code Meaning
General error (such as a malformed request body, amongst other things)
10001 Unknown account
10002 Unknown application
10003 Unknown channel
10004 Unknown guild
10005 Unknown integration
10006 Unknown invite
10007 Unknown member
10008 Unknown message
10009 Unknown permission overwrite
10010 Unknown provider
10011 Unknown role
10012 Unknown token
10013 Unknown user
10014 Unknown emoji
10015 Unknown webhook
10016 Unknown webhook service
10020 Unknown session
10026 Unknown ban
10027 Unknown SKU
10028 Unknown Store Listing
10029 Unknown entitlement
10030 Unknown build
10031 Unknown lobby
10032 Unknown branch
10033 Unknown store directory layout
10036 Unknown redistributable
10038 Unknown gift code
10049 Unknown stream
10050 Unknown premium server subscribe cooldown
10057 Unknown guild template
10059 Unknown discoverable server category
10060 Unknown sticker
10062 Unknown interaction
10063 Unknown application command
10065 Unknown voice state
10066 Unknown application command permissions
10067 Unknown Stage Instance
10068 Unknown Guild Member Verification Form
10069 Unknown Guild Welcome Screen
10070 Unknown Guild Scheduled Event
10071 Unknown Guild Scheduled Event User
10087 Unknown Tag
20001 Bots cannot use this endpoint
20002 Only bots can use this endpoint
20009 Explicit content cannot be sent to the desired recipient(s)
20012 You are not authorized to perform this action on this application
20016 This action cannot be performed due to slowmode rate limit
20018 Only the owner of this account can perform this action
20022 This message cannot be edited due to announcement rate limits
20024 Under minimum age
20028 The channel you are writing has hit the write rate limit
20029 The write action you are performing on the server has hit the write rate limit
20031 Your Stage topic, server name, server description, or channel names contain words that are not allowed
20035 Guild premium subscription level too low
30001 Maximum number of guilds reached (100)
30002 Maximum number of friends reached (1000)
30003 Maximum number of pins reached for the channel (50)
30004 Maximum number of recipients reached (10)
30005 Maximum number of guild roles reached (250)
30007 Maximum number of webhooks reached (10)
30008 Maximum number of emojis reached
30010 Maximum number of reactions reached (20)
30013 Maximum number of guild channels reached (500)
30015 Maximum number of attachments in a message reached (10)
30016 Maximum number of invites reached (1000)
30018 Maximum number of animated emojis reached
30019 Maximum number of server members reached
30030 Maximum number of server categories has been reached (5)
30031 Guild already has a template
30032 Maximum number of application commands reached
30033 Max number of thread participants has been reached (1000)
30034 Max number of daily application command creates has been reached (200)
30035 Maximum number of bans for non-guild members have been exceeded
30037 Maximum number of bans fetches has been reached
30038 Maximum number of uncompleted guild scheduled events reached (100)
30039 Maximum number of stickers reached
30040 Maximum number of prune requests has been reached. Try again later
30042 Maximum number of guild widget settings updates has been reached. Try again later
30046 Maximum number of edits to messages older than 1 hour reached. Try again later
30047 Maximum number of pinned threads in a forum channel has been reached
30048 Maximum number of tags in a forum channel has been reached
30052 Bitrate is too high for channel of this type
30056 Maximum number of premium emojis reached (25)
30058 Maximum number of webhooks per guild reached (1000)
40001 Unauthorized. Provide a valid token and try again
40002 You need to verify your account in order to perform this action
40003 You are opening direct messages too fast
40004 Send messages has been temporarily disabled
40005 Request entity too large. Try sending something smaller in size
40006 This feature has been temporarily disabled server-side
40007 The user is banned from this guild
40012 Connection has been revoked
40032 Target user is not connected to voice
40033 This message has already been crossposted
40041 An application command with that name already exists
40043 Application interaction failed to send
40058 Cannot send a message in a forum channel
40060 Interaction has already been acknowledged
40061 Tag names must be unique
40062 Service resource is being rate limited
40066 There are no tags available that can be set by non-moderators
40067 A tag is required to create a forum post in this channel
50001 Missing access
50002 Invalid account type
50003 Cannot execute action on a DM channel
50004 Guild widget disabled
50005 Cannot edit a message authored by another user
50006 Cannot send an empty message
50007 Cannot send messages to this user
50008 Cannot send messages in a non-text channel
50009 Channel verification level is too high for you to gain access
50010 OAuth2 application does not have a bot
50011 OAuth2 application limit reached
50012 Invalid OAuth2 state
50013 You lack permissions to perform that action
50014 Invalid authentication token provided
50015 Note was too long
50016 Provided too few or too many messages to delete. Must provide at least 2 and fewer than 100 messages to delete
50017 Invalid MFA Level
50019 A message can only be pinned to the channel it was sent in
50020 Invite code was either invalid or taken
50021 Cannot execute action on a system message
50024 Cannot execute action on this channel type
50025 Invalid OAuth2 access token provided
50026 Missing required OAuth2 scope
50027 Invalid webhook token provided
50028 Invalid role
50033 Invalid Recipient(s)
50034 A message provided was too old to bulk delete
50035 Invalid form body (returned for both application/json and multipart/form-data bodies), or invalid Content-Type provided
50036 An invite was accepted to a guild the application’s bot is not in
50039 Invalid Activity Action
50041 Invalid API version provided
50045 File uploaded exceeds the maximum size
50046 Invalid file uploaded
50054 Cannot self-redeem this gift
50055 Invalid Guild
50067 Invalid request origin
50068 Invalid message type
50070 Payment source required to redeem gift
50073 Cannot modify a system webhook
50074 Cannot delete a channel required for Community guilds
50080 Cannot edit stickers within a message
50081 Invalid sticker sent
50083 Tried to perform an operation on an archived thread, such as editing a message or adding a user to the thread
50084 Invalid thread notification settings
50085 before value is earlier than the thread creation date
50086 Community server channels must be text channels
50091 The entity type of the event is different from the entity you are trying to start the event for
50095 This server is not available in your location
50097 This server needs monetization enabled in order to perform this action
50101 This server needs more boosts to perform this action
50109 The request body contains invalid JSON.
50132 Ownership cannot be transferred to a bot user
50138 Failed to resize asset below the maximum size: 262144
50144 Cannot mix subscription and non subscription roles for an emoji
50145 Cannot convert between premium emoji and normal emoji
50146 Uploaded file not found.
50600 You do not have permission to send this sticker.
60003 Two factor is required for this operation
80004 No users with DiscordTag exist
90001 Reaction was blocked
110001 Application not yet available. Try again later
130000 API resource is currently overloaded. Try again a little later
150006 The Stage is already open
160002 Cannot reply without permission to read message history
160004 A thread has already been created for this message
160005 Thread is locked
160006 Maximum number of active threads reached
160007 Maximum number of active announcement threads reached
170001 Invalid JSON for uploaded Lottie file
170002 Uploaded Lotties cannot contain rasterized images such as PNG or JPEG
170003 Sticker maximum framerate exceeded
170004 Sticker frame count exceeds maximum of 1000 frames
170005 Lottie animation maximum dimensions exceeded
170006 Sticker frame rate is either too small or too large
170007 Sticker animation duration exceeds maximum of 5 seconds
180000 Cannot update a finished event
180002 Failed to create stage needed for stage event
200000 Message was blocked by automatic moderation
200001 Title was blocked by automatic moderation
220001 Webhooks posted to forum channels must have a thread_name or thread_id
220002 Webhooks posted to forum channels cannot have both a thread_name and thread_id
220003 Webhooks can only create threads in forum channels
220004 Webhook services cannot be used in forum channels
240000 Message blocked by harmful links filter

Example JSON Error Response

RPC is the local Discord server running on localhost. Access to the RPC server requires approval from Discord.

Источник

В данном разделе приводится описание ошибок, возникающих при выполнении запросов в рамках протокола OAuth 2.0 и OpenId Connect 1.0.

Далее будет представлена информация по кодам ошибок.

В запросе не передан обязательный параметр, либо значения переданного параметра некорректно, либо параметр пристутствует в запросе несколько раз, либо весь запрос имеет неправильный формат.

Тип ответа не поддерживается.

Указанный в запросе response_type не поддерживается.

  • В запросе указан параметр response_type со значениями отличными от
    • code ,
    • token ,
    • id_token ,
    • id_token token ,
    • code id_token
    • code token
    • code id_token token .

    invalid_scope

    Неправильная область использования.

    Возможные причины

    login_required

    Запрос не может быть выполнен в интерактивном режиме (с указанием параметра prompt со значением none ).

    Возможные причины

    • Запрос не может быть выполнен в неинтерактивном режиме, так как требуется аутентификация пользователя.

    Ошибки конечной точки /token

    invalid_request

    В запросе не передан обязательный параметр, либо значения переданного параметра некорректно, либо параметр пристутствует в запросе несколько раз, либо весь запрос имеет неправильный формат.

    Возможные причины

    invalid_client

    Не удалось осуществить аутентификацию клиента.

    Возможные причины

    invalid_grant

    Разрешение, используемое клиентом, не является действительным.

    Возможные причины

    • Не передан параметр password в сценарии с использованием учётных данных владельца ресурсов.
    • Сервер не настроен на обработку сценария с использованием учётных данных владельца ресурсов.
    • Не удалось аутентифицировать пользователя по переданным username и password .
    • Сценарий с использованием учётных данных владельца ресурсов не может быть использован для данной учётной записи пользователя из-за включенной вторичной аутентификации.
    • Не передан код авторизации в сценарии с кодом авторизации.
    • Переданный код авторизации истёк или не действителен.
    • Переданный код авторизации был получен другим клиентом.

    unauthorized_client

    API Errors Discord – это достаточно распространенная категория ошибок, возникающих во время авторизации в приложении мессенджера. И в основном они связаны со сбоем, произошедшем на стороне разработчиков и серверов. Как правило, вины пользователей в подобных неполадках нет, а появляться они могут по разным причинам. Например, из-за слишком большой нагрузки, технических работ и попросту случайного бага. Но, как показывает статистика, программисты Дискорда быстро принимают меры для устранения ошибок и возвращают сервису былую работоспособность. Однако предлагаем ознакомиться с основными проблемами и способами их решения.

    API Errors в Discord – какие бывают и почему возникают?

    По доступной в интернете информации становится понятно, что API Errors – это ошибки, которые возникают во время авторизации в приложении мессенджера. И, что самое интересное, столкнуться с ними можно как на компьютере, так и на мобильном устройстве.

    На самом деле существует несколько категорий багов, но наиболее часто встречаются только две:

    Произошла ошибка API – что делать?

    И первым делом нужно отметить, что самостоятельно устранить API Errors в Discord практически невозможно – от вас они попросту не зависят.

    Мы рекомендуем следовать алгоритму, показывающему неплохие результаты (но только, если произошел не глобальный сбой):

    1. Пытаемся выполнить авторизацию в учетной записи посредством официального сайта, а не программы.
    2. Если ситуация не изменилась, то устанавливаем на смартфон мобильное приложение Discord. При его наличии и авторизации выполняем удаление программы, а затем повторную установку. Открываем приложение и входим в свой аккаунт.
    3. Если все работает, то авторизуемся и на компьютере. В противном случае, когда ничего не помогло, рекомендуем в настройках изменить сервер. Например, остановившись на наиболее ближайшем варианте.

    Дискорд API Errors latency – что это? А под этим понимается очередная ошибка, связанная с авторизацией в приложении мессенджера. И ее уже никак не получится устранить самостоятельно – остается только ждать, пока разработчики примут меры. Если у вас не заходит в Дискорд, то API Errors latency наблюдается у многих пользователей.

    Таким образом, мы рассмотрели основные Discord API Errors, встречающиеся в программе мессенджера. И, как правило, они связаны со сбоями на стороне разработчиков. Есть дополнительные вопросы по теме материала? Мы готовы на них ответить в комментариях!

    Создание Discord бота на Python Туториал, Python, Discord, Длиннопост

    После установки самого python’а (проверить правильность установки можно написав в консоли: «python -V», возможно потребуется перезагрузка) установим модуль discord.py ( https://discordpy.readthedocs.io/en/latest/ -это ссыль на официальную документацию), сделать это можно прописав в консоли: » pip install discord.py «. С установкой чего-либо окончено.

    Теперь перейдем к Discord’у:

    1. Создадим сам сервер:

    Создание Discord бота на Python Туториал, Python, Discord, Длиннопост

    2. Создадим текстовый канал «получение ролей» (название значения не имеет):

    Создание Discord бота на Python Туториал, Python, Discord, Длиннопост

    3. Добавим сами роли для выбора:

    Создание Discord бота на Python Туториал, Python, Discord, Длиннопост

    Создание Discord бота на Python Туториал, Python, Discord, Длиннопост

    Я в данном случае создал две роли исключительно для примера:

    Создание Discord бота на Python Туториал, Python, Discord, Длиннопост

    4. Копируем и сохраняем в расширении .py файлы:

    Q: как сохранить код в расширении .py?

    A: используйте блокнот:

    создаете новый файл, вставляете код, в левом верхнем углу: файл >> сохранить как

    Создание Discord бота на Python Туториал, Python, Discord, Длиннопост

    5. Не закрывая файлы переходим на сайт ( https://discordapp.com/developers ), регаемся, переходим во вкладку «Applications» и создаем новое приложение:

    Создание Discord бота на Python Туториал, Python, Discord, Длиннопост

    Далее называем его по любому, со всем соглашаемся.

    Переходим во вкладку «Bot»,

    Создание Discord бота на Python Туториал, Python, Discord, Длиннопост

    Создание Discord бота на Python Туториал, Python, Discord, Длиннопост

    далее его можно как-либо назвать и поменять аватарку. После макияжа переходим во вкладку «OAuth2»:

    Создание Discord бота на Python Туториал, Python, Discord, Длиннопост

    Пролистываем немного ниже:

    Создание Discord бота на Python Туториал, Python, Discord, Длиннопост

    В окне «SCOPES» выбираем «bot», во втором выбираем «Administrator», далее копируем и впоследствии переходим по ссылке, там все подтверждаем.

    Создание Discord бота на Python Туториал, Python, Discord, Длиннопост

    После авторизации переходим во вкладку «Bot» и копируем токен.

    Создание Discord бота на Python Туториал, Python, Discord, Длиннопост

    Далее открываем файл » config.py » созданный ранее и вместо надписи «тут токен» вставляем реальный токен. Хочется отметить то что токен меняется при смене имени бота и аватарки, если у вас появятся проблемы, стоит обратить внимание на токен.

    Создание Discord бота на Python Туториал, Python, Discord, Длиннопост

    Создание Discord бота на Python Туториал, Python, Discord, Длиннопост

    Добавить реакции можно нажав пкм:

    Создание Discord бота на Python Туториал, Python, Discord, Длиннопост

    Далее копируем ID поста, кликнув пкм:

    Создание Discord бота на Python Туториал, Python, Discord, Длиннопост

    Создание Discord бота на Python Туториал, Python, Discord, Длиннопост

    Перейдем к самим ролям, для этого копируем эмодзи из реакций (если вы из брали с ссайта который я оставлял выше то копируйте от туда, если вы их выбирали в ds то скопируйте их в ds и вставте на сайт и скопируйте оттуда) и вставляем в config в ординарных апострофах с двух сторон и через двоеточие указываем id роли, в конце строк (кроме последней) ставим запятые

    Создание Discord бота на Python Туториал, Python, Discord, Длиннопост

    Взять id можно кликнув пкм по названию роли.

    В итоге должно получиться так:

    Создание Discord бота на Python Туториал, Python, Discord, Длиннопост

    в значении переменной «MAX_ROLES_PER_USER» указываем кол-во ролей которые может получить 1 юзер, значение «EXCROLES» оставляем пустым.

    сохраняем config и code в одну папку в которой нет ничего кроме этих файлов и она названа по английски:

    Создание Discord бота на Python Туториал, Python, Discord, Длиннопост

    Далее в консоли прописываем: «cd <путь к файлу>»

    «<метка тома диска на котором находится папка>»

    Создание Discord бота на Python Туториал, Python, Discord, Длиннопост

    вот так вот. Осталось поставить роль бота выше ролей которые вы будите выдавать. Иначе появится ошибка (Forbidden(‘403 Forbidden (error code: 50013): Missing Permissions’)). Проверка прошла успешно!

    Спасибо за внимание!

    Программирование на python

    218 постов 7.5K подписчика

    Правила сообщества

    Публиковать могут пользователи с любым рейтингом. Однако!

    Приветствуется:

    • уважение к читателям и авторам

    • простота и информативность повествования

    • тег python2 или python3, если актуально

    • код публиковать в виде цитаты, либо ссылкой на специализированный сайт

    Не рекомендуется:

    • допускать оскорбления и провокации

    • распространять вредоносное ПО

    • просить решить вашу полноценную задачу за вас

    Я редко конечно ставлю минусы но ставить питон из ms store. это дико, даже для меня

    Зачем выдавать чужой код, за свой?
    автора кода — Хауди

    еще один конкурент «9 вите иташки»?

    Правильно пишется «наподобие».

    Хочу для себя изучить питон, что посоветуете? Смотрела курсы, не подошли. Как лучше изучать? Может, книга толковая есть?

    на первом этапе(python — V) выдало ошибку

    Traceback (most recent call last):

    NameError: name ‘python’ is not defined

    у меня выдаёт ошибку

    File «C:UsersHP-PCAppDataLocalProgramsPythonPython39libsite-packagesaiohttp connector.py «, line 938, in _wrap_create_connection

    Хочешь нарисовать свою карту для D&D? Тебе к нам!

    Хочешь нарисовать свою карту для D&D? Тебе к нам! Рисование, Dungeons & Dragons, Туториал, Набор, Discord, Длиннопост

    Добрый вечер постояльцам таверны и активны пользователям Пикабу!

    В недавнем опросе в вконтакте, постояльцы отметили что у них есть желание научиться рисовать карты для их приключений! Очень рад этому :)

    Поэтому я решил не останавливаться и завлечь как можно людей в данную атмосферу рисования.

    Что это такое?

    Данный пост — небольшая информация для дальнейшего рисования карт для D&D5e, ты же (Пикабушник) можешь присоединиться к нам и следить за будущими постами, а также принять участие в выборе первого туториала.

    Может быть это масштабный континент? Забытая пещера? Решай сам!

    Самый популярный запрос будет нарисован и разобран для обучения.

    Что нужно для этого?

    В группе Вконтакте не написано какие «инструменты» должны быть у художника (это будет в отдельном посте), но так как мы на Пикабу, то стоит все же рассказать.

    Инструменты:
    Листы Бумаги А4 или СкетчБук
    Простой карандаш
    Карандаш H
    Карандаш HB
    Карандаш 3B
    Ластик
    Стружилка

    Программы:
    Krita — покраска, добавление и создание своих токенов, эффекты и т.д.

    Ответы на вопросы

    — Да, это бесплатно

    — Как и где можно будет посмотреть туториал?

    — Сам туториал будет проходить по Discord. Дата и время проведения будет в группе Вконтакте.

    Также в группе будет выложена статья с этим же туториалом и на пикабу тоже :)

    — Зачем показывать туториал и там и там? Почему не сразу создать статью?

    — Первое. Появился вопрос или проблема? Спроси у картографа и получи решение!

    Второе. Атмосфера. Вместе с вами такие энтузиасты как вы!

    Я пытаюсь добавить Discord OAuth в мобильное приложение с помощью PKCE. Я могу успешно пройти аутентификацию с помощью DiscordAPI и получаю code обратно с сервера.

    Я попробовал несколько подходов к получению моего токена, но все они провалились.

    Я также попытался использовать объект StringContent , например так:

    Оба эти результата в Bad Request

    Попытка (2) с помощью RestSharp

    Дополнительная информация:

    Чтобы соответствовать PKCE, мне нужен code_verifier . Вот как я генерирую код. (Обратите внимание, я не пытаюсь использовать это как код авторизации.)

    Я передаю результат как code_challenge , получая свой код авторизации.

    Вот где я узнал, что PKCE был необходим.

    Обновление:

    Тем не менее, этот рабочий процесс PKCE недокументирован . Поскольку я потратил 500 баллов, я начисляю баллы тому, кто сможет разрешить рабочий процесс PKCE OAuth.

    2 ответа

    Вы делаете запрос на неправильный URL. Поток кода создается для предотвращения утечки клиентского токена. Поток выглядит следующим образом

    1. Клиент запрашивает код с сервера раздора
    2. Клиент отправляет этот код на ваш сервер
    3. Ваш сервер передает код на дискорд-сервер со своими секретами
    4. Сервер Discord отвечает обратно на настроенный redirect_uri, чтобы получить токен.

    Примечание: есть 2 перенаправления uri, 1, который разрешает код, и другой, который разрешает токен.

    Затем Discord ответит вашему redirect_uri коду и состоянию

    Примечание. Исходный запрос на Авторизацию не содержит вашего клиентского секрета, клиентский секрет используется только с вашего сервера. Таким образом, только сервер может запросить AuthTokens Примечание. В большинстве мест, поддерживающих oauth, необходимо настроить URL-адрес перенаправления с сервера.
    Примечание: состояние также будет возвращено с кодом, подтверждающим, что отправленное вами состояние является возвращенным.

    Возьмите возвращенный вам код (NhhvTDYsFcdgNLnnLijcl7Ku7bEEeee) и используйте запрос запроса токена, используя ваш оригинальный пример с правильным кодом:

    Обратите внимание, что при отправке запроса на конечную точку токена вы используете

    ‘Content-Type’: ‘application / x-www-form-urlencoded’

    Если у вас все еще есть проблемы с потоком, используйте Postman, который имеет встроенную поддержку OAuth, и получите токен, посмотрите, что они отправляют с помощью fiddler, и эмулируйте его.

    Ну, после некоторого исследования я мог бы иметь представление о том, что происходит. Вы пытаетесь получить токен на основе созданного вами кода авторизации?

    Вы должны использовать этот код на этапе получения токена.

    Я не знаю, если это что-то меняет, но я считаю, что в соответствии с документацией нет такого параметра, как «scopes», это должен быть «scope».

    Читайте также:

        

    • Почему нельзя класть на компьютер книги тетради и т п
    •   

    • Ноутбук сам выключается и сам включается
    •   

    • Как открыть файл rvt в скетчап
    •   

    • Как запустить notepad через командную строку
    •   

    • Леново к 33 а 42 очистить память
  • Example: how to disable a discord bots OAuth2 code

    import base64
    
    API_ENDPOINT = 'https://discord.com/api/v6'
    CLIENT_ID = '332269999912132097'
    CLIENT_SECRET = '937it3ow87i4ery69876wqire'
    
    def get_token():
      data = {
        'grant_type': 'client_credentials',
        'scope': 'identify connections'
      }
      headers = {
        'Content-Type': 'application/x-www-form-urlencoded'
      }
      r = requests.post('%s/oauth2/token' % API_ENDPOINT, data=data, headers=headers, auth=(CLIENT_ID, CLIENT_SECRET))
      r.raise_for_status()
      return r.json()

    Tags:

    Misc Example

    Related


    Go to discordapp


    r/discordapp

    Imagine a Place… where you can belong to a school club, a gaming group, or a worldwide art community. Where just you and handful of friends can spend time together. A place that makes it easy to talk every day and hang out more often.




    Members





    Online



    How the fuck do I make a bot join a server?

    All of the stuff with OAuth is going over my head, can someone explain it to me? I just want to have a my bot, which currently does nothing, join a server. What do I have to do to make that happen?

    Archived post. New comments cannot be posted and votes cannot be cast.

    Понравилась статья? Поделить с друзьями:
  • Oasis сплит система ошибка e6
  • Oasis бойлер ошибка ee
  • Oart dll ошибка при запуске word
  • Oart dll ошибка office 2016
  • Nxcooking dll ошибка mass effect