The audio does not play on the voice channel - discord.js

The bot connects to the voice channel, but there is no sound. Here's my code status.
I've tried many ways, but it's the same reaction over and over again. I need your advice
const { createAudioResource, createAudioPlayer, joinVoiceChannel, NoSubscriberBehavior, AudioPlayerStatus, generateDependencyReport, getVoiceConnection, VoiceConnectionStatus } = require('#discordjs/voice');
module.exports = {
name: "play",
async execute(message, args, client ) {
arguments = args.shift(2)
///const arguments = args.shift(1)
////console.log(arguments)
const connection = joinVoiceChannel({
channelId: message.member.voice.channelId,
guildId: message.guildId,
adapterCreator: message.guild.voiceAdapterCreator
})
const player = createAudioPlayer()
const resource = createAudioResource('../music/123.mp3')
player.play(resource, {seek: 0, volume: 1.0})
await wait(5000)
console.log("time")
connection.destroy();
}
}
and pakage
"dependencies": {
"#discordjs/builders": "^1.2.0",
"#discordjs/opus": "^0.8.0",
"#discordjs/rest": "^1.1.0",
"#discordjs/voice": "^0.11.0",
"discord-api-types": "^0.37.8",
"discord.js": "^14.3.0",
"ffmpeg-static": "^5.1.0",
"libsodium-wrappers": "^0.7.10",
"ms": "^2.1.3",
"node.js": "^0.0.1-security",
"redis": "^4.3.1"

The problem with your code is that you did not subscribe to the connection.
You should do:
const connection = joinVoiceChannel({
channelId: message.member.voice.channelId,
guildId: message.guildId,
adapterCreator: message.guild.voiceAdapterCreator
})
const player = createAudioPlayer()
const resource = createAudioResource('../music/123.mp3')
player.play(resource, {seek: 0, volume: 1.0})
connection.subscribe(player);
And if you want to destroy the connection after the resource ended, You can use the idle event:
const {AudioPlayerStatus} = require('#discordjs/voice');
player.on(AudioPlayerStatus.Idle, () => {
connection.destroy();
});

Related

Discord js - Ticket system

TICKET PROBLEM
When I reopen the ticket and want to close it again, the "interaction.channel.edit" function is not working, why?
There are no errors, version v13
When I close my ticket before reopening, everything is fine
//Now I am writing a sample message because they are stating that I wrote the code alone
const client = require("../index");
const { createTranscript } = require('discord-html-transcripts');
const { MessageEmbed, MessageActionRow, MessageButton, Message } = require("discord.js");
client.on("interactionCreate", async (interaction) => {
// Slashe
if (interaction.isCommand()) {
await interaction.deferReply({ ephemeral: false }).catch((error) => { console.log(error)});
const cmd = client.slashCommands.get(interaction.commandName);
if (!cmd)
return interaction.followUp({ content: "Wystapil jakis blad!" });
const args = [];
for (let option of interaction.options.data) {
if (option.type === "SUB_COMMAND") {
if (option.name) args.push(option.name);
option.options?.forEach((x) => {
if (x.value) args.push(x.value);
});
} else if (option.value) args.push(option.value);
}
interaction.member = interaction.guild.members.cache.get(interaction.user.id);
cmd.run(client, interaction, args);
}
// Context menu
if (interaction.isContextMenu()) {
await interaction.deferReply({ ephemeral: false });
const command = client.slashCommands.get(interaction.commandName);
if (command) command.run(client, interaction);
}
// Buttony
if(interaction.isButton()) {
await interaction.deferUpdate()
if(interaction.customId === 'verify') {
let error = 0
const roleAdd = interaction.guild.roles.cache.get('949702807517265930')
const roleRemove = interaction.guild.roles.cache.get('949702776508792864')
if(!interaction.guild.me.permissions.has('ADMINISTRATOR')) {
const channel = interaction.guild.channels.cache.get("949716268146131066")
const embed = new MessageEmbed()
.setColor('RED')
.setTitle("ERROR")
.setDescription("Nie posiadam permissji potrzebnych do weryfikacji!")
.setTimestamp();
error = 1
channel.send({ embeds:[embed]});
}
if(interaction.guild.me.roles.highest.position <= roleAdd.position){
const channel = interaction.guild.channels.cache.get("949716268146131066")
const embed = new MessageEmbed()
.setColor('RED')
.setTitle("ERROR")
.setDescription("Moja rola jest niżej niż rola, którą dodaje podczas weryfikacji!")
.setTimestamp();
error = 1
channel.send({ embeds:[embed]});
}
if(interaction.guild.me.roles.highest.position <= roleRemove.position){
const channel = interaction.guild.channels.cache.get("949716268146131066")
const embed = new MessageEmbed()
.setColor('RED')
.setTitle("ERROR")
.setDescription("Moja rola jest niżej niż rola, którą zabieram podczas weryfikacji")
.setTimestamp();
error = 1
channel.send({ embeds:[embed]});
}
if(error > 0){
interaction.guild.members.cache.get("613438379174133770").send("Błąd podczas weryfikacji!")
return interaction.member.send("Wystąpił błąd podczas weryfikacji!");
}
await interaction.member.roles.add(roleAdd)
await interaction.member.roles.remove(roleRemove)
interaction.member.send("Pomyślnie zweryfikowano!")
}if(interaction.customId === 'ticket-open'){
if(interaction.guild.channels.cache.find(ch => ch.topic == interaction.user.id)) {
return interaction.followUp({
content: `Posiadasz już ticket!`,
ephemeral: true
})}
interaction.guild.channels.create(`Ticket-${interaction.user.username}`, {
parent: '949978511324635136',
permissionOverwrites: [{
id: interaction.user.id,
allow: ['VIEW_CHANNEL', 'SEND_MESSAGES']
},
{
id: '949701839560011797',
deny: ['VIEW_CHANNEL', 'SEND_MESSAGES']
},
{
id: client.user.id,
allow: ['VIEW_CHANNEL', 'SEND_MESSAGES']
}],
topic: interaction.user.id
})
.then(async(tick) => {
interaction.followUp({
content: `Ticket otworzony <#${tick.id}>`,
ephemeral: true
})
const tickEmbed = new MessageEmbed()
.setColor('GREEN')
.setFooter({
text: `${interaction.user.username} ${new Date().getFullYear()}`,
iconURL: interaction.user.displayAvatarURL({ dynamic: true })
})
.setTitle("Ticket")
.setDescription(`**Otworzyłeś/aś ticket, poczekaj cierpliwie, aż ktoś z administracji Cie obsłuży, nie pinguj oraz zachowaj kulturę na tickecie**`);
const closeButton = new MessageButton()
.setCustomId("close-button")
.setLabel("Zamknij")
.setEmoji("🔒")
.setStyle("SECONDARY");
const row = new MessageActionRow()
.setComponents(closeButton);
tick.send({
content: `Cześć <#${interaction.user.id}>, administracja za chwilę Cie obsłuży <#&949982338031423541>`,
embeds: [tickEmbed],
components: [row]
})
})
} if(interaction.customId === 'close-button'){
if(interaction.channel.name.includes(`zamkniety`)) return interaction.followUp({ content: 'Ticket jest już zamknięty!', ephemeral: true });
const buttonTak = new MessageButton()
.setCustomId('close-tak')
.setLabel('Zamknij')
.setStyle('SECONDARY')
const buttonNie = new MessageButton()
.setCustomId('close-nie')
.setLabel('Anuluj')
.setStyle('DANGER')
const raw = new MessageActionRow()
.setComponents([buttonTak, buttonNie])
interaction.channel.send({
content:'Czy napewno chcesz zamknąć ticket?',
components: [raw]
})
} if(interaction.customId === 'close-tak'){
const usd = interaction.guild.members.cache.get(interaction.channel.topic)
const name = usd.user.username
interaction.channel.edit({
name: "zamkniety",
permissionOverwrites: [{
id: interaction.channel.topic,
deny: ['SEND_MESSAGES', 'VIEW_CHANNEL']
}, {
id: '949701839560011797',
deny: ['SEND_MESSAGES', 'VIEW_CHANNEL'],
}, {
id: client.user.id,
allow: ['SEND_MESSAGES', 'VIEW_CHANNEL'],
}],
})
const message = await interaction.channel.messages.fetch(interaction.message.id).catch(() => null);
if (message) {
interaction.message.delete()
}
const embed = new MessageEmbed()
.setDescription(`Ticket zamknięty przez <#${interaction.user.id}>`)
interaction.channel.send({embeds:[embed]})
setTimeout(() => {
const embed2 = new MessageEmbed()
.setDescription(`\`\`\`System kontroli ticketów po zamknięciu\`\`\``)
.setColor('YELLOW');
const buttonReopen = new MessageButton()
.setCustomId("reopenButton")
.setLabel("Otworz")
.setEmoji('🔓')
.setStyle('SECONDARY')
const buttonTranscript = new MessageButton()
.setCustomId("transcriptButton")
.setLabel("Transcript")
.setEmoji('📝')
.setStyle('SECONDARY')
const buttonDelete = new MessageButton()
.setCustomId("deleteButton")
.setLabel("Usun")
.setEmoji('⛔')
.setStyle('SECONDARY')
const row = new MessageActionRow()
.setComponents([ buttonTranscript, buttonReopen, buttonDelete])
interaction.channel.send({
embeds:[embed2],
components: [row]
})
}, 500)
} if(interaction.customId === 'close-nie'){
const message = await interaction.channel.messages.fetch(interaction.message.id).catch(() => null);
if (message) {
interaction.message.delete()
}
} if(interaction.customId === 'reopenButton') {
const usd = interaction.guild.members.cache.get(interaction.channel.topic)
const name = usd.user.username
interaction.channel.edit({
permissionOverwrites: [{
id: interaction.channel.topic,
allow: ['SEND_MESSAGES', 'VIEW_CHANNEL']
}, {
id:'949701839560011797' ,
deny: ['SEND_MESSAGES', 'VIEW_CHANNEL'],
}, {
id: client.user.id,
allow: ['SEND_MESSAGES', 'VIEW_CHANNEL'],
}],
name: `ticket`
})
const embed = new MessageEmbed()
.setDescription(`Ticket został ponownie otworzony przez <#${interaction.user.id}> (${interaction.user.username})`)
.setColor('GREEN')
interaction.channel.send({embeds:[embed]})
const message = await interaction.channel.messages.fetch(interaction.message.id).catch(() => null);
if (message) {
interaction.message.delete()
}
}
// } if(interaction.customId === 'transcriptButton'){
// interaction.channel.send({ content: "Tworzenie zapisu..." })
// const user = await client.users.fetch(interaction.channel.topic)
// const transcript = await createTranscript(interaction.channel, {
// limit: -1,
// fileName: `ticket-${interaction.channel.topic}.html`,
// returnBuffer: false,
// })
// client.channels.cache.get("950383700904931368").send({
// files: [transcript]
// }).then(() => {
// interaction.channel.delete()
// })
// }
}
});

Discord js Voice | How to use AudioResource

I'm trying to create an AudioResource according to the documentation, but I don't know what to fill in edges and streams. I only have yt(youtube-url) from ytdl-core. Please advise what information is required. I try create Audio Resource via new Voice.AudioResource on way documentation. I know about createAudioResource, but is there any possibility to do it differently?
client.on('messageCreate', (message) => {
if(message.content == '!test'){
const VoiceConnection = new Voice.VoiceConnection({
channelId: message.member.voice.channel.id,
guildId: message.guild.id,
selfDeaf: true,
}, {
adapterCreator: message.guild.voiceAdapterCreator,
debug: true
})
VoiceConnection.rejoin()
const Player = new Voice.AudioPlayer()
const Resource = new Voice.AudioResource([], [yt(youtube-url)]) // error
VoiceConnection.subscribe(Player)
Player.play(Resource)
}
})
createAudioPlayer isn't the most stable audio player but it is the only one fully supported by the Discord.js Developers at this time. It should be a good idea using the way they support.
Take some minutes to read this document it is very important.
I think you want something like this:
audioPlayer.play(createAudioResource(stream))
I did not test this code but I think it works:
const { joinVoiceChannel } = require('#discordjs/voice');
const connection = joinVoiceChannel({
channelId: channel.id,
guildId: channel.guild.id,
adapterCreator: channel.guild.voiceAdapterCreator,
});
const { createAudioPlayer } = require('#discordjs/voice');
const player = createAudioPlayer();
const songURL= 'https://www.youtube.com/watch?v=Ak5oJcXSnQw'
const stream = ytdl(songURL, {filter: 'audioonly'});
player.play(createAudioResource(stream));

How to send Server Region in Embed Discord JS v13?

I have a Server Info command which worked in v12 but I updated to v13. In v12 when I send the Command it Responds with the correct region but in v13 when I send the command, responds at server region with undefined, help!
This is server info command:
const Discord = require('discord.js');
module.exports = {
name: "serverinfo",
aliases: ["si"],
description: "Shows all Info about the Server!",
execute: async (message, args, client) => {
let region;
switch (message.guild.region) {
case "europe":
region = '🇪🇺 europe';
break;
case "russia":
region = '🇷🇺 russia';
break;
case "us-east":
region = '🇺🇸 us-east'
break;
case "us-west":
region = '🇺🇸 us-west';
break;
case "us-south":
region = '🇺🇸 us-south'
break;
case "us-central":
region = '🇺🇸 us-central'
break;
}
const embed = new Discord.MessageEmbed()
.setThumbnail(message.guild.iconURL({dynamic : true}))
.setColor('#dd6fb9')
.setTitle(`**Bot Command**`)
.setFooter("#" + message.author.tag, message.author.displayAvatarURL({dynamic : true}))
.addFields(
{
name: `Region: `,
value: `${region}`,
inline: true
}
await message.channel.send( { embeds: [embed] }).then(setTimeout(() => message.delete())).then(msg =>{
setTimeout(() => msg.delete(), 120000)});
},
};
A guild no longer has the attribute region. You can however get the preferredLocale of the server:
const Discord = require('discord.js');
module.exports = {
name: "serverinfo",
aliases: ["si"],
description: "Shows all Info about the Server!",
execute: async (message, args, client) => {
const embed = new Discord.MessageEmbed()
.setThumbnail(message.guild.iconURL({dynamic : true}))
.setColor('#dd6fb9')
.setTitle(`**Bot Command**`)
.setFooter("#" + message.author.tag, message.author.displayAvatarURL({dynamic : true}))
.addFields(
{
name: `Region: `,
value: `${message.guild.preferredLocale}`,
inline: true
}
await message.channel.send( { embeds: [embed] }).then(setTimeout(() => message.delete())).then(msg =>{
setTimeout(() => msg.delete(), 120000)});
},
};

DiscordJS v13 AudioPlayer is stuck on buffering when trying to stream audio from a youtube video

Here is the code so far for my discord music bot. I believe the bot has the appropriate permissions, and is able to join the voice channel of the person who called the "!play" command. The issue I am having is that I can't seem to figure out why the audio stream is stuck on the "buffering" state. The docs states that the "buffering" state should either go through or fail, but it appears to be stuck.
client.on("messageCreate", async message => {
if (message.content.slice(0, 6) == "!play ") {
// check input to see if it is a youtube URL
let input = message.content.slice(6);
if (isYoutubeUrl(input)) {
url = input;
} else {
formatInput(input);
url = await searchVideo(searchTerm);
}
if (message.member.voice.channelId !== null) {
const permissions = message.member.voice.channel.permissionsFor(message.client.user);
if (!permissions.has("CONNECT") || !permissions.has("SPEAK")) {
return message.channel.send(
"I need the permissions to join and speak in your voice channel!"
);
}
const connection = joinVoiceChannel({
channelId: message.member.voice.channel.id,
guildId: message.guild.id,
adapterCreator: message.guild.voiceAdapterCreator
})
const stream = await ytdl(url, { filter:'audioonly' });
const player = createAudioPlayer();
var resource = createAudioResource(stream, { seek: 0, volume: 1 });
player.play(resource);
connection.subscribe(player);
} else {
message.reply("You need to be in a voice channel to play music!");
}
}
})
Here is what comes up when I console.log the player itself
<ref *1> AudioPlayer {
_events: [Object: null prototype] {},
_eventsCount: 0,
_maxListeners: undefined,
subscribers: [
PlayerSubscription {
connection: [VoiceConnection],
player: [Circular *1]
}
],
_state: {
status: 'buffering',
resource: AudioResource {
playbackDuration: 0,
started: false,
silenceRemaining: -1,
edges: [Array],
playStream: [OggDemuxer],
metadata: null,
silencePaddingFrames: 5,
audioPlayer: [Circular *1]
},
onReadableCallback: [Function: onReadableCallback],
onFailureCallback: [Function: onFailureCallback],
onStreamError: [Function: onStreamError]
},
behaviors: { noSubscriber: 'pause', maxMissedFrames: 5 },
debug: [Function (anonymous)],
[Symbol(kCapture)]: false
}
Turns out that the stream was not the issue. I just needed to use the "getVoiceConnection" component from the "#discordjs/voice" package and broadcast the stream to that connection instead.

TypeError: Cannot read property '0' of undefined (discord.js)

const data = suggestedEmbed.embeds[0];
Hi, I'm having this error and I don't know why it is saying that the code above is the problem. Any solutions for this problem? Thank you for reading.
Code:
module.exports = {
category: "Utility",
description: "Accept valid suggestions!",
expectedArgs: "<messageID> <Reason>",
minArgs: 2,
guildOnly: true,
ownerOnly: true,
callback: ({message, args}) => {
const messageID = args[0]
const acceptQuery = args.slice(1).join(" ");
try{
const suggestionChannel = message.guild.channels.cache.get('834459599699443782');
const suggestedEmbed = suggestionChannel.messages.fetch(messageID);
console.log(suggestedEmbed)
const data = suggestedEmbed.embeds[0];
const acceptEmbed = new Discord.MessageEmbed()
.setAuthor(data.author.name, data.author.iconURL())
.setColor('GREEN')
.setDescription(data.description)
.addField("📊 Status ✅ Accepted! Expect this coming soon!", acceptQuery);
suggestedEmbed.edit(acceptEmbed);
const user = client.users.cache.find((u) => u.tag === data.author.name);
user.send("Your suggestion has been accepted! Thank you for this suggestion, expect this coming soon!")
} catch(err) {
console.log(err)
}
}
}

Resources