So, first you need to go here here and create an application (it will need you to log in). Click on «New Application». You’ll see a couple of things.
App name is the username of your bot. Description is kinda irrelevant, and so is Redirect URIs, so you can leave them blank. Same goes for the «App Icon» (which is the profile picture of your bot), but I suggest putting something there. So technically all you need to do is fill out the App name. After filling in the blanks, create your app.
Now, you’ll see something called «Client/Application ID: [numbers]», and «Token: <click to reveal>. Reveal your «Token», and write it down somewhere. Then copy your Client/Application ID and paste it to this link’s <client id> (delete the brackets also):
https://discordapp.com/oauth2/authorize?client_id=<CLIENT_ID>&scope=bot
so it looks something like
https://discordapp.com/oauth2/authorize?client_id=123123123123123&scope=bot
Now enter that URL to your browsers URL bar.
It might ask for a log in. If so, log in. Then, chose the server you want your bot to be on.
Now you’re almost done. Now go to your bot’s files. Depending on your bot, there should be a config file where you can enter your «bot token». On Music Bot (aka Rhino Bot), you’ll find this on config>options.ini. On Red Bot, the bot will ask for a token when you run it for the first time. When you find where you’re supposed to enter your token, simply paste the token which you wrote down somewhere earlier.
And now you’re done.
I’m trying to make a discord bot (with the bot tag) that can join other servers.
I will be able to do this, if I can set up a redirect URI for it. I already have the bot account set up, and it already functions with it (except for joining servers).
I was wondering how to set up a redirect URI for discord OAuth2?
nortex_dev
1511 gold badge2 silver badges7 bronze badges
asked Jun 4, 2016 at 1:45
1
To add your bot to a server you need to make a redirect url with your Client ID
Just replace the Client Id with your Client Id:
https://discordapp.com/oauth2/authorize?&client_id=[CLIENTID]&scope=bot
That’s all! Now you just need to click on it!
answered Oct 8, 2016 at 19:00
MondanzoMondanzo
691 silver badge3 bronze badges
1
You need to have your own webserver with some path to make your redirect url. For example, if you owned example.com, you could have example.com/discord be the url to redirect the client to after they login via Discord.
answered Jun 18, 2016 at 4:30
NathanNathan
2,6315 gold badges28 silver badges43 bronze badges
I’m assuming you are trying to use the guilds.join scope and it tells you to give a redirect URI. I think you are mistaking the guilds.join for the bot because it is actually the scope for letting your application join servers for the client (you can see this by going on the link https://discordapp.com/oauth2/authorize?&client_id=[CLIENTID]&scope=guilds.join
and replace [CLIENTID]
with the application client ID).
This means the link with the scope guilds.join will be on a website that you own and once the user either grants and denies this, the grant page will redirect the client back to the website.
Also, your bot cannot actually self-join servers simply because of how it was made. Bots must be manually authorized through OAuth. If you want a bot to join the server itself, it could use the invite link to get the server and DM the server owner (that can be found using the property) a OAuth link for the bot. Since the bot is not in the server it wants to join, you will need to do this method through the rest client. If you don’t mind doing it like other bots, you can get the bot to provide the join link like other bots with a command like !invite
.
Edit: If you want more information about using guilds.join, the documentation link is here: https://discordapp.com/developers/docs/resources/guild#add-guild-member
answered Feb 2, 2020 at 16:56
Ситуация:
Я пытаюсь создать простого бота Discord с pycord, но каждый раз, когда я запускаю код, он выдает эту ошибку:
Traceback (most recent call last):
File "main.py", line 3, in <module>
bot = discord.Bot()
AttributeError: module 'discord' has no attribute 'Bot'
Код:
import discord
bot = discord.Bot()
@bot.slash_command()
async def test(ctx):
await ctx.send('Success!')
bot.run('token')
Что я сделал:
Я уже проверил, установлен ли у меня pycord и верен ли мой токен.
3 ответа
Лучший ответ
PyCord 2 beta 1 только что был выпущен, поэтому теперь вы можете установить его с помощью
pip install py-cord==2.0.0b1
А не устанавливать версию из исходников.
Однако, чтобы пример заработал, вам нужно добавить область applications.commands
к URL-адресу OAuth2 и повторно зарегистрировать бота на тестовом сервере.
Кроме того, краткое руководство теперь предлагает добавить список идентификаторов гильдий (серверов). при создании slash_command
:
Атрибут
guild_ids
содержит список гильдий, в которых эта команда будет активен. Если вы его опустите, команда будет глобально доступны, и регистрация может занять до часа.
4
Mark Booth
30 Янв 2022 в 05:21
При просмотре вашего сообщения об ошибке:
Traceback (most recent call last):
File "main.py", line 3, in <module>
bot = discord.Bot()
AttributeError: module 'discord' has no attribute 'Bot'
Важно заметить, что AttributeError сообщает вам, что модуль, который вы импортировали, не имеет атрибута Bot ().
Это указывает на то, что вы его неправильно используете.
Ознакомьтесь с документацией для правильного использования, а также на этот руководство
Вы увидите, что вам нужно использовать.
# bot.py
import os
import discord
from dotenv import load_dotenv
load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')
client = discord.Client()
@client.event
async def on_ready():
print(f'{client.user} has connected to Discord!')
client.run(TOKEN)
Редактировать после комментария @Taku
После комментария ниже я считаю, что может потребоваться обновление библиотеки, как это сделано в примере
Помимо требования префикса команды, как это сделано в примере в URL-адресе
import discord
from discord.ext import commands
bot = commands.Bot(command_prefix=">")
@bot.command()
async def ping(ctx):
await ctx.send("pong")
bot.run("token")
2
Kwsswart
26 Окт 2021 в 17:39
Причина этой ошибки в том, что ваша версия pycord — v1.7.3, которая не поддерживает используемый вами синтаксис. Вам необходимо выполнить обновление до версии 2.0.0 с помощью этих команд (Windows):
git clone https://github.com/Pycord-Development/pycord
cd pycord
pip install -U .
Или pip install -U .[voice]
, если вам требуется голосовая поддержка
2
Hridesh MG
28 Янв 2022 в 10:47
Содержание
- Discord API errors Elevated и Latency в Discord инструкции как исправить
- API Errors в Discord – какие бывают и почему возникают?
- Произошла ошибка API – что делать?
- Что означает сбой API в Discord и как это исправить?
- # Errors
- # Types of Errors
- # API Errors
- # discord.js errors
- # JavaScript errors
- # WebSocket and Network errors
- # How to diagnose API errors
- # Message
- # Method
- # Common discord.js and API errors
- # An invalid token was provided.
- # Request to use token, but token was unavailable to the client.
- # EmbedBuilder field values may not be empty.
- # The messages must be an Array, Collection, or number.
- # Members didn’t arrive in time.
- # MaxListenersExceededWarning: Possible EventEmitter memory leak detected.
- # Cannot send messages to this user.
- # Common miscellaneous errors
- # code ENOENT. syscall spawn git.
- # code ELIFECYCLE
- Name already in use
- 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 в Дискорд – как исправить?
Мы рекомендуем следовать алгоритму, показывающему неплохие результаты (но только, если произошел не глобальный сбой):
- Пытаемся выполнить авторизацию в учетной записи посредством официального сайта, а не программы.
- Если ситуация не изменилась, то устанавливаем на смартфон мобильное приложение Discord. При его наличии и авторизации выполняем удаление программы, а затем повторную установку. Открываем приложение и входим в свой аккаунт.
- Если все работает, то авторизуемся и на компьютере. В противном случае, когда ничего не помогло, рекомендуем в настройках изменить сервер. Например, остановившись на наиболее ближайшем варианте.
Дискорд 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.
Источник
I’m trying to make a discord bot (with the bot tag) that can join other servers.
I will be able to do this, if I can set up a redirect URI for it. I already have the bot account set up, and it already functions with it (except for joining servers).
I was wondering how to set up a redirect URI for discord OAuth2?
nortex_dev
1511 gold badge2 silver badges7 bronze badges
asked Jun 4, 2016 at 1:45
1
To add your bot to a server you need to make a redirect url with your Client ID
Just replace the Client Id with your Client Id:
https://discordapp.com/oauth2/authorize?&client_id=[CLIENTID]&scope=bot
That’s all! Now you just need to click on it!
answered Oct 8, 2016 at 19:00
MondanzoMondanzo
691 silver badge3 bronze badges
1
You need to have your own webserver with some path to make your redirect url. For example, if you owned example.com, you could have example.com/discord be the url to redirect the client to after they login via Discord.
answered Jun 18, 2016 at 4:30
NathanNathan
2,6315 gold badges28 silver badges43 bronze badges
I’m assuming you are trying to use the guilds.join scope and it tells you to give a redirect URI. I think you are mistaking the guilds.join for the bot because it is actually the scope for letting your application join servers for the client (you can see this by going on the link https://discordapp.com/oauth2/authorize?&client_id=[CLIENTID]&scope=guilds.join
and replace [CLIENTID]
with the application client ID).
This means the link with the scope guilds.join will be on a website that you own and once the user either grants and denies this, the grant page will redirect the client back to the website.
Also, your bot cannot actually self-join servers simply because of how it was made. Bots must be manually authorized through OAuth. If you want a bot to join the server itself, it could use the invite link to get the server and DM the server owner (that can be found using the property) a OAuth link for the bot. Since the bot is not in the server it wants to join, you will need to do this method through the rest client. If you don’t mind doing it like other bots, you can get the bot to provide the join link like other bots with a command like !invite
.
Edit: If you want more information about using guilds.join, the documentation link is here: https://discordapp.com/developers/docs/resources/guild#add-guild-member
answered Feb 2, 2020 at 16:56