discord | discord channels | discord guilds | Search

This code utilizes several functions to interact with the Discord API, including registering and retrieving commands, updating interactions and commands, and requesting authentication. These functions, such as registerCommand, getCommands, and requestAuthQ, send HTTP requests (GET, POST, PATCH) to the Discord API to perform their respective operations.

Run example

npm run import -- "discord commands"

discord commands


const {DEFAULT_APPLICATION} = importer.import("discord configuration")
const {timeout} = importer.import("discord utilities")
const {requestAuthQ} = importer.import("discord request")


async function registerCommand(cmd, desc, guildId = null) {
  // TODO: guild specific commands
  //url = "https://discord.com/api/v8/applications/<my_application_id>/guilds/<guild_id>/commands"
  var json
  if(typeof cmd == 'object') {
    json = cmd
  } else {
    json = {
      'name': cmd,
      'description': desc
    }
  }
  console.log('Registering command ', json.name)
  await timeout(2000)
  return await requestAuthQ({
    headers: {
      'Content-Type': 'application/json'
    },
    method: 'POST',
    url: guildId
      ? `applications/${DEFAULT_APPLICATION}/guilds/${guildId}/commands`
      : `applications/${DEFAULT_APPLICATION}/commands`,
    data: JSON.stringify(json)
  })
}

async function getCommands(guildId = null) {
  return await requestAuthQ({
    method: 'GET',
    url: guildId
      ? `applications/${DEFAULT_APPLICATION}/guilds/${guildId}/commands`
      : `applications/${DEFAULT_APPLICATION}/commands`
  })
}

async function getCommand(commandId, guildId = null) {
  return await requestAuthQ({
    method: 'GET',
    url: guildId
      ? `applications/${DEFAULT_APPLICATION}/guilds/${guildId}/commands/${commandId}`
      : `applications/${DEFAULT_APPLICATION}/commands/${commandId}`
  })
}

async function updateInteraction(message, interactionId, interactionToken) {
  var json = typeof message == 'string' ? ({
      'content': message
    }) : message
  return await requestAuthQ({
    headers: {
      'Content-Type': 'application/json'
    },
    method: 'PATCH',
    url: `webhooks/${DEFAULT_APPLICATION}/${interactionToken}/messages/@original`,
    data: JSON.stringify(json)
  })
}

async function updateCommand(cmd, desc, commandId, guildId = null) {
  if(typeof cmd == 'object') {
    json = cmd
  } else {
    json = {
      'name': cmd,
      'description': desc
    }
  }
  console.log('Updating command ', json.name)
  await timeout(2000)
  return await requestAuthQ({
    method: 'PATCH',
    headers: {
      'Content-Type': 'application/json'
    },
    url: guildId
      ? `applications/${DEFAULT_APPLICATION}/guilds/${guildId}/commands/${commandId}`
      : `applications/${DEFAULT_APPLICATION}/commands/${commandId}`,
    data: JSON.stringify(json)
  })
}

async function deleteCommand(commandId, guildId = null) {
  console.log('Deleting command ', commandId)
  return await requestAuthQ({
    method: 'DELETE',
    url: guildId 
      ? `applications/${DEFAULT_APPLICATION}/guilds/${guildId}/commands/${commandId}`
      : `applications/${DEFAULT_APPLICATION}/commands/${commandId}`
  })
}

module.exports = {
  registerCommand,
  getCommands,
  getCommand,
  updateInteraction,
  deleteCommand,
  updateCommand,
}

What the code could have been:

const {
  DEFAULT_APPLICATION,
  timeout,
  requestAuthQ
} = require('./discord-utility-functions');

// Function to register a new command
async function registerCommand(cmd, desc, guildId = null) {
  const commandData = typeof cmd === 'object'? cmd : { name: cmd, description: desc };
  console.log(`Registering command ${commandData.name}`);
  await timeout(2000);
  const url = guildId
   ? `applications/${DEFAULT_APPLICATION}/guilds/${guildId}/commands`
    : `applications/${DEFAULT_APPLICATION}/commands`;
  return await requestAuthQ({
    headers: { 'Content-Type': 'application/json' },
    method: 'POST',
    url,
    data: JSON.stringify(commandData)
  });
}

// Function to retrieve a list of commands
async function getCommands(guildId = null) {
  const url = guildId
   ? `applications/${DEFAULT_APPLICATION}/guilds/${guildId}/commands`
    : `applications/${DEFAULT_APPLICATION}/commands`;
  return await requestAuthQ({ method: 'GET', url });
}

// Function to retrieve a specific command
async function getCommand(commandId, guildId = null) {
  const url = guildId
   ? `applications/${DEFAULT_APPLICATION}/guilds/${guildId}/commands/${commandId}`
    : `applications/${DEFAULT_APPLICATION}/commands/${commandId}`;
  return await requestAuthQ({ method: 'GET', url });
}

// Function to update an existing interaction (DEPRECATED)
async function updateInteraction(message, interactionId, interactionToken) {
  const url = `webhooks/${DEFAULT_APPLICATION}/${interactionToken}/messages/@original`;
  const data = typeof message ==='string'? { content: message } : message;
  return await requestAuthQ({
    headers: { 'Content-Type': 'application/json' },
    method: 'PATCH',
    url,
    data: JSON.stringify(data)
  });
}

// Function to update an existing command
async function updateCommand(cmd, desc, commandId, guildId = null) {
  const commandData = typeof cmd === 'object'? cmd : { name: cmd, description: desc };
  console.log(`Updating command ${commandData.name}`);
  await timeout(2000);
  const url = guildId
   ? `applications/${DEFAULT_APPLICATION}/guilds/${guildId}/commands/${commandId}`
    : `applications/${DEFAULT_APPLICATION}/commands/${commandId}`;
  return await requestAuthQ({
    headers: { 'Content-Type': 'application/json' },
    method: 'PATCH',
    url,
    data: JSON.stringify(commandData)
  });
}

// Function to delete a command
async function deleteCommand(commandId, guildId = null) {
  console.log(`Deleting command ${commandId}`);
  const url = guildId
   ? `applications/${DEFAULT_APPLICATION}/guilds/${guildId}/commands/${commandId}`
    : `applications/${DEFAULT_APPLICATION}/commands/${commandId}`;
  return await requestAuthQ({ method: 'DELETE', url });
}

module.exports = {
  registerCommand,
  getCommands,
  getCommand,
  updateInteraction, // DEPRECATED
  deleteCommand,
  updateCommand,
};

Code Breakdown

Importing Dependencies

The code starts by importing dependencies from other modules using the importer.import function.

const {DEFAULT_APPLICATION} = importer.import('discord configuration')
const {timeout} = importer.import('discord utilities')
const {requestAuthQ} = importer.import('discord request')

Registering a Command

The registerCommand function is an asynchronous function that registers a new command with Discord. It takes three parameters: cmd (the command name), desc (the command description), and guildId (the ID of the guild where the command should be registered).

async function registerCommand(cmd, desc, guildId = null) {
  //...
}

It constructs a JSON object representing the command and sends a POST request to the Discord API to register the command.

Retrieving Commands

The getCommands function is an asynchronous function that retrieves a list of commands for a specific guild.

async function getCommands(guildId = null) {
  //...
}

It sends a GET request to the Discord API to retrieve the commands.

Retrieving a Command

The getCommand function is an asynchronous function that retrieves a specific command by its ID.

async function getCommand(commandId, guildId = null) {
  //...
}

It sends a GET request to the Discord API to retrieve the command.

Updating an Interaction

The updateInteraction function is an asynchronous function that updates the content of an interaction.

async function updateInteraction(message, interactionId, interactionToken) {
  //...
}

It sends a PATCH request to the Discord API to update the interaction.

Updating a Command

The updateCommand function is an asynchronous function that updates a specific command.

async function updateCommand(cmd, desc, commandId, guildId = null) {
  //...
}

It constructs a JSON object representing the updated command and sends a PATCH request to the Discord API to update the command.

Requesting Authentication

The requestAuthQ function is an asynchronous function that sends a request to the Discord API with authentication. It is used by the other functions to send requests to the API.

async function requestAuthQ(options) {
  //...
}