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).
Related
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.
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.
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.
Hi I am following a tutorial on Youtube but I can't figure out why it's not working. Can someone explain to me why it isn't working?
There are no errors in the console but the role doesn't get added
Since you're using discord.js^12.x module, I can still see you use member.removeRoles() and member.addRoles(), which are deprecated. And also, the member variable you made was a user property not a guildMember property. Try to follow the code below:
const Discord = require('discord.js');
const { prefix } = require('../config.json');
module.exports = {
name: 'coloradd',
description: 'Give You Your Color',
execute(message, args, client) {
if (!message.content.startsWith(prefix) || message.author.bot) return;
const colors = message.guild.roles.cache.filter(c => c.name.startsWith('#'))
let str = args.join(' ')
let role = colors.find(role => role.name.slice(1).toLowerCase() === str.toLowerCase());
if (!role) {
return message.channel.send('That color doens\'t exist')
} try {
const member = message.member; // Use `message.member` instead to get the `guldMember` property.
// `addRoles()` and `removeRoles()` are deprecated.
member.roles.remove(colors);
member.roles.add(role);
message.channel.send('Your Have Received Your Color !')
} catch (e) {
let embed = new Discord.MessageEmbed()
.setTitle('Error')
.setColor('RED')
.setDescription('There is an error with the role Hierarchy Or my permissions. Make Sure I am above the color roles')
return (embed)
}
}
}
Visit these guides to help you understand more about the subject:
Discordjs.guide - Guide - Changes from v11 to v12
Discordjs.guide - Guide - Adding a role to a guildMember
Discord.js.org - Docs - guildMember Property
Discord.js.org - Docs - User Property
const Discord = require('discord.js');
const randomPuppy = require('random-puppy');
const subreddits = [
"memes",
"DeepFriedMemes",
"bonehurtingjuice",
"surrealmemes",
"dankmemes",
"meirl",
"me_irl",
"funny"
]
exports.exec = (client, message, args, user) => {
var randSubreddit = subreddits[Math.round(Math.random() * (subreddits.length - 1))];
randomPuppy(randSubreddit)
.then(url => {
const embed = new Discord.RichEmbed()
.setFooter(`${randSubreddit} ● Subreddit`)
.setDescription(`[Image URL](${url})`)
.setImage(url)
.setColor(0);
return message.channel.send({ embed });
})
};
Hey guys, left discord coding behind about a year ago and I've come back to this error (title) It was working quite fine a year ago, and now nothing. (Haven't changed anything).
I'm a wee bit confused on how or why this is now happening.
Any help is appreciated as I've got no clue.
Thank you in advance :)
Edit - Not running Discord.js v12 so RichEmbed still applies. :)
[unhandledRejection]
TypeError: Cannot convert undefined or null to object
at Function.entries (<anonymous>)
at module.exports (C:\Users\worrit\Downloads\Peepo_Redacted\Peepo_Revive\node_modules\lowercase-kevs\index.js:5:36)
at normalizeArguments (C:\Users\worrit\Downloads\Peepo_Redacted\Peepo_Revive\node_modules\random-puppy\node_modules\got\index.js:222:5)
at got (C:\Users\worrit\Downloads\Peepo_Redacted\Peepo_Revive\node_modules\random-puppy\node_modules\got\index.js:302:20)
at randomPuppy (C:\Users\worrit\Downloads\Peepo_Redacted\Peepo_Revive\node_modules\random-puppy\index.js:31:12)
at module.exports (C:\Users\worrit\Downloads\Peepo_Redacted\Peepo_Revive\node_modules\random-puppy\index.js:67:16)
at Object.exports.exec (C:\Users\worrit\Downloads\Peepo_Redacted\Peepo_Revive\commands\image-fetch\meme.js:17:9)
at module.exports (C:\Users\worrit\Downloads\Peepo_Redacted\Peepo_Revive\handlers\commandHandler.js:299:34)
[/unhandledRejection]
const Discord = require('discord.js');
const randomPuppy = require('random-puppy');
const subreddits = [
"memes",
"DeepFriedMemes",
"bonehurtingjuice",
"surrealmemes",
"dankmemes",
"meirl",
"me_irl",
"funny"
]
exports.exec = (client, message, args, user) => {
var randSubreddit = subreddits[Math.round(Math.random() * (subreddits.length - 1))];
randomPuppy(randSubreddit)
.then(url => {
const embed = new Discord.RichEmbed()
.setFooter(`${randSubreddit} ● Subreddit`)
.setDescription(`[Image URL](${url})`)
.setImage(url)
.setColor(0);
message.channel.send({embed});
})
};
Issue is on this line. embed is undefined.
return message.channel.send({ embed });
If this was working in the past and only recently stopped working then I suspect it's either one of two things;
One of the subreddits in your array no longer exists, or the api is outdated.
You can debug this by adding a console.log(embed) before the return statement and then one by one, remove each .function() call until embed no longer === undefined.
Might also be worth npm install every package again.