GithubHelp home page GithubHelp logo

discord-example-app's Introduction

Getting Started app for Discord

This project contains a basic rock-paper-scissors-style Discord app written in JavaScript, built for the getting started guide.

Demo of app

Project structure

Below is a basic overview of the project structure:

├── examples    -> short, feature-specific sample apps
│   ├── app.js  -> finished app.js code
│   ├── button.js
│   ├── command.js
│   ├── modal.js
│   ├── selectMenu.js
├── .env.sample -> sample .env file
├── app.js      -> main entrypoint for app
├── commands.js -> slash command payloads + helpers
├── game.js     -> logic specific to RPS
├── utils.js    -> utility functions and enums
├── package.json
├── README.md
└── .gitignore

Running app locally

Before you start, you'll need to install NodeJS and create a Discord app with the proper permissions:

  • applications.commands
  • bot (with Send Messages enabled)

Configuring the app is covered in detail in the getting started guide.

Setup project

First clone the project:

git clone https://github.com/discord/discord-example-app.git

Then navigate to its directory and install dependencies:

cd discord-example-app
npm install

Get app credentials

Fetch the credentials from your app's settings and add them to a .env file (see .env.sample for an example). You'll need your app ID (APP_ID), bot token (DISCORD_TOKEN), and public key (PUBLIC_KEY).

Fetching credentials is covered in detail in the getting started guide.

🔑 Environment variables can be added to the .env file in Glitch or when developing locally, and in the Secrets tab in Replit (the lock icon on the left).

Install slash commands

The commands for the example app are set up in commands.js. All of the commands in the ALL_COMMANDS array at the bottom of commands.js will be installed when you run the register command configured in package.json:

npm run register

Run the app

After your credentials are added, go ahead and run the app:

node app.js

⚙️ A package like nodemon, which watches for local changes and restarts your app, may be helpful while locally developing.

If you aren't following the getting started guide, you can move the contents of examples/app.js (the finished app.js file) to the top-level app.js.

Set up interactivity

The project needs a public endpoint where Discord can send requests. To develop and test locally, you can use something like ngrok to tunnel HTTP traffic.

Install ngrok if you haven't already, then start listening on port 3000:

ngrok http 3000

You should see your connection open:

Tunnel Status                 online
Version                       2.0/2.0
Web Interface                 http://127.0.0.1:4040
Forwarding                    https://1234-someurl.ngrok.io -> localhost:3000

Connections                  ttl     opn     rt1     rt5     p50     p90
                              0       0       0.00    0.00    0.00    0.00

Copy the forwarding address that starts with https, in this case https://1234-someurl.ngrok.io, then go to your app's settings.

On the General Information tab, there will be an Interactions Endpoint URL. Paste your ngrok address there, and append /interactions to it (https://1234-someurl.ngrok.io/interactions in the example).

Click Save Changes, and your app should be ready to run 🚀

Other resources

  • Read the documentation for in-depth information about API features.
  • Browse the examples/ folder in this project for smaller, feature-specific code examples
  • Join the Discord Developers server to ask questions about the API, attend events hosted by the Discord API team, and interact with other devs.
  • Check out community resources for language-specific tools maintained by community members.

discord-example-app's People

Contributors

cabbage63 avatar ianmitchell avatar jayydoesdev avatar justinbeckwith avatar komali2 avatar matthova avatar oakwoodgates avatar renovate-bot avatar shaydewael avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

discord-example-app's Issues

Unauthorized

I get the following response when starting the app.js

Error: {"message":"401: Unauthorized","code":0}
    at DiscordRequest (file:///C:/Users/domin/Desktop/Projects/zen-discord-back-end-service/utils.js:37:11)
    at processTicksAndRejections (node:internal/process/task_queues:96:5)
    at async HasGuildCommand (file:///C:/Users/domin/Desktop/Projects/zen-discord-back-end-service/commands.js:17:17)

I've been for hours trying to find out what the issue is. I've even been using Postman and console logged the environment variables and they are correct (I think). Is the Discord token supposed to be in this format as un URI?
discord.com/api/oauth2/authorize?client_id=<client_id>&permissions=<permission_int>&scope=bot%20applications.commands

connect ETIMEDOUT

When I want to run the project, there is an error. I tried proxy, firewall, etc., but there is no solution. What are the possible reasons and solutions?
FetchError: request to https://discord.com/api/v10/applications/1118079193654251581/commands failed, reason: connect ETIMEDOUT 162.159.136.232:443
at ClientRequest. (file:///D:/Users/Desktop/discord-example-app/node_modules/node-fetch/src/index.js:108:11)
at ClientRequest.emit (node:events:525:35)
at TLSSocket.socketErrorListener (node:_http_client:494:9)
at TLSSocket.emit (node:events:513:28)
at emitErrorNT (node:internal/streams/destroy:157:8)
at emitErrorCloseNT (node:internal/streams/destroy:122:3)
at processTicksAndRejections (node:internal/process/task_queues:83:21) {
type: 'system',
errno: 'ETIMEDOUT',
code: 'ETIMEDOUT',
erroredSysCall: 'connect'
}

Modal Interaction Response showing error "This interaction failed"

In example https://github.com/discord/discord-example-app/blob/main/examples/modal.js, whenever I run the command "test" to open the modal I get an error in discord that "This interaction failed".

The modal still opens and works properly, however I don't want to see this error message.

I'm using the latest version of discord.js and the only aspect of the demo code I've changed is it looks like InteractionResponseType.APPLICATION_MODAL has become InteractionResponseType.MODAL.

Other responses work fine like sending InteractionResponseType.CHANNEL_MESSAGE_WITH_SOURCE, but the MODAL specific interaction always throws an error.

Unauthorized issue

When I ran npm run register it said 401
Error: {"message":"401: Unauthorized","code":0}
at DiscordRequest (file:///C:/Users/kbrow/Downloads/discord-example-app/utils.js:36:11)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
at async InstallGlobalCommands (file:///C:/Users/kbrow/Downloads/discord-example-app/utils.js:48:5)
when I put everything in correctly in the .env file

ngrok validation error

Failed to register ngRok URL when trying to follow instructions. I always get the same validation error:
{"code": 50035, "errors": {"interactions_endpoint_url": {"_errors": [{"code": "APPLICATION_INTERACTIONS_ENDPOINT_URL_INVALID", "message": "The specified interactions endpoint URL could not be verified."}]}}, "message": "Invalid Form Body"}

VerifyDiscordRequest should return an async function

In utils.js, the function returned by VerifyDiscordRequest() should be async, because verifyKey is async. verifyKey() is currently not awaited, which means isValidRequest is a Promise which is always thruthy.

However, this means that express.json({ verify: VerifyDiscordRequest(process.env.PUBLIC_KEY) }) will not work, because the verify function is expected to be synchronous. Therefore it would probably be better to refactor this and rather use the verifyKeyMiddleware from discord-interactions.

Interactions endpoint URL with ngrok

Similar issue closed without a solution.

Trying to add a URL from ngrok on the interactions endpoint URL of the app configuration, there is an error that refuses to save the data even when the connection is successful.

Screen Shot 2022-11-20 at 18 04 43

{
    "code": 50035,
    "errors": {
        "interactions_endpoint_url": {
            "_errors": [
                {
                    "code": "APPLICATION_INTERACTIONS_ENDPOINT_URL_INVALID",
                    "message": "The specified interactions endpoint URL could not be verified."
                }
            ]
        }
    },
    "message": "Invalid Form Body"
}

Feature Request: Friend Invite Link

Hello Discord Team,

I hope this message finds you well. I would like to propose a feature that I believe would enhance the user experience on Discord: the ability to create a direct invite link for adding friends.

Currently, users can only send friend requests by entering usernames and discriminators. Introducing a feature that allows users to generate a unique invite link to share with friends would simplify the process and make it more accessible, especially for those who may not know how to find someone’s username or are new to the platform.

This feature could work similarly to how server invites function, allowing users to share a link that, when clicked, would automatically send a friend request to the user associated with that link.

Validation errors

Hello! Thank you to whoever is kind enough to read this and help me out. I've been following the guide for making a discord bot and i'm stuck at the spot where it asks me to add a Interactive Endpoint URL and i click the share button within glitch and then add the /interactions and try to save, but it says

Validation errors:
interactions_endpoint_url: The specified interactions endpoint url could not be verified.

Errors During "npm run register"

I'm receiving the following error message when I try to complete "npm run register" step. I've identified the error lies within the utils.js file but I'm not sure what needs to change. Any ideas?

401
Error: {"message":"401: Unauthorized","code":0}
at DiscordRequest (file:///C:/Users/sjdel/OneDrive/Desktop/VSC%20Projects/discord-example-app/utils.js:36:11)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
at async InstallGlobalCommands (file:///C:/Users/sjdel/OneDrive/Desktop/VSC%20Projects/discord-example-app/utils.js:48:5)

Consider adding minimum node version to README

Example App will not work on older versions of Node and minimum requirements aren't listed anywhere. User will face an error like

app.js:1
(function (exports, require, module, __filename, __dirname) { import 'dotenv/config';
                                                                     ^^^^^^^^^^^^^^^

SyntaxError: Unexpected string
    at new Script (vm.js:83:7)
    at createScript (vm.js:267:10)
    at Object.runInThisContext (vm.js:319:10)
    at Module._compile (internal/modules/cjs/loader.js:685:28)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:733:10)
    at Module.load (internal/modules/cjs/loader.js:620:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:560:12)
    at Function.Module._load (internal/modules/cjs/loader.js:552:3)
    at Function.Module.runMain (internal/modules/cjs/loader.js:775:12)
    at startup (internal/bootstrap/node.js:300:19)

which will be cryptic for new users to get past. (tested on 11.2.0, resolved on 16.17)

Discord does not seem to handle interactions properly.

Hi.
I'm trying the getting started guide from discord dev portal and I have a weird behavior.
When I use the /test command on discord everything looks good on ngrok and in my terminal but no message is shown in the discord channel.
image
image
image
image

Am I the only one ?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.