Discord.js bot was working, added one extra command and everything broke. Can anyone help me figure out why? - javascript

Tried to venture in to the realm of making discord bots. Followed along with a fairly simple tutorial, tweaking it along the way to fit what I was trying to make. The bot originally worked, but I went back in to add the "Mistake" command, and suddenly it's not working. I added in console.log pretty much everywhere, trying to figure out how far everything was getting.
When I start the bot, it will spit out the "Bot Online" log. When I input a command, it will spit out the "Commands" log, but it won't register the command at all. I've tried looking for any minor typos, missing brackets, etc... but I just can't seem to figure out what's gone wrong. I'm hoping that someone here can help! Thank you!
const Discord = require('discord.js');
const config = require('./config.json');
const client = new Discord.Client();
const SQLite = require('better-sqlite3');
const sql = new SQLite('./scores.sqlite');
client.on('ready', () => {
console.log('Bot Online');
const table = sql.prepare("SELECT count(*) FROM sqlite_master WHERE type='table' AND name = 'goals';").get();
if (!table['count(*)']) {
sql.prepare('CREATE TABLE goals (id TEXT PRIMARY KEY, user TEXT, guild TEXT, goals INTEGER);').run();
sql.prepare('CREATE UNIQUE INDEX idx_goals_id ON goals (id);').run();
sql.pragma('synchronous = 1');
sql.pragma('journal_mode = wal');
}
//Statements to get and set the goal data
client.getGoals = sql.prepare('SELECT * FROM goals WHERE user = ? AND guild = ?');
client.setGoals = sql.prepare('INSERT OR REPLACE INTO goals (id, user, guild, goals) VALUES (#id, #user, #guild, #goals);');
});
client.on('message', (message) => {
if (message.author.bot) return;
let goalTotal;
if (message.guild) {
goalTotal = client.getGoals.get(message.author.id, message.guild.id);
if (!goalTotal) {
goalTotal = {
id: `${message.guild.id}-${message.author.id}`,
user: message.author.id,
guild: message.guild.id,
goals: 0,
};
}
}
if (message.content.indexOf(config.prefix) !== 0) return;
const args = message.content.slice(config.prefix.length).trim().split(/ +/g);
const command = args.shift().toLowerCase();
console.log('Commands');
if (command === 'Goals') {
console.log('Goals');
return message.reply(`You Currently Have ${goalTotal.goals} Own Goals.`);
}
if (command === 'OwnGoal') {
console.log('Own Goal');
const user = message.mentions.users.first() || client.users.cache.get(args[0]);
if (!user) return message.reply('You must mention someone.');
let userscore = client.getGoals.get(user.id, message.guild.id);
if (!userscore) {
userscore = {
id: `${message.guild.id}-${user.id}`,
user: user.id,
guild: message.guild.id,
goals: 0,
};
}
userscore.goals++;
console.log({ userscore });
client.setGoals.run(userscore);
return message.channel.send(`${user.tag} has betrayed his team and now has a total of ${userscore.goals} own goals.`);
}
if (command === 'Mistake') {
console.log('Mistake');
const user = message.mentions.users.first() || client.users.cache.get(args[0]);
if (!user) return message.reply('You must mention someone.');
let userscore = client.getGoals.get(user.id, message.guild.id);
if (!userscore) {
return message.reply('This person has no Rocket Bot activity.');
}
if (userscore === 0) {
return message.reply('This player currently has no goals.');
}
if (userscore > 0) {
userscore.goals--;
}
console.log({ userscore });
client.setGoals.run(userscore);
return message.channel.send(`${user.tag} was falsely accused and now has a total of ${userscore.goals} own goals.`);
}
if (command === 'Leaderboard') {
console.log('Leaderboard');
const leaderboard = sql.prepare('SELECT * FROM goals WHERE guild = ? ORDER BY goals DESC;').all(message.guild.id);
const embed = new Discord.MessageEmbed()
.setTitle('Rocket Bot Leaderboard')
.setAuthor(client.user.username, client.user.avatarURL())
.setDescription('Total Goals Scored Against Own Team:')
.setFooter('Rocket Bot')
.setThumbnail('https://imgur.com/a/S9HN4bT')
.setColor('0099ff');
for (const data of leaderboard) {
embed.addFields({
name: client.users.cache.get(data.user).tag,
value: `${data.goals} goals`,
inline: true,
});
}
return message.channel.send({ embed });
}
if (command === 'RocketHelp') {
console.log('Help');
return message.reply(
'Rocket Bot Commands:' +
'\n' +
'!Goals - See How Many Goals You Have Scored Against Your Own Team' +
'\n' +
'!OwnGoal - Tag Another Player With # To Add One To Their Total' +
'\n' +
'!Mistake - Tag Another Player With # To Subtract One From Their Total' +
'\n' +
'!Leaderboard - Show The Current Leaderboard'
);
}
});
client.login(config.token);

You are improperly splitting the message content. You added g to the regex by accident.
Correct line:
const args = message.content.slice(config.prefix.length).trim().split(/ +/);
Because of improper args split, it could not find any command at all, hence no console log was invoked after Commands.

Related

How Would I Make an External Database File? - Discord.JS

I am trying to build a discord bot, that would do leveling and warns and such, but i have no idea how I would link a file to the main javascript file so i can have all the database code be "external". I want to use SQLite for my database.
This is currently what i have
client.on("ready", () => {
// Check if the table "points" exists.
const table = sql.prepare("SELECT count(*) FROM sqlite_master WHERE type='table' AND name = 'scores';").get();
if (!table['count(*)']) {
// If the table isn't there, create it and setup the database correctly.
sql.prepare("CREATE TABLE scores (id TEXT PRIMARY KEY, user TEXT, guild TEXT, points INTEGER, level INTEGER);").run();
// Ensure that the "id" row is always unique and indexed.
sql.prepare("CREATE UNIQUE INDEX idx_scores_id ON scores (id);").run();
sql.pragma("synchronous = 1");
sql.pragma("journal_mode = wal");
}
// And then we have two prepared statements to get and set the score data.
client.getScore = sql.prepare("SELECT * FROM scores WHERE user = ? AND guild = ?");
client.setScore = sql.prepare("INSERT OR REPLACE INTO scores (id, user, guild, points, level) VALUES (#id, #user, #guild, #points, #level);");
});
client.on("messageCreate", message => {
if (message.author.bot) return;
let score;
if (message.guild) {
score = client.getScore.get(message.author.id, message.guild.id);
if (!score) {
score = { id: `${message.guild.id}-${message.author.id}`, user: message.author.id, guild: message.guild.id, points: 0, level: 1 }
}
score.points++;
const curLevel = Math.floor(0.1 * Math.sqrt(score.points));
if (score.level < curLevel) {
score.level++;
message.reply(`You've leveled up to level **${curLevel}**! Ain't that dandy?`);
}
client.setScore.run(score);
}
if (message.content.indexOf(config.prefix) !== 0) return;
const args = message.content.slice(config.prefix.length).trim().split(/ +/g);
const command = args.shift().toLowerCase();
if (command === "give") {
// Limited to guild owner - adjust to your own preference!
if (!message.author.id === message.guild.ownerId) return message.reply("You're not the boss of me, you can't do that!");
const user = message.mentions.users.first() || client.users.cache.get(args[0]);
if (!user) return message.reply("You must mention someone or give their ID!");
const pointsToAdd = parseInt(args[1], 10);
if (!pointsToAdd) return message.reply("You didn't tell me how many points to give...");
// Get their current points.
let userScore = client.getScore.get(user.id, message.guild.id);
// It's possible to give points to a user we haven't seen, so we need to initiate defaults here too!
if (!userScore) {
userScore = { id: `${message.guild.id}-${user.id}`, user: user.id, guild: message.guild.id, points: 0, level: 1 }
}
userScore.points += pointsToAdd;
// We also want to update their level (but we won't notify them if it changes)
let userLevel = Math.floor(0.1 * Math.sqrt(score.points));
userScore.level = userLevel;
// And we save it!
client.setScore.run(userScore);
return message.channel.send(`${user.tag} has received ${pointsToAdd} points and now stands at ${userScore.points} points.`);
}
if (command === "leaderboard") {
/*const top10 = sql.prepare("SELECT * FROM scores WHERE guild = ? ORDER BY points DESC LIMIT 10;").all(message.guild.id);*/
// Now shake it and show it! (as a nice embed, too!)
const embed = new EmbedBuilder()
.setTitle("Leader board")
.setDescription("Our top 10 points leaders!")
.setColor("#ff0000")
.addFields({ name: '\u200b', value: '\u200b' });
/*for (const data of top10) {
embed.addFields({ name: client.users.cache.get(data.user).tag, value: `${data.points} points (level ${data.level})` });
}*/
return message.channel.send({ embed: embed });
}
// Command-specific code here!
});
The Idea is that when someone messages in chat, the bot will see that message and randomize the amount of XP given to a member. I dont have a full idea on how this can be done externally, if it can.
If i understand this correctly, you want another JS file to be run inside of your current file. Node JS makes this pretty easy!
require('./filename.js')
(also, you might want to use external files to store your commands too!)

Discord.js v12.5.3 Anyone know why this doesn't work?

EDIT: ColinD solved my problem but now the message doesn't delete and I have no idea why the message wont delete because its worked for me before with bots
Code:
const discord = require('discord.js')
const newEmbed = require('embedcord')
const randomHex = require('random-hex')
module.exports = (client, message, options) => {
let links = require('./links.json')
let foundLink = false
let banReason = (options && options.banReason) || 'Sent a phishing link.'
let logs = (options && options.logs)
let member = message.mentions.members.first()
for(var i in links) {
if(message.content.toLowerCase().includes(links[i])) foundLink = true
}
if(foundLink) {
if(message.author.hasPermission('ADMINISTRATOR'))
return
message.delete()
member.ban({reason: banReason})
const embed = newEmbed(
'**Member Banned**',
`${randomHex.generate()}`,
`Member was banend for ${options.banReason}`
)
logs.send(embed)
}
}
Your return position might be preventing anything below if from running try changing this
if (foundLink) {
if (message.author.hasPermission('ADMINISTRATOR')) return;
const embed = newEmbed(
'**Member Banned**',
`${randomHex.generate()}`,
`Member was banend for ${options.banReason}`
);
message.delete();
member.ban({
reason: banReason
});
logs.send(embed);
}
Or this if you want if/else
if (foundLink) {
if (message.author.hasPermission('ADMINISTRATOR')) {
return;
} else {
const embed = newEmbed(
'**Member Banned**',
`${randomHex.generate()}`,
`Member was banend for ${options.banReason}`
);
message.delete();
member.ban({
reason: banReason
});
logs.send(embed);
}
}
EDIT: ColinD solved my problem but now the message doesn't delete and I have no idea why the message wont delete because its worked for me before with bots
foundLink variable is unnecessary, you can move your code inside the loop.
Use message.member.hasPermission() instead of message.author.hasPermission().
Example code for v12.5.3(Message Event):
client.on('message', (message) => {
if (message.author.bot) return; // Ignore bot messages
const { member, channel, guild } = message; // Get the message author, channel, and guild
if (!member || !channel || !guild) return; // Ignore messages without a member, channel or guild
const { links } = require('./links.json'); // Get links from json file
for (let i = 0; i < links.length; i++) { // Check if the message contains a link in the links.json file
if (message.content.toLowerCase().includes(links[i])) { // If the message contains a link
if (member.hasPermission('ADMINISTRATOR')) return; // If the member has the administrator permission, don't ban them
const banReason = 'Sent a phishing link'; // Reason for the ban
message.delete(); // Delete the message
guild.member(member).ban({ reason: banReason }); // Ban the member
channel.send(`${member.displayName} has been banned for sending a phishing link.`) // Send a message to the channel
break;
}
}
})

Discord.JS 13 slash command display a targets users specific user role in and embed,

I am trying to make a slash command that displays a users specific roles when the command is issued.
run: async (client, interaction) => {
try{
const { member, channelId, guildId, applicationId,
commandName, deferred, replied, ephemeral,
options, id, createdTimestamp , roles, cache
} = interaction;
const { guild } = member;
let UserOption = options.getUser("which_user");
if(!UserOption) UserOption = member.user;
try{
await guild.members.fetch();
const member = guild.members.cache.get(UserOption.id);
const roles = member.roles;
const userFlags = UserOption.flags.toArray();
const activity = UserOption.presence?.activities[0];
//create the EMBED
const embeduserinfo = new MessageEmbed()
embeduserinfo.setThumbnail(member.user.displayAvatarURL({ dynamic: true, size: 512 }))
embeduserinfo.setAuthor("Information about: " + member.user.username + "#" + member.user.discriminator, member.user.displayAvatarURL({ dynamic: true }), "https://discord.gg/FQGXbypRf8")
embeduserinfo.addField('**❱ Username:**',`<#${member.user.id}>\n\`${member.user.tag}\``,true)
//embeduserinfo.addField('**❱ ID:**',`\`${member.id}\``,true)
embeduserinfo.addField('**❱ Avatar:**',`[\`Link to avatar\`](${member.user.displayAvatarURL({ format: "png" })})`,true)
embeduserinfo.addField('**❱ Joined Discord:**', "\`"+moment(member.user.createdTimestamp).format("DD/MM/YYYY") + "\`\n" + "`"+ moment(member.user.createdTimestamp).format("hh:mm:ss") + "\`",true)
embeduserinfo.addField('**❱ Joined MetroVan:**', "\`"+moment(member.joinedTimestamp).format("DD/MM/YYYY") + "\`\n" + "`"+ moment(member.joinedTimestamp).format("hh:mm:ss")+ "\`",true)
//embeduserinfo.addField(`❱ [${roles.cache.size}] Roles: `, roles.cache.size < 25 ? Array.from(roles.cache.values()).sort((a, b) => b.rawPosition - a.rawPosition).map(role => `<#&${role.id}>`).join(', ') : roles.cache.size > 25 ? trimArray(roles.cache) : 'None')
if (roles.cache.find(r => r.id === "893330818624282656"))
{
embeduserinfo.addField("test")
}
embeduserinfo.setColor(ee.color)
embeduserinfo.setFooter(ee.footertext, ee.footericon)
//send the EMBED
interaction.reply({embeds: [embeduserinfo], ephemeral: false})
}catch (e){
console.log(e)
}
} catch (e) {
console.log(String(e.stack).bgRed)
}
}
}
if targeted member has role 893330818624282656 display this embed.addField
if (roles.cache.find(r => r.id === "893330818624282656"))
{
embeduserinfo.addField("test")
}
Step by step goal
User 1 uses slash command to view users 2 profile
User 1 executes slash command /profile #user2
An embedd is sent to the channel the command is executed in with ephemeral: true (changed in code once programming is completed)
User 2 will have one of three roles.
123456789 / 123456788 / 123456787
DMS OPEN / DMS ASK / DMS CLOSED
Embed will display one of the 3 roles as
DMS ARE OPEN
YOU MUST ASKED TO DM IN #CHANNEL
DMS ARE CLOSED
This is the problem
embeduserinfo.addField("test")
test is the name of the field but there is no value
If you want to add an empty value that won’t throw an error, do this:
embeduserinfo.addField("test", "** **")
Or if you want to make it an empty name, just reverse the parameters. Otherwise you should just make it the value it should have.

roles are not being changed for the mentioned user

When a staff does !mute #user time , it should give the role Muted and take away the role Speaker, this does not happen though, instead everything else happens and the roles are not given or taken away.
const Discord = require('discord.js');
const bot = new Discord.Client();
const ms = require('ms');
const token = '';
const PREFIX = '!';
bot.on('ready', () => {
console.log('This bot is active!');
})
bot.on('message', message => {
let args = message.content.substring(PREFIX.length).split(" ");
switch (args[0]) {
case 'mute':
if(!message.member.hasPermission("MUTE_MEMBERS")) return message.reply("You cannot run this command");
let mperson = message.guild.member(message.mentions.users.first() || message.guild.members.cache.get(args[1]));
if(!mperson) return message.reply("I cannot find the user " + mperson)
var mainrole = message.guild.roles.cache.get("718166462862196777");
var muterole = message.guild.roles.cache.get("717606607910993930");
if(!muterole) return message.reply("Couldn't find the mute role.")
let time = args[2];
if(!time){
return message.reply("You didnt specify a time!");
}
mperson.roles.add(mainrole).catch(console.error)
mperson.roles.remove(muterole).catch(console.error);
message.channel.send(`${mperson.user} has now been muted for ${ms(ms(time))}`)
setTimeout(function(){
mperson.roles.add(mainrole)
mperson.roles.remove(muterole);
console.log(muterole)
message.channel.send(`${mperson.user} has been unmuted.`)
}, ms(time));
break;
}
});
bot.login(token);
The roles that I want to add and remove from the mentioned player do not change, any way that I can fix this?
I changed mperson.roles.add(mainrole).catch(console.error) to mperson.roles.add("717631710761844757").catch(console.error) and now everything works. This is discord.js v12.

Why doesn't kicking people work using discord.js

const Discord = require("discord.js"),
bot = new Discord.Client();
let pre = "?"
bot.on("message", async msg => {
var msgArray = msg.content.split(" ");
var args = msgArray.slice(1);
var prisonerRole = msg.guild.roles.find("name", "Prisoner");
let command = msgArray[0];
if (command == `${pre}roll`) {
if (!msg.member.roles.has(prisonerRole.id)) {
roll = Math.floor(Math.random()*6)+1;
msg.reply(`You rolled a ${roll}`)
} else {
msg.reply(`HaHa NOOB, you're in prison you don't get priveleges!`)
}
}
if (command == `${pre}kick`) {
var leaderRole = msg.guild.roles.find("name", "LEADER");
var co_leaderRole = msg.guild.roles.find("name", "CO-LEADER");
if (msg.member.roles.has(leaderRole.id) ||
msg.member.roles.has(co_leaderRole.id)) {
var kickUser = msg.guild.member(msg.mentions.users.first());
var kickReason = args.join(" ").slice(22);
msg.guild.member(kickUser).kick();
msg.channel.send(`${msg.author} has kicked ${kickUser}\nReason: ${kickReason}`);
} else {
return msg.reply("Ya pleb, you can't kick people!");
}
}
})
bot.login("token").then(function() {
console.log('Good!')
}, function(err) {
console.log('Still good, as long as the process now exits.')
bot.destroy()
})
Everything works except actually kicking the person. The message sends nut it doesn't kick people. For example, when I type in ?kick #BobNuggets#4576 inactive, it says
#rishabhase has kicked #BobNuggets
Reason: inactive
But it doesn't actually kick the user, which is weird, can you help me?
Change
msg.guild.member(kickUser).kick();
to
kickUser.kick();
also, make sure the bot is elevated in hierarchy
Use kickUser.kick();
I recommend using a command handler to neaten up your code. You don't want all your commands in one .js file.
Try something like this for the Ban command itself. I use this for my Bot:
client.on("message", (message) => {
if (message.content.startsWith("!ban")) {
if(!message.member.roles.find("name", "Role that can use this bot"))
return;
// Easy way to get member object though mentions.
var member= message.mentions.members.first();
// ban
member.ban().then((member) => {
// Successmessage
message.channel.send(":wave: " + member.displayName + " has been successfully banned :point_right: ");
}).catch(() => {
// Failmessage
message.channel.send("Access Denied");
});
}
});
That should work, set the role you want to use it (cAsE sEnSiTiVe) and change !ban to whatever you feel like using. If you change all "ban"s in this to kick, it will have the same effect. If this helped you, mark this as the answer so others can find it, if not, keep looking :)

Categories