CodingTrain / Discord-Bot-Examples

Bot Examples for Fall 2023
20 stars 7 forks source link

About ephemeral and deferred responses #3

Closed dipamsen closed 1 year ago

dipamsen commented 1 year ago

Ways to respond to an interaction

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

Deferred Responses

Ephemeral Responses

More


(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).


supercrafter100 commented 1 year ago

For clarity reasons, I'd recommend moving interaction.deferReply() all the way to the top of the interaction handling. So it's the first thing that happens. The way you suggested it's sortof inbetween the existing fetching code.

dipamsen commented 1 year ago

Sure, that works as well (I was emphasizing that the call should at least be before the async call.)