Discord bot code keeps getting errors. (JS) - discord

I'm trying to code a Discord bot and I have never done that before so this is very new to me. But whatever I do to the code there is ALWAYS an error. It keeps saying in the text editor that nothing is wrong but when I start the code and debug it using Node.js it says unexpected token } or unexpected token ), I just don't know why it says that.
const Discord = require('discord.js');
const { prefix, token, bs } = require('./config.json');
const client = new Discord.Client();
client.once('ready', () => {
console.log('Ready!');
});
const exampleEmbed = new Discord.MessageEmbed().setTitle('Epic programmer and super cool :)');
client.on('message', message => {
if (message.content === `${prefix}ping`) {
message.channel.send('Pong.');
} else if (message.content === `${prefix}beep`) {
message.channel.send('Boop.');
} else if (message.content === `${prefix}server`) {
message.channel.send({ embed: exampleEmbed.setTitle(`Server name: ${message.guild.name}\nTotal members: ${message.guild.memberCount}`) });
} else if (message.content === `${prefix}user-info`) {
message.channel.send({ embed: exampleEmbed.setTitle(`Your username: ${message.author.username}\nYour ID: ${message.author.id}`) });
} else if (message.content === `Cable creepersaur`) {
message.channel.send({ embed: exampleEmbed.setTitle('Epic programmer and super cool :)') });
} else if (message.content === `${prefix}commands`) {
message.channel.send({ embed: exampleEmbed.setTitle(`c!ping\nc!beep\nc!server\nc!user-info\nCable creepersaur\nc!box`) });
} else if (message.content === `${prefix}box`) {
message.channel.send({ embed: exampleEmbed.setTitle(`🟦🟦🟦🟦🟦🟦🟦🟦🟦\nπŸŸ¦β¬›β¬›β¬›β¬›β¬›β¬›β¬›πŸŸ¦\nπŸŸ¦β¬›β¬›β¬›β¬›β¬›β¬›β¬›πŸŸ¦\nπŸŸ¦β¬›β¬›β¬›β¬›β¬›β¬›β¬›πŸŸ¦\n🟦🟦🟦🟦🟦🟦🟦🟦🟦`) }).then(function (myMessage) {
myMessage.react("πŸ‘")
.then(myMessage.react("πŸ‘Ž"));
});
}
});
client.login(token);
I keep trying to remove and add some } and ) brackets but it never works. It worked really well before and now that I tried to add a custom emoji it doesn't work. (I removed the custom emoji after).
This is the entire error message:
Debugger attached.
Waiting for the debugger to disconnect...
internal/modules/cjs/loader.js:1109
throw err;
^
SyntaxError: c:\Users\mathur\Desktop\CableBot\config.json: Unexpected token } in JSON at position 95
at parse (<anonymous>)
at Object.Module._extensions..json (internal/modules/cjs/loader.js:1106:22)
at Module.load (internal/modules/cjs/loader.js:928:32)
at Function.Module._load (internal/modules/cjs/loader.js:769:14)
at Module.require (internal/modules/cjs/loader.js:952:19)
at require (internal/modules/cjs/helpers.js:88:18)
at Object.<anonymous> (c:\Users\mathur\Desktop\CableBot\Cable.js:2:31)
at Module._compile (internal/modules/cjs/loader.js:1063:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
at Module.load (internal/modules/cjs/loader.js:928:32)
Process exited with code 1
I am using Visual Studio code on windows. I don't know if that affects anything but I know that debugging and showing what you did wrong is different on different Text editors.

Related

My bot has been offline with no error, it was working yesterday

I get an error, which is below, this worked great yesterday, it's just not working today.
const express = require("express");
const app = express();
app.listen(3000, () => {
console.log("Project is running!");
})
app.get("/", (req, res) => {
res.send("Hello World!");
})
const Discord = require("discord.js")
const client = new Discord.Client({ intents: ["GUILDS", "GUILD_MESSAGES"] });
client.on("messageCreate", message => {
if(message.content === "jobs") {
message.channel.send("fortnite battle royale");
}
})
client.on("messageCreate", message => {
if(message.content === "ping") {
message.channel.send("pong, you idiot, you should know the rest");
}
})
client.on("messageCreate", message => {
if(message.content === "pls dont help") {
message.channel.send(message.author.toString() + " " +"ok, i wont, all you had to do was ask... also dank memer stole this command");
}
})
client.on("messageCreate", message => {
if (message.author.bot) return;
if(message.content.includes("dream")) {
var msgnumber= (Math.floor((Math.random() * 2) + 1));
console.log(msgnumber);
if (msgnumber===1) {
message.channel.send("did someone say dream!?");
} else if (msgnumber===2) {
message.channel.send("why we talkin' about dream... huh!?")
}
}
})
client.on('messageCreate', message => {
if (message.content === '!ping') {
message.channel.send(`πŸ“Latency is ${Date.now() - message.createdTimestamp}ms. API Latency is ${Math.round(client.ws.ping)}ms`);
}
});
client.on("messageCreate", message => {
if(message.content === "username") {
message.channel.send(message.author.username);
}
})
client.on('ready', () => {
console.log('Bot is online!')
client.user.setActivity('not being entertained', {type : 'PLAYING'} )
})
client.login(process.env.token);
This was working great yesterday, earlier it was online yet not responding to commands.
I am hosting this in Replit. Am I doing something wrong? I do not get a message stating my bot is online, as I was yesterday when it was working.
Update: I am now getting an error, which in my opinion is a good sign.
node:events:504
throw er; // Unhandled 'error' event
^
Error: listen EADDRINUSE: address already in use :::3000
at Server.setupListenHandle [as _listen2] (node:net:1330:16)
at listenInCluster (node:net:1378:12)
at Server.listen (node:net:1465:7)
at Function.listen (/home/runner/DiscordBot/node_modules/express/lib/application.js:635:24)
at Object.<anonymous> (/home/runner/DiscordBot/index.js:4:5)
at Module._compile (node:internal/modules/cjs/loader:1103:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1157:10)
at Module.load (node:internal/modules/cjs/loader:981:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:77:12)
Emitted 'error' event on Server instance at:
at emitErrorNT (node:net:1357:8)
at processTicksAndRejections (node:internal/process/task_queues:83:21) {
code: 'EADDRINUSE',
errno: -98,
syscall: 'listen',
address: '::',
port: 3000
}
exit status 1
You are hosting on Replit, a service that runs hundreds of servers, often with several users' projects running on the same machine (especially for free users). You cannot simply choose an arbitrary port and expect it to be free. Any other user on Replit that happens to be on the same machine as you could have already claimed the port 3000, if that port is even available to Replit's users at all. There may not have been a user running on port 3000 on the same Replit server as you earlier, but now there is. This is why you are getting this error. Port 3000 is also a very popular port, so it is not a good idea to try and use that as your port on Replit.
Luckily, mass-hosting services like Replit account for this by providing you with an environment variable that contains an open port designated to your project. You can access it using process.env.PORT, like so:
app.listen(process.env.PORT, () => {
console.log("Project is running!");
})
This will guarantee you avoid the port already-in-use error you are getting. This also avoids the mess involved with trying to close ports (which you do not really have control over on Replit anyways), making your other question unnecessary.
Address already in use means that the port you are trying to allocate for your current execution is already occupied/allocated to some other process
if you are using linux :
sudo lsof -t -i tcp:3000 | sudo xargs kill
if you are using windows
netstat -ano | findstr :3000
then you wil lget a pid run this command and change 50968 with the pid you get
taskkill /PID 50968 /F
or try
npx kill-port 3000

TypeError [INVALID_TYPE]: Supplied options is not an object error when trying to ban someone

My ban command checks if a user is bannable then bans them. My kick does the same thing but it actually works. The ban message sends so the user is bannable but doesn't actually get banned. Here's my code
if (memberTarget.bannable) {
if (
message.member.roles.highest.position >
message.guild.members.cache.get(target.id).roles.highest.position
) {
target.ban(reason);
let banReason = new Discord.MessageEmbed()
.setDescription(`**${target.user.tag}** has been banned.`)
.addField("Reason:", `${!reason ? "Unspecified" : `${reason}`}`)
.setFooter(
`banned by ${message.author.tag}`,
"https://cdn.discordapp.com/attachments/375020097431011328/881012463645126686/3dgifmaker15131.gif"
)
.setColor("#000000");
message.reply({ embeds: [banReason] }).catch((err) => {
message.channel.send({ embeds: [banReason] });
});
}
My problem with this is everytime I try to go and kick someone, I get my error:
if (!memberTarget.bannable) {
let lowPerms = new Discord.MessageEmbed()
.setDescription(
`<:role:887134365476335626> I lack the required permission to ban **${target.user.tag}**.`
)
.setColor("#000000");
message.reply({ embeds: [lowPerms] });
}
This happens even why I try to kick someone with no roles and my bot had administrative permissions.
The actual error itself:
C:\Users\\Documents\GitHub\omex\node_modules\discord.js\src\managers\GuildBanManager.js:142
if (typeof options !== 'object') throw new TypeError('INVALID_TYPE', 'options', 'object', true);
^
TypeError [INVALID_TYPE]: Supplied options is not an object.
at GuildBanManager.create (C:\Users\\Documents\GitHub\omex\node_modules\discord.js\src\managers\GuildBanManager.js:142:44)
at GuildMemberManager.ban (C:\Users\\Documents\GitHub\omex\node_modules\discord.js\src\managers\GuildMemberManager.js:364:28)
at GuildMember.ban (C:\Users\\Documents\GitHub\omex\node_modules\discord.js\src\structures\GuildMember.js:299:31)
at Object.execute (C:\Users\\Documents\GitHub\omex\commands\ban.js:32:22)
at Client.<anonymous> (C:\Users\\Documents\GitHub\omex\index.js:133:20)
at Client.emit (node:events:394:28)
at MessageCreateAction.handle (C:\Users\\Documents\GitHub\omex\node_modules\discord.js\src\client\actions\MessageCreate.js:23:14)
at Object.module.exports [as MESSAGE_CREATE] (C:\Users\\Documents\GitHub\omex\node_modules\discord.js\src\client\websocket\handlers\MESSAGE_CREATE.js:4:32)
at WebSocketManager.handlePacket (C:\Users\\Documents\GitHub\omex\node_modules\discord.js\src\client\websocket\WebSocketManager.js:345:31)
at WebSocketShard.onPacket (C:\Users\\Documents\GitHub\omex\node_modules\discord.js\src\client\websocket\WebSocketShard.js:443:22) {
[Symbol(code)]: 'INVALID_TYPE'
}
The error attached in question is originated via this specific line:
target.ban(reason)
The GuildMember#ban([options]) if needed to be called with options the options must be an array of options / object like so
target.ban({
reason: `${!reason ? "Unspecified" : `${reason}`}`
});
NodeJS is freaking out because I'm guessing the reason you passed into target.ban() is a string, not an object. In discord.js, you have to provide an object into the GuildMember#ban() method, like this:
target.ban({ reason });
You can also choose how many days (from 0-7) of messages to delete, like this:
target.ban({ days: 7, reason }); // Deletes all messages the member banned sent within the past 7 days

I am getting an error when I run a command with my discord bot

I am using [this][1] Minecraft server util and I am getting the following error. Is there anyway I can fix this error?
Please note that the error is not when the bot is run its when the command -rcon is run.
This is my code for the command handler, and the command. This is attempting to run the command "list" using rcon.
Code: https://pastebin.com/QWysjvnu
If there is a better way I can be running commands through discord please let me know.
client.commands.get('rcon').execute(message, args, server);
^
TypeError: Cannot read property 'execute' of undefined
at Client.<anonymous> (/Users/myname/Downloads/Esentrix Bot/main.js:47:36)
at Client.emit (events.js:376:20)
at MessageCreateAction.handle (/Users/myname/Downloads/Esentrix Bot/node_modules/discord.js/src/client/actions/MessageCreate.js:31:14)
at Object.module.exports [as MESSAGE_CREATE] (/Users/myname/Downloads/Esentrix Bot/node_modules/discord.js/src/client/websocket/handlers/MESSAGE_CREATE.js:4:32)
at WebSocketManager.handlePacket (/Users/myname/Downloads/Esentrix Bot/node_modules/discord.js/src/client/websocket/WebSocketManager.js:384:31)
at WebSocketShard.onPacket (/Users/myname/Downloads/Esentrix Bot/node_modules/discord.js/src/client/websocket/WebSocketShard.js:444:22)
at WebSocketShard.onMessage (/Users/myname/Downloads/Esentrix Bot/node_modules/discord.js/src/client/websocket/WebSocketShard.js:301:10)
at WebSocket.onMessage (/Users/myname/Downloads/Esentrix Bot/node_modules/ws/lib/event-target.js:132:16)
at WebSocket.emit (events.js:376:20)
at Receiver.receiverOnMessage (/Users/myname/Downloads/Esentrix Bot/node_modules/ws/lib/websocket.js:835:20)```
------RCON Command-------
module.exports = {
name: 'mcstats',
description: "This command runs commands in Esentrix via rcon!",
execute(message, args){
const util = require('minecraft-server-util');
const client = new util.RCON('esentrixmc.plox.vip', { port: 25575, enableSRV: true, timeout: 5000, password: 'my password here' }); // These are the default options
client.on('output', (message) => {
console.log(message);
// The client must be closed AFTER receiving the message.
// Closing too early will cause the client to never output
// any message.
client.close();
});
client.connect()
.then(() => client.run('list')) // List all players online
.catch((error) => {
console.error(error);
});
}
}
[1]: https://github.com/PassTheMayo/minecraft-server-util
Issue #1: You're nesting your module into a parent element named execute, your module will not be found this way.
Issue #2: Your module has a name of 'mcstats', not rcron. Use the correct name.
Main File:
client.commands.get('mcstats').execute(message, args, server);
Command File:
module.exports = {
name: 'mcstats',
description: "This command runs commands in Esentrix via rcon!",
execute(message, args){
const util = require('minecraft-server-util');
const client = new util.RCON('esentrixmc.plox.vip', { port: 25575, enableSRV: true, timeout: 5000, password: 'my password here' }); // These are the default options
client.on('output', (message) => {
console.log(message);
// The client must be closed AFTER receiving the message.
// Closing too early will cause the client to never output
// any message.
client.close();
});
client.connect()
.then(() => client.run('list')) // List all players online
.catch((error) => {
console.error(error);
});
}
}

Error when trying to code a music player for Discord bot

So I am trying to code a Discord bot via discord.js-commando in Visual Studio Code. I am trying to code the music player, and I am able to get the bot to join the voice channel. When inputting the URL I want it to play, though, the terminal gives me this error:
(node:17316) DeprecationWarning: Collection#filterArray: use
Collection#filter instead
(node:17316) UnhandledPromiseRejectionWarning: TypeError: Cannot read
property '524399562249601026' of undefined
at Play
(C:\Users\Vincent\Documents\AstralBot\commands\music\join_channel.js:6:24)
at message.member.voiceChannel.join.then.connection
(C:\Users\Vincent\Documents\AstralBot\commands\music\join_channel.js:48:25)
at process._tickCallback (internal/process/next_tick.js:68:7)
(node:17316) UnhandledPromiseRejectionWarning: Unhandled promise rejection.
This error originated either by throwing inside of an async function without
a catch block, or by rejecting a promise which was not handled with
.catch(). (rejection id: 1)
(node:17316) [DEP0018] DeprecationWarning: Unhandled promise rejections are
deprecated. In the future, promise rejections that are not handled will
terminate the Node.js process with a non-zero exit code.
This is the code:
const commando = require('discord.js-commando');
const YTDL = require('ytdl-core');
function Play(connection, message)
{
var server = server[message.guild.id]
server.dispatcher = connection.playStream(YTDL(server.queue[0], {filter: "audioonly"}));
server.queue.shift();
server.dispatcher.on("end", function(){
if(server.queue[0])
{
Play(connection, message);
}
else
{
connection.disconnect();
}
});
}
class JoinChannelCommand extends commando.Command
{
constructor(client)
{
super(client,{
name: 'play',
group: 'music',
memberName: 'play',
description: 'Plays whatever you link from YouTube.'
});
}
async run(message, args)
{
if(message.member.voiceChannel)
{
if(!message.guild.voiceConnection)
{
if(!servers[message.guild.id])
{
servers[message.guild.id] = {queue: []}
}
message.member.voiceChannel.join()
.then(connection =>{
var server = servers[message.guild.id];
message.reply("Successfully joined!")
server.queue.push(args);
Play(connection, message);
})
}
else
{
message.reply("You must first join a voice channel before inputting the command.")
}
}
}
}
module.exports = JoinChannelCommand;
I'm a little new to this so any help would be appreciated, thank you.
The issue occurs at var server = server[message.guild.id] saying it can't read property 524399562249601026 of undefined. So in this context server is undefined.
Looking at more snippets of your code, I think you made a typo in that it should be servers[...] instead of server[...].

weird "count property undefined"

I need help with this, honestly, I've given up on this, 'cause it should work. I don't know if it's a discord.js bug or something but I couldn't find where the issue is.
const Discord = require('discord.js');
const live = "πŸ‘";
const rmke = "πŸ‘Ž";
module.exports.run = async(bot, message, args) => {
let msg = await message.channel.send("Vote! LIVE πŸ‘ RMK πŸ‘Ž");
await msg.react(live);
await msg.react(rmke);
const reactions = await msg.awaitReactions(reaction => reaction.emoji.name === live || reaction.emoji.name === rmke, {
time: 15000
});
let embed = new Discord.RichEmbed()
.setTitle("Ready")
.setDescription("Results")
.addField("LIVE!", `${live}: ${reactions.get(live).count -1 }`)
.addField("RMK!", `${rmke}: ${reactions.get(rmke).count -1 }`);
message.channel.send({
embed: embed
});
}
module.exports.help = {
name: "vta"
}
(node:8592) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'count' of undefined
at Object.module.exports.run (C:\Users\user\Documents\Mod9z\commands\vota.js:16:60)
(node:8592) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:8592) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
If nobody reacts reactions.get(live) and reactions.get(rmke) will be undefined because your bot reacts before the awaitReactions and so that one won't be counted.
The easiest way to deal with this would be:
reactions.get(live) ? reactions.get(live).count : 0

Resources