fhsu-csci441-team-a / myTrafficWizard

Repo to house code for the myTrafficWizard app
0 stars 0 forks source link

Now Properly Destroying the Discord Connection #99

Closed NicoleReneNewcomb closed 5 months ago

NicoleReneNewcomb commented 5 months ago

Figured out how to properly and thoroughly and utterly destroy the persistent, hard-to-kill Discord connection.

fhsu-tbanderson commented 5 months ago

Few things in the discordBotModel.js file:

  1. Can the intents be set inside the constructor?
// set intents (permissions) for Discord bot
const myIntents = new IntentsBitField();
myIntents.add(
  IntentsBitField.Flags.Guilds,
  IntentsBitField.Flags.GuildPresences, 
  IntentsBitField.Flags.GuildMembers,
  IntentsBitField.Flags.GuildMessages,
  IntentsBitField.Flags.MessageContent,
  IntentsBitField.Flags.DirectMessages);

// this class handles the request to send a message to Discord
class DiscordBotModel {

  #client;

  // creates new connection to Discord Bot each time instantiated
  constructor() {
    this.#client = new Client({ intents: myIntents });
    this.#client.login(process.env.DISCORD_API_TOKEN);
  1. The last console.log statement is after a return and would never execute, it should be removed.

    
    async postMessage(userID, formattedMessage) {
    
    try {
    
      // Send the formatted message to the channel
      const response = await this.#client.users.send(userID, formattedMessage);
    
      // log the response
      console.log(response);
    
      // return response
      return response;
      console.log("testing return after");

3. The destruction of the client object is set to wait for the client to be ready. Don't believe this is necessary as the client can be destroyed even if it not logged in or ready. This could cause unexpected behavior. 

finally { try { // Wait for the client to become ready before destroying it await new Promise(resolve => { this.#client.once('ready', () => resolve()); });

    // Destroy the client connection (after being ready)
    this.#client.destroy();
    console.log("The Discord connection has been destroyed.")
  } catch (error) {
    console.error("Error while destroying Discord connection:", error);
  }
}

4. This is subjective but there are redundant comments throughout the file. A comment is redundant if it describes something that describes itself. Comments should say things that the code cannot say itself. Below are examples of redundant comments:

// import discord.js library to interact with Discord API const { Client, IntentsBitField } = require('discord.js');

// log the response console.log(response);

// Send the formatted message to the channel const response = await this.#client.users.send(userID, formattedMessage);

// return response return response;

// export the DiscordBotModel class so other files can use it module.exports = DiscordBotModel;