Audio Discord Bot Play/Pause - javascript

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.

Related

Discord.js 12.0.0 msg.content returning blank

I'm making a stats checker bot in discord.js v12.0.0 because I don't want to deal with slash commands and intents, just wanted this to be a quick little project that I throw together. But, after coding for a while a command I made didn't work, and I decided to console log msg.content to see if that was the issue. It shows as completely blank when I log msg.content, as well as logging msg itself. NO, I am not running a self bot, I read that doing that can also give this issue.
Images:
Code:
import Discord from 'discord.js';
const client = new Discord.Client();
import fetch from 'node-fetch';
client.on('ready', () => {
console.log(`online`);
});
let lb;
async function fet() {
await fetch("https://login.deadshot.io/leaderboards").then((res) => {
return res.json();
}).then((res) => {
lb = res;
})
}
client.on('message', async msg => {
console.log(msg)
let channel = msg.channel.id;
if (msg.author.id == client.user.id) return;
if (channel != 1015992080897679370) return;
await fet();
let r;
for (var x in lb.all.kills) {
if (msg.content.toLowerCase() == lb.all.kills[x].name.toLowerCase()) {
r = lb.all.kills[x].name;
}
}
if (!r) return msg.channel.send('Error: user not found')
})
client.login(token)
Discord enforced the Message Content privileged intent, since September 1st.
Here's the announcement from Discord Developers server (invite)
Source message: Discord Developers #api-announcements
You can fix this, but you do need to use intents...
const client = new Discord.Client({
ws: {
intents: [Discord.Intents.ALL, 1 << 15]
}
})
You also need to flip the Message Content intent switch in developer portal
It's much better to update to version 13+, v12 is deprecated and is easily broken.

Play Audio when Joining a Voice Channel DiscordJS v13

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
}

discord.js - Audio Bot creation, only plays sound clips that are less than 50KB

Goal
I want to be able to play longer audio files using my discord bot.
Working Code
Using Discord.js and Node.js, I have created a discord bot.
So far my code is able to join a voice call and can only play very short audio files <50KB. Which is great, besides the short file part.
Testing Process: to test different audiofiles, I simply replace the path, during the resource creation, to be the desired audio file.
I have tested 5 short files and it works great! But the three long files >~75KB, that I have, do not work. No errors pop up, it just doesn't play.
const { SlashCommandBuilder } = require('#discordjs/builders');
const { joinVoiceChannel } = require('#discordjs/voice');
const { createAudioPlayer , createAudioResource, StreamType} = require('#discordjs/voice');
const { createReadStream } = require('node:fs');
const { join } = require('node:path');
const { VoiceConnectionStatus, AudioPlayerStatus } = require('#discordjs/voice');
module.exports = {
data: new SlashCommandBuilder()
.setName('jensenrage')
.setDescription('Joins channel and plays jensen\'s rage'),
async execute(interaction){
const { joinVoiceChannel } = require('#discordjs/voice');
const channel = interaction.member.voice.channel
const connection = joinVoiceChannel({
channelId: channel.id,
guildId: channel.guild.id,
adapterCreator: channel.guild.voiceAdapterCreator,
});
const resource = createAudioResource(createReadStream(join(__dirname, '../AudioFiles/short.mp3')), {
inlineVolume : true
});
resource.volume.setVolume(0.2);
const player = createAudioPlayer();
connection.subscribe(player);
player.play(resource)
await interaction.reply( "Enjoy!")
}
}
I have looked into why this is, but most of the answers do not explain why the short files play but the long ones do not.
I am assuming that this line is the the issue, but unsure why.
const resource = createAudioResource(createReadStream(join(__dirname, '../AudioFiles/short.mp3')), {
inlineVolume : true
});
These are my dependencies
--------------------------------------------------
Core Dependencies
- #discordjs/voice: 0.8.0
- prism-media: 1.3.2
- prism-media: 1.3.2
Opus Libraries
- #discordjs/opus: 0.5.3
- opusscript: 0.0.8
Encryption Libraries
- sodium: not found
- libsodium-wrappers: 0.7.10
- tweetnacl: not found
FFmpeg
- version: 4.4.1-essentials_build-www.gyan.dev
- libopus: yes

problem trying to send a client.reply as an embed Message with discord.js

actually i´m working and learning about discord.js and node.js to make a bot, but i have a simple issue, and i don´t know why the embed messages doesn´t work, i tried with the documentarion examples and code of other devs, but in all cases when i try to send the message to a channel, using client.reply(embed) throws me an error saying me that can send an empty message.
i´m using the last version of discord.js (v13.3.1) and i´m using the basic documentation event and the command handlers (works perfectly if i don´t try to send embeds).
This is my index.js and my help.js files:
//This is my index.js i don´t have problem with this but i include it if there are an issue related with this topic.
const fs = require('fs');
const { Client, Collection, Intents } = require('discord.js');
const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES] });
const { token } = require('./config.json');
client.commands = new Collection();
const commandFiles = fs.readdirSync('./Commands').filter(file => file.endsWith('.js'));
for (const file of commandFiles) {
const command = require(`./Commands/${file}`);
client.commands.set(command.data.name, command);
}
client.on('interactionCreate', async interaction => {
if (!interaction.isCommand()) return;
const command = client.commands.get(interaction.commandName);
if (!command) return;
try {
await command.execute(interaction);
} catch (error) {
console.error(error);
return interaction.reply({ content: 'Parece que ha ocurrido algun problema con el comando.', ephemeral: true });
}
});
const eventFiles = fs.readdirSync('./Events').filter(file => file.endsWith('.js'));
for (const file of eventFiles) {
const event = require(`./Events/${file}`);
if (event.once) {
client.once(event.name, (...args) => event.execute(...args));
} else {
client.on(event.name, (...args) => event.execute(...args));
}
}
client.login(token);
Now the help.js , this is going to be a Command, but i don´t wanna only to code the commands using the SlashCommands, because of it i´m triying to create this as an event:
//This is the help command using an event
const { clientId } = require("../config.json");
const { MessageEmbed } = require("discord.js");
//testx is going to store the embed message
const testx = new MessageEmbed().setTitle('Test').setDescription('Test');
module.exports = {
name: 'messageCreate',
execute(client) {
//This condition determines if isn´t a message of the bot, and if the written command is !!help
if (client.author.id !== clientId && client.content === '!!help') {
//if the condition is true, send the embed message
//client.reply(testx); //the problem is here.
console.log(testx);
}
},
};
And this is the error i got from the terminal:
DiscordAPIError: Cannot send an empty message
at RequestHandler.execute (C:\Users\ //...and more info of my dirs
if i print the testx const in my console, i can see the two values i setted in the const filled with the text "Test", i don´t know why isn´t work or what i need to take this to work.
Thanks and i appreciate any help.
In V13, embeds must be sent differently.
client.reply({embeds: [testx]});
I also recommend editing client to interaction in your command files as it may be misleading, or to actually pass the client and interaction, as you'll most likely need to access the client at some point.
Also, you seem to be confusing interactions with messages.
Interactions do not have an author property, you must use user or member.
They also do not have a content property, to get an argument you must use interaction.options
You also, as far as I can see, are not actually deploying your commands. It looks like you've merged the V12 and V13 command handler tutorial together. I reccomend reading this tutorial again, and making sure you're doing it properly for V13.

Cannot read properties of undefined (reading 'join') Discord.js

im trying to create my discord music bot, but when i run it. It cannot join my voiceChannel, returning this error: channel_info.channelId.join is not a function. Below, my code:
const Discord = require('discord.js');
const bot = new Discord.Client({ intents: ["GUILDS", "GUILD_MESSAGES"] });
const ytdl = require('ytdl-core');
const streamOptions = { seek: 0, volume: 1 };
const botToken = 'mytoken';
bot.login(botToken);
bot.on('ready', () => {
console.log('to olain');
});
bot.on('message', msg => {
if (msg.author.bot) {
return;
}
if (msg.content.toLowerCase().startsWith(';p')) {
const channel_info = msg.member.guild.voiceStates.cache.find(user => user.id == msg.author.id);
if (channel_info.channelId == null) {
return console.log('Canal não encontrado!');
}
console.log('Canal encontrado');
channel_info.channelId.join().then(connection => {
const stream = ytdl('https://www.youtube.com/watch?v=BxmMGnvvDCo', { filter: 'audioonly' });
const DJ = connection.playStream(stream, streamOptions);
DJ.on('end', end => {
channel_info.channelId.leave();
});
})
.catch(console.error);
}
});
There are several issues in this code. Even if we fix some of these issues, this code will still not work due to differences between discord.js v12 and v13. Let's get started.
Issue #1
This is not one of the core issues causing your code to not work, but it's something useful to consider. You are doing this to get the voice state of the message author:
msg.member.guild.voiceStates.cache.find(user => user.id == msg.author.id);
When you could easily do the exact same thing in a much shorter, less-likely-to-produce-errors way:
msg.member.voice;
Issue #2
Now this is a core issue causing your code to not work. In fact, it is causing the error in your question. You are trying to do:
channel_info.channelId.join();
That does not make sense. You are trying to join a channel ID? channelId is just a String of numbers like so: "719051328038633544". You can't "join" that String of numbers. You want to join the actual channel that the member is in, like so:
channel_info.channel.join();
Issue #3
Based on how you are using a channelId property instead of channelID, I assume you are on discord.js v13. Voice channels do not have a .join() method on v13; in fact, discord.js v13 has no support for joining or playing audio in voice channels. You must install the discord.js/voice package in order to join a voice channel in discord.js v13. This is critical. Even if you fix the above two issues, you must solve this third issue or your code will not work (unless you downgrade to discord.js v12).

Categories

Resources