How do I use Repl.it's database? - javascript

I need my bot to save user violations to a database when a user uses a command. For example, when #violate #user red light pass is used, the bot should save the red light pass to the database for the mentioned user. I'm using Repl.it's database and this is my code:
client.on("message", async message => {
if (message.content.toLowerCase().startsWith("#violations")) {
let violation = await db.get(`wallet_${message.author.id}`)
if (violation === null) violation = "you dont have any tickets"
let pembed = new Discord.MessageEmbed()
.setTitle(`${message.author.username} violations`)
.setDescription(`المخالفات المرورية : ${violation}`)
.setColor("RANDOM")
.setFooter("L.S.P.D")
message.channel.send(pembed)
}
if (message.channel.id === '844933512514633768') {
if (!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).split(/ +/);
console.log(args);
const command = args.shift().toLowerCase();
if (command == 'red light pass') {
const member = message.mentions.members.first(); //
let light = "red lightpass"
await db.set(`wallet_${memeber}`, light)
}
}
})

First of all, in `wallet_${memeber}`, memeber is not defined. You probably intended to use `wallet_${member}`.
I believe the issue is you're using the key `wallet_${message.author.id}` (e.g. 'wallet_12345') to get the violation/ticket, but then `wallet_${member}` (e.g. 'wallet_<#12345>') (e.g. 'wallet) to set the violation. Interpolating a GuildMember in a string calls its toString method, which creates a string of the mention of the member, not the id.
Also, it's good practice to use === instead of == as == casts the items being compared so things like 3 == '03' and [] == false are true.
The final code should like this:
if (command === "red light pass") {
const member = message.mentions.members.first();
const light = "red lightpass";
// Note how I've changed this to member.id (which is just a shortcut for
// member.user.id) from memeber
await db.set(`wallet_${member.id}`, light);
}

Related

Check if the message sender has a specific role

I'm new in Discord bot coding and I want to create a command where the bot only replies if the message sender has a specific role.
According to the discord.js documentation I have to use GuildMemberRoleManager.cache. Sadly, it isn't working.
The whole command looks like this:
client.on('messageCreate', (message) => {
if (
message.content.toLowerCase() === prefix + 'test' &&
GuildMemberRoleManager.cache.has(AdminRole)
)
message.reply('test');
});
You should get the author's roles. Only members have roles, so you will need to get the author as a member using message.member. message.member returns a GuildMember and GuildMembers have a roles property that returns a GuildMemberRoleManager (the one you mentioned in your original post).
Its cache property is a collection of the roles of this member, so you can use its has() method to check if the user has the admin role:
client.on('messageCreate', (message) => {
let adminRole = 'ADMIN_ROLE';
let isAdmin = message.member.roles.cache.has(adminRole);
if (message.content.toLowerCase() === prefix + 'test' && isAdmin)
message.reply('test');
});
Define the variables which will make you easy to understand as you are new
const guild = message.guild.id;
const role = guild.roles.cache.get("role id");
const cmduser = message.author;
const member = await guild.members.fetch(cmduser.id);
and make if statement like
if(member.roles.cache.has(role.id)) {
return message.channel.send("test")
}
if you want bot to check if user have administrator perm than
message.member.hasPermission('ADMINISTRATOR')
Check all perm flags on Discord Perm Flags
So according to your code it will be
const guild = message.guild.id;
const role = guild.roles.cache.get("role id");
const cmduser = message.author;
const member = await guild.members.fetch(cmduser.id);
client.on("messageCreate",(message) => {
if(message.content.toLowerCase() === prefix + "test" && member.roles.cache.has(role.id))
message.reply("test")
})

How to set a variable to a voice channel specified by a user - Discord.js

I'm pretty new to discord.js and JavaScript in general so apologies if this is something really simple!
I'm working on a Discord bot and I'm trying to make it set a variable to a voice channel specified by the user. Currently, ChosenChannel remains null. It works if I replace args with the channel name directly in the code (line 8) but then it can't be changed by a user.
Thanks in advance for any help!
client.on ('message', message => {
if (!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).split(/ +/);
const command = args.shift().toLowerCase();
if (command == 'setchannel') {
//set ChosenChannel to a channel within the current server that matches the name typed by the user (not currently working!)
ChosenChannel = message.guild.channels.cache.find(channel => channel.name === args);
//alert user if ChosenChannel is not an actual channel
if (ChosenChannel == null) {
message.channel.send('Unable to find channel');
//alert user if ChosenChannel is not a voice channel
} else if (ChosenChannel.type !== 'voice') {
message.channel.send('That does not seem to be a voice channel');
//otherwise, confirm that the command worked, and print the name of the channel
} else {
message.channel.send('The chosen channel is: ');
message.channel.send(ChosenChannel.name);
}
}
});
args is an array, the channel's name is a string. So you'll need to convert args to a string by joining it back by a space character.
if (command == 'setchannel') {
//set chosenChannel to a channel within the current server that matches the name typed by the user (not currently working!)
const channelName = args.join(' ')
const chosenChannel = message.guild.channels.cache.find(
(channel) => channel.name === channelName,
);
//alert user if chosenChannel is not an actual channel
if (!chosenChannel) {
message.channel.send('Unable to find channel');
//alert user if chosenChannel is not a voice channel
} else if (chosenChannel.type !== 'voice') {
message.channel.send('That does not seem to be a voice channel');
//otherwise, confirm that the command worked, and print the name of the channel
} else {
message.channel.send('The chosen channel is: ');
message.channel.send(chosenChannel.name);
}
}
Actually, channel names can't have spaces, so it will be always the first element of args, so you could also use it like this:
if (command == 'setchannel') {
//set chosenChannel to a channel within the current server that matches the name typed by the user (not currently working!)
const chosenChannel = message.guild.channels.cache.find(
(channel) => channel.name === args[0],
);
// ...

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

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.

Trying to add a role to a mentioned user

I am trying to make a bot for a game of tag. I am making it so you can mention a user and it adds the 'IT' role to them, but when they don't mention a member, it's added to them. My code is here:
const args = message.content.slice(prefix.length).trim().split(/ +/g);
if (message.content.startsWith(`${prefix}tag`)) {
if (!message.mentions.users.size) {
let roleenter = message.guild.roles.get("555947490315075600");
let member = message.member;
member.addRole(roleenter).catch(console.error);
message.reply("you are now it!")
client.channels.get("555943069271457792").send(member + " is now in!")
await message.guild.fetchMembers();
const role = message.guild.roles.get("555947490315075600");
for (const member of role.members.array()) {
await member.removeRole(role);
}} else {
let member = message.mentions.users.first();
let roleenter = message.guild.roles.get("555947490315075600");
member.addRole(roleenter).catch(console.error);
message.reply("you are now it!")
client.channels.get("555943069271457792").send(member + " is now in!")
await message.guild.fetchMembers();
const role = message.guild.roles.get("555947490315075600");
for (const member of role.members.array()) {
await member.removeRole(role);
Whenever I try #tag #user, it says member.addRole is not a function when I use it earlier on and it works.
Change this line:
let member = message.mentions.users.first();
To this line:
let member = message.mentions.members.first();
You used the user Object of the mentioned user, but you have to use the guildMember Object because you can‘t assign a role to an user.

Applying a role if users do not have other roles

Users are still getting the public role regardless of the role they have
I'm sorry if the answer here is fairly obvious but I'm learning javascript as I write this bot. I'm aiming for users to be able to do !name and gain a role called "public" as long as they don't have a role listed in the code (General, Captain, etc.).
client.on('message', async message => {
if (message.channel.id === '535226845654810624'); {
if(message.content.startsWith('!name')) {
if (message.member.roles.some(role => role.name === 'General', 'Captain', 'Lieutenant', 'Sergeant', 'Corporal', 'Recruit'));
const newname = message.content.split(' ').slice(1).join(' ');
message.member.setNickname(newname);
}
else {(message.content.startsWith('!name'));} {
if(message.channel.id === '535226845654810624') {
const newname = message.content.split(' ').slice(1).join(' ');
message.member.setNickname(newname);
const newrole = message.guild.roles.find(x => x.name === 'Public');
message.member.addRole(newrole);
message.delete();
}
}
I'm sure the code is completely ugly. I'm still learning. Right now regardless of if they have the Gen/Capt/Lieutenant/etc roles they still gain the public role.
client.on('message', async message => {
if(message.channel.id === '535226845654810624') {
if (message.content.startsWith('!name')) {
const newname = message.content.split(' ').slice(1).join(' ');
message.member.setNickname(newname);
const newrole = message.guild.roles.find(x => x.name === 'Public');
message.member.addRole(newrole);
message.delete();
}
}
This is the code I had before adding in the attempt to ignore the role add if they have the other roles. I'm not sure how to change this to what I'm looking for.
Take a look at the below code, give it a try and let me know what the result is. There were several errors with your code which I'm quite surprised your editor didn't pick up (or atleast didn't error out the code), such as having a semicolon right after defining an if statement, the extra curly brackets after your else statement, etc.
Anyway, the code below checks if the command entered is !name and if so, it assigns the new nickname to the user. After that it checks if the user has any of the specified roles, and if he does not, he gets a new role 'Public'.
client.on('message', async message => {
if (message.channel.id === '535226845654810624') {
if(message.content.startsWith('!name')) {
// Users are allowed to change their nicknames no matter their roles
const newname = message.content.split(' ').slice(1).join(' ');
message.member.setNickname(newname);
// Define the roles which need to be checked
const roleNames = ['General', 'Captain', 'Lieutenant', 'Sergeant', 'Corporal', 'Recruit'];
// If the user does not have any of the roles above, assign them the role 'Public'
if (!message.member.roles.some(role => roleNames.includes(role.name))) {
const newrole = message.guild.roles.find(x => x.name === 'Public');
message.member.addRole(newrole);
message.delete();
}
}
}
});

Categories