D
D
Den182021-12-07 19:56:11
Node.js
Den18, 2021-12-07 19:56:11

What is the problem with slash commands?

I ran into a problem using slash commands on version 13 of discord js.
When the bot is on 1.2 servers, everything works fine with no errors and fast response.
But when I launch a bot, which is 500+, it starts to get stupid and such errors

DiscordAPIError: Unknown interaction
    at RequestHandler.execute (C:\Program Files (x86)\Bot\node_modules\discord.js\src\rest\RequestHandler.js:298:13)
    at processTicksAndRejections (node:internal/process/task_queues:96:5)
    at async RequestHandler.push (C:\Program Files (x86)\Bot\node_modules\discord.js\src\rest\RequestHandler.js:50:14)
    at async CommandInteraction.reply (C:\Program Files (x86)\Bot\node_modules\discord.js\src\structures\interfaces\InteractionResponses.js:99:5) {
  method: 'post',
  path: '/interactions/917815534404386826/aW50ZXJhY3Rpb246OTE3ODE1NTM0NDA0Mzg2ODI2OlFEdldSZU16NDJ3dWZ2ekRSekcwenhSS0E4OXYwM1hJZzZJc2NFNmVUTXF3cEcyeTF4WnZhRHRqZVl1aW5BbFpuZ1Roc0FXNW90VndFOEhsZ3B0aHRwUm1NVldMWGVVY1ZNSzJvZTd2Q0p1YUhEME1KVzFTQVgxWE5CYUdVOUdp/callback',
  code: 10062,
  httpStatus: 404,
  requestData: { json: { type: 4, data: [Object] }, files: [ [Object] ] }
}

I have already tried both a powerful computer and a powerful Internet. Maybe someone faced such problems.
Connecting to a MySQL database.
All commands are in the same index.js file, but I tried to separate them into different files (still the same)
For example, all the commands are designed like this:
try {
    if(interaction.commandName === 'info') {
        if (interaction.options.getString('category') === 'server') {
            const { utc } = require('moment')
            pool.query(`SELECT lang FROM data WHERE GuildID = ?`, [interaction.guild.id], async function (err, result, fields) {
                    if (err) console.log(err);

                if (result[0]['lang'] === 'rus') {
                                            
                    let embed = new MessageEmbed()
                    .setThumbnail(interaction.guild.iconURL({dynamic : true}))
                    .setColor('#f3f3f3')
                    .setTitle(`Информация о сервере ${interaction.guild.name}`)
                    .setDescription(`**Участники**
                    >Всего: ${interaction.guild.memberCount}\n
                    **Каналы**
                    >Всего: ${interaction.guild.channels.cache.size}
                    >Текстовых: ${interaction.guild.channels.cache.filter(c => c.type === 'GUILD_TEXT').size}
                    >Новостных: ${interaction.guild.channels.cache.filter(c => c.type === 'GUILD_NEWS').size}
                    >Голосовых: ${interaction.guild.channels.cache.filter(c => c.type === 'GUILD_VOICE').size}
                    >Категорий: ${interaction.guild.channels.cache.filter(c => c.type === 'GUILD_CATEGORY').size}\n
                    **Инфо**
                    >Владелец: ${(await interaction.guild.fetchOwner()).user.tag}
                    >Дата создания: ${utc(interaction.guild.createdAt).format('DD MMMM YYYY')}
                    >Количество ролей: ${interaction.guild.roles.cache.size}
                    >Требование 2FA: ${interaction.guild.verified ? 'Включено' : `Выключено`}
                    >Количество бустов: ${interaction.guild.premiumSubscriptionCount >= 1 ? `${interaction.guild.premiumSubscriptionCount}` : `Нет бустов`}
                    >Количество эмоций: ${interaction.guild.emojis.cache.size >= 1 ? `${interaction.guild.emojis.cache.size}` : `Нет эмоций`}`)
                    .setFooter(`ID сервера ${interaction.guild.id}` )
                    return interaction.reply({ embeds: [embed] }).catch(function(err){
                        if(err) {
                            console.log(err)
                        }
                    });
                }
            })
        }
    }    
} catch(err) {
    console.log(err);
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
nowm, 2021-12-07
@Den18

Discord has such a feature that interaction must be answered within 3 seconds. If not in time, it starts to give such an error. There are several options:

  1. Immediately after the interaction has been received, interaction.deferReply should be called. Calling deferReply allows you to extend the response time to 15 minutes. Then, as usual, do pool.query and then interaction.reply
    await interaction.deferReply();
    // После вызова кода выше, дискорд даёт ещё 15 минут 
    // на то, чтобы отправить ответ.
    
    // [Тут какой-то ваш код, который долго работает]
    
    await interaction.reply('Информация о сервере: бла-блабла');

  2. You can use the Follow-ups mechanism . In this case, you immediately respond with interaction.reply, then do pool.query, and then add more text with interaction.followUp:
    await interaction.reply('Ща, погодь, нужно в БД посмотреть...');
    // После вызова кода выше, дискорд даёт ещё 15 минут 
    // на то, чтобы отправить follow up.
    
    // [Тут какой-то ваш код, который долго работает]
    
    await interaction.followUp('Вот, нашёл: Информация о сервере: бла-блабла');
    // Код выше добавляет к ответу текст "Вот, нашёл: Информация о сервере: бла-блабла" 
    // (фраза «Ща, погодь» никуда не пропадает)

  3. You can respond immediately in the same way, but instead of interaction.followUp, call interaction.editReply. In this case, 15 minutes are also given to call editReply.
    await interaction.reply('Подождите...');
    // После вызова кода выше, дискорд даёт ещё 15 минут 
    // на то, чтобы отредактировать это сообщение
    
    // [Тут какой-то ваш код, который долго работает]
    
    await interaction.editReply('Информация о сервере: бла-блабла');
    // Код выше заменяет "Подождите.." на "Информация о сервере: бла-блабла"

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question