Git Product home page Git Product logo

discord-interactions-js's Introduction

discord-interactions

version ci Downloads

Types and helper functions that may come in handy when you implement a Discord Interactions webhook.

Installation

npm install discord-interactions

Usage

Use the InteractionType and InteractionResponseType enums to figure out how to respond to a webhook.

Use verifyKey to check a request signature:

 const signature = req.get('X-Signature-Ed25519');
 const timestamp = req.get('X-Signature-Timestamp');
 const isValidRequest = verifyKey(req.rawBody, signature, timestamp, 'MY_CLIENT_PUBLIC_KEY');
 if (!isValidRequest) {
   return res.status(401).end('Bad request signature');
 }

Note that req.rawBody must be populated by a middleware (it is also set by some cloud function providers).

If you're using an express-like API, you can simplify things by using the verifyKeyMiddleware. For example:

app.post('/interactions', verifyKeyMiddleware('MY_CLIENT_PUBLIC_KEY'), (req, res) => {
  const message = req.body;
  if (message.type === InteractionType.APPLICATION_COMMAND) {
    res.send({
      type: InteractionResponseType.CHANNEL_MESSAGE_WITH_SOURCE,
      data: {
        content: 'Hello world',
      },
    });
  }
});

Make sure that you do not use other middlewares like body-parser, which tamper with the request body, for interaction routes.

Exports

This module exports the following:

InteractionType

An enum of interaction types that can be POSTed to your webhook endpoint.

InteractionResponseType

An enum of response types you may provide in reply to Discord's webhook.

InteractionResponseFlags

An enum of flags you can set on your response data.

MessageComponentTypes

An enum of message component types that can be used in messages and modals.

Message components

Types for the different message component structures: Button, ActionRow, StringSelect, and InputText.

Also includes the enums ButtonStyleTypes and TextStyleTypes, and a StringSelectOption type.

verifyKey(rawBody: Buffer, signature: string, timestamp: string, clientPublicKey: string): Promise<boolean>

Verify a signed payload POSTed to your webhook endpoint.

verifyKeyMiddleware(clientPublicKey: string)

Express-style middleware that will verify request signatures (make sure you include this before any other middleware that modifies the request body).

discord-interactions-js's People

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-interactions-js's Issues

Error: Bad request signature

export function VerifyDiscordRequest(clientKey) {
return function (req, res, buf) {
const signature = req.get('X-Signature-Ed25519');
const timestamp = req.get('X-Signature-Timestamp');

const isValidRequest = verifyKey(buf, signature, timestamp, clientKey);
if (!isValidRequest) {
  res.status(401).send('Bad request signature');
  throw new Error('Bad request signature');

};
}

Slash commands update might have broken my bot

https://canary.discord.com/channels/613425648685547541/697138785317814292/832859421952180245

Slash Commands Update (Midnight Snack Edition)

We have released a change to HTTP interactions which modifies how responses are handled. Due in part to this, you should ensure you respond to HTTP interactions with a valid Content-Type header. Interactions received via the gateway (INTERACTION_CREATE events) are unaffected by this change.

My bot was working fine through AWS lambda using this package until recently. Have there been any issues around this update?

verifyKeyMiddleware used in conjunction with bodyParser stops requests from getting to the callback

When using both verifyKeyMiddleware and bodyParser.json() (in any order) together, my app.post callback doesn't run, however if i comment out one of the app.use lines, it works:

const express = require("express");
const bodyParser = require("body-parser");
const { InteractionResponseType, InteractionType, verifyKeyMiddleware } = require("discord-interactions");

const config = require("./config.json");

const app = express();
const port = 3000;

app.use(verifyKeyMiddleware(config.publicKey));
app.use(bodyParser.json());

app.post("/", (req, res) => {
  console.log("here");
  const message = req.body;
  console.log(message.type);
  if (message.type === InteractionType.COMMAND) {
    res.send({
      type: InteractionResponseType.CHANNEL_MESSAGE_WITH_SOURCE,
      data: {
        content: 'Hello world',
      }
    });
  } else {
    res.send({})
  }
})

app.listen(port, () => {
  console.log(`Example app listening at http://localhost:${port}`)
})

How does discord use win getProcess function in javascript?

This is a personal doubt question and not a issue in this repo ig...
I'm asking here because this repo seemed a correct place to ask about it..

Incase anyone ever noticed when u have a discord application installed and you use discord web it prompts u to open in discord app so most prolly its using getprocess win library function
Does anyone mnd sharing how that's done in javascript or typescript ... I cant find any stuff related to that 😭

Thanks

1

1

Error: Point#multiply: invalid scalar, expected positive integer In Express Middleware

When trying to save the "Interactions Endpoint URL" using the Express Middleware, I get this error:

/var/home/dobby/n/bin/node /var/home/dobby/interactions/index.js
Example app listening at http://localhost:3000
/var/home/dobby/interactions/node_modules/noble-ed25519/index.js:255
            throw new Error('Point#multiply: invalid scalar, expected positive integer');
                  ^

Error: Point#multiply: invalid scalar, expected positive integer
    at ExtendedPoint.multiply (/var/home/dobby/interactions/node_modules/noble-ed25519/index.js:255:19)
    at Object.verify (/var/home/dobby/interactions/node_modules/noble-ed25519/index.js:610:35)
    at processTicksAndRejections (node:internal/process/task_queues:93:5)

Process finished with exit code 1

The code looks like this:

const express = require("express");
const { verifyKeyMiddleware } = require("discord-interactions");

const app = express();
const port = 3000;

app.post("/", verifyKeyMiddleware("<CLIENT_PUBLIC_KEY>"), (req, res) => {
  if (req.body.json()["type"] === 1) {
    res.json({ "type": 1 });
  }
})

app.listen(port, () => {
  console.log(`Example app listening at http://localhost:${port}`)
})

I'm also using ngrok for tunnelling the webhook url.

MessageEmbed .addFields No Longer Supports User Mentions

When using MessageEmbed.addField users can be mentioned without any issue in a embedded message.

EG:

var.addField{ name: From: <@${feedbackFound.user_id}>} correctly displays @UserName

Where as:

var.addFields{ name: From: <@${feedbackFound.user_id}>} instead displays <@123456789>

Is this intended? Does the new .addFields intentially not support user mentions?

discord-interactions throws error 'Invalid signature'

When I send a POST request I get this error: [discord-interactions] Invalid signature
This is what I get on the console: [discord-interactions]: Invalid verifyKey parameters Error: Value is not a valid hex string

Here's the code:

const express = require('express');
const { InteractionType, InteractionResponseType, verifyKeyMiddleware } = require('discord-interactions');

const app = express();

app.post('/interactions', verifyKeyMiddleware('client-public-key-here'), (req, res) => {
  const interaction = req.body;
  if (interaction.type === InteractionType.APPLICATION_COMMAND) {
    res.send({
      type: InteractionResponseType.CHANNEL_MESSAGE_WITH_SOURCE,
      data: {
        content: 'Hello world',
      },
    });
}

Replace `tweetnacl` with `discord-verify`

The tweetnacl library has a massive impact on bot performance due to its usage of non-native code. discord-verify uses new native methods for verification that results in a dramatic performance increase.

This was the real world performance benefits the Truth or Dare bot saw when they swapped off of discord-interactions and deployed discord-verify:

image

The library also protects against additional security concerns such as replay attacks.

Use case

Can someone explain me what would be the potential use case of this package? I'm new to this repo and wanted to use this package 🗡️

Thanks

application modal throws invalid interaction after upgrade

I was using 3.2.0, in one place I return an APPLICATION_MODAL, after upgrading to 3.4.0 the interaction returning the 200 with the exact same component throws invalid interacion in discord.

Im returning the component like this:

{
  type: InteractionResponseType.APPLICATION_MODAL,
  data: {
    title: 'Insert code.',
    custom_id: 'associate-code',
    components: [
      {
        type: 1,
        components: [
          {
            type: 4,
            custom_id: 'associate-code',
            label: 'Associate Code',
            style: 2,
            min_length: 12,
            max_length: 12,
            placeholder: 'Insert code',
            required: true
          }
        ]
      }
    ]
  }
}

README #Export Looks Wierd

https://github.com/discord/discord-interactions-js#exports

image

  1. Can we improve remove the extra heading tags used here.
  2. We're basically providing a definition to all the export modules, can we do something like this
    eg:

Exports

This module exports the following:

  • InteractionType: An enum of interaction types that can be POSTed to your webhook endpoint.
  • InteractionResponseType: An enum of response types you may provide in reply to Discord's webhook.

I would love to open a PR if we need this 🍡

Middleware throws instead of rejecting if request is invalid

when sending an invalid request without the proper headers, instead of rejecting, the middleware throws an error:

                throw new Error('Value is not a valid hex string');
                       ^
Error: Value is not a valid hex string
     at valueToUint8Array (/home/ven/Bots/tldr-discord/node_modules/discord-interactions/dist/index.js:89:23)

I sent this request via

curl -XPOST https://domain/interactions

This is my first time using express, so I'm not sure if this is the intended behaviour. But I think it would be better to simply reject if the request is invalid

Edit: After inspecting the code, it seems like this is already being handled correctly, so it confuses me that I am getting this error: Any clue what could be causing this?

This library login feauture no longer works

I was with a friend a we tried to use my serverless bot and it gave interaction failed, on vercel dashboard there is 401 Unauthorized but in my code I give it with a message but there wasn't a message so it can't be from my code

Suggestion: Change verifyKey function to be pure JS friendly

Hello,
The current implementation of verify key function has Buffer as typeof accepted input which are NodeJS specific and require heavy polyfills for pure JS (serverless/service-workers)

We can instead use

import * as ed from "@noble/ed25519"

const verifyKey = async (
  signature: string,
  timestamp: string,
  body: string,
  clientPublicKey: string
) => {
  const message = new TextEncoder().encode(timestamp + body)
  const isVerified = await ed.verify(signature, message, clientPublicKey)
  return isVerified
}

export default verifyKey

Cons:

  • change the argument types
  • dependent library

Pros:

  • now can be used in service-workers or pure JS environment

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.