【问题标题】:Discord Bot responding multiple times on an eventDiscord Bot 多次响应事件
【发布时间】:2021-08-13 02:30:05
【问题描述】:

问题是当歌曲被添加到队列中时,机器人会多次响应。第一次运行命令时,它只响应一次,当该事件第二次发生时,它会响应两次。

示例: *玩加比博混搭 播放:Gabibbo 混搭-00:26。 第二次: *play Gabibbo Mashup 播放:Gabibbo 混搭 - 00:26 播放:Gabibbo Mashup - 00:26)

代码:

const Discord = require('discord.js');
const client = new Discord.Client();
const keepAlive = require('./server.js');
const distube = new DisTube(client, { searchSongs: false, emitNewSongOnly: true })

const prefix = "*"
client.on("ready", () => {
    console.log('I am ready')
});

client.on("message", async (message) => {
    if (message.author.bot) return;
    if (!message.content.startsWith(prefix)) return;
    const args = message.content.slice(prefix.length).trim().split(/ +/g);
    const command = args.shift();

    // Queue status template
    const status = (queue) => `Volume: \`${queue.volume}%\` | Filter: \`${queue.filter || "Off"}\` | Loop: \`${queue.repeatMode ? queue.repeatMode == 2 ? "All Queue" : "This Song" : "Off"}\` | Autoplay: \`${queue.autoplay ? "On" : "Off"}\``;

    // DisTube event listeners, more in the documentation page
    distube
        .on("playSong", (message, queue, song) => message.channel.send(
            `Playing: **${song.name}** - **${song.formattedDuration}**`))
            
        .on("addSong", (message, queue, song) => message.channel.send(
            `Added **${song.name}** - **${song.formattedDuration}** to the queue by ${song.user}`,
            
        ))
        .on("playList", (message, queue, playlist, song) => message.channel.send(
            `Play **${playlist.name}** playlist (${playlist.songs.length} songs).\nRequested by: ${song.user}\nNow playing **${song.name}** - **${song.formattedDuration}**\n${status(queue)}`
        ))
        
        .on("addList", (message, queue, playlist) => message.channel.send(
            `Added **${playlist.name}** playlist (${playlist.songs.length} songs) to queue\n${status(queue)}`
           
        ))
        
        // DisTubeOptions.searchSongs = true
        .on("searchResult", (message, result) => {
            let i = 0;
            message.channel.send(`**Choose an option from below**\n${result.map(song => `**${++i}**. ${song.name} - \`${song.formattedDuration}\``).join("\n")}\n*Enter anything else or wait 60 seconds to cancel*`);
            
        })
        // DisTubeOptions.searchSongs = true
        .on("searchCancel", (message) => message.channel.send(`Searching canceled`))
        .on("error", (message, e) => {
            console.error(e)
            message.channel.send("An error encountered: " + e);
        });
        if (["p", "play"].includes(command)){
            if (!args[0]) return message.channel.send('You must state something to play');
            if (!message.member.voice.channel) return message.channel.send('You must be in a voice channel to play music');
            distube.play(message, args.join(" "));
        }
        if (command == 'stop') {
            const bot = message.guild.members.cache.get(client.user.id);
            if (!message.member.voice.channel) return message.channel.send('You must be in a voice channel to stop music');
            if (bot.voice.channel !== message.member.voice.channel) message.channel.send('You must be in the same voice channel as me.');
            distube.stop(message, args.join(" "));
            message.channel.send('I have stopped that song for you')
        }

        if  (["s", "skip"].includes(command)){
            distube.skip(message);
            message.channel.send('I have skipped that song')
        } 
        if (command == 'queque') {
            let queue = distube.getQueue(message);
        message.channel.send('Current queue:\n' + queue.songs.map((song, id) =>
            `**${id + 1}**. **${song.name}** - **${song.formattedDuration}**`
        ).slice(0, 10).join("\n"));
       
        }
         if (["repeat", "loop"].includes(command)) {
        distube.setRepeatMode(message, parseInt(args[0]))
        message.channel.send(`${song.name} is looped`)
        }
        if ([`3d`, `bassboost`, `echo`, `karaoke`, `nightcore`, `vaporwave`].includes(command)) {
            let filter = distube.setFilter(message, command);
            message.channel.send("Current queue filter: " + (filter || "Off"));
        }
});

keepAlive();
client.login(process.env.TOKEN);

【问题讨论】:

    标签: javascript discord.js distube


    【解决方案1】:

    每次收到消息时,都会添加更多事件侦听器:

    client.on("message", async (message) => {
        // other stuff
        distube.on("playSong", (message, queue, song) => message.channel.send(
            `Playing: **${song.name}** - **${song.formattedDuration}**`
        ));
    });
    

    需要改为

    client.on("message", async (message) => {
        // other stuff
    });
    distube.on("playSong", (message, queue, song) => message.channel.send(
        `Playing: **${song.name}** - **${song.formattedDuration}**`
    ));
    

    const Discord = require('discord.js');
    const client = new Discord.Client();
    const keepAlive = require('./server.js');
    const distube = new DisTube(client, { searchSongs: false, emitNewSongOnly: true })
    
    const prefix = "*"
    client.on("ready", () => {
        console.log('I am ready')
    });
    
    client.on("message", async (message) => {
        if (message.author.bot) return;
        if (!message.content.startsWith(prefix)) return;
        const args = message.content.slice(prefix.length).trim().split(/ +/g);
        const command = args.shift();
    
        // Queue status template
        const status = (queue) => `Volume: \`${queue.volume}%\` | Filter: \`${queue.filter || "Off"}\` | Loop: \`${queue.repeatMode ? queue.repeatMode == 2 ? "All Queue" : "This Song" : "Off"}\` | Autoplay: \`${queue.autoplay ? "On" : "Off"}\``;
        if (["p", "play"].includes(command)){
            if (!args[0]) return message.channel.send('You must state something to play');
            if (!message.member.voice.channel) return message.channel.send('You must be in a voice channel to play music');
            distube.play(message, args.join(" "));
        }
        if (command == 'stop') {
            const bot = message.guild.members.cache.get(client.user.id);
            if (!message.member.voice.channel) return message.channel.send('You must be in a voice channel to stop music');
            if (bot.voice.channel !== message.member.voice.channel) message.channel.send('You must be in the same voice channel as me.');
            distube.stop(message, args.join(" "));
            message.channel.send('I have stopped that song for you')
        }
    
        if  (["s", "skip"].includes(command)){
            distube.skip(message);
            message.channel.send('I have skipped that song')
        } 
        if (command == 'queque') {
            let queue = distube.getQueue(message);
        message.channel.send('Current queue:\n' + queue.songs.map((song, id) =>
            `**${id + 1}**. **${song.name}** - **${song.formattedDuration}**`
        ).slice(0, 10).join("\n"));
    
        }
         if (["repeat", "loop"].includes(command)) {
        distube.setRepeatMode(message, parseInt(args[0]))
        message.channel.send(`${song.name} is looped`)
        }
        if ([`3d`, `bassboost`, `echo`, `karaoke`, `nightcore`, `vaporwave`].includes(command)) {
            let filter = distube.setFilter(message, command);
            message.channel.send("Current queue filter: " + (filter || "Off"));
        }
    });
    
    // DisTube event listeners, more in the documentation page
    distube
        .on("playSong", (message, queue, song) => message.channel.send(
            `Playing: **${song.name}** - **${song.formattedDuration}**`))
    
        .on("addSong", (message, queue, song) => message.channel.send(
            `Added **${song.name}** - **${song.formattedDuration}** to the queue by ${song.user}`,
    
        ))
        .on("playList", (message, queue, playlist, song) => message.channel.send(
            `Play **${playlist.name}** playlist (${playlist.songs.length} songs).\nRequested by: ${song.user}\nNow playing **${song.name}** - **${song.formattedDuration}**\n${status(queue)}`
        ))
    
        .on("addList", (message, queue, playlist) => message.channel.send(
            `Added **${playlist.name}** playlist (${playlist.songs.length} songs) to queue\n${status(queue)}`
    
        ))
    
        // DisTubeOptions.searchSongs = true
        .on("searchResult", (message, result) => {
            let i = 0;
            message.channel.send(`**Choose an option from below**\n${result.map(song => `**${++i}**. ${song.name} - \`${song.formattedDuration}\``).join("\n")}\n*Enter anything else or wait 60 seconds to cancel*`);
    
        })
        // DisTubeOptions.searchSongs = true
        .on("searchCancel", (message) => message.channel.send(`Searching canceled`))
        .on("error", (message, e) => {
            console.error(e)
            message.channel.send("An error encountered: " + e);
        });
    keepAlive();
    client.login(process.env.TOKEN);

    【讨论】:

    • 如果我在以下位置关闭代码块:client.on("message", async (message) => { // other stuff }) 系统无法访问命令变量
    • 据我所知,您没有在任何distube 事件处理程序中使用command
    • 你是对的,但我需要在事件处理程序之后使用它,其中实际上有命令:` if (["p", "play"].includes(command)){ if ( !args[0]) return message.channel.send('你必须声明要玩的东西'); if (!message.member.voice.channel) return message.channel.send('你必须在语音频道才能播放音乐'); distube.play(消息,args.join(“”)); }`
    • 你只需要将 distube 事件处理程序移到外面,其他的都应该留在里面。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-07-13
    • 2021-12-16
    • 1970-01-01
    • 2017-10-02
    • 2021-04-15
    • 2020-12-15
    相关资源
    最近更新 更多