I've been trying all night to get a simple task working, but yet I am not able to figure out how.
Basically what I achieved is that the Bot joins a Voice Channel when somebody joins, play an Audio file and that's it. What I want to achieve is that it joins when somebody joins, play the Audio file and then leave and as when somebody leaves the voice chat. It's supposed to join the voice chat, play a different audio file and then leave again.
All in all seems easy, but I've been banging my head against it with no results. If possible I would also like to have the code be tidy there aswell.
Here is the code (using discord.js v13):
client.on('voiceStateUpdate', (oldState, newState) => {
if (oldState.channelId === null) {
console.log("Joined")
//playAudio(newState.channelId, './files/bruh.mp3')
const connection = joinVoiceChannel({
channelId: newState.channelId,
guildId: newState.guild.id,
adapterCreator: newState.guild.voiceAdapterCreator,
})
console.log(newState.guild.voiceAdapterCreator)
const player = createAudioPlayer();
connection.subscribe(player)
const resource = createAudioResource('./files/riff.mp3')
player.play(resource)
} else if (newState.channelId === null) {
console.log("Left")
}
});
Edith: With when somebody joins. I mean when somebody joins Voice Chat.
After a Good Nights sleep I was able to figure it out, for anyone corious, here is the code!
var isReady = true
function playAudio(chID, guID, adpID, audioFile) {
isReady = false
const connection = joinVoiceChannel({
channelId: chID,
guildId: guID,
adapterCreator: adpID,
})
const player = createAudioPlayer();
connection.subscribe(player)
const resource = createAudioResource(audioFile)
player.play(resource)
player.on(AudioPlayerStatus.Idle, () => {
connection.destroy()
});
isReady = true
}
Related
I recently made a discord word filter bot and I was wondering how I could make it configurable per server? I want to be able to make a command that adds words to be filtered to the code and I want people to be able to add a custom prefix per server. I also want people to be able to set their log channel per server. Can someone help me with this please? I spent a lot of time on this bot and I dont want to just keep making more of the same bot for different servers. I'm using discord.js 12.5.3. I'll attach my code below.
const Discord = require('discord.js');
const client = new Discord.Client();
client.once('ready', async () => {
console.log('yay, the bot is online')
client.user.setActivity('im real', {type: 'PLAYING'})
})
client.on('message', async message => {
if(message.channel.type === 'dm' || message.author.bot) return;
const logChannel = client.channels.cache.find(channel => channel.id === '921730444498726924')
let words = [“bad”, “words”, “here”]
let foundInText = false;
for (var i in words) {
if (message.content.toLowerCase().includes(words[i].toLowerCase())) foundInText = true;
}
if (foundInText) {
let logEmbed = new Discord.MessageEmbed()
.setDescription(<#${message.author.id}> Said a bad word)
.addField('The Message', message.content)
.setColor('RANDOM')
.setTimestamp()
logChannel.send(logEmbed)
let embed = new Discord.MessageEmbed()
.setDescription('That word is not allowed here')
.setColor('RANDOM')
.setTimestamp()
let msg = await message.channel.send(embed);
message.delete()
msg.delete({timeout: '3500'})
}
})
I've tried following a tutorial but it didn't help because I need one specifically for my case. If anyone could help, that would be great.
I know a lot of people already asked how to play music from youtube in discord voice channel, but I can't find anything about playing local files on djs version 13.2.0!
I tried using this code:
const { createReadStream } = require('fs');
const { join } = require('path');
const { createAudioResource, StreamType, createAudioPlayer, joinVoiceChannel } = require('#discordjs/voice');
joinVoiceChannel({
channelId: message.member.voice.channel.id,
guildId: message.guild.id,
adapterCreator: message.guild.voiceAdapterCreator
});
message.guild.me.voice.setRequestToSpeak(true);
let resource = createAudioResource(join(../music/audio.mp3, 'audio.mp3'));
const player = createAudioPlayer();
player.play(resource);
When I try to eval() it - my bot joins the channel (stage channel) and says everything worked, but it's not playing anything! How can I make my bot play local music files in stage channel?
There are 2 problems here.
Firstly, the path is completely wrong. It is not a string and even if you try to change it to a string it will be invalid as the first argument ends with audio.mp3, and the second one is audio.mp3. Use this path instead:
let resource = createAudioResource(join('..', 'music', 'audio.mp3'));
Secondly, you are playing audio in the player, but not the voice connection. You must subscribe to the audio player.
This should be the final code:
const player = createAudioPlayer()
joinVoiceChannel({
channelId: message.member.voice.channel.id,
guildId: message.guild.id,
adapterCreator: message.guild.voiceAdapterCreator
}).subscribe(player)
message.guild.me.voice.setRequestToSpeak(true);
let resource = createAudioResource(join('..', 'music', 'audio.mp3'));
player.play(resource)
I recently installed Discord.js 13.1.0 and my music commands broke because, apparently, channel.join(); is not a function, although I have been using it for months on 12.5.3...
Does anybody know a fix for this?
Some parts of my join command:
const { channel } = message.member.voice;
const voiceChannel = message.member.voice.channel;
await channel.join();
It results in the error.
Discord.js no longer supports voice. You need to use the other package they made (#discordjs/voice). You can import joinVoiceChannel from there.
//discord.js and client declaration
const { joinVoiceChannel } = require('#discordjs/voice');
client.on('messageCreate', message => {
if(message.content === '!join') {
joinVoiceChannel({
channelId: message.member.voice.channel.id,
guildId: message.guild.id,
adapterCreator: message.guild.voiceAdapterCreator
})
}
})
Hey I'm working with this bot that's open-source It's the most responsive bot for messing with my friends and uses Discord.js
The issue I have is when the bot detects voice it starts the audio file from the beginning. I want it to pause then resume the file unless its reached the end. Unfortunately I am not familiar with discord.js
If anyone can give me a hand that would be fantastic!
const fs = require('fs'),
{ Client, } = require('discord.js')
const { token, bypass } = require('./config.json')
const client = new Client()
let previousChannel, connection, dispather;
client
.on('ready', () => {
console.log(`Logged in as ${client.user.tag}`)
})
.on('voiceStateUpdate', async (oldState, newState) => {
if (newState.id == client.user.id) return
if (newState.channelID !== null) previousChannel = newState.channelID
if (newState.channelID == null && !bypass.includes(newState.id) && !!previousChannel) {
client.channels.cache.get(previousChannel).leave()
return [previousChannel, dispather] = [null, null];
}
if (bypass.includes(newState.id)) return
let channel = client.channels.cache.get(newState.channelID)
if (!channel) return
return connection = await channel.join()
})
.on('guildMemberSpeaking', async (member, speaking) => {
if (!connection) return
if (bypass.includes(member.user.id)) return
if (!dispather)
dispather = connection.play(fs.createReadStream('./audio.mp3'), {
volume: 1
})
else if (dispather && !speaking.bitfield) {
dispather.destroy()
dispather = undefined
}
})
.on('error', console.log)
.on('warn', console.log)
.login(token)
process.on('unhandledRejection', console.log)
You could use StreamDispatcher's .resume() and .pause() methods.
if (speaking.bitfield) {
dispather.resume();
} else {
dispather.pause();
}
If you are using Node.js v14.17.0+ there may be some weird bugs occurring.
I also found this happening for LTS v14.17.0
Fixed by using v14.16
Also you might find helpful Discord.js's new Voice API implementation they are working on.
We're working on a new implementation of Discord's Voice API that has better playback quality and is more reliable than what we currently support in Discord.js v12.
The new library solves many of the issues that users are facing, and as part of this, we're dropping built-in support for voice in our next major release.
I'm making a discord bot and I came across a problem, if I type $join into chat, I want the bot to join the voice channel I'm in and play a sound. That is working but when the bot is already in the voice channel and I type $join again, it just plays the sound again and I want it to play the sound only once when it connects to the channel. I tried to solve it with some if, else and return functions but it didn't work, thanks for help.
This is my code working like I described.
message.delete({
timeout: 5000
})
const voiceChannel = message.member.voice.channel
if (voiceChannel) {
const connection = await voiceChannel.join()
const dispatcher = connection.play("./sounds/xxx.mp3")
dispatcher.setVolume(0.5)
} else {
message.reply("you need to be in a voice channel!").then(message => {
message.delete({
timeout: 5000
})
})
}
You need to check whether the channel of your voice connection is the same you're about to join: if so, you don't need to do anything (you're already in the channel), otherwise you join, make the sound etc...
You can do this with VoiceConnection.channel
Here's how I would do it:
const voiceChannel = message.member.voice.channel
if (voiceChannel) {
// Check if any of the ALREADY EXISTING connections are in that channel, if not connect
if (!client.voice.connections.some(conn => conn.channel.id == voiceChannel.id)) {
const connection = await voiceChannel.join()
const dispatcher = connection.play("./sounds/xxx.mp3")
dispatcher.setVolume(0.5)
} // else: you're already in the channel
} else {
let m = await message.reply("You need to be in a voice channel!")
m.delete({ timeout: 5000 })
}