#Bot semi-online –– can send messages but slash commands don't work

34 messages · Page 1 of 1 (latest)

wispy charm
#

After a couple of hours, the bot turns offline in the Discord user list (right side). When this happens:

  • Slash commands and buttons (interactions) don't work.
  • But the bot can still send messages into channels.
  • I don't use client.user.setStatus() anywhere in the project.
  • Restarting the bot results in a fully working bot again.
  • there are no related error (track traces).

FYI: when the bot works (first few hours), all functionalities work (commands, sending messages, filtering game, etc).

candid mauve
#

• What's your exact discord.js npm list discord.js and node node -v version?
• Post the full error stack trace, not just the top part!
• Show your code!
• Explain what exactly your issue is.
• Not a discord.js issue? Check out #useful-servers.

wispy charm
#

Part of code:

const client = new Client({ intents: [GatewayIntentBits.Guilds] })
client.commands = new Collection();

client.on('ready', () => {
  deployCommands(client)
    .then(str => {
      log(`Successfully registered ${str} application commands. Bot is ready to receive commands.`);
    }).catch(error => logError(error));
});

client.on('interactionCreate', async interaction => {
  if (!interaction.isChatInputCommand()) return;
  const command = client.commands.get(interaction.commandName);
  if (!command) return;

  // Defer interaction to prevent unknown interaction.
  interaction.deferReply({ ephemeral: true })
    .catch(reason => logError(reason))
    .then(async () => {
      try {
        await command.execute(interaction);
      } catch (error) {
        logError(error);
        interaction.editReply({
          embeds: [getEmbed(false).setTitle('Error: unknown cause.')],
          ephemeral: true
        }).catch(reason => logError(reason));
      }
    });
});

client.login(process.env.DISCORD_TOKEN)
  .catch(reason => {
    logError(reason);
    exit(1);
  });

async function deployCommands(client) {
  return new Promise(async function(resolve, reject) {
    const commands = [];
    const commandsPath = join(__dirname, 'commands');
    const commandFiles = sync(join(commandsPath, '**', '*.js'));

    for (const file of commandFiles) {
      const command = await import(pathToFileURL(file));
      commands.push(command.data.toJSON());
      client.commands.set(command.data.name, command);
    }

    new REST({ version: '10' })
      .setToken(client.token)
      .put(Routes.applicationGuildCommands(client.user.id, process.env.GUILD_ID), { body: commands })
      .then(() => resolve(`${commands.length} / ${commandFiles.length}`))
      .catch(reject);
    });
  }
}
plucky yoke
#

Most likely there're no logs, because you don't log anything to the console during the error. Just void input .catch(logError()).
Shouldn't you pass the function to it, not call it? .catch(logError)

wispy charm
wispy charm
#

Updated version:

  • Stack trace: none.
  • Code: see above (fixed console logging with Syjalo's post).
  • Discord.JS version: [email protected]
  • Node version: v16.17.1
  • Problem: the bot appears offline and interactions are not acknowledged. However, the bot still runs according to PM2 and can post in guild channels. Note: this happens after the bot already ran a couple of hours without any issues.

I can answer any questions you may have so I can find the cause of this problem.

wispy charm
#

Thanks for your reply.

  • Would you mind elaborating on --watch (edit: on whether this may really be the cause)? I purposely chose pm2 for this feature so I don't have to keep an eye out every day. I keep track of its restarts (and unstable restarts) so if I should believe pm2, the bot didn't crash. So I'm not sure if this is the cause of the problem.
  • I debug in VS Code but opted to use the live bot's logs because the problem appears after a solid few hours. To be fair, I haven't tried to reproduce the problem in VS Code yet so I'll do that tomorrow.
  • I believe that the 2 errors are unrelated to the problem. They appear after I restarted the bot as seen by their timestamps. The button clicks and slash command used before the restart do not appear in the logs (estimated timestamps: 23:27:4523:28:10).
wispy charm
#

I think we're deviating from the main issue, but here's the code of /ipStatistics.js.

import { SlashCommandBuilder, CommandInteraction, PermissionFlagsBits } from 'discord.js';
import { getIpStatistics } from '../../../playerLog.js';
import { logError } from '../../../stringUtils.js';
import { isValidIp, getEmbed } from '../../util.js';

export const data = new SlashCommandBuilder()
  .setName('statistics')
  .setDescription('Show kick statistics of an IP.')
  .setDMPermission(false)
  .addStringOption(option => option
    .setName('ip')
    .setDescription('IP of player.')
    .setRequired(true)
    .setMinLength(7)
    .setMaxLength(15)
  );
    
export async function execute(interaction) {
  const ip = String(interaction.options.get('ip', true)?.value);

  if (!isValidIp(ip)) return interaction.editReply({
    embeds: [getEmbed(false).setTitle(`Error: \`${ip}\` is not a valid IPv4.`)],
    ephemeral: true
  }).catch(error => logError(error));

  const statsObj = getIpStatistics(ip);

  const embed = getEmbed(statsObj.doesExist)
    .setTitle(statsObj.doesExist
      ? `Statistics of IP \`${ip}\``
      : `Error: could not find IP \`${ip}\` in logs.`)
    .setDescription(statsObj.doesExist
      ? statsObj.description
      : null);

  return interaction.editReply({ // <-- Line 43.
    embeds: [embed],
    ephemeral: true
  }).catch(error => logError(error)); // <-- caught error as seen in output.
}```

I ran this example (of a slash command) in VSCode to verify the bot doesn't crash after reproducing the error in the output console. To clarify, such tests were done before I pushed the code to the VPS (pm2).

I would share my project if it would lead to a solution. But it's a private repository of another person so I can't (won't) do that.

**Edit:** `interaction.editReply()` because in `bot.js`, the interaction was deferred with `interaction.deferReply({ ephemeral: true })`.
#

Do you mean this as seen in a previous post (first code post)?

interaction.deferReply({ ephemeral: true })
    .catch(reason => logError(reason))
    .then(async () => { // <-- Waiting here.
      try {
        await command.execute(interaction); // <-- After deferring, execute command.
      } catch (error) {
        logError(error);
        interaction.editReply({
          embeds: [getEmbed(false).setTitle('Error: unknown cause.')],
          ephemeral: true
        }).catch(reason => logError(reason));
      }
    });
});
azure kindle
#

huh?

#

why await

wispy charm
#

That's already so in the video.

#

The await in await command.execute(interaction) doesn't have much use. As for awaiting the deferReply(), this is handled by the .then().

azure kindle
#

if so, that's pointless, as the execute() is called in a then()

#

and the result of that all isn't assigned anywhere

#

yes

#

where is the "slash command"

#

and when does that run

#

or where is it called

#

is it inside of the then() by any chance

wispy charm
#

I explained that in an earlier post. " They appear after I restarted the bot as seen by their timestamps. The button clicks and slash command used before the restart do not appear in the logs (estimated timestamps: 23:27:4523:28:10)."

I stayed polite in the hope to find a solution I may overlooked. But to be quite frank, I've tested all commands before I pushed them to the VPS (pm2). They all work perfectly and I haven't found a bug so far. The bot does not crash. What you see are error outputs by design (.catch(error => logError(error));). That said, I do want to thank you for taking the time to try to help me.

wispy charm
#

The unknown interaction was likely because your bot crashed mid way through an interaction and then auto restarted because of pm2 and tried to finish the interaction which was no longer available - just spit balling here
Ps. Restarting an application doesn't result in continuing where it left off. It's a restart from the start.

#

I'll try to reproduce the problem on a different machine tomorrow though. Perhaps it has to do with a unstable internet connection of the VPS. 😦

azure kindle
#

what might try to complete it

wispy charm
azure kindle
#

unless you run the command again from somewhere else, logically that should never happen, as you run the command in a then() on the deferReply

#

what is that supposed to mean

#

you can stop shitposting

wispy charm
#

Sadly he doesn't know what he's talking about. Anyway... @azure kindle I doubt you've seen this problem before, or have you? I noticed you posted in the other (maybe) related thread too.

azure kindle
#

no, sorry, besides some basic logic i'm not that deep into interactions, i don't even use them myself

wispy charm
#

And I'm grateful for his help. Please bother some other people.

azure kindle
#

the fact that i don't use interactions myself doesn't change the fact that i know how promises work