Ошибка api дискорд бот

Обновлено: 07.07.2024

One of the most appealing aspect of the command extension is how easy it is to define commands and how you can arbitrarily nest groups and commands to have a rich sub-command system.

Commands are defined by attaching it to a regular Python function. The command is then invoked by the user using a similar signature to the Python function.

For example, in the given command definition:

With the following prefix ( $ ), it would be invoked by the user via:

A command must always have at least one parameter, ctx , which is the Context as the first one.

Essentially, these two are equivalent:

Any parameter that is accepted by the Command constructor can be passed into the decorator. For example, to change the name to something other than the function would be as simple as doing this:

Parameters¶

Since we define commands by making Python functions, we also define the argument passing behaviour by the function parameters.

Certain parameter types do different things in the user side and most forms of parameter types are supported.

Positional¶

The most basic form of parameter passing is the positional parameter. This is where we pass a parameter as-is:

On the bot using side, you can provide positional arguments by just passing a regular string:

../../_images/positional1.jpg

To make use of a word with spaces in between, you should quote it:

../../_images/positional2.jpg

As a note of warning, if you omit the quotes, you will only get the first word:

../../_images/positional3.jpg

Since positional arguments are just regular Python arguments, you can have as many as you want:

Variable¶

Sometimes you want users to pass in an undetermined number of parameters. The library supports this similar to how variable list parameters are done in Python:

This allows our user to accept either one or many arguments as they please. This works similar to positional arguments, so multi-word parameters should be quoted.

For example, on the bot side:

../../_images/variable1.jpg

If the user wants to input a multi-word argument, they have to quote it like earlier:

../../_images/variable2.jpg

Do note that similar to the Python function behaviour, a user can technically pass no arguments at all:

../../_images/variable3.jpg

Since the args variable is a tuple , you can do anything you would usually do with one.

Keyword-Only Arguments¶

When you want to handle parsing of the argument yourself or do not feel like you want to wrap multi-word user input into quotes, you can ask the library to give you the rest as a single argument. We do this by using a keyword-only argument, seen below:

You can only have one keyword-only argument due to parsing ambiguities.

On the bot side, we do not need to quote input with spaces:

../../_images/keyword1.jpg

Do keep in mind that wrapping it in quotes leaves it as-is:

../../_images/keyword2.jpg

By default, the keyword-only arguments are stripped of white space to make it easier to work with. This behaviour can be toggled by the Command.rest_is_raw argument in the decorator.

Invocation Context¶

As seen earlier, every command must take at least a single parameter, called the Context .

This parameter gives you access to something called the “invocation context”. Essentially all the information you need to know how the command was executed. It contains a lot of useful information:

Context.guild to fetch the Guild of the command, if any.

Context.message to fetch the Message of the command.

Context.author to fetch the Member or User that called the command.

Context.send() to send a message to the channel the command was used in.

The context implements the abc.Messageable interface, so anything you can do on a abc.Messageable you can do on the Context .

Converters¶

Adding bot arguments with function parameters is only the first step in defining your bot’s command interface. To actually make use of the arguments, we usually want to convert the data into a target type. We call these Converters .

Converters come in a few flavours:

A regular callable object that takes an argument as a sole parameter and returns a different type.

  • These range from your own function, to something like bool or int .

A custom class that inherits from Converter .

Basic Converters¶

At its core, a basic converter is a callable that takes in an argument and turns it into something else.

For example, if we wanted to add two numbers together, we could request that they are turned into integers for us by specifying the converter:

We specify converters by using something called a function annotation. This is a Python 3 exclusive feature that was introduced in PEP 3107.

This works with any callable, such as a function that would convert a string to all upper-case:

Unlike the other basic converters, the bool converter is treated slightly different. Instead of casting directly to the bool type, which would result in any non-empty argument returning True , it instead evaluates the argument as True or False based on its given content:

Advanced Converters¶

Sometimes a basic converter doesn’t have enough information that we need. For example, sometimes we want to get some information from the Message that called the command or we want to do some asynchronous processing.

For this, the library provides the Converter interface. This allows you to have access to the Context and have the callable be asynchronous. Defining a custom converter using this interface requires overriding a single method, Converter.convert() .

An example converter:

The converter provided can either be constructed or not. Essentially these two are equivalent:

Having the possibility of the converter be constructed allows you to set up some state in the converter’s __init__ for fine tuning the converter. An example of this is actually in the library, clean_content .

If a converter fails to convert an argument to its designated target type, the BadArgument exception must be raised.

Inline Advanced Converters¶

If we don’t want to inherit from Converter , we can still provide a converter that has the advanced functionalities of an advanced converter and save us from specifying two types.

For example, a common idiom would be to have a class and a converter for that class:

This can get tedious, so an inline advanced converter is possible through a classmethod() inside the type:

Discord Converters¶

Working with Discord Models is a fairly common thing when defining commands, as a result the library makes working with them easy.

For example, to receive a Member you can just pass it as a converter:

When this command is executed, it attempts to convert the string given into a Member and then passes it as a parameter for the function. This works by checking if the string is a mention, an ID, a nickname, a username + discriminator, or just a regular username. The default set of converters have been written to be as easy to use as possible.

A lot of discord models work out of the gate as a parameter:

Having any of these set as the converter will intelligently convert the argument to the appropriate target type you specify.

Under the hood, these are implemented by the Advanced Converters interface. A table of the equivalent converter is given below:

By providing the converter it allows us to use them as building blocks for another converter:

Special Converters¶

The command extension also has support for certain converters to allow for more advanced and intricate use cases that go beyond the generic linear parsing. These converters allow you to introduce some more relaxed and dynamic grammar to your commands in an easy to use manner.

typing.Union¶

A typing.Union is a special type hint that allows for the command to take in any of the specific types instead of a singular type. For example, given the following:

The what parameter would either take a discord.TextChannel converter or a discord.Member converter. The way this works is through a left-to-right order. It first attempts to convert the input to a discord.TextChannel , and if it fails it tries to convert it to a discord.Member . If all converters fail, then a special error is raised, BadUnionArgument .

Note that any valid converter discussed above can be passed in to the argument list of a typing.Union .

typing.Optional¶

A typing.Optional is a special type hint that allows for “back-referencing” behaviour. If the converter fails to parse into the specified type, the parser will skip the parameter and then either None or the specified default will be passed into the parameter instead. The parser will then continue on to the next parameters and converters, if any.

Consider the following example:

../../_images/optional1.jpg

In this example, since the argument could not be converted into an int , the default of 99 is passed and the parser resumes handling, which in this case would be to pass it into the liquid parameter.

This converter only works in regular positional parameters, not variable parameters or keyword-only parameters.

Greedy¶

The Greedy converter is a generalisation of the typing.Optional converter, except applied to a list of arguments. In simple terms, this means that it tries to convert as much as it can until it can’t convert any further.

Consider the following example:

When invoked, it allows for any number of members to be passed in:

../../_images/greedy1.jpg

The type passed when using this converter depends on the parameter type that it is being attached to:

Positional parameter types will receive either the default parameter or a list of the converted values.

Variable parameter types will be a tuple as usual.

Keyword-only parameter types will be the same as if Greedy was not passed at all.

Greedy parameters can also be made optional by specifying an optional value.

When mixed with the typing.Optional converter you can provide simple and expressive command invocation syntaxes:

This command can be invoked any of the following ways:

The usage of Greedy and typing.Optional are powerful and useful, however as a price, they open you up to some parsing ambiguities that might surprise some people.

For example, a signature expecting a typing.Optional of a discord.Member followed by a int could catch a member named after a number due to the different ways a MemberConverter decides to fetch members. You should take care to not introduce unintended parsing ambiguities in your code. One technique would be to clamp down the expected syntaxes allowed through custom converters or reordering the parameters to minimise clashes.

To help aid with some parsing ambiguities, str , None , typing.Optional and Greedy are forbidden as parameters for the Greedy converter.

Error Handling¶

When our commands fail to parse we will, by default, receive a noisy error in stderr of our console that tells us that an error has happened and has been silently ignored.

In order to handle our errors, we must use something called an error handler. There is a global error handler, called on_command_error() which works like any other event in the Event Reference . This global error handler is called for every error reached.

Most of the time however, we want to handle an error local to the command itself. Luckily, commands come with local error handlers that allow us to do just that. First we decorate an error handler function with Command.error() :

The first parameter of the error handler is the Context while the second one is an exception that is derived from CommandError . A list of errors is found in the Exceptions page of the documentation.

Checks¶

There are cases when we don’t want a user to use our commands. They don’t have permissions to do so or maybe we blocked them from using our bot earlier. The commands extension comes with full support for these things in a concept called a Checks .

A check is a basic predicate that can take in a Context as its sole parameter. Within it, you have the following options:

Return True to signal that the person can run the command.

Return False to signal that the person cannot run the command.

Raise a CommandError derived exception to signal the person cannot run the command.

  • This allows you to have custom error messages for you to handle in the error handlers .

To register a check for a command, we would have two ways of doing so. The first is using the check() decorator. For example:

This would only evaluate the command if the function is_owner returns True . Sometimes we re-use a check often and want to split it into its own decorator. To do that we can just add another level of depth:

Since an owner check is so common, the library provides it for you ( is_owner() ):

When multiple checks are specified, all of them must be True :

If any of those checks fail in the example above, then the command will not be run.

When an error happens, the error is propagated to the error handlers . If you do not raise a custom CommandError derived exception, then it will get wrapped up into a CheckFailure exception as so:

If you want a more robust error system, you can derive from the exception and raise it instead of returning False :

Since having a guild_only decorator is pretty common, it comes built-in via guild_only() .

Global Checks¶

Sometimes we want to apply a check to every command, not just certain commands. The library supports this as well using the global check concept.

For example, to block all DMs we could do the following:

Be careful on how you write your global checks, as it could also lock you out of your own bot.

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 API. В этом случае для создания виртуальных ассистентов вовсе не требуется обладать полным кодом и понимать всю специфику работы приложения. Будет вполне достаточно использовать уже готовые инструменты, значительно упрощающие процесс разработки (как правило, применяются модули Node.js и Python). Также начинающим программистам помогут готовые коды, расположенные на популярных форумах. В общем, предлагаем разобраться с этой темой, остановившись на важных нюансах и особенностях.

Discord API – что это и где найти?

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


Как подключиться к Discord API при создании бота?

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

  • Переходим на страницу Дискорд Developers и выполняем авторизацию в своем аккаунте. А после этого заходим во вкладку Bot и нажимаем на кнопку New Application .


  • Вводим название самого приложения и кликаем Create , дополнительно подтвердив действие.


Как результат – вы успешно подключились к Дискорд API и воспользовались функционалом для разработчиков. Теперь дело за малым – осталось разработать бота и проверить, насколько корректно он работает. Если нужно, то подробные инструкции получится отыскать на YouTube (в основном по английским запросам). Также не забудьте установить само приложение мессенджера, указав в Google «Discordapp API download platform WIN» и посетив официальный сайт.

Как сделать авторизацию через Дискорд?

Периодически на русских и зарубежных форумах, связанных с разработкой, встречается такой вопрос: Discord API authorization frontend – как сделать? Этим интересуются создатели сайтов, которым необходимо сделать авторизацию через популярный мессенджер. На самом деле ничего самим придумывать не придется – достаточно использовать уже готовые инструменты. В это случае – функционал входа OAuth2:

Вы можете перейти по указанным ссылкам, чтобы самостоятельно ознакомиться и изучить материал. Также не забывайте про YouTube – там можно найти несколько русских видео на эту тему.

Таким образом, мы рассмотрели, для чего нужен Дискорд API и как использовать столь полезную возможность в разработке. Оказалось, что создавать ботов можно и на компьютере с Windows, и с macOS, и даже с Linux. Остались дополнительные вопросы? Будем рады ответить на них в комментариях!

Example: DiscordAPIError: Cannot send an empty message

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 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

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.

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.

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 Docs.

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.

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

Or using Constants:

You can find a list of constants here

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.

  • 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)
  • Simply showing the token and copying that, instead of clicking regenerate and copying that.

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.

Another common error–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.

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.

Another common error–this error originates from the client requesting members from the API through the WebSocket and the member chunks not arriving in time and triggering the timeout. The most common cause of this error is a bad connection; however, it can also be caused by fetching many members, upwards of 50 thousand. To fix this, run the bot on a location with better internet, such as a VPS. If this does not work for you, you will have to manually change the hardcoded member fetching timeout in the source code.

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:

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.

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

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:

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