Bad Audio Quality With discordjs/voice - discord.js

I am trying to make a Discord music bot with Discord.js v14 and #discord.js/voice and I have got it to join a voice channel and play an mp3 file. However, the audio quality is terrible (bass is VERY bad) - but the mp3 file is fine when played normally.
My code:
const connection = DiscordVoice.joinVoiceChannel({
channelId: `1021824877130424461`,
guildId: `729979584296124467`,
adapterCreator: interaction.guild.voiceAdapterCreator,
})
const player = DiscordVoice.createAudioPlayer({
behaviors: {
noSubscriber: DiscordVoice.NoSubscriberBehavior.Pause,
},
})
player.on(DiscordVoice.AudioPlayerStatus.Playing, () => {
console.log('The audio player has started playing!')
});
const resource = DiscordVoice.createAudioResource(path.join(process.cwd(), `/Ready_Set_Chill.mp3`), { inlineVolume: true })
resource.volume.setVolumeLogarithmic(100)
player.play(resource)
connection.subscribe(player)
interaction.reply(`Playing.`)
Any help would be much appreciated!

Related

Discord.js Ping Latency Inside Embed from Slash Command

Newbie here. I am trying to get a slash command to send an embed with the amount of time it took between the initial message and the message response time. I am getting TypeError: Cannot read properties of undefined (reading 'createdTimestamp') and Error [INTERACTION_ALREADY_REPLIED]: The reply to this interaction has already been sent or deferred. I've jumped around looking at others code trying to find a way to make this work but slash command handling still doesn't make a lot of sense to me. My code block is below. I followed along with https://discordjs.guide so if you have any other suggestions with structure feel free to comment them below. Thank you!
const { SlashCommandBuilder } = require('#discordjs/builders');
const { MessageEmbed } = require('discord.js');
module.exports = {
data: new SlashCommandBuilder()
.setName('ping')
.setDescription('Replies with Pong!'),
async execute(interaction) {
await interaction.reply("Pinging bot...").then (async (msg) =>{
const exampleEmbed = new MessageEmbed()
.setColor('0x0000ff')
.setTitle('Pong! :ping_pong:')
.addField("Time taken: ", `${msg.createdTimestamp - message.createdTimestamp}`)
.setThumbnail("https://78.media.tumblr.com/be43242341a7be9d50bb2ff8965abf61/tumblr_o1ximcnp1I1qf84u9o1_500.gif")
interaction.editReply({ embeds: [exampleEmbed] });
})
},
};
first you need to fetch the reply you send, u can use fetchReply to get the interaction reply. instead of replying with "Pinging bot..." you can defer the reply and then use the createdTimestamp. A basic example of a ping command would be
const { SlashCommandBuilder } = require('#discordjs/builders');
module.exports = {
data: new SlashCommandBuilder()
.setName('ping')
.setDescription('Replies with Pong!'),
async execute(interaction) {
const sent = await interaction.reply({ content: 'Pinging...', fetchReply: true });
await interaction.editReply(`:ping_pong: Pong!\n:stopwatch: Uptime: ${Math.round(interaction.client.uptime / 60000)} minutes\n:sparkling_heart: Websocket heartbeat: ${interaction.client.ws.ping}ms.\n:round_pushpin: Rountrip Latency: ${sent.createdTimestamp - interaction.createdTimestamp}ms`);
},
};
You can customize the response into an embed or however you like. The djs guide has a section on ping command here

Discord.js Forward DM message to specific channel

So, I need a way to forward a message sent in the bot's dm to a specific channel in my server.
this is the code that I got so far:
execute(message, args) {
if(message.channel.type == "dm"){
let cf = args.join(' ')
const cfAdm = message.guild.channels.cache.get('767082831205367809')
let embed = new discord.MessageEmbed()
.setTitle('**CONFISSรƒO**')
.setDescription(cf)
.setColor('#000000')
const filter = (reaction, user) => ['๐Ÿ‘', '๐Ÿ‘Ž'].includes(reaction.emoji.name);
const reactOptions = {maxEmojis: 1};
cfAdm.send(embed)
.then(function (message) {
message.react('๐Ÿ‘')
.then(() => message.react('๐Ÿ‘Ž'))
/**** start collecting reacts ****/
.then(() => message.awaitReactions(filter, reactOptions))
/**** collection finished! ****/
.then(collected => {
if (collected.first().emoji.name === '๐Ÿ‘') {
const cfGnr = message.guild.channels.cache.get('766763882097672263')
cfGnr.send(embed)
}
})
});
}
else {
message.delete()
message.channel.send('Send me this in the dm so you can stay anon')
.then (message =>{
message.delete({timeout: 5000})
})
}
}
But for some reason that I can't seem to understand, it gives me this error:
TypeError: Cannot read property 'channels' of null
If anyone can help me, that would be greatly apreciated.
Thanks in advance and sorry for the bad english
The error here is that you are trying to call const cfAdm = message.guild.channels.cache.get('ID') on a message object from a Direct Message channel ( if(message.channel.type == "dm"){)
DMs don't have guilds, therefore message.guild is null and message.guild.channels does not exist.
You will need to first access the channel some other way. Luckily, Discord.js has a way to access all channels the bot can work with* (you don't need to muck around with guilds because all channels have unique IDs):
client.channels.fetch(ID) or client.channels.cache.get(ID)
(I have not tested this but it seems fairly straight forward)
*See the link for caveats that apply to bots in a large amount of servers.

how to make your bot send more than one direct embedded messages on discord

I'm new to coding and to be honest sometimes i don't know what i am doing, i try looking for videos online but i cant find the right answer or i don't get what they are trying to say.I hope someone can tell me what to do or what i am doing wrong in this coding.
const Discord = require("discord.js");
const colors = require("./colors.json");
const bot = new Discord.Client({disableEveryone: true});
const token = 'my token';
const PREFIX = '!';
bot.on("ready", async () => {
console.log(`${bot.user.username} is online!`)
bot.user.setActivity("Live chat", {type: "HELPING"});
})
bot.on("message", async message => {
let args = message.content.substring(PREFIX.length).split(" ");
if (message.author.bot) return;
if (message.content.startsWith ("!Help") || (message.content.startsWith ("!help"))){
let uEmbed = new Discord.MessageEmbed()
.setColor(colors.blue)
.setTitle("**Hello there Human how can i help you today?**")
.addField('**1. If you need help or have an issue with a purchase please type**', '**Purchase**')
.addField('**2. If you need help or have an issue with Impulse mod please type**', '**Impulse**')
.addField('**3. If you need help or have an issue with GTA V Game key please type**', '**GTA V**')
.addField('**4. If you need help or have an issue with Spotify Premium Key type**', '**Spotify**')
.setTimestamp()
.setFooter(`Live chat bot | At your service`, bot.user.defaultAvatarURL)
message.author.send({embed: uEmbed})
}
if (message.content.startsWith ("Purchase") || (message.content.startsWith ("purchase"))){
let uEmbed = new Discord.MessageEmbed()
.setColor(colors.aqua)
.setTitle("**Our bot is not ready for this command**")
.addfiled ("please creat a ticket on the **#ใ€Ž๐ŸŽซใ€support-ticket chennel** in the Knight-Shop Server and staff will be in touch with you shortly.")
.setTimestamp()
.setFooter(`Live chat bot | At your service`, bot.user.defaultAvatarURL)
message.author.send({embed: uEmbed});
}
})
bot.login(token);
(node:3864) UnhandledPromiseRejectionWarning: TypeError: (intermediate value).setColor(...).setTitle(...).addfiled is not a function
In general you should learn the base language first before using a framework / API, in this case you made a simple typo, addfiled instead of addField like you did above

Discord.JS music bot instantly disconnects

I am trying to make a Discord Music Bot (discord.js), but everytime the bot connects to the channel to play music it disconnects instantly.
This is the tutorial I have followed: https://gabrieltanner.org/blog/dicord-music-bot
There are not any errors and the ffmpeg is installed.
I am running the bot on a centos 8 VPS, and I have other bots that work fine (not music ones xD)
In the play function, delete the line that contains serverQueue.voiceChannel.leave();.
function play(guild, song) {
const serverQueue = queue.get(guild.id);
if (!song) {
serverQueue.voiceChannel.leave();
queue.delete(guild.id);
return;
}
}
The resulting code should like this:
function play(guild, song) {
const serverQueue = queue.get(guild.id);
if (!song) {
queue.delete(guild.id);
return;
}
}
Maybe you can setTimeout for this
if (!song) {
setTimeout(function () {
serverQueue.voiceChannel.leave();
queue.delete(guild.id);
return;
}, 300000);
}

voiceConnection.receiver and voiceReciever.createPCMStream not receiving data

The title is my problem. Here is the code I'm using:
const voiceChannel = message.guild.channels.find(channel => channel.name === args[0]);
if (!voiceChannel || voiceChannel.type !== 'voice') {
return message.reply(`I couldn't find the voice channel ${args[0]}.`);
}
await voiceChannel.join();
let connection = message.guild.voiceConnection;
connection.on('speaking', (user, speaking) => {
if(speaking) {
const receiver = connection.createReceiver();
const stream = receiver.createPCMStream(user);
receiver.on('opus', (user, buffer) => {
console.log('got some data');
});
stream.on('data', chunk => {
console.log(chunk.length);
});
}
});
Nothing prints in the console, so I guess the stream and voice receiver just aren't receiving any data. Also, I've looked at lots of posts and lots of people use this code and it works for them. If anybody knows why this is happening please help!!
Thanks in advance.
It's a bit late to answer but might help someone else.
You must send a silent frame first.
const { Readable } = require('stream');
class Silence extends Readable {
_read() {
this.push(Buffer.from([0xF8, 0xFF, 0xFE]));
}
}
Once the connection is established with the voice channel you can do something like this:
connection.on('ready', ()=>{
connection.play(new Silence(), { type: 'opus' });
})
For more details, you can visit this page

Resources