Integration requires code grant discord ошибка

Which package is this bug report for?

discord.js

Issue description

run below code with you bot token

Code sample

const { Client, Intents } = require('discord.js');

(async () => {
  const client = new Client({
    intents: [
      Intents.FLAGS.GUILDS,
      Intents.FLAGS.GUILD_MEMBERS,
      Intents.FLAGS.GUILD_MESSAGES,
    ],
  });
  client.login(
    'Bot <Token>'
  );
  client.once('ready', async () => {
    console.log('Bot is ready');
    console.log(
      client.generateInvite({
        scopes: ['bot', 'email', 'guilds', 'identify', 'guilds.join'],
        permissions: ['ADMINISTRATOR'],
      })
    );
  });
})();

output of the above code

https://discord.com/api/oauth2/authorize?client_id=myClientId&scope=bot+email+guilds+identify+guilds.join&permissions=8

  • replaced actual client id with myClientId keyword

Package version

13.7.0

Node.js version

16.15.0

Operating system

ubuntu

Priority this issue should have

High (immediate attention needed)

Which partials do you have configured?

Not applicable (subpackage bug)

Which gateway intents are you subscribing to?

Not applicable (subpackage bug)

I have tested this issue on a development release

No response

How to Fix Code Grant Error When Inviting Personalized Bot

Modified on: Wed, 22 Mar, 2023 at 6:49 PM

The Personalized Bot (aka Custom Bbot) may give this error when you are finalizing its configuration:

Follow the steps below to resolve this issue.

Step 1:

  1. Visit https://discord.com/developers/applications/ and select the application. 
  2. Now, go to the Bot tab and turn off the Requires oauth2 code grant under the Authorization Flow (It is the second toggle from the top to the bottom).
  3. Discord will prompt save changes, select yes.

Note: 
• As a good practice, it is important to also enable all the Privileged Gateway Intents options under the cited steps: Presence Intent, Server members intent and message content intent. 
• They are important to make your Personalized Bot work properly. 
• Remember to always save the changes.

Step 2:

  1. Press Reset Token (if you have 2FA, it will require the Discord 6 digits code from your Authenticator App).
  2. Copy the code new token and visit https://mee6.xyz/dashboard/
  3. Now, go to the Bot Personalizer menu and paste the token to invite the Personalized Bot (it might require you to disable any Window Popup Blocker in case you don’t see the invitation window — You can find the configuration by visiting your browser settings).

If you have any questions about this, do not hesitate to join our Support Server✌️

Чтобы подключить бота Discord в ваше приложение, вам понадобятся токен бота (для настройки модуля) и ID канала, в который вы будете отправлять сообщения (для формы отправки).

Расскажем, как создать сервер, канал и бота Discord, а после добавить созданного бота на ваш сервер. О том, как настроить отправку сообщений на платформе AppMaster.io, можно прочитать в этой статье.

Создать сервер и канал, скопировать ID канала

Для начала вам нужно создать новый сервер в Discord (или получить права администратора на уже существующем). Откройте страницу вашей учетной записи Discord в браузере — так будет удобнее перемещаться между страницами настроек.

1. Нажмите на «+» на левой панели.

2. Выберите шаблон сервера в зависимости от вашей сферы или создайте собственный.

3. Укажите, для каких целей хотите его использовать.

4. Выберите изображение будущего сервера и укажите его название (1), затем нажмите Create. (2).

5. Сервер создан. По умолчанию в него уже добавлены два канала — текстовый и голосовой (1). Чтобы изменить настройки канала, нажмите значок шестеренки (2). Добавить новый канал можно, нажав на «+» рядом с названием раздела. Мы не будем создавать новый канал и для подключения нашего бота используем уже существующий канал general.

6. Теперь нужно получить ID выбранного канала. Для этого нужно сначала включить режим разработчика в настройках вашего профиля. Нажмите на значок шестеренки рядом с вашим никнеймом и фотографией.

7. Перейдите в раздел APP SETTINGS, на вкладку Advanced (1) и переместите селектор Developer mode — режим разработчика активируется (2).

8. Вернитесь из меню настроек и кликните по нужному каналу правой клавишей мыши (1), во всплывающем меню выберите Copy ID — идентификатор вашего канала будет скопирован (2). Сохраните его в любом текстовом документе, чтобы не возвращаться к этому шагу.

Создать бота и добавить его на сервер, скопировать токен бота

Чтобы создать бота, перейдите на специальную страницу Discord для разработчиков: https://discord.com/developers/. Откройте ее в соседней вкладке браузера, не выходя из вашей учетной записи Discord.

Сначала вам нужно создать приложение, затем в этом приложении создать бота и настроить для него разрешения, и только после этого — добавлять бота на сервер.

1. На вкладке Applications выберите New Application.

2. Введите название будущего приложения (1) и нажмите Create (2).

3. Приложение создано. Перейдите не вкладку Bot (1) и нажмите Add Bot, чтобы добавить нового бота.

4. Согласитесь добавить бота в ваше приложение.

5. Бот создан. На вкладке Bot отобразится вся информация о нем. Тут можно изменить его имя, добавить изображение и скопировать токен бота (1). Этот токен понадобится вам для настройки модуля Discord на платформе Appmaster.i. Каждый раз при внесении изменений портал разработчика будет предлагать вам сохранить их (2).

Сохраните токен бота, чтобы при последующей настройке не возвращаться к этому шагу.

6. Теперь перейдите на вкладку OAuth2 (1) — тут можно настроить разрешения и получить ссылку на вашего бота. В разделе SCOPES выберите bot(2), в BOT PERMISSIONS отметьте разрешения, которые хотите ему предоставить, в нашем случае — только отправка сообщений, поэтому выберите Send Message(3). После скопируйте автоматически сгенерированную Discord ссылку(4).

7. Вставьте скопированную ссылку в адресную строку браузера и перейдите по ней — откроется окошко вашего приложения. Выберите ваш сервер в раскрывающемся списке (1) и нажмите Continue (2).

8. Убедитесь, что приложению (а значит, и созданному в нем боту) даны только необходимые разрешения, после чего добавьте его на ваш сервер.

9. Теперь вернитесь на ваш сервер. Бот оставил приветственное сообщение — значит, что он успешно добавлен и функционирует.

Через AppMaster.io Studio подключить бота в приложение

Итак, все готово. Вы получили токен бота для модуля Discord и ID канала для формы отправки сообщения. Теперь перейдите в AppMaster.io Studio и настройте отправку сообщений из вашего приложения, следуя инструкции Модуль Discord: подключение бота и отправка сообщений.

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

I am trying to implement Discord OAuth2 in my node.js Application. As soon as I try to get the access token from the given authorization code, I always get the HTTP response Error 400 {«error»: «invalid_grant»}

let xhr = new XMLHttpRequest()
xhr.open('POST', 'https://discord.com/api/oauth2/token')

xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')

let payload ={
    client_id: clientID,
    client_secret: clientSecret,
    grant_type: 'authorization_code',
    code: code,
    redirect_uri: redirectUrl,
    scope: 'identify'
};

console.log(payload)
xhr.send(JSON.stringify(payload))

xhr.onreadystatechange = () => {
    console.log(xhr.status)
    console.log(xhr.responseText)
}

xhr.onerror = () => {
    console.log('Failed')
}

asked Jun 17, 2020 at 16:34

lukeplyz's user avatar

Okay I solved the issue. For everyone who is experiencing the same issue that I had, I solved it by using axios and querystring to send the POST request to the Discord API (https://github.com/discord/discord-api-docs/issues/1131)

It seems that there is a problem with the JSON and the x-www-form-urlencoded format.

answered Jun 18, 2020 at 15:14

lukeplyz's user avatar

lukeplyzlukeplyz

811 silver badge6 bronze badges

payload should not be a js object but a form data i.e

let payload = new FormData();
payload.append("key in string","value in string")

answered Nov 12, 2020 at 9:05

Gokul Kurup's user avatar

1

I had the same issue when trying to use on Next.js’s GetServerSideProps function.

After searching a lot, I found an closed issue on Github solving this problem
(Github Issue: Deep Linking with OAuth2 Not Working). Basically, we could not use JSON object on authentication request’s body. We must use URLSearchParams object instead.

The payload should look like:

const payload = new URLSearchParams()

payload.append('client_id', process.env.DISCORD_CLIENT_ID)
payload.append('client_secret', process.env.DISCORD_CLIENT_SECRET)
payload.append('grant_type', 'authorization_code')
payload.append('redirect_uri', process.env.DISCORD_REDIRECT_URI)
payload.append('code', accessCode)
payload.append('scope', 'identify')

answered Nov 24, 2020 at 0:51

Isaac Lourenço's user avatar

In my case, it was a very silly error.
Instead of «response_type», I sent «response_type » (with a space); I randomly realized when I printed the HTML-formatted string and saw a %20 😂
Make sure the parameters have the correct names!

answered Jan 12, 2021 at 23:08

Sasino's user avatar

SasinoSasino

1042 silver badges11 bronze badges

(READ DESC) HOW TO /DISCORD BOT CODE GRANT ERROR — YOUTUBE

read-desc-how-to-discord-bot-code-grant-error-youtube image

Have you tried to make a discord bot and showed up,:code grant required?? Follow the simple steps from the video and it will 100% workEdited with Filmigo:htt…
From youtube.com
Author DeviKiv
Views 7.5K


INTEGRATION REQUIRES CODE GRANT IN BOT – DISCORD

integration-requires-code-grant-in-bot-discord image

Integration requires code grant in bot daniel inderos May 27, 2021 18:10 … so i made a discord bot but when i try to add it to my server this happens, help me. 1. 2 Comments 2 comments. Sort by Date Votes. Joe …
From support.discord.com


DISCORD ADMINISTRATOR BOT — BHOLENATHCOS.COM

discord administrator bot; Feb 06, 2022 new york cosmos team 1977. No Comments | 0 likes | how to beat professional ai fifa 20 …
From bholenathcos.com


BOT REQUIRES CODE GRANT — ABENTEUER-SINGLEMOM.CH

Step 3 â Handling Your First User Command Youâ ve successfully set up a coding environment and created the basic code for logging in to a Discord bot. Whether the bot should require a code grant or not: Returns {Promise} deleteApp apps.deleteApp(appID) Parameter Type Description; appID: String: The client ID of the application you wish to …
From abenteuer-singlemom.ch


DISCORD — BOT COMMANDS NOT WORKING IN «CHANNEL THREADS» FEATURE

The PyPi version of discord.py is only updated to version 1.7.3.However, discord.py only added support for threads in the 2.0 major update. To update to this version, do:
From stackoverflow.com


REQUIRE OAUTH2 CODE GRANT DISCORD — XN—N3CFTFAN7CR7RH2C.COM

Discord bot providing live killmails and intel for the game EVE Online. Within Discord, there are multiple types of OAuth2 authentication. We support the authorization code grant, the implicit grant, client credentials, and some modified special-for-Discord flows for Bots and Webhooks Discord Confirm your action by selecting Yes, do it! The …
From xn--n3cftfan7cr7rh2c.com


BOT REQUIRES CODE GRANT

Bot Requires Code Grant As required to grant flow if your access. All your bot info about this is required! Discord as followers to code su…
From sufferjose.blogspot.com


BOT REQUIRES CODE GRANT · ISSUE #1 · MAGICALSOCIETY/ESO-ASSISTANT

It’s not possible to add this bot to Discord servers, since it requires code grant. This needs to be turned off, otherwise the bot cannot be used. See ref link: https://discordbots.co.uk/docs/b…
From github.com


INTEGRATION REQUIRES CODE GRANT IN BOT — DISCORD

Integration requires code grant in bot daniel inderos 2021年05月27日 18:10; so i made a discord bot but when i try to add it to my server this happens, help me. 1. 2 コメント 2件のコメント . 並べ替え基準 日付 …
From support.discord.com


BOT REQUIRES CODE GRANT JOBS, EMPLOYMENT | FREELANCER

Search for jobs related to Bot requires code grant or hire on the world’s largest freelancing marketplace with 19m+ jobs. It’s free to sign up and bid on jobs.
From freelancer.com


LAVORI E ASSUNZIONI DI DISCORD BOT REQUIRES CODE GRANT | FREELANCER

Cerca lavori di Discord bot requires code grant o assumi sulla piattaforma di lavoro freelance più grande al mondo con oltre 20 mln di lavori. Registrati e fai offerte sui lavori gratuitamente.
From freelancer.co.it


OAUTH2 DOCUMENTATION IMPLICITLY STATES APPLICATION.COMMANDS …

Description The text in https://discord.com/developers/docs/topics/oauth2#advanced-bot-authorization hasn’t been updated to reflect the addition of the …
From github.com


ERROR WHEN USING PICKLE FOR A DISCORD BOT — STACK OVERFLOW

Probably it is in emoji_var. You should check what you have in emoji_var — print (emoji_var), print ( type (emoji_var) ). And see if you need it or if you can get values from emoji_var as strings, list, dict, int which are pickleabel. – furas. Aug 30, 2020 at 8:43. using Google I found similar problem Why is python pickle failing to dump …
From stackoverflow.com


CôNG VIệC, THUê DISCORD BOT REQUIRES CODE GRANT | FREELANCER

Tìm kiếm các công việc liên quan đến Discord bot requires code grant hoặc thuê người trên thị trường việc làm freelance lớn nhất thế giới với hơn 21 triệu công việc. Miễn phí khi đăng ký và chào giá cho công việc.
From vn.freelancer.com


OAUTH2 DISCORD BOT CODE EXAMPLE — CODEGREPPER.COM

import base64 API_ENDPOINT = ‘https://discord.com/api/v6’ CLIENT_ID = ‘332269999912132097’ CLIENT_SECRET = ‘937it3ow87i4ery69876wqire’ def get_token(): data …
From codegrepper.com


PDISCORD PYTHON BOT REQUIRE ROLES CODE EXAMPLE

Python answers related to “pdiscord python bot require roles” add role discord .py; create a role with discord.py; discord py fetch channel by id; discord py join and leave call; discord.py add role on member join; discord.py bot notification youtube script; discord.py check if user has role; discord.py fetch channel
From codegrepper.com


GIVING A BOT PERMISSIONS IN MY DISCORD : DISCORDAPP — REDDIT

In all honestly give popular bots like dyno and mee6 admin because you have no potential risk at something bad happening but small bots only on 100-200 servers should in no cases be given admin. Also bots with .say should not be given admin (like fredboat) because then a normal user can type .say everyone and it actually works. 3.
From reddit.com


INTEGRATION REQUIRES CODE GRANT DISCORD

Carl-bot is a fully customizable and modular discord bot featuring reaction roles, automod, logging, custom commands and much more. Sentry Integration Platform | Sentry Our integration tutorials are used by creators of all kinds to get apps and integrations up and running in no time — no technical knowledge required.
From parkerslakecommunity.com


INTEGRATION REQUIRES CODE GRANT DISCORD — CAPTUREMEDIA.CH

Using discord oauth2. A simple guide and an example nodeJS … Fill in App Name field, and click the Add Redirect button. Qtum 2021 Roadmap Explanation — Qtum Integration requires code grant in bot. API Reference — Quart-Discord 2.2.0b1 documentation Bot reqiures code grant · Issue #1366 · Just-Some-Bots … UiPath uses OAuth authentication …
From capturemedia.ch


BASIC-DISCORD-BOT | #BOT | BASIC DISCORD BOT

Code Snippets; Community Discussions; Vulnerabilities; Install ; Support ; kandi X-RAY | basic-discord-bot REVIEW AND RATINGS. Basic discord bot. Support. basic-discord-bot has a low active ecosystem. It has 7 star(s) with 1 fork(s). It had no major release in the last 12 months. It has a neutral sentiment in the developer community. Quality . basic-discord-bot has no …
From kandi.openweaver.com


INTEGRATION REQUIRES CODE GRANT DISCORD — WORDSOFLIFE.COM

On your bot’s application page, in the «Bot» tab, turn off the «Requires OAuth2 Code Grant» option. The authorization code is a temporary code that the client will exchange for an access token. Speedrun your web development Autocode is a toolkit for building amazing bots, apps and websites with APIs. SSO Grant Support — Standard OAuth2.0 Grants: Authorization Code, …
From wordsoflife.com


INTEGRATION REQUIRES CODE GRANT DISCORD — TMFLEET.COM

conair style and volumize brush » integration requires code grant discord
From tmfleet.com


BOT REQUIRES CODE GRANT

All groups and messages … …
From groups.google.com


DISCORD BOT COMMANDS CODE JOBS, EMPLOYMENT | FREELANCER

Search for jobs related to Discord bot commands code or hire on the world’s largest freelancing marketplace with 19m+ jobs. It’s free to sign up and bid on jobs.
From freelancer.com


INTEGRATION REQUIRES CODE GRANT DISCORD — PERFECTLYME21.CA

andrew wamsley sister; what is the difference between ofw and immigrant. abandoned places in hamden ct; hospital job vacancy near me; short term student accommodation bristol
From perfectlyme21.ca


REQUIRE OAUTH2 CODE GRANT DISCORD — ENGLISH.DCNEPAL.COM

require oauth2 code grant discorddessert food truck atlanta. smart phone name crossword clue. require oauth2 code grant discordwhat is consumerism in marketing with examples. managing virtual classes ppt. require oauth2 code grant discordused corvette convertible in florida. down syndrome development chart; necromunda cawdor book; bj’s bakery cake order …
From english.dcnepal.com


15 BEST DISCORD BOTS FOR 2022 (REVIEWED AND RANKED) — CODELESS

Mudae is another top bot on Discord. It has more than 9 million discord servers. It is perfect for manga lovers, video games and anime. If you are one of the anime lovers, this is a perfect fit for your server. Mudae is the best bot for its game where you can catch husbandos and waifus of famous video games and manga.
From codeless.co


HOW TO MAKE A DISCORD BOT USING PYTHON AND DISCORD API

Follow the steps given below to create a discord bot account. The first step would be to log in to the Discord Website. Next, Navigate to the “Application Page” and click on the “New Application” button. Now, the next page will ask you to create the application name. Name the application and click on “Create”.
From deasilex.com


OAUTH2 DOCUMENTATION IMPLICITLY STATES `APPLICATION.COMMANDS` …

The text would inform readers that both the bot and application.commands scopes do not require code grant flows. Current Behavior. The text implicitly states that authorising with the application.commands scope requires a code grant flow. Screenshots/Videos. No response. Client and System Information. Firefox Nightly on Android (100.0a1; Build …
From coder.social


CODE A DISCORD BOT AND HOST IT FOR FREE — FREECODECAMP.ORG

3. Click on the “New Application” button. 4. Give the application a name and click “Create”. 5. Go to the “Bot” tab and then click “Add Bot”. You will have to confirm by clicking «Yes, do it!» Keep the default settings for Public Bot (checked) and Require OAuth2 Code Grant (unchecked). Your bot has been created.
From freecodecamp.org


Я продолжаю получать invalid_grant ошибка при попытке получить токен OAuth от Google для подключения к api контактов. Вся информация верна, и я триппл проверил это, так что в тупике.

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

14 ответов


Я столкнулся с этой проблемой, когда я явно не запрашивал «автономный» доступ при отправке пользователя в OAuth «вы хотите дать этому приложению разрешение на прикосновение к вашим вещам?» страница.

убедитесь, что вы указали access_type=offline в своем запросе.

подробности здесь:https://developers.google.com/accounts/docs/OAuth2WebServer#offline

(также: я думаю, Google добавил Это ограничение в конце 2011 года. Если у вас есть старые токены до этого, для авторизации автономного использования необходимо отправить пользователей на страницу разрешений.)


я столкнулся с этой же проблемой, несмотря на указание «оффлайн» access_type в моем запросе в соответствии с ответом bonkydog. Короче говоря, я обнаружил, что решение, описанное здесь, сработало для меня:

https://groups.google.com/forum/#!topic/google-analytics-data-export-api/4uNaJtquxCs

по сути, при добавлении клиента OAuth2 в консоль Google API Google предоставит вам «идентификатор клиента «и» адрес электронной почты «(если вы выберете «webapp» в качестве своего тип клиента.) И, несмотря на вводящие в заблуждение соглашения об именах Google, они ожидают, что вы отправите «адрес электронной почты» как значение client_id параметр при доступе к их API OAuth2.

это применяется при вызове обоих этих URL-адресов:

  • https://accounts.google.com/o/oauth2/auth
  • https://accounts.google.com/o/oauth2/token

обратите внимание, что вызов первого URL будет успеха если вы вызываете его с вашим «идентификатором клиента» вместо вашего «адреса электронной почты». Однако использование кода, возвращенного из этого запроса, не будет работать при попытке получить маркер носителя из второго URL-адреса. Вместо этого вы получите сообщение «Error 400» и «invalid_grant».


хотя это старый вопрос, кажется, что многие все еще сталкиваются с ним — мы потратили дни на то, чтобы отслеживать это сами.

в спецификации OAuth2 «invalid_grant» является своего рода catch-all для всех ошибок, связанных с недопустимыми/истекшими/отозванными токенами (auth grant или refresh token).

для нас проблема была двоякой:

  1. пользователь активно отозвал доступ к нашему приложению
    Имеет смысл, но сделать это через 12 часов после отзыв,Google перестает отправлять сообщение об ошибке в ответ:
    “error_description” : “Token has been revoked.”
    Это довольно вводит в заблуждение, потому что вы предположите, что сообщение об ошибке существует все время, что не так. Вы можете проверить, имеет ли ваше приложение доступ в страница разрешения приложений.

  2. пользователь сбросил / восстановил свой пароль Google
    В Декабре 2015 Года, Google изменил их поведение по умолчанию так этот сброс пароля для пользователей, не являющихся пользователями Google Apps, автоматически отменит все токены обновления приложений пользователя. При отзыве сообщение об ошибке следует тому же правилу, что и в предыдущем случае, поэтому вы получите «error_description» только в первые 12 часов. Кажется, нет никакого способа узнать, был ли пользователь вручную отозван доступ (intentful) или это произошло из-за сброса пароля (побочный эффект).

помимо них, существует множество других возможностей причины, которые могут вызвать ошибку:

  1. серверные часы / время не синхронизированы
  2. не авторизован для доступа в автономном режиме
  3. Дросселируется Google
  4. использование токенов обновления с истекшим сроком действия
  5. пользователь неактивен в течение 6 месяцев
  6. используйте электронную почту работника службы вместо идентификатора клиента
  7. слишком много доступа токены в короткие сроки
  8. клиент SDK может быть устаревшим
  9. неверный / неполный токен обновления

я написал короткую статью суммирование каждого элемента с некоторым руководством по отладке, чтобы помочь найти виновника. Надеюсь, это поможет.


Я столкнулся с той же проблемой. Для меня я исправил это, используя адрес электронной почты (строка, которая заканчивается на …@developer.gserviceaccount.com) вместо идентификатора клиента для значения параметра client_id. Имя, установленное Google, запутывает здесь.


У меня было такое же сообщение об ошибке «invalid_grant», и это было потому, что
authResult [‘code’]
отправка с клиентской стороны javascript не был получен правильно на сервере.

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


моя проблема заключалась в том, что я использовал этот URL:

https://accounts.google.com/o/oauth2/token

когда я должен был использовать этот URL:

https://www.googleapis.com/oauth2/v4/token

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


Если вы используете библиотеку scribe, просто настройте автономный режим, как предложил bonkydog
вот код:

OAuthService service = new ServiceBuilder().provider(Google2Api.class).apiKey(clientId).apiSecret(apiSecret)
                .callback(callbackUrl).scope(SCOPE).offline(true)
                .build();

https://github.com/codolutions/scribe-java/

1

автор: Oleksii Kyslytsyn


используя Android clientId (без client_secret), я получал следующий ответ об ошибке:

{
 "error": "invalid_grant",
 "error_description": "Missing code verifier."
}

Я не могу найти документацию для поля «code_verifier», но я обнаружил, что если вы установите для него равные значения в запросах авторизации и токена, он удалит эту ошибку. Я не уверен, какое значение должно быть или должно ли оно быть безопасным. Он имеет некоторую минимальную длину (16? символы), но я нашел параметр null тоже работает.

Я использую AppAuth для запроса авторизации в моем клиенте Android, который имеет :

final GoogleAuthorizationCodeTokenRequest req = new GoogleAuthorizationCodeTokenRequest(
                    TRANSPORT,
                    JSON_FACTORY,
                    getClientId(),
                    getClientSecret(),
                    code,
                    redirectUrl
);
req.set("code_verifier", null);          
GoogleTokenResponse response = req.execute();

Это глупый ответ, но проблема для меня заключалась в том, что я не понял, что мне уже был выдан активный токен oAuth для моего пользователя google, который я не смог сохранить. Решение в этом случае-перейти в консоль api и сбросить секрет клиента.

есть множество других ответов на SO для этого эффекта, например
Reset Client Secret OAuth2-нужно ли клиентам повторно предоставлять доступ?


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

фото: узел.пример с JS в Google OAuth2, которые перестали работать invalid_grant в

Примечание: ответ OAuth также станет недействительным, если пароль, используемый в первоначальной авторизации, был изменен.

Если в среде bash, вы можете использовать следующее, Чтобы удалить устаревший ответ:

rm /Users/<username>/.credentials/<authorization.json>


есть две основные причины для invalid_grant в ошибка, которую вы должны позаботиться до запроса POST для токена обновления и токена доступа.

  1. заголовок запроса должен содержать «content-type: application / x-www-form-urlencoded»
  2. ваша полезная нагрузка запроса должна быть url-кодированными данными формы, не отправляйте как объект json.

RFC 6749 OAuth 2.0 определена invalid_grant в как:
предоставленное разрешение на авторизацию (например, код авторизации, учетные данные владельца ресурса) или токен обновления недействительны, истекли, отозваны, не соответствуют URI перенаправления, используемому в запросе авторизации, или был выдан другому клиенту.

Я нашел еще одну хорошую статью, здесь вы найдете много других причин для этого ошибка.

https://blog.timekit.io/google-oauth-invalid-grant-nightmare-and-how-to-fix-it-9f4efaf1da35


на этом сайте
console.developers.google.com

на этой консоли выберите ваш проект, введите url клятвы.
url-адрес обратного вызова oauth будет перенаправлен, когда OAuth success


после рассмотрения и попытки всех других способов здесь, вот как я решил проблему в nodejs с googleapis модуль в сочетании с request модуль, который я использовал для извлечения маркеров вместо предусмотренного getToken() способ:

const request = require('request');

//SETUP GOOGLE AUTH
var google = require('googleapis');
const oAuthConfigs = rootRequire('config/oAuthConfig')
const googleOAuthConfigs = oAuthConfigs.google

//for google OAuth: https://github.com/google/google-api-nodejs-client
var OAuth2 = google.auth.OAuth2;
var googleOAuth2Client = new OAuth2(
    process.env.GOOGLE_OAUTH_CLIENT_ID || googleOAuthConfigs.clientId, 
    process.env.GOOGLE_OAUTH_CLIENT_SECRET || googleOAuthConfigs.clientSecret, 
    process.env.GOOGLE_OAUTH_CLIENT_REDIRECT_URL || googleOAuthConfigs.callbackUrl);

/* generate a url that asks permissions for Google+ and Google Calendar scopes
https://developers.google.com/identity/protocols/googlescopes#monitoringv3*/
var googleOAuth2ClientScopes = [
    'https://www.googleapis.com/auth/plus.me',
    'https://www.googleapis.com/auth/userinfo.email'
];

var googleOAuth2ClientRedirectURL = process.env.GOOGLE_OAUTH_CLIENT_REDIRECT_URL || googleOAuthConfigs.callbackUrl; 

var googleOAuth2ClientAuthUrl = googleOAuth2Client.generateAuthUrl({
  access_type: 'offline', // 'online' (default) or 'offline' (gets refresh_token)
  scope: googleOAuth2ClientScopes // If you only need one scope you can pass it as string
});

//AFTER SETUP, THE FOLLOWING IS FOR OBTAINING TOKENS FROM THE AUTHCODE


        const ci = process.env.GOOGLE_OAUTH_CLIENT_ID || googleOAuthConfigs.clientId
        const cs = process.env.GOOGLE_OAUTH_CLIENT_SECRET || googleOAuthConfigs.clientSecret
        const ru = process.env.GOOGLE_OAUTH_CLIENT_REDIRECT_URL || googleOAuthConfigs.callbackUrl
        var oauth2Client = new OAuth2(ci, cs, ru);

        var hostUrl = "https://www.googleapis.com";
        hostUrl += '/oauth2/v4/token?code=' + authCode + '&client_id=' + ci + '&client_secret=' + cs + '&redirect_uri=' + ru + '&grant_type=authorization_code',
        request.post({url: hostUrl}, function optionalCallback(err, httpResponse, data) {
            // Now tokens contains an access_token and an optional refresh_token. Save them.
            if(!err) {
                //SUCCESS! We got the tokens
                const tokens = JSON.parse(data)
                oauth2Client.setCredentials(tokens);

                //AUTHENTICATED PROCEED AS DESIRED.
                googlePlus.people.get({ userId: 'me', auth: oauth2Client }, function(err, response) {
                // handle err and response
                    if(!err) {
                        res.status(200).json(response);
                    } else {
                        console.error("/google/exchange 1", err.message);
                        handleError(res, err.message, "Failed to retrieve google person");
                    }
                });
            } else {
                console.log("/google/exchange 2", err.message);
                handleError(res, err.message, "Failed to get access tokens", err.code);
            }
        });

Я просто использовать request чтобы сделать запрос api через HTTP, как описано здесь:
https://developers.google.com/identity/protocols/OAuth2WebServer#offline

POST /oauth2/v4/token HTTP/1.1
Host: www.googleapis.com
Content-Type: application/x-www-form-urlencoded

code=4/P7q7W91a-oMsCeLvIaQm6bTrgtp7&
client_id=8819981768.apps.googleusercontent.com&
client_secret={client_secret}&
redirect_uri=https://oauth2.example.com/code&
grant_type=authorization_code

попробуйте изменить url-адрес requst на

https://www.googleapis.com/oauth2/v4/token

0

автор: Sergiy Voytovych


Bot Designer for Discord — Wiki

Troubleshooting

This page contains a number of troubleshooting that can help you to solve problems that BDFD users often encounter.

Summary

Troubleshooting for…

  1. $onJoined[]
    • The Callback Doesn’t Work
  2. Moderation And Server Management Related Commands
    • The Bot Can’t Assign Or Take Roles
    • Gives an Error When Trying To Moderate a Member
    • Gives an Error When Trying To Purge Messages
  3. $addReactions and $addCmdReactions
    • The Bot Fails To Add Reactions
  4. $time
    • The Function Returns an Error
  5. Economy Related Commands
    • Negative Balance
      • Pay Command
      • Roulette Command
    • Desynchronized Balance
      • The Balance Is Different On Different Servers
      • The Displayed Balance Is Different For Different Commands
  6. Leaderboards
    • The Leaderboard Is Empty
    • The User’s Value Isn’t Updated
  7. Bot Issues
    • The Bot Is Offline
    • The Bot Doesn’t Respond
    • The Bot Goes Offline From Time To Time
    • Desynchronization of Commands
      • Ghost Command
    • The Bot Takes A Long Time To Respond
    • The Slash Commands Doesn’t Appear
    • Integration Requires Code Grant
  8. App Issues
    • The Ad Button Doesn’t Work
    • Ghost Functions From The Changelog
    • The Translation Feature Doesn’t Work

Let’s Troubleshoot Everything!


$onJoined[]

The Callback Doesn’t Work

The Null Reason
You misspelled the callback name. Make sure you don’t make any mistakes in the callback name.
Also, remember that callbacks are case-sensitive: you can’t write $onjoined[Channel ID], you must write $onJoined[Channel ID].

The 1st Reason
You specified the wrong Channel ID.
How to get the Channel ID correctly:

For Desktop

Before starting, make sure you have Developer Mode enabled on Discord.

dev-desktop

id-desktop

For Mobile

Before starting, make sure you have Developer Mode enabled on Discord.

dev-mobile

id-mobile

Using a Function

Using the $channelID, $mentionedChannels or $findChannel functions, you can get the Channel ID of the desired channel.
Check out these functions:

  1. $channelID
  2. $mentionedChannels
  3. $findChannel

The 2nd Reason
Your bot doesn’t have the sendmessages and/or the embedlinks permission that allow the bot to send messages (or embed messages) in a given channel.
Best Practice Solution
Grant both of these permissions to the bot in the desired channel through the channel’s permissions settings:

edit-channel
perms
add
search
message
embed
save

The 3rd Reason
There’s a critical error in your code.
Callbacks can’t return errors that occurred during code execution.
Therefore, sometimes it’s difficult to solve errors in the callback code.
Best Practice Solution
Try debugging your command as a text command. In most cases, they’re backward compatible with the $onJoined callback, since both, by default, process the actions of the command author (when a user joins the server, this user becomes the «author» of this callback).

The 4th Reason
Members Intent isn’t enabled.
This callback requires the Members Intent to be enabled.

Read the Gateway Intents Guide for more details.

The 5th Reason
You have several commands with this callback.
You can only have one command with this callback. If you want to make a unique welcome message for multiple servers instead of just one, then check out Per-Server $onJoined.


The Bot Can’t Assign Or Take Roles

The 1st Reason
Your bot doesn’t have the manageroles permission.
Make sure that one of the roles that the bot has, has this permission enabled.

perm-mroles

The 2nd Reason
You are trying to assign or take roles that are higher than the highest role your bot has.

Gives an Error When Trying To Moderate a Member

The 1st Reason
Your bot has lower priority than the specified user.
This means that the highest role your bot has is lower in position than the highest role the specified user has.
Or, the specified user is the owner of the server.

The 2nd Reason
Your bot doesn’t have the required permissions.
Make sure that the permission list of any role that the bot has, have these required permissions.

Gives an Error When Trying To Purge Messages

The 1st Reason
Your bot doesn’t have the managemessages permission.
Make sure that one of the roles that the bot has, has this permission enabled.

perm-mmesages

The 2nd Reason
You are trying to purge messages that have been around for more than two weeks.
BDFD uses a bulk request to purge messages, and it can’t process messages that are more than two weeks old.


$addReactions and $addCmdReactions

The Bot Fails To Add Reactions

The 1st Reason
The user has blocked the bot, so the bot can’t react to the user’s messages. This works exactly the same if the user has blocked another user.

The 2nd Reason
You’re specifying the emoji in the function argument incorrectly.

  • Default emojis.
    - $addCmdReactions[:joy:]
    + $addCmdReactions[😂]
    
  • Custom emojis.
    - $addCmdReactions[:pikachu:]
    - $addCmdReactions[\:pikachu:]
    + $addCmdReactions[<:pikachu:951437967711420456>]
    

    You must use the Emoji ID form of the desired emoji.

The 3rd Reason
Case with custom emojis.
Your bot must share a server with the specified emoji in order to use it. It works like Discord Nitro.


$time

The Function Returns an Error

The 1st Reason
Incorrect use of the function. The function doesn’t return the current time or anything like that.
The function’s role is to change the timezone for time-related functions (such as $day, $hour, and so on)

The 2nd Reason
Incorrect time zone or incorrect time zone format.
BDFD uses the official IANA time zone database for time zone information.
Please use the TZ Database name from this list in the $time function.

- $time[America]
- $time[New_York]
+ $time[America/New_York]

  • This part will have fully working and quality code examples that you can use in your bot.
  • In this part, examples and more will be based on the local economy and BDScript 2.
Variable Name Default Variable Value Our Variable Value Target’s Variable Value
Money 0 100 120

Negative Balance

The 1st Possible Solution
Adding limiters or if statements that will prevent actions in which the executor’s or target’s balance becomes negative.
This solution can be an alternative to «Prevent actions when the amount is greater than the user’s balance».

Argument Content
1st — Target Afternoon
2nd — Amount 50
3rd — Comment Happy Birthday!

View Arguments Formatting In Code.

  • Target
    $var[target;$findUser[$message[1];no]]
    
  • Amount
    $var[amount;$message[2]]
    
  • Comment
    $var[comment;$trimSpace[$replaceText[$replaceText[$message;$message[1];];$message[2];]]]
    

  • Limiters Method
    $var[ourNewBalance;$sub[$getUserVar[Money];$var[amount]]]
    
    $onlyIf[$var[ourNewBalance]>0;Error Message]
    
  • If Statements Method
    $var[ourNewBalance;$sub[$getUserVar[Money];$var[amount]]]
    
    $if[$var[ourNewBalance]<0]
        Error Message
    $else
        Code
    $endif
    

Pay Command

Expand Code Example (67 lines)

$nomention
$allowMention

$if[$argCount[$message]<2]
    $color[FF544C]
    $title[Payment System]
    $description[Missing Argumets! Example Command: `!pay <user> <amount> (comment)`]
    $stop
$endif

$var[target;$findUser[$message[1];no]]
$var[amount;$message[2]]
$var[comment;$trimSpace[$replaceText[$replaceText[$message;$message[1];];$message[2];]]]

$if[$var[target]==]
    $color[FF544C]
    $title[Payment System]
    $description[User (1st argument) not found on the server!]
    $stop
$endif

$if[$var[target]==$authorID]
    $color[FF544C]
    $title[Payment System]
    $description[You cannot pay yourself!]
    $stop
$endif

$if[$isNumber[$var[amount]]==false]
    $color[FF544C]
    $title[Payment System]
    $description[Amount (2nd argument) must be a number!]
    $stop
$endif

$if[$checkContains[$var[amount];.]==true]
    $color[FF544C]
    $title[Payment System]
    $description[Amount (2nd argument) must be an integer!]
    $stop
$endif

$if[$var[amount]<0]
    $color[FF544C]
    $title[Payment System]
    $description[Amount (2nd argument) cannot be less than 0!]
    $stop
$endif

$if[$var[comment]==]
    $var[comment;Not provided.]
$endif

$var[ourNewBalance;$sub[$getUserVar[Money];$var[amount]]]

$if[$var[ourNewBalance]<0]
    $color[FF544C]
    $title[Payment System]
    $description[❌ Hey <@$authorID>! What are you left with if you try to make such a payment?]
$else
    $color[7EFF88]
    $title[Payment System]
    $description[✔ You have successfully paid <@$var[target]> $var[amount] money! **Comment**: $var[comment]]

    $setUserVar[Money;$sum[$getUserVar[Money;$var[target]];$var[amount]];$var[target]]
    $setUserVar[Money;$var[ourNewBalance]]

    $if[$isUserDMEnabled[$var[target]]==true]
        $sendEmbedMessage[$dmChannelID[$var[target]];;Payment System;;Good time! <@$authorID> paid you $var[amount] money and left a comment: $var[comment];7EFF88]
    $endif
$endif

Expand Code Breakdown

  •   $if[$argCount[$message]<2]
          $color[FF544C]
          $title[Payment System]
          $description[Missing Argumets! Example Command: `!pay <user> <amount> (comment)`]
          $stop
      $endif
    

    Checks the number of arguments in the code.
    If there are less than 2 arguments, an embed error will be returned and code execution will be stopped.

  •   $var[target;$findUser[$message[1];no]]
      $var[amount;$message[2]]
      $var[comment;$trimSpace[$replaceText[$replaceText[$message;$message[1];];$message[2];]]]
      <...>
      $var[ourNewBalance;$sub[$getUserVar[Money];$var[amount]]]
    

    Argument formatting.

    •   $var[ourNewBalance;$sub[$getUserVar[Money];$var[amount]]]
      

      Calculates the our future balance after making a payment.

  •   $if[$var[target]==]
          $color[FF544C]
          $title[Payment System]
          $description[User (1st argument) not found on the server!]
          $stop
      $endif
    

    Checks if the target is present on the current server.
    If not, an embed error will be returned and code execution will be stopped.

  •   $if[$var[target]==$authorID]
          $color[FF544C]
          $title[Payment System]
          $description[You cannot pay yourself!]
          $stop
      $endif
    

    Checks if the command author is the target.
    If yes, an embed error will be returned and code execution will be stopped.

  •   $if[$isNumber[$var[amount]]==false]
          $color[FF544C]
          $title[Payment System]
          $description[Amount (2nd argument) must be a number!]
          $stop
      $endif
    

    Checks if the specified amount is a valid number.
    If not, an embed error will be returned and code execution will be stopped.

  •   $if[$checkContains[$var[amount];.]==true]
          $color[FF544C]
          $title[Payment System]
          $description[Amount (2nd argument) must be an integer!]
          $stop
      $endif
    

    Checks if the specified amount is an integer.
    If not, an embed error will be returned and code execution will be stopped.
    Exists in order to avoid payments with floating (decimal) numbers.

  •   $if[$var[amount]<0]
          $color[FF544C]
          $title[Payment System]
          $description[Amount (2nd argument) cannot be less than 0!]
          $stop
      $endif
    

    Checks if the specified amount is less than 0.
    If yes, an embed error will be returned and code execution will be stopped.

  •   $if[$var[comment]==]
          $var[comment;Not provided.]
      $endif
    

    Checks for a comment. If there is no comment (the argument is empty), «Not provided.» will be written as comment.

  •   $if[$var[ourNewBalance]<0]
          $color[FF544C]
          $title[Payment System]
          $description[❌ Hey <@$authorID>! What are you left with if you try to make such a payment?]
      $else
          $color[7EFF88]
          $title[Payment System]
          $description[✔ You have successfully paid <@$var[target]> $var[amount] money! **Comment**: $var[comment]]
    
          $setUserVar[Money;$sum[$getUserVar[Money;$var[target]];$var[amount]];$var[target]]
          $setUserVar[Money;$var[ourNewBalance]]
    
          $if[$isUserDMEnabled[$var[target]]==true]
              $sendEmbedMessage[$dmChannelID[$var[target]];;Payment System;;Good time! <@$authorID> paid you $var[amount] money and left a comment: $var[comment];7EFF88]
          $endif
      $endif
    

    The main part of the command, where:

    1. Checking whether our balance will be negative. If yes, an embed error will be returned.
    2. Changing our variable value (money withdrawal) and the target’s variable value (money replenishment).
      $setUserVar[Money;$sum[$getUserVar[Money;$var[target]];$var[amount]];$var[target]]
      $setUserVar[Money;$var[ourNewBalance]]
      
    3. Sending an embed message to the target’s DMs that we have made a payment.
      The message will be sent only if the target’s DMs are enabled.

      $if[$isUserDMEnabled[$var[target]]==true]
          $sendEmbedMessage[$dmChannelID[$var[target]];;Payment System;;Good time! <@$authorID> paid you $var[amount] money and left a comment: $var[comment];7EFF88]
      $endif
      

Expand Attachments

p-ex-1
p-ex-2
p-ex-3
p-ex-4
p-ex-5
p-ex-6

The 2nd Possible Solution
Setting the balance to 0 if the future balance becomes negative.
This solution may be suitable for gambling-related commands, if you do not want the user’s balance to become negative in case of losses.

Argument Content
1st — Bet 60

View Arguments Formatting In Code.

  • Bet
    $var[bet;$message[1]]
    

$var[ourNewBalance;$sub[$getUserVar[Money];$var[bet]]]

$if[$var[ourNewBalance]<0]
    $var[ourNewBalance;0]
$endif

Roulette Command

Expand Code Example (53 lines)

$nomention

$var[bet;$message[1]]

$if[$isNumber[$var[bet]]==false]
    $color[FF544C]
    $title[Roulette]
    $description[Bet must be a number!]
    $stop
$endif

$if[$checkContains[$var[bet];.]==true]
    $color[FF544C]
    $title[Roulette]
    $description[Bet must be an integer!]
    $stop
$endif

$if[$var[bet]>$getUserVar[Money]]
    $color[FF544C]
    $title[Roulette]
    $description[The bet cannot be higher than your balance!]
    $stop
$endif

$if[$var[bet]<0]
    $color[FF544C]
    $title[Roulette]
    $description[The bet cannot be less than 0!]
    $stop
$endif

$var[bet;$multi[$var[bet];2]]

$if[$random[1;3]==1]
    $var[ourNewBalance;$sum[$getUserVar[Money];$var[bet]]]
    
    $color[7EFF88]
    $title[Roulette]
    $description[Wow, you are lucky! You have won $var[bet]!]
$else
    $var[ourNewBalance;$sub[$getUserVar[Money];$var[bet]]]
    
    $color[FF544C]
    $title[Roulette]
    $if[$var[ourNewBalance]<0]
        $var[ourNewBalance;0]
        $description[What a pity! You lost and became bankrupt!]
    $else
        $description[What a pity! You have lost the $var[bet].]
    $endif
$endif

$setUserVar[Money;$var[ourNewBalance]]

Expand Code Breakdown

  •   $var[bet;$message[1]]
    

    Argument formatting.

  •   $if[$isNumber[$var[bet]]==false]
          $color[FF544C]
          $title[Roulette]
          $description[Bet must be a number!]
          $stop
      $endif
    

    Checks if the bet is a valid number.
    If not, an embed error will be returned and code execution will be stopped.

  •   $if[$checkContains[$var[bet];.]==true]
          $color[FF544C]
          $title[Roulette]
          $description[Bet must be an integer!]
          $stop
      $endif
    

    Checks if the bet is an integer.
    If not, an embed error will be returned and code execution will be stopped.
    Exists in order to avoid bets with floating (decimal) numbers.

  •   $if[$var[bet]>$getUserVar[Money]]
          $color[FF544C]
          $title[Roulette]
          $description[The bet cannot be higher than your balance!]
          $stop
      $endif
    

    Checks if the bet is higher than our balance.
    If yes, an embed error will be returned and code execution will be stopped.

  •   $if[$var[bet]<0]
          $color[FF544C]
          $title[Roulette]
          $description[The bet cannot be less than 0!]
          $stop
      $endif
    

    Checks if the bet is less than 0.
    If yes, an embed error will be returned and code execution will be stopped.

  •   $if[$random[1;3]==1]
          $var[ourNewBalance;$sum[$getUserVar[Money];$var[bet]]]
          <...>
      $else
          $var[ourNewBalance;$sub[$getUserVar[Money];$var[bet]]]
          <...>
          $if[$var[ourNewBalance]<0]
              $var[ourNewBalance;0]
              <...>
          $else
              <...>
          $endif
      $endif
    
      $setUserVar[Money;$var[ourNewBalance]]
    

    Manages roulette results. If $random[1;3] equals 1, then we win and the bet is added to the balance in the doubled amount. Otherwise, the bet will be taken away from the balance in doubled amount.
    If the future balance in case of loss will be negative, it will be set to 0.

Expand Attachments

r-ex-1
r-ex-2
r-ex-3

Desynchronized Balance

The Balance Is Different On Different Servers

This is because you’re probably using $setUserVar and $getUserVar in your economy. But these functions are based as local variables. Their values are unique for each server.
If you want the same balance on all servers, you should use $setVar and $getVar (with userID arguments). These functions are based on global user variables.

The Displayed Balance Is Different For Different Commands

Most often this is because you’ve mixed up the variable functions and you’re using the wrong variable type.
For example, if you use $setUserVar and $getUserVar in the Roulette command and $getVar in the Balance command, this will show different values. The solution to this is to replace $getVar with $getUserVar in the Balance command, or vice versa, replace $setUserVar and $getUserVar with $setVar and $getVar accordingly in the Roulette command.
Note: don’t forget that global user variables require a userID argument.


Leaderboards

The Leaderboard Is Empty

The 1st Reason
You’ve chosen the wrong leaderboard function.

  • If you’re using the $setUserVar/$getUserVar functions, you should use the $userLeaderboard function.
  • If in your’re using the $setVar/$getVar functions, you should use the $globalUserLeaderboard function.
  • If you’re using the $setServerVar/$getServerVar functions, you should use the $serverLeaderboard function.

The 2nd Reason
(In case you are using the $getLeaderboardValue function)
You specified the wrong variable type.

  • If you’re using the $setUserVar/$getUserVar functions, you should specify the user as type.
  • If in your’re using the $setVar/$getVar functions, you should specify the globalUser as type.
  • If you’re using the $setServerVar/$getServerVar functions, you should specify the server as type.

The 3rd Reason
The leaderboard haven’t generated yet.
Sometimes it takes a while to generate the leaderboard.

The User’s Value Isn’t Updated

As with the generation of the leaderboard, updating it can also take a while.
This can be mainly due to the fact that the leaderboard has a large database (i.e. the total number of users with a modified variable value other than the default).


Bot Issues

The Bot Is Offline

The 1st Reason
The node is restarting. While the node is restarting, logically, the bot can’t work.
Usually restarting doesn’t take more than 5-10 minutes.
So please wait a while and have a cup of tea or coffee while the node restarts.

The 2nd Reason
For some reason, your bot’s token is no longer valid or the BDFD app thinks so.
You can solve this problem by regenerating your bot’s token on the developer portal and then replacing the old token with the new one in the BDFD app bot’s Settings tab.

The 3rd Reason
Not a common problem, but possible. The node your bot is running on is experiencing problems.
In this case, join the support server, create a ticket using the !new command and tell the staff your bot’s ID and node number, if you know it (node number can be found out using the $botNode function when your bot is online).
The staff will inform the developers of the current problems, providing the scale of the problem (affected bots and/or nodes).
Please don’t regenerate your bot token in this case, as it leads to node change. If everyone starts changing their node because there is a problem on that node, then a healthy node can also be affected by this problem.

The Bot Doesn’t Respond

The 1st Reason
If your bot is based on text commands and you don’t have the Message Content Intent enabled.
You must enable it in your bot’s settings to use text commands.
Read the Gateway Intents Guide for more details.

The 2nd Reason
Your bot doesn’t have the necessary permissions.
In order for your bot to respond correctly to a command, it must have permissions for Send Messages, Embed Links (if your code has embed functions), and Read Messages in order for the bot to have access to the channel.

The Bot Goes Offline From Time To Time

This is due to the fact that nodes are restarted from time to time to maintain the stable operation of all the bots that also work on this node.

Desynchronization of Commands

Desynchronization of commands means, for example, that you have deleted a command but the bot still responds to it (aka. Ghost Command), or you see different code of your command in the web app and another in the mobile app.

Ghost Command

Not many people encounter this problem, but it’s still worth mentioning.
This problem is related to database synchronization (between your application data and your bot’s data in the database).
Solution Options
The 1st Solution
Restart the app.
Close the app from Recent apps and reopen it. This may result in a deleted command reappearing due to desync with the database. You can just delete that command again.

The 2nd Solution
Attempting to forcibly restart the bot.
You can do this in the settings of your bot in the app. Restarting the bot can send a retransfer of data from the application to the database, and then the deleted command will be deleted for real.

The Solution Options Didn’t Help
In this case, join the support server, create a ticket using the !new command and tell the staff your bot’s ID.
The staff will mention one of the developers to take a look at this problem with your bot.

The Bot Takes A Long Time To Respond

The 1st Reason
Your code is too long and/or complicated.
This may be the obvious reason if it is. Executing large and complex code takes more resources.
When writing code, you should think about how to make it more compact and less complex, but in a way that makes your idea come to fruition.

The 2nd Reason
Your bot was rate limited. This can happen because of excessive requests to Discord API, performed by BDFD functions (such as $addEmoji and others).
You should not stack such functions and try to perform them all at once.

The 3rd Reason
The node your bot is running on is experiencing some slight problems (such as a rate limits). If you’re sure this is the case, you can regenerate the bot’s token and replace it with a new one. This will cause your bot to change its node.

The Slash Commands Doesn’t Appear

The 1st Reason
Old version of the application. Make sure that you have a latest version of the application installed.
New versions of the application have been improved and updated, and new features have been added. In addition, errors with the validity check of the slash commands have been fixed. You will be warned if you set up your slash command incorrectly, in which case the application will not allow you to save the slash command.

The 2nd Reason
Slash commands are cached by discord, so it takes time before they appear in discord.

They’re also cached on the client side, if they were successfully cached in discord. If other users have a new slash command and you don’t, restart the discord client.
Restarting will cause existing slash commands to be cleared and new ones will cache.

The 3rd Reason
Conflict of slash commands due to other services that you’re no longer using. For example, if two slash commands of same type have the same name, but one is created using a third-party service, and the other through the BDFD, this can cause a conflict and the slash command will not appear.
You can solve this problem by Syncing slash commands with discord in the bot’s settings. This removes third-party service slash commands and leaves only those that were created in our application.

sync

Integration Requires Code Grant

You can only get this error when trying to invite a bot to any server.
Most likely, you have accidentally or unknowingly enabled the Require OAuth2 Code Grant option in your bot’s settings in the developer portal.
This is the reason why you get this error.

This option is required only for applications with scopes such as identify, email, and others to work with the user account in Discord. But BDFD doesn’t have such support, so you should not enable this option or choose any other scopes other than bot and application.commands.


App Issues

The Ad Button Doesn’t Work

The 1st Reason
Unstable Internet connection. Make sure your Internet connection is stable and not too slow, because you have to load the ad first to watch it. This is why you see «Loading ad…».

The 2nd Reason
There’re no more ads for you. If that’s the reason, there’s nothing we can do about it, it’s the provider who provides the ads, not us. Try to see the ad later. If the case persists, go to support server, create a ticket using the !new command and inform the staff about your problem by providing a screen recording longer than 30 seconds.

The 3nd Reason
The advertising provider we use is blocked in your country or region. There is nothing we can do in this case.

Possible Solutions

  1. Clearing the application cache and restarting it.
  2. Using VPN services. This may be the best solution for the 2nd and 3rd reasons, and in some cases for the 1st reason.
  3. In a desperate case, restart the smartphone and/or reinstall the app.

    If you decide to reinstall the app, make sure that you are logged in to the app, otherwise you will lose access to your bots.

Ghost Functions From The Changelog

In this section, the easiest way to explain everything is through dialogue:

  • Random Guy: I was told by a friend that a new function, $botOwnerID, has just been added to the changelog or recently. I’m trying to use it, but it just doesn’t work. What I mean is:
    I5dLLUVB
  • Shiro: This is normal. Right, the function has already been added and exists, but it can’t be used at the moment. The nodes (the place where your bots work) have not yet been updated, or your exact node has not yet been updated. The update will slowly be released to each node over time. It isn’t released to all nodes at once for the purpose of testing the stability and performance of the update.
  • Shiro: Usually, all nodes are updated by the end of the month.
  • Random Guy: Allright, thank you! I will wait patiently!
  • Shiro: You’re welcome, Random Guy.

The Translation Feature Doesn’t Work

The 1st Reason
There’s no translation support for your language yet. You should wait patiently for them, or if you speak English well, you can help to translate our app yourself!
If you would like to help, go to our support server and create a ticket (using the !new command). You can then apply for the Translator role there by asking support for it.

The 2nd Reason
Your main system language is incorrect.
Our app uses the main system language for translations and it disregards any secondary languages.
So, for example, if you have English as your main system language and Russian as your second system language, the app will stay in English.

In order to have the app in Russian, you should reorder your language settings and set Russian as the main one.


That’s Where The List Of Troubleshootings Ends

If you know of other problems that users often encounter or have suggestions, feel free to let us know on the support server or by contributing!

Troubleshooting

This page contains a number of troubleshooting that can help you to solve problems that BDFD users often encounter.

Summary

Troubleshooting for…

  1. $onJoined[]
    • The Callback Doesn’t Work
  2. Moderation And Server Management Related Commands
    • The Bot Can’t Assign Or Take Roles
    • Gives an Error When Trying To Moderate a Member
    • Gives an Error When Trying To Purge Messages
  3. $addReactions and $addCmdReactions
    • The Bot Fails To Add Reactions
  4. $time
    • The Function Returns an Error
  5. Economy Related Commands
    • Negative Balance
      • Pay Command
      • Roulette Command
    • Desynchronized Balance
      • The Balance Is Different On Different Servers
      • The Displayed Balance Is Different For Different Commands
  6. Leaderboards
    • The Leaderboard Is Empty
    • The User’s Value Isn’t Updated
  7. Bot Issues
    • The Bot Is Offline
    • The Bot Doesn’t Respond
    • The Bot Goes Offline From Time To Time
    • Desynchronization of Commands
      • Ghost Command
    • The Bot Takes A Long Time To Respond
    • The Slash Commands Doesn’t Appear
    • Integration Requires Code Grant
  8. App Issues
    • The Ad Button Doesn’t Work
    • Ghost Functions From The Changelog
    • The Translation Feature Doesn’t Work

Let’s Troubleshoot Everything!


$onJoined[]

The Callback Doesn’t Work

The Null Reason
You misspelled the callback name. Make sure you don’t make any mistakes in the callback name.
Also, remember that callbacks are case-sensitive: you can’t write $onjoined[Channel ID], you must write $onJoined[Channel ID].

The 1st Reason
You specified the wrong Channel ID.
How to get the Channel ID correctly:

For Desktop

Before starting, make sure you have Developer Mode enabled on Discord.

dev-desktop

id-desktop

For Mobile

Before starting, make sure you have Developer Mode enabled on Discord.

dev-mobile

id-mobile

Using a Function

Using the $channelID, $mentionedChannels or $findChannel functions, you can get the Channel ID of the desired channel.
Check out these functions:

  1. $channelID
  2. $mentionedChannels
  3. $findChannel

The 2nd Reason
Your bot doesn’t have the sendmessages and/or the embedlinks permission that allow the bot to send messages (or embed messages) in a given channel.
Best Practice Solution
Grant both of these permissions to the bot in the desired channel through the channel’s permissions settings:

edit-channel
perms
add
search
message
embed
save

The 3rd Reason
There’s a critical error in your code.
Callbacks can’t return errors that occurred during code execution.
Therefore, sometimes it’s difficult to solve errors in the callback code.
Best Practice Solution
Try debugging your command as a text command. In most cases, they’re backward compatible with the $onJoined callback, since both, by default, process the actions of the command author (when a user joins the server, this user becomes the «author» of this callback).

The 4th Reason
Members Intent isn’t enabled.
This callback requires the Members Intent to be enabled.

Read the Gateway Intents Guide for more details.

The 5th Reason
You have several commands with this callback.
You can only have one command with this callback. If you want to make a unique welcome message for multiple servers instead of just one, then check out Per-Server $onJoined.


The Bot Can’t Assign Or Take Roles

The 1st Reason
Your bot doesn’t have the manageroles permission.
Make sure that one of the roles that the bot has, has this permission enabled.

perm-mroles

The 2nd Reason
You are trying to assign or take roles that are higher than the highest role your bot has.

Gives an Error When Trying To Moderate a Member

The 1st Reason
Your bot has lower priority than the specified user.
This means that the highest role your bot has is lower in position than the highest role the specified user has.
Or, the specified user is the owner of the server.

The 2nd Reason
Your bot doesn’t have the required permissions.
Make sure that the permission list of any role that the bot has, have these required permissions.

Gives an Error When Trying To Purge Messages

The 1st Reason
Your bot doesn’t have the managemessages permission.
Make sure that one of the roles that the bot has, has this permission enabled.

perm-mmesages

The 2nd Reason
You are trying to purge messages that have been around for more than two weeks.
BDFD uses a bulk request to purge messages, and it can’t process messages that are more than two weeks old.


$addReactions and $addCmdReactions

The Bot Fails To Add Reactions

The 1st Reason
The user has blocked the bot, so the bot can’t react to the user’s messages. This works exactly the same if the user has blocked another user.

The 2nd Reason
You’re specifying the emoji in the function argument incorrectly.

  • Default emojis.
    - $addCmdReactions[:joy:]
    + $addCmdReactions[😂]
    
  • Custom emojis.
    - $addCmdReactions[:pikachu:]
    - $addCmdReactions[:pikachu:]
    + $addCmdReactions[<:pikachu:951437967711420456>]
    

    You must use the Emoji ID form of the desired emoji.

The 3rd Reason
Case with custom emojis.
Your bot must share a server with the specified emoji in order to use it. It works like Discord Nitro.


$time

The Function Returns an Error

The 1st Reason
Incorrect use of the function. The function doesn’t return the current time or anything like that.
The function’s role is to change the timezone for time-related functions (such as $day, $hour, and so on)

The 2nd Reason
Incorrect time zone or incorrect time zone format.
BDFD uses the official IANA time zone database for time zone information.
Please use the TZ Database name from this list in the $time function.

- $time[America]
- $time[New_York]
+ $time[America/New_York]

  • This part will have fully working and quality code examples that you can use in your bot.
  • In this part, examples and more will be based on the local economy and BDScript 2.
Variable Name Default Variable Value Our Variable Value Target’s Variable Value
Money 0 100 120

Negative Balance

The 1st Possible Solution
Adding limiters or if statements that will prevent actions in which the executor’s or target’s balance becomes negative.
This solution can be an alternative to «Prevent actions when the amount is greater than the user’s balance».

Argument Content
1st — Target Afternoon
2nd — Amount 50
3rd — Comment Happy Birthday!

View Arguments Formatting In Code.

  • Target
    $var[target;$findUser[$message[1];no]]
    
  • Amount
    $var[amount;$message[2]]
    
  • Comment
    $var[comment;$trimSpace[$replaceText[$replaceText[$message;$message[1];];$message[2];]]]
    
  • Limiters Method
    $var[ourNewBalance;$sub[$getUserVar[Money];$var[amount]]]
    
    $onlyIf[$var[ourNewBalance]>0;Error Message]
    
  • If Statements Method
    $var[ourNewBalance;$sub[$getUserVar[Money];$var[amount]]]
    
    $if[$var[ourNewBalance]<0]
        Error Message
    $else
        Code
    $endif
    

Pay Command

Expand Code Example (67 lines)

$nomention
$allowMention

$if[$argCount[$message]<2]
    $color[FF544C]
    $title[Payment System]
    $description[Missing Argumets! Example Command: `!pay <user> <amount> (comment)`]
    $stop
$endif

$var[target;$findUser[$message[1];no]]
$var[amount;$message[2]]
$var[comment;$trimSpace[$replaceText[$replaceText[$message;$message[1];];$message[2];]]]

$if[$var[target]==]
    $color[FF544C]
    $title[Payment System]
    $description[User (1st argument) not found on the server!]
    $stop
$endif

$if[$var[target]==$authorID]
    $color[FF544C]
    $title[Payment System]
    $description[You cannot pay yourself!]
    $stop
$endif

$if[$isNumber[$var[amount]]==false]
    $color[FF544C]
    $title[Payment System]
    $description[Amount (2nd argument) must be a number!]
    $stop
$endif

$if[$checkContains[$var[amount];.]==true]
    $color[FF544C]
    $title[Payment System]
    $description[Amount (2nd argument) must be an integer!]
    $stop
$endif

$if[$var[amount]<0]
    $color[FF544C]
    $title[Payment System]
    $description[Amount (2nd argument) cannot be less than 0!]
    $stop
$endif

$if[$var[comment]==]
    $var[comment;Not provided.]
$endif

$var[ourNewBalance;$sub[$getUserVar[Money];$var[amount]]]

$if[$var[ourNewBalance]<0]
    $color[FF544C]
    $title[Payment System]
    $description[❌ Hey <@$authorID>! What are you left with if you try to make such a payment?]
$else
    $color[7EFF88]
    $title[Payment System]
    $description[✔ You have successfully paid <@$var[target]> $var[amount] money! **Comment**: $var[comment]]

    $setUserVar[Money;$sum[$getUserVar[Money;$var[target]];$var[amount]];$var[target]]
    $setUserVar[Money;$var[ourNewBalance]]

    $if[$isUserDMEnabled[$var[target]]==true]
        $sendEmbedMessage[$dmChannelID[$var[target]];;Payment System;;Good time! <@$authorID> paid you $var[amount] money and left a comment: $var[comment];7EFF88]
    $endif
$endif

Expand Code Breakdown

  •   $if[$argCount[$message]<2]
          $color[FF544C]
          $title[Payment System]
          $description[Missing Argumets! Example Command: `!pay <user> <amount> (comment)`]
          $stop
      $endif
    

    Checks the number of arguments in the code.
    If there are less than 2 arguments, an embed error will be returned and code execution will be stopped.

  •   $var[target;$findUser[$message[1];no]]
      $var[amount;$message[2]]
      $var[comment;$trimSpace[$replaceText[$replaceText[$message;$message[1];];$message[2];]]]
      <...>
      $var[ourNewBalance;$sub[$getUserVar[Money];$var[amount]]]
    

    Argument formatting.

    •   $var[ourNewBalance;$sub[$getUserVar[Money];$var[amount]]]
      

      Calculates the our future balance after making a payment.

  •   $if[$var[target]==]
          $color[FF544C]
          $title[Payment System]
          $description[User (1st argument) not found on the server!]
          $stop
      $endif
    

    Checks if the target is present on the current server.
    If not, an embed error will be returned and code execution will be stopped.

  •   $if[$var[target]==$authorID]
          $color[FF544C]
          $title[Payment System]
          $description[You cannot pay yourself!]
          $stop
      $endif
    

    Checks if the command author is the target.
    If yes, an embed error will be returned and code execution will be stopped.

  •   $if[$isNumber[$var[amount]]==false]
          $color[FF544C]
          $title[Payment System]
          $description[Amount (2nd argument) must be a number!]
          $stop
      $endif
    

    Checks if the specified amount is a valid number.
    If not, an embed error will be returned and code execution will be stopped.

  •   $if[$checkContains[$var[amount];.]==true]
          $color[FF544C]
          $title[Payment System]
          $description[Amount (2nd argument) must be an integer!]
          $stop
      $endif
    

    Checks if the specified amount is an integer.
    If not, an embed error will be returned and code execution will be stopped.
    Exists in order to avoid payments with floating (decimal) numbers.

  •   $if[$var[amount]<0]
          $color[FF544C]
          $title[Payment System]
          $description[Amount (2nd argument) cannot be less than 0!]
          $stop
      $endif
    

    Checks if the specified amount is less than 0.
    If yes, an embed error will be returned and code execution will be stopped.

  •   $if[$var[comment]==]
          $var[comment;Not provided.]
      $endif
    

    Checks for a comment. If there is no comment (the argument is empty), «Not provided.» will be written as comment.

  •   $if[$var[ourNewBalance]<0]
          $color[FF544C]
          $title[Payment System]
          $description[❌ Hey <@$authorID>! What are you left with if you try to make such a payment?]
      $else
          $color[7EFF88]
          $title[Payment System]
          $description[✔ You have successfully paid <@$var[target]> $var[amount] money! **Comment**: $var[comment]]
    
          $setUserVar[Money;$sum[$getUserVar[Money;$var[target]];$var[amount]];$var[target]]
          $setUserVar[Money;$var[ourNewBalance]]
    
          $if[$isUserDMEnabled[$var[target]]==true]
              $sendEmbedMessage[$dmChannelID[$var[target]];;Payment System;;Good time! <@$authorID> paid you $var[amount] money and left a comment: $var[comment];7EFF88]
          $endif
      $endif
    

    The main part of the command, where:

    1. Checking whether our balance will be negative. If yes, an embed error will be returned.
    2. Changing our variable value (money withdrawal) and the target’s variable value (money replenishment).
      $setUserVar[Money;$sum[$getUserVar[Money;$var[target]];$var[amount]];$var[target]]
      $setUserVar[Money;$var[ourNewBalance]]
      
    3. Sending an embed message to the target’s DMs that we have made a payment.
      The message will be sent only if the target’s DMs are enabled.

      $if[$isUserDMEnabled[$var[target]]==true]
          $sendEmbedMessage[$dmChannelID[$var[target]];;Payment System;;Good time! <@$authorID> paid you $var[amount] money and left a comment: $var[comment];7EFF88]
      $endif
      

Expand Attachments

p-ex-1
p-ex-2
p-ex-3
p-ex-4
p-ex-5
p-ex-6

The 2nd Possible Solution
Setting the balance to 0 if the future balance becomes negative.
This solution may be suitable for gambling-related commands, if you do not want the user’s balance to become negative in case of losses.

Argument Content
1st — Bet 60

View Arguments Formatting In Code.

  • Bet
    $var[bet;$message[1]]
    
$var[ourNewBalance;$sub[$getUserVar[Money];$var[bet]]]

$if[$var[ourNewBalance]<0]
    $var[ourNewBalance;0]
$endif

Roulette Command

Expand Code Example (53 lines)

$nomention

$var[bet;$message[1]]

$if[$isNumber[$var[bet]]==false]
    $color[FF544C]
    $title[Roulette]
    $description[Bet must be a number!]
    $stop
$endif

$if[$checkContains[$var[bet];.]==true]
    $color[FF544C]
    $title[Roulette]
    $description[Bet must be an integer!]
    $stop
$endif

$if[$var[bet]>$getUserVar[Money]]
    $color[FF544C]
    $title[Roulette]
    $description[The bet cannot be higher than your balance!]
    $stop
$endif

$if[$var[bet]<0]
    $color[FF544C]
    $title[Roulette]
    $description[The bet cannot be less than 0!]
    $stop
$endif

$var[bet;$multi[$var[bet];2]]

$if[$random[1;3]==1]
    $var[ourNewBalance;$sum[$getUserVar[Money];$var[bet]]]
    
    $color[7EFF88]
    $title[Roulette]
    $description[Wow, you are lucky! You have won $var[bet]!]
$else
    $var[ourNewBalance;$sub[$getUserVar[Money];$var[bet]]]
    
    $color[FF544C]
    $title[Roulette]
    $if[$var[ourNewBalance]<0]
        $var[ourNewBalance;0]
        $description[What a pity! You lost and became bankrupt!]
    $else
        $description[What a pity! You have lost the $var[bet].]
    $endif
$endif

$setUserVar[Money;$var[ourNewBalance]]

Expand Code Breakdown

  •   $var[bet;$message[1]]
    

    Argument formatting.

  •   $if[$isNumber[$var[bet]]==false]
          $color[FF544C]
          $title[Roulette]
          $description[Bet must be a number!]
          $stop
      $endif
    

    Checks if the bet is a valid number.
    If not, an embed error will be returned and code execution will be stopped.

  •   $if[$checkContains[$var[bet];.]==true]
          $color[FF544C]
          $title[Roulette]
          $description[Bet must be an integer!]
          $stop
      $endif
    

    Checks if the bet is an integer.
    If not, an embed error will be returned and code execution will be stopped.
    Exists in order to avoid bets with floating (decimal) numbers.

  •   $if[$var[bet]>$getUserVar[Money]]
          $color[FF544C]
          $title[Roulette]
          $description[The bet cannot be higher than your balance!]
          $stop
      $endif
    

    Checks if the bet is higher than our balance.
    If yes, an embed error will be returned and code execution will be stopped.

  •   $if[$var[bet]<0]
          $color[FF544C]
          $title[Roulette]
          $description[The bet cannot be less than 0!]
          $stop
      $endif
    

    Checks if the bet is less than 0.
    If yes, an embed error will be returned and code execution will be stopped.

  •   $if[$random[1;3]==1]
          $var[ourNewBalance;$sum[$getUserVar[Money];$var[bet]]]
          <...>
      $else
          $var[ourNewBalance;$sub[$getUserVar[Money];$var[bet]]]
          <...>
          $if[$var[ourNewBalance]<0]
              $var[ourNewBalance;0]
              <...>
          $else
              <...>
          $endif
      $endif
    
      $setUserVar[Money;$var[ourNewBalance]]
    

    Manages roulette results. If $random[1;3] equals 1, then we win and the bet is added to the balance in the doubled amount. Otherwise, the bet will be taken away from the balance in doubled amount.
    If the future balance in case of loss will be negative, it will be set to 0.

Expand Attachments

r-ex-1
r-ex-2
r-ex-3

Desynchronized Balance

The Balance Is Different On Different Servers

This is because you’re probably using $setUserVar and $getUserVar in your economy. But these functions are based as local variables. Their values are unique for each server.
If you want the same balance on all servers, you should use $setVar and $getVar (with userID arguments). These functions are based on global user variables.

The Displayed Balance Is Different For Different Commands

Most often this is because you’ve mixed up the variable functions and you’re using the wrong variable type.
For example, if you use $setUserVar and $getUserVar in the Roulette command and $getVar in the Balance command, this will show different values. The solution to this is to replace $getVar with $getUserVar in the Balance command, or vice versa, replace $setUserVar and $getUserVar with $setVar and $getVar accordingly in the Roulette command.
Note: don’t forget that global user variables require a userID argument.


Leaderboards

The Leaderboard Is Empty

The 1st Reason
You’ve chosen the wrong leaderboard function.

  • If you’re using the $setUserVar/$getUserVar functions, you should use the $userLeaderboard function.
  • If in your’re using the $setVar/$getVar functions, you should use the $globalUserLeaderboard function.
  • If you’re using the $setServerVar/$getServerVar functions, you should use the $serverLeaderboard function.

The 2nd Reason
(In case you are using the $getLeaderboardValue function)
You specified the wrong variable type.

  • If you’re using the $setUserVar/$getUserVar functions, you should specify the user as type.
  • If in your’re using the $setVar/$getVar functions, you should specify the globalUser as type.
  • If you’re using the $setServerVar/$getServerVar functions, you should specify the server as type.

The 3rd Reason
The leaderboard haven’t generated yet.
Sometimes it takes a while to generate the leaderboard.

The User’s Value Isn’t Updated

As with the generation of the leaderboard, updating it can also take a while.
This can be mainly due to the fact that the leaderboard has a large database (i.e. the total number of users with a modified variable value other than the default).


Bot Issues

The Bot Is Offline

The 1st Reason
The node is restarting. While the node is restarting, logically, the bot can’t work.
Usually restarting doesn’t take more than 5-10 minutes.
So please wait a while and have a cup of tea or coffee while the node restarts.

The 2nd Reason
For some reason, your bot’s token is no longer valid or the BDFD app thinks so.
You can solve this problem by regenerating your bot’s token on the developer portal and then replacing the old token with the new one in the BDFD app bot’s Settings tab.

The 3rd Reason
Not a common problem, but possible. The node your bot is running on is experiencing problems.
In this case, join the support server, create a ticket using the !new command and tell the staff your bot’s ID and node number, if you know it (node number can be found out using the $botNode function when your bot is online).
The staff will inform the developers of the current problems, providing the scale of the problem (affected bots and/or nodes).
Please don’t regenerate your bot token in this case, as it leads to node change. If everyone starts changing their node because there is a problem on that node, then a healthy node can also be affected by this problem.

The Bot Doesn’t Respond

The 1st Reason
If your bot is based on text commands and you don’t have the Message Content Intent enabled.
You must enable it in your bot’s settings to use text commands.
Read the Gateway Intents Guide for more details.

The 2nd Reason
Your bot doesn’t have the necessary permissions.
In order for your bot to respond correctly to a command, it must have permissions for Send Messages, Embed Links (if your code has embed functions), and Read Messages in order for the bot to have access to the channel.

The Bot Goes Offline From Time To Time

This is due to the fact that nodes are restarted from time to time to maintain the stable operation of all the bots that also work on this node.

Desynchronization of Commands

Desynchronization of commands means, for example, that you have deleted a command but the bot still responds to it (aka. Ghost Command), or you see different code of your command in the web app and another in the mobile app.

Ghost Command

Not many people encounter this problem, but it’s still worth mentioning.
This problem is related to database synchronization (between your application data and your bot’s data in the database).
Solution Options
The 1st Solution
Restart the app.
Close the app from Recent apps and reopen it. This may result in a deleted command reappearing due to desync with the database. You can just delete that command again.

The 2nd Solution
Attempting to forcibly restart the bot.
You can do this in the settings of your bot in the app. Restarting the bot can send a retransfer of data from the application to the database, and then the deleted command will be deleted for real.

The Solution Options Didn’t Help
In this case, join the support server, create a ticket using the !new command and tell the staff your bot’s ID.
The staff will mention one of the developers to take a look at this problem with your bot.

The Bot Takes A Long Time To Respond

The 1st Reason
Your code is too long and/or complicated.
This may be the obvious reason if it is. Executing large and complex code takes more resources.
When writing code, you should think about how to make it more compact and less complex, but in a way that makes your idea come to fruition.

The 2nd Reason
Your bot was rate limited. This can happen because of excessive requests to Discord API, performed by BDFD functions (such as $addEmoji and others).
You should not stack such functions and try to perform them all at once.

The 3rd Reason
The node your bot is running on is experiencing some slight problems (such as a rate limits). If you’re sure this is the case, you can regenerate the bot’s token and replace it with a new one. This will cause your bot to change its node.

The Slash Commands Doesn’t Appear

The 1st Reason
Old version of the application. Make sure that you have a latest version of the application installed.
New versions of the application have been improved and updated, and new features have been added. In addition, errors with the validity check of the slash commands have been fixed. You will be warned if you set up your slash command incorrectly, in which case the application will not allow you to save the slash command.

The 2nd Reason
Slash commands are cached by discord, so it takes time before they appear in discord.

They’re also cached on the client side, if they were successfully cached in discord. If other users have a new slash command and you don’t, restart the discord client.
Restarting will cause existing slash commands to be cleared and new ones will cache.

The 3rd Reason
Conflict of slash commands due to other services that you’re no longer using. For example, if two slash commands of same type have the same name, but one is created using a third-party service, and the other through the BDFD, this can cause a conflict and the slash command will not appear.
You can solve this problem by Syncing slash commands with discord in the bot’s settings. This removes third-party service slash commands and leaves only those that were created in our application.

sync

Integration Requires Code Grant

You can only get this error when trying to invite a bot to any server.
Most likely, you have accidentally or unknowingly enabled the Require OAuth2 Code Grant option in your bot’s settings in the developer portal.
This is the reason why you get this error.

This option is required only for applications with scopes such as identify, email, and others to work with the user account in Discord. But BDFD doesn’t have such support, so you should not enable this option or choose any other scopes other than bot and application.commands.


App Issues

The Ad Button Doesn’t Work

The 1st Reason
Unstable Internet connection. Make sure your Internet connection is stable and not too slow, because you have to load the ad first to watch it. This is why you see «Loading ad…».

The 2nd Reason
There’re no more ads for you. If that’s the reason, there’s nothing we can do about it, it’s the provider who provides the ads, not us. Try to see the ad later. If the case persists, go to support server, create a ticket using the !new command and inform the staff about your problem by providing a screen recording longer than 30 seconds.

The 3nd Reason
The advertising provider we use is blocked in your country or region. There is nothing we can do in this case.

Possible Solutions

  1. Clearing the application cache and restarting it.
  2. Using VPN services. This may be the best solution for the 2nd and 3rd reasons, and in some cases for the 1st reason.
  3. In a desperate case, restart the smartphone and/or reinstall the app.

    If you decide to reinstall the app, make sure that you are logged in to the app, otherwise you will lose access to your bots.

Ghost Functions From The Changelog

In this section, the easiest way to explain everything is through dialogue:

  • Random Guy: I was told by a friend that a new function, $botOwnerID, has just been added to the changelog or recently. I’m trying to use it, but it just doesn’t work. What I mean is:
    I5dLLUVB
  • Shiro: This is normal. Right, the function has already been added and exists, but it can’t be used at the moment. The nodes (the place where your bots work) have not yet been updated, or your exact node has not yet been updated. The update will slowly be released to each node over time. It isn’t released to all nodes at once for the purpose of testing the stability and performance of the update.
  • Shiro: Usually, all nodes are updated by the end of the month.
  • Random Guy: Allright, thank you! I will wait patiently!
  • Shiro: You’re welcome, Random Guy.

The Translation Feature Doesn’t Work

The 1st Reason
There’s no translation support for your language yet. You should wait patiently for them, or if you speak English well, you can help to translate our app yourself!
If you would like to help, go to our support server and create a ticket (using the !new command). You can then apply for the Translator role there by asking support for it.

The 2nd Reason
Your main system language is incorrect.
Our app uses the main system language for translations and it disregards any secondary languages.
So, for example, if you have English as your main system language and Russian as your second system language, the app will stay in English.

In order to have the app in Russian, you should reorder your language settings and set Russian as the main one.


That’s Where The List Of Troubleshootings Ends

If you know of other problems that users often encounter or have suggestions, feel free to let us know on the support server or by contributing!

Понравилась статья? Поделить с друзьями:

Интересное по теме:

  • Integer overflow txd workshop ошибка как исправить
  • Integer expression expected ошибка bash
  • Intel extreme tuning utility ошибка 0x80070643
  • Intel extreme tuning utility выдает ошибку
  • Integ unit mode subaru ошибка

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

    ;-) :| :x :twisted: :smile: :shock: :sad: :roll: :razz: :oops: :o :mrgreen: :lol: :idea: :grin: :evil: :cry: :cool: :arrow: :???: :?: :!: