Giter Site home page Giter Site logo

discord-bot-examples's Introduction

Discord Bot Examples

This repository provides the source code used throughout the Discord bot tutorial series of TheCodingTrain. Each folder corresponds to the final code showcased in that episode of the tutorial series together with an explanation of what changes and additions were made during that episode.

Each episode builds ontop of the previous one. So if you've got questions on why some things are done the way they are in existing code, have a look at previous episodes!

Video Tutorials

Additional resources

Get help!

Stuck on an issue that you can't figure out how to fix? Do you want to create a new feature but don't know how to tackle it? The amazing Coding Train Discord community is always prepared to help you with any issue or questions you're having!

discord-bot-examples's People

Contributors

dipamsen avatar kfahn22 avatar klinegareth avatar shiffman avatar supercrafter100 avatar vitorhonna avatar

Stargazers

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

Watchers

 avatar  avatar  avatar  avatar

discord-bot-examples's Issues

About ephemeral and deferred responses

Ways to respond to an interaction

(All info is sourced from Discord Developer Portal - Receiving and Responding and DiscordJS Guide - Response Methods)

Deferred Responses

  • Any interaction received by the bot must be acknowledged within 3 seconds. During this time interval, the user is shown a loading state "Sending Command...".
  • If 3 seconds are passed without acknowledgement, the interaction will be invalidated, and an ephemeral message "This interaction failed" will be shown to the user.
  • This means, that interaction.reply() must be called within 3 seconds of the execute function being called.
  • Some commands may take more than 3 seconds to execute. In this case, we can initially acknowledge the response, by creating an initial empty deferred response (this must be created within 3 seconds of execution) by calling interaction.deferReply(). This will act as an acknowledgement, and the user loading state will show a <bot> is thinking... message. It also gives a 15 minute timeframe to perform the execution of the command.
  • To actually reply to the deferred interaction, we can use interaction.editReply(), or interaction.followUp(), which will edit the loading state and show the actual response. (This must be sent withing 15 minutes of receiving the interaction.)

Ephemeral Responses

  • This is a way to respond to a slash command, such that only the executor of the slash command can see the response.
  • By setting ephemeral: true to any response function (reply(), deferReply(), followUp()), the corresponding response will only be visible to the user who initiated the interaction, with a message below, "Only you can see this".

More

  • For any interaction, follow up responses can be sent (apart from the initial response) by using interaction.followUp(). This also has a 15 minute timeframe since receiving the interaction.
  • The initial response can be edited (also within 15 minutes of receiving the interaction) by using interaction.editReply().

(issue in gif.js)

deferReply() call should be moved above fetch to tenor api (gif.js)

  // URL constructed with the provided or default keyword
  let url = `https://tenor.googleapis.com/v2/search?q=${keywords}&key=${process.env.TENORKEY}&client_key=a2z_discord_bot&contentfilter=high`;

+  // Initially acknowledging the command interaction with a deferred reply
+  await interaction.deferReply({ ephemeral: false });

  // Fetching data from Tenor API
  let response = await fetch(url);
  let json = await response.json();
  console.log(json);
  console.log(json.results[0].media_formats);

  // Randomly select a GIF from the response
  const index = Math.floor(Math.random() * json.results.length);

  // Creating an embed to display the GIF in the Discord message
  const embed = new EmbedBuilder().setImage(json.results[index].media_formats.gif.url);

-  // Initially acknowledging the command interaction with a hidden (ephemeral) reply
-  await interaction.deferReply({ ephemeral: false });

  // Following up with the selected GIF embedded in the message
  await interaction.followUp({
    embeds: [embed],
    content: 'GIF from Tenor: ' + keywords,
  });

Also, the comment refers to the reply as "ephemeral", which it is not (as ephemeral: false is set, which is also the default).


Remove non-required Guilds intent

I'm just going to post this here because technically in the example bot the Guilds intent isn't even required. This intent just sends events related to guilds but the example code doesn't even require that at the moment. You can find a list of intents + the events they can receive on the official Discord Documentation that you can find here: https://discord.com/developers/docs/topics/gateway#gateway-intents

Though I currently assume the intent is there as an example that you should put them there.

image

Combine step 4 and step 7 in the README

Currently, you're inviting the bot itself and then authorizating the command application seperately. This can be done in a single step by just including the application.commands scope when you're inviting the bot to your server.

A TypeScript version would be great, it's very hard to upgrade as-is

The new JS version of this came out just when I was looking to learn to make a Discord bot. It worked great after previous false starts in other languages.

But after getting to a certain point I tried to convert it to TypeScript and found it far beyond my capabilities. Especially the deploy-command.js

Propose using discord api for deploying commands

Discord.JS

// ...  stuff to get all the commands using djs ... //

// Construct and prepare an insance of the REST module
const rest = new REST().setToken(process.env.TOKEN);

// and deploy your commands!
(async () => {
  try {
    console.log(`Started refreshing ${commands.length} application (/) commands.`);

    // The put method is used to fully refresh all commands in the guild with the current set
    const data = await rest.put(Routes.applicationGuildCommands(process.env.CLIENTID, process.env.SERVERID), {
      body: commands,
    });

    console.log(`Successfully reloaded ${data.length} application (/) commands.`);
  } catch (error) {
    // And of course, make sure you catch and log any errors!
    console.error(error);
  }
})();

Discord API

// ...  stuff to get all the commands using djs ... //

// Deploy your commands!
(async () => {
  try {
    console.log(`Started refreshing ${commands.length} application (/) commands.`);

    // make a PUT request, with the commands as the body
    const url = `https://discord.com/api/applications/${process.env.CLIENTID}/commands`
    const res = await fetch(url, {
      method: "PUT", 
      headers: {
        "Content-Type": "application/json",
        Authorization: "Bot " + process.env.TOKEN
      }, 
      body: JSON.stringify(commands)
    })
    const data = await res.json()

    console.log(`Successfully reloaded ${data.length} application (/) commands.`);
  } catch (error) {
    // And of course, make sure you catch and log any errors!
    console.error(error);
  }
})();

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.