Discord.js | Bot doesn't join VC and doesn't give error - javascript

so basically when I execute my play cmd with the song I want while I am in VC, my bot does not respond to it and doesn't give any errors but if I just type play without the song I want, I get my Please provide song response.
This is the main file
const distube = require('distube');
client.distube = new distube(client, { searchSongs: true, emitNewSongOnly: true })
client.distube
.on('playSong', (message, queue, song) => message.channel.send(
`Playing \`${song.name}\` - \`${song.formattedDuration}\`\nRequested by: ${song.user}\n${status(queue)}`,
))
.on('addSong', (message, queue, song) => message.channel.send(
`Added ${song.name} - \`${song.formattedDuration}\` to the queue by ${song.user}`,
))
.on('error', (message, e) => {
message.channel.send(`An error occured: ${e}`)
})
and this is the play cmd:
const distube = require("distube");
module.exports = {
name: 'play',
aliases: ['p'],
description: 'play a song!',
async execute(client, message, args) {
const VC = message.member.voice.channel;
if(!VC) return message.reply('Join VC or no music!');
const music = args.join(" ");
if(!music) return message.reply("Please provide me a song name");
await client.distube.play(message, music);
}
}
the packages I use are:
npm i distube
npm i #discordjs/opus
npm i ffmpeg-static
for references, these are the things that I looked at:
https://distube.js.org/guide/example-bot.html
https://www.youtube.com/watch?v=tbPqM6JcGA4&t=883s
This is also not the first time I'm getting this error. I tried using different packages before but still didn't work. All of them don't respond when I provide the song I want. Basically, my only problem is that the bot doesn't join the VC. Does anyone know how to fix this?

In order to operate distube, you also require ytdl-core in your arsenal of packages, which you can install with the same npm install command as always.

This is due to you enables searchSongs but doesn't listen to searchResult event.
Simply edit searchSongs: false in your DisTube constructor to fix this.

Related

Getting "Missing Access" error in console

I'm working on an add role command in discord.js v13 and this is the error I am getting:
Error
const { MessageEmbed } = require("discord.js");
const Discord = require("discord.js")
const config = require("../../botconfig/config.json");
const ee = require("../../botconfig/embed.json");
const settings = require("../../botconfig/settings.json");
module.exports = {
name: "addrole",
category: "Utility",
permissions: ["MANAGE_ROLES"],
aliases: ["stl"],
cooldown: 5,
usage: "addrole <user> <role>",
description: "Add a role to a member",
run: async (client, message, args, plusArgs, cmdUser, text, prefix) => {
/**
* #param {Message} message
*/
if (!message.member.permissions.has("MANAGE_ROLES")) return message.channel.send("<a:mark_rejected:975425274487398480> **You are not allowed to use this command. You need `Manage Roles` permission to use the command.**")
const target = message.mentions.members.first();
if (!target) return message.channel.send(`<a:mark_rejected:975425274487398480> No member specified`);
const role = message.mentions.roles.first();
if (!role) return message.channel.send(`<a:mark_rejected:975425274487398480> No role specified`);
await target.roles.add(role)
message.channel.send(`<a:mark_accept:975425276521644102> ${target.user.username} has obtined a role`).catch(err => {
message.channel.send(`<a:mark_rejected:975425274487398480> I do not have access to this role`)
})
}
}
What your error means is that your bot doesn't have permissions to give a role to a user. It might be trying to add a role which has a higher position than the bot's own role. One way to stop the error is to give the bot the highest position. The bot will also require the MANAGE_ROLES permission in the Discord Developers page to successfully add roles in the first place. If you want to learn more about role permissions, I suggest you go here => Roles and Permissions. Also, when you are using .catch() at the end, all it is checking for is if the message.channel.send() at the end worked and if not, then send a message to channel telling that the bot was not able to add the role. Instead you need to use .then() after adding the role and then use .catch() to catch the error. Then, your code might look like this:
target.roles.add(role).then(member => {
message.channel.send(`<a:mark_accept:975425276521644102> ${target.user.username} has obtined a role`)
}).catch(err => {
message.channel.send(`<a:mark_rejected:975425274487398480> I do not have access to this role`)
})

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).

invite Created event

so I'm making a Discord Bot, with auto logging capabilities, until now I managed due to do most of the code, these include the command for setting a mod-log channel and the event code, here's the code for the command:
let db = require(`quick.db`)
module.exports = {
name: "modlog",
aliases: ["modlogs", "log", "logs"],
description: "Change the modlogs channel of the current server",
permission: "MANAGE_CHANNELS",
usage: "modlog #[channel_name]",
run: async (client, message, args) => {
if(!message.member.hasPermission(`MANAGE_CHANNELS`)) {
return message.channel.send(`:x: You do not have permission to use this command!`)
} else {
let channel = message.mentions.channels.first();
if(!channel) return message.channel.send(`:x: Please specify a channel to make it as the modlogs!`)
await db.set(`modlog_${message.guild.id}`, channel)
message.channel.send(`Set **${channel}** as the server's modlog channel!`)
}
}
}
And the inviteCreate event:
client.on("inviteCreate", async invite => {
const log = client.channels.cache.get(`${`modlog_${message.guild.id}`}`)
let inviteCreated = new Discord.MessageEmbed()
log.send(`An invite has been created on this server!`)
})
The issue is that since the inviteCreate event only accepts one parameter (I think that's what they are called) which is invite, there is no message parameter, so message becomes undefined, does anyone have a solution?
Thanks!
You don't need message in this case. See the documentation of invite.
Your message.member can be replaced with invite.inviter
Your message.channel can be replaced with invite.channel
Your message.guild can be replaced with invite.guild
Invites also have a guild property, that's the guild the invite is for, so you can use that instead of the message.guild:
client.on('inviteCreate', async (invite) => {
const log = client.channels.cache.get(`${`modlog_${invite.guild.id}`}`);
let inviteCreated = new Discord.MessageEmbed();
log.send(`An invite has been created on this server!`);
});

Why does the purge command not work? (no errors) discord.js

Bot #1 (Eulogist Official Bot)
Bot #2 (Prosser Recoveries)
So here we have two of my bots. the purge command is:
const { MessageEmbed } = require("discord.js");
const config = require("../../config.json");
module.exports = {
config: {
name: "purge",
description: "Purges messages",
usage: " ",
category: "moderation",
accessableby: "Moderators",
aliases: ["clear", "prune"],
},
run: async (prosser, message, args) => {
message.delete();
let hrps = new MessageEmbed()
.setTitle(`**Command:** ${config["Bot_Info"].prefix}purge`)
.setDescription(
`**Aliases:** /prune, /clear\n**Description:** Delete a number of messages from a channel. (limit 100)\n**Usage:**\n${config["Bot_Info"].prefix}purge 20\n${config["Bot_Info"].prefix}bc`
)
.setColor();
let done = new MessageEmbed()
.setDescription(`Purged \`${args[0]}\` message(s). ✅`)
.setColor(`${config["Embed_Defaults"].EmbedColour}`);
if (!message.member.hasPermission("MANAGE_MESSAGES"))
return message.reply("Doesn't look like you can do that");
if (!args[0]) return message.channel.send(hrps);
message.channel.bulkDelete(args[0]).then(() => {
message.channel
.send(done)
.then((msg) => msg.delete({ timeout: 1000 }));
});
},
};
These two bots have the same purge command but only one of the bots command works. (i've checked perms & invited to different servers).
Has anyone got a solution for this?
Fixed! All i done was moved the js file to a different command folder and it suddenly worked.

Discord JS (Bot Presence)

So, in Discord, users can have a custom status, however, when I try to set my bot up with one nothing happens...Even though CUSTOM_STATUS is available
I have bot.user.setPresence({ activity: { name: "Testing", type: "CUSTOM_STATUS" }, status: "online" });
inside of the ready event. I was just wondering why this doesn't work and if there is a work around
According to the docs.
Bots cannot set a CUSTOM_STATUS, it is only for custom statuses received from users
The valid types you could choose from are:
PLAYING
STREAMING
LISTENING
WATCHING
Try client.user.setActivity(Your Status)
I am using this and its working fine
If you are using v12 then i cant help you
You should make sure that your setPresence command is in your ready event. For example, this is my ready command:
const {PREFIX} = require('../config.json');
const { Message } = require('discord.js');
const message = require('./message.js');
//must update when new module.exports event happens
const leaveEvent = require('../util/guildMemberRemove');
const invitecounterEvent = require('../util/guildMemberAddinvitecounter');
const modmailEvent = require('../util/modmail');
module.exports = (client, message) => {
//must update when new module.exports event happens
leaveEvent(client);
invitecounterEvent(client);
modmailEvent(client);
console.log(' ');
console.log(`Hi, ${client.user.username} is now online! My Prefix is ${PREFIX}`);
console.log(`Bot has started, with ${client.users.size} users, in ${client.channels.size} channels of ${client.guilds.size} guilds.`);
//client.user.setActivity(`Serving ${client.guilds.size} servers`); (big servers only)
client.user.setActivity('U', { type: 'WATCHING' }) //PLAYING, STREAMING, LISTENING, WATCHING, CUSTOM_STATUS
.then(presence => console.log(`Activity set to: WATCHING ${presence.activities[0].name}`))
.catch(console.error);
console.log(`Ready as ${client.user.tag} to serve in ${client.channels.cache.size} channels on ${client.guilds.cache.size} servers, for a total of ${client.users.cache.size} users.`);
client.generateInvite(['SEND_MESSAGES', 'MANAGE_GUILD', 'MENTION_EVERYONE', 'ADMINISTRATOR',])
.then(link => {
console.log(`Generated bot invite link: ${link}`);
// eslint-disable-next-line no-undef
inviteLink = link;
});
};
The part that should help you is client.user.setActivity('U', { type: 'WATCHING' })
The different types you can do are PLAYING, STREAMING, LISTENING, and WATCHING.

Categories

Resources