I've been working on this code for a discord bot that tracks a the voice channels of a server until a specific person joins which then the bot joins and then plays an audio. However whenever I start up my file, it keeps on saying
[nodemon] starting `node index.js`
[nodemon] clean exit - waiting for changes before restart
I have no clue why, I've looked online and I haven't seen any other people having the same issue as me, and if they did the answer didn't help.
Here is my code.
const { Client, GatewayIntentBits } = require('discord.js');
const { Lavalink } = require('discord.js-lavalink');
class MyBot {
// The Discord.js client object that represents our bot
client;
// The ID of the specific person we want to track
userIdToTrack;
// The audio file to play when the specific person joins
audioFile;
constructor(client, userIdToTrack, audioFile) {
// Save the client object and user ID and audio file for later use
this.client = "[bot token]";
this.userIdToTrack = '[discord id]';
this.audioFile = '[file name]';
}
onGuildVoiceJoin(event) {
// Get the member who just joined the voice channel
const member = event.member;
// If the member is the specific person we want to track...
if (member.id === this.userIdToTrack) {
// Get the voice channel that the member joined
const voiceChannel = event.channel;
// Join the voice channel with the bot
voiceChannel.guild.voice.channel.join();
// Play the audio file using Lavalink
lavalink.play(voiceChannel, {
track: '[file name]',
});
const client = new Client({
token: 'bot token]',
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.MessageContent,
GatewayIntentBits.GuildVoiceStates,
GatewayIntentBits.GuildPresences,
],
});
// Create a new instance of the Lavalink class and connect to the Lavalink nodes
const lavalink = new Lavalink({
client: client,
nodes: [
{ host: 'ratio-w', port: 2334, password: 'youshallnotpass' },
],
});
lavalink.connect();
client.on('ready', () => {
console.log('The bot is ready');
// Create a new instance of the bot, passing in the client object, user ID, and audio file
const bot = new MyBot("bot token", "user id", "file name");
// Listen for voice state update events, which are triggered when a user joins or leaves a voice channel
client.on('voiceStateUpdate', (oldState, newState) => {
// Check if the user we want to track has just joined a voice channel
if (newState.member.id === userIdToTrack && newState.channel) {
// Get the voice channel the user joined
const voiceChannel = newState.channel;
// Join the voice channel with the bot
voiceChannel.join().then(connection => {
// Play the audio file using Lavalink
lavalink.play(voiceChannel, {
track: audioFile,
});
});
}
});
client.on('messageCreate', message => {
if (message.content === 'ping') {
message.reply('hey <#user id>, you STINK!!!!111!');
}
});
client.on('messageCreate', message => {
if (message.content === 'shut up [redacted]') {
message.reply('yeah <#user id> shut up smelly');
}
});
client.on('messageCreate', message => {
if (message.content === 'stop being a nerd [redacted]') {
message.reply('<#user id> be like :nerd:');
}
});
});
process.on('unhandledRejection', (reason, promise) => {
console.log('Unhandled Rejection at:', reason.stack || reason)
// Recommended: send the information to sentry.io
// or whatever crash reporting service you use
})
client.login('[bot id]');}}}
I tried fixing any possible syntax errors, I've tried looking online but no help was found, I've properly started lavalink (I think), I've edited some of the code so that all possible parts are fixed. I've downloaded all possible directories like updating discord.js, node.js, lavalink.js, and more I think.
Related
So I'm working on a Discord bot using JS and DiscordJSv14, and want the bot to use audio from a voice chat to send to another bot, some type of listen and snitch bot.
So far I got the Bot's connecting to the voice call but can't get any of the packets to send to the other bot.
Here's some code I've got so far:
const connection = joinVoiceChannel({
channelId: C.id,
guildId: guild.id,
adapterCreator: guild.voiceAdapterCreator,
selfDeaf: false,
selfMute: false,
group: this.client.user.id,
});
if (isListener) {
console.log("Listener Is Joining Voice And Listening...");
const encoder = new OpusEncoder(48000, 2);
let subscription = connection.receiver.subscribe(ID); // ID = Bot's ID
// Basically client.user.id
subscription.on("data", (chunk) => {
console.log(encoder.decode(chunk));
});
}
Console won't log anything about the chunk
Using DiscordJSv14 + #discordjs/opus
Everything worked fine I just needed to add the following code below.
this.client = new Client({
intents: [GatewayIntentBits.GuildVoiceStates, GatewayIntentBits.GuildMessages, GatewayIntentBits.Guilds],
});
I have this very basic code for a very basic discord bot
since the new discord.js version 13 you need to declare intents.
I tried doing that using the bitmap 32767 (basically declaring all intents), however the bot doesnt trigger the "messageCreate" event when a message is send
in the dms it only works in servers.
All privileged gateway intents on the developer site have been set to true.
What am I missing?
const Discord = require("discord.js");
const allIntents = new Discord.Intents(32767);
const client = new Discord.Client({ intents: allIntents });
require("dotenv").config();
const botName = "Miku";
client.once("ready", () => {
//gets executed once at the start of the bot
console.log(botName + " is online!");
});
client.on("messageCreate", (message) => {
console.log("got a message");
});
(async() => {
//bot connects with Discord api
client.login(process.env.TOKEN);
})();
You cannot listen for events in the Direct Messages unless they are direct responses/replies/reactions to the initial message.
For example, you can send a message to new members and wait for a response:
client.on('guildMemberAdd', member =>{
member.send("Welcome to the server!");
message.awaitReactions(filter, { max: 1, time: 60000, errors: ['time'] })
.then((collected) => {
//Now, write your code here that handles the reactions.
});
but there is no way to listen for events within the Direct Messages. As in, client.on... will never fire because of a DM event.
So I want it where, if a user gets banned from this specified guild, it will ban them in every other guild that the bot is in. Do I use fetch bans to do this?
Before we continue you need to make sure that you are requesting the following intents when creating your bot, as they are necessary to achieve your goal: GUILDS, GUILD_BANS.
const { Client, Intents } = require('discord.js');
const client = new Client({
intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_BANS]
});
You should also set up a constant called MAIN_GUILD_ID or something along those lines:
const MAIN_GUILD_ID = 'ID';
Now you need to listen to the guildBanAdd event and check if the GuildBan.guild#id equals the main Guild#id (making sure the user was banned in the main Guild).
client.on('guildBanAdd', async ban => {
if (ban.guild.id !== MAIN_GUILD_ID) return;
});
Then you can loop through all of the Guilds your bot is in and ban the user there.
client.on('guildBanAdd', async ban => {
if (ban.guild.id !== MAIN_GUILD_ID) return;
// Getting the guilds from the cache and filtering the main guild out.
const guilds = await client.guilds.cache.filter(guild => guild.id !== MAIN_GUILD_ID);
guilds.forEach(guild => {
guild.members.ban(ban.user, {
reason: `${ban.user.tag} was banned from ${guild.name}.`
}).then(() => {
console.log(`Banned ${ban.user.tag} from ${guild.name}.`);
}).catch(err => {
console.error(`Failed to ban ${ban.user.tag} from ${guild.name}.`, err);
});
})
});
I'm assuming this is for a private bot that is in a few guilds, otherwise, if the bot is in a few hundred or more guilds it will get your application rate-limited pretty fast.
I have two servers with my bot on it with two groups of friends. On one server, the bot and I both have admin perms, and I can mute someone who doesn't have those perms. On the other server, I'm the owner and the bot has admin, but I can't mute anyone. I get the error 'Missing Permissions'.
Here's the code:
const Discord = require('discord.js')
const ms = require('ms')
module.exports = {
name: 'mute',
execute(message, args) {
if(!args.length) return message.channel.send("Please Specify a time and who to mute. For example, '!mute #antobot10 1d' And then send the command. Once the command is sent, type the reason like a normal message when I ask for it!")
const client = message.client
if (!message.member.hasPermission('MANAGE_ROLES')) return message.channel.send("You don't have permission to use that command!")
else {
const target = message.mentions.members.first();
const filter = (m) => m.author.id === message.author.id
const collector = new Discord.MessageCollector(message.channel, filter, { time: 600000, max: 1 })
const timeGiven = args[1]
message.channel.send('The reason?')
collector.on('collect', m => {
collector.on('end', d => {
const reason = m
message.channel.send(`${target} has been muted`)
target.send(`You have been muted on ${message.guild.name} for the following reason: ***${reason}*** for ${timeGiven}`)
if(message.author.client) return;
})
})
let mutedRole = message.guild.roles.cache.find(role => role.name === "MUTE");
target.roles.add(mutedRole)
setTimeout(() => {
target.roles.remove(mutedRole); // remove the role
target.send('You have been unmuted.')
}, (ms(timeGiven))
)
}
}
}
Ok, I'm not exactly sure what I did, but it's working now. I think I just changed it so that the MUTE role had 0 permissions instead of normal permissions but making it so that if you have the role you can't talk in that certain channel.
Thanks for the answers!
If your bot's role is below the role of the user you are attempting to mute, there will be a missing permissions error. In your server settings, drag and drop the bot role as high in the hierarchy it will go. This will solve your problem.
I am making a discord bot that is being activated by voice recognition, im at the very beginning right now im making him join a voice channel (which is working), and im trying to make a command to make him leave.
const commando = require('discord.js-commando');
class LeaveChannelCommand extends commando.Command
{
constructor(client){!
super(client,{
name: 'leave',
group: 'music',
memberName: 'leave',
description: 'leaves a voice channel'
});
}
async run(message, args)
{
if(message.guild.voiceConnection)
{
message.guild.voiceConnection.disconnect();
}
else
{
message.channel.sendMessage("seccessfully left")
}
}
}
module.exports = LeaveChannelCommand;
right now you can type !leave from anywhere in the server and the bot leaves,
i want to make it possible to control him only from the same voice channel,
what should i do
It's fairly easy to do. All you need to do is grab the bot's voiceChannel and the user's voiceChannel (if he is in one) and check if they are the same.
Below you can find some example code. Give it a try and let me know how it goes.
async run(message, args)
{
// If the client isn't in a voiceChannel, don't execute any other code
if(!message.guild.voiceConnection)
{
return;
}
// Get the user's voiceChannel (if he is in one)
let userVoiceChannel = message.member.voiceChannel;
// Return from the code if the user isn't in a voiceChannel
if (!userVoiceChannel) {
return;
}
// Get the client's voiceConnection
let clientVoiceConnection = message.guild.voiceConnection;
// Compare the voiceChannels
if (userVoiceChannel === clientVoiceConnection.channel) {
// The client and user are in the same voiceChannel, the client can disconnect
clientVoiceConnection.disconnect();
message.channel.send('Client has disconnected!');
} else {
// The client and user are NOT in the same voiceChannel
message.channel.send('You can only execute this command if you share the same voiceChannel as the client!');
}
}