Discord. js проблема с dming при использовании команды dm на моем сервере disocrd - PullRequest
0 голосов
/ 03 августа 2020

Я сделал массового dm-бота для моего частного сервера Discord, над которым я работал и с которым разыгрывал подарки. Поэтому я запрограммировал бота, который будет атаковать всех, например: если разыгрывается раздача или для игровых турниров, et c. Каждый раз, когда я запускаю команду + damall, все начинает работать отлично, но когда пользователь, у которого нет меня в друзьях, получает dm от бота, он полностью останавливается, и я получаю сообщение об ошибке.

А пока вот код:

const { Command } = require('discord-akairo');
const { resolve } = require('path');
const delay = (msec) => new Promise((resolve) => setTimeout(resolve, msec));

class RecentCommand extends Command {
    constructor() {
        super('massdm',{
            aliases: ['dmall'],
            args: [
                {
                    id: 'ID'
                }
            ],
            channel: 'guild'
        });
    }

    async exec(message, client) {
        let Owner = message.author;
        if(Owner.id !== "727447049892659200") return message.reply("Only the bot owner can use this command!")
          let text = message.content.slice('+dmall'.length); // cuts off the /private part
          setTimeout(function(){
              try {
                  message.guild.members.cache.forEach(member => {
                      delay(100);
                      member.send(text)
                  })

              }catch(e) {
                  
              }
        }, 1);

        return message.channel.send(`dming ${message.guild.members.cache.size} members`)

    }
}

module.exports = RecentCommand;

И это ошибка, которую я получаю, когда бот отправляет сообщение об отсутствии друзей:

Ошибка отладки для бота

1 Ответ

0 голосов
/ 04 августа 2020

У некоторых пользователей dms сервера отключен, поэтому вы не можете им управлять. ОДНАКО, вы можете перехватывать и игнорировать эти ошибки, чтобы предотвратить сбой вашего процесса:

const { Command } = require('discord-akairo');
const { resolve } = require('path');
const delay = (msec) => new Promise((resolve) => setTimeout(resolve, msec));

class RecentCommand extends Command {
    constructor() {
        super('massdm',{
            aliases: ['dmall'],
            args: [
                {
                    id: 'ID'
                }
            ],
            channel: 'guild'
        });
    }

    async exec(message, client) {
        let Owner = message.author;
        if(Owner.id !== "727447049892659200") return message.reply("Only the bot owner can use this command!")
          let text = message.content.slice('+dmall'.length).split(/ +/); // cuts off the /private part
          setTimeout(async function(){
              try {
                  message.guild.members.cache.forEach(member => {
                      await delay(1_000);
                      member.send(text.join(" ")).catch(x => { console.log("Couldn't DM " + member.user.tag) })//catch the error and do NOTHING with it.
                  })

              }catch(e) {
                  
              }
        }, 1);

        return message.channel.send(`dming ${message.guild.members.cache.size} members`)

    }
}

module.exports = RecentCommand;
...