简体   繁体   中英

How to play random sound

I'm making a discord bot, and I want it to play a random mp3 file when it joins channel.

case"join":
            message.delete( {timeout: 5000})
            const voiceChannel = message.member.voice.channel
            if(voiceChannel) {
                const connection = await voiceChannel.join()
                const files = fs.readdirSync("./sounds/")
                const randFile = files[Math.floor(Math.random() * files.length)]
                const dispatcher = connection.play(randFile)
            } else {
                message.reply("you need to be in a voice channel!").then(message => message.delete( {timeout: 5000}))
            }
            break;

When I type $join in chat, it joins voice channel that I'm in but doesn't play anything.

You forgot to add the file path.

case "join":
message.delete({ timeout: 5000 })
const voiceChannel = message.member.voice.channel
if (voiceChannel) {
  const connection = await voiceChannel.join()
  const files = fs.readdirSync("./sounds/")
  const randFile = files[Math.floor(Math.random() * files.length)]
  const dispatcher = connection.play(`./sounds/${randFile}`) // Obviously change `.mp3` to the file extension of your sound files.
} else {
  message.reply("you need to be in a voice channel!").then(message => message.delete({ timeout: 5000 }))
}
break;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM