I'm making a discord bot and need to capture text from a users command such as !add var1 var2 var3 var4 var5 var6 with vars being information that needs to be placed into mysql. the code functions well as is but I'm new to node.js and discord and can't find anything on google on how to capture command input to use as database values.
const prefix = "!";
client.on("message", message => {
if (message.content.startsWith(prefix + "kos")) {
connection.query("SELECT kos_id, kos_name, kos_coords,kos_seenby FROM rogue_kos ORDER BY
kos_name", function(err, rows, fields) {
rows.forEach(function(row) {
console.log(row.kos_id, row.kos_name, row.kos_coords, row.kos_seenby, row.kos_date);
const embed = new Discord.RichEmbed()
.setTitle('Records Management')
.setColor(3447003)
.setDescription('Please select an option.')
.setTimestamp()
.addField('1. View KoS List', 'Respond with "1" to SEARCH records')
.addField('2. Add to KoS List', 'Respond with "2" to ADD a record - Currently
Unavailable.');
message.channel.send({embed})
message.channel.awaitMessages(response => (response.content === '1' || response.content ===
"2"), {
max: 1,
time: 100000,
errors: ['time']
}).then(mg => {
if (mg.first().content === "1"){ //Have to use .first() because mg is a Collection
const embed = new Discord.RichEmbed()
.setTitle('Search Results')
.setColor(3447003)
.setDescription('ID | NAME | COORDS | ADDED BY | DATE ADDED\n\n' + row.kos_id + ' | ' +
row.kos_name + ' | ' + row.kos_coords + ' | ' + row.kos_seenby + ' | ' + row.kos_date)
.setTimestamp()
message.channel.send({embed})
}else if (mg.first().content === "2"){
const embed = new Discord.RichEmbed()
.setTitle('Add Record')
.setColor(3447003)
.setDescription('Currently Unavailable')
.setTimestamp()
message.channel.send({embed})
}
}).catch((err) => {
message.channel.send("Ran out of time!");
})
})
})
}
});
I don't know if the syntax is the same, but with an sqlite3 database you would use a query like this
const arg = commandArgs;
const user = message.author;
const query = `UPDATE yourTableNameHere SET yourColumn=? WHERE user_id= ?`
db.run(query, [arg, user],(err, rows) {
if (err) {
return console.error(err.message);
}
***your if/else statements here***
});
Of course this isn't exact, but it may give you an idea of how to do it. Also, you would want to add restrictions and checks to make sure the command argument is what you're expecting.
Related
I'm trying to create a discord bot using a different syntax you could say and trying to integrate a bunch of different commands. The original command I was trying to add was the "fees.js" below. And the bot wasn't responding to the command, but isn't crashing in the console either. I tried testing with a simple ping command that would respond with "Pong!" within an embed, but still doesn't respond. Below I've attached my index.js, fees.js, and my test ping.js
const Discord = require("discord.js");
const client = new Discord.Client({ intents: ["GUILDS", "GUILD_MESSAGES", "GUILD_MESSAGE_REACTIONS"] }, { partials: ["MESSAGE", "CHANNEL", "REACTION", "MANAGE_ROLES"] })
require("dotenv").config();
const prefix = "-";
const fs = require("fs");
client.commands = new Discord.Collection();
const commandFiles = fs.readdirSync("./commands/").filter(file => file.endsWith('.js'));
for (const file of commandFiles) {
const command = require(`./commands/${file}`);
client.commands.set(command.name, command);
}
client.on("ready", () => {
console.log(`Logged in as ${client.user.tag}!`);
});
client.on("messageCreate", message => {
if (message.author.bot) return;
if (message.content === prefix + 'reactionrole') {
if (!message.member.roles.cache.has('885603457938108476')) {
return message.channel.send('You dont have access to this!');
}
if (!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).split(/ +/);
const command = args.shift().toLowerCase();
if (command === "ping") {
client.commands.get("ping").execute(message, args, Discord, client);
}
}
});
client.login('Token');
fees.js
module.exports = {
name: 'fee',
description: 'This command will calculate the payouts for every major platform\n`!fee <amount>`\nexample: `!fee 100`',
async execute(message) {
const fees = {
'StockX Level 1 (9.5%)': n => .095 * n,
'StockX Level 2 (9%)': n => .09 * n,
'StockX Level 3 (8.5%)': n => .085 * n,
'StockX Level 4 (8%)': n => .08 * n,
'Goat 90+ (9.5% + $5.00 + 2.9%)': n => 0.095 * n + 5 + (0.905 * n * 0.029),
'Goat 70-89 (15% + $5.00 + 2.9%)': n => 0.15 * n + 5 + (0.85 * n * 0.029),
'Goat 50-69 (20% + $5.00 + 2.9%)': n => 0.20 * n + 5 + (0.80 * n * 0.029),
'Ebay (12.9% + $0.30': n => 0.129 * n + 0.3,
'Paypal (2.9% + $0.30)': n => (0.029 * n) + 0.3,
'Grailed (9% + 2.9%)': n => 0.089 * n + 0.911 * n * 0.029,
}
const embed = new Discord.MessageEmbed();
embed.setTitle("Fee Calculator")
if (msg.content.split(" ").length == 2) {
if (isNaN(message.content.split(" ")[1])) {
embed.setDescription('Please input a number');
}
else {
const [, number] = message.content.split(' ');
Object.keys(fees).forEach(fee => {
embed.addField(`${fee} Payout`, `$${Number(number - fees[fee](number)).toFixed(2)}`);
});
}
}
else if (message.content.split(" ").length > 2) {
embed.setDescription("This command takes only 1 argument");
}
else if (message.content.split(" ").length == 1) {
embed.setDescription("Please put a price to calculate fees");
}
else {
embed.setDescription("Please input a price")
}
message.channel.send(embed);
}
}
ping.js
module.exports = {
name: 'ping',
description: 'This command will display the latency between Discord and our servers\n`!ping`\nexample: `!ping`',
permission: 'USE_APPLICATION_COMMANDS',
async execute(message, args, Discord, client) {
const embed = new Discord.MessageEmbed()
.setTitle("Ping")
.setColor('#5104DB')
.setDescription(`Pong!`)
message.channel.send({ embeds: [embed] });
}
}
On September 1st, Discord made message content a privileged intent. Maybe you should check your application settings over at Discord Developers? Also you might want to consider switching to Slash Commands.
EDIT:
I noticed that you are checking if the command equals to "reactionrole", before checking for equality to "ping". Maybe try moving the if statement outside of that check?
I want to try to store my command cooldown in any sort of storage, I think sqlite will be good, but I don't know how to implement it for a cooldown.. I was checking one guide here https://anidiots.guide/coding-guides/sqlite-based-points-system/#you-get-points-and-you-get-points-and-everybody-gets-points, it's for storage points and levels.. Unfortunately I'm not able edit this example into my needs, to store the cooldown for each user.
'use strict';
const SQLite = require("better-sqlite3");
const sql = new SQLite("./cooldowns.sqlite");
const humanizeDuration = require('humanize-duration');
// Require the necessary discord.js classes
const { Client, Intents, Collection } = require('discord.js');
const config = require("./config.json");
const { MessageEmbed } = require('discord.js');
const cooldowns = new Map();
const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES] });
client.on('ready', () => {
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.getCooldown = sql.prepare("SELECT * FROM scores WHERE user = ? AND guild = ?");
client.setCooldown = sql.prepare("INSERT OR REPLACE INTO scores (id, user, guild, points, level) VALUES (#id, #user, #guild, #points, #level);");
client.user.setActivity("thinking...", { type: 'PLAYING' });
console.log('Bot is online!')
});
client.on("messageCreate", message => {
if (message.author.bot) return;
// This is where we'll put our code.
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 === 'mycommand') {
const cooldown = cooldowns.getCooldown(message.author.id);
if (!cooldown) {
cooldowns = {
id: `${message.author.id}`,
user: message.author.id,
cooldown: 0
}
}
if (cooldown) {
const remaining = humanizeDuration(cooldown - Date.now(), { round: true }, { units: ["d","h","m","s"] });
message.reply(`Your cooldown is. ${remaining}`)
return;
}
async function main() {
const messages = await message.channel.messages.fetch({ limit: 1 });
const lastMessage = messages.last();
const isValidDate = (dateString) => new Date(dateString).toString() !== 'Invalid Date'
if(isValidDate(lastMessage.content) == false && lastMessage.content !== 'mycommand')
message.reply("I need your date of birth!.")
if(lastMessage.content === 'mycommand')
message.reply("Please provide me your date of birth.")
if(isValidDate(lastMessage.content) == true && lastMessage.content !== 'mycommand') {
cooldowns.set(message.author.id, Date.now() + 604800000);
message.reply("Check your DMs.")
message.react("emoji"); //react with emoji to the issued command
const predictions = ["Prediction 1", "Prediction 2", "Prediction 3", "Prediction 4", "Prediction 5", "Prediction 6", "Prediction 7"]
const randomprediction = predictions[Math.floor(Math.random() * predictions.length)];
const prediction1 = new MessageEmbed()
.setColor('#ff7518')
.setAuthor(client.user.username, client.user.displayAvatarURL())
.setTitle(`Weekly message` + lastMessage.author.username + `#` + lastMessage.author.discriminator)
.setDescription(randomprediction);
message.author.send({ embeds: [prediction1] });
var random = Math.random()
if (random < 0.9) {
message.author.send("Congrats! You received this message " + '<#' + message.author.id + '>!')
message.channel.send('Congrats again! ' + '<#' + message.author.id + '>');
}
setTimeout(() => cooldowns.delete(message.author.id), 604800000);
client.setCooldown.run(cooldowns);
}
}
}
The problem is I don't know how to edit the sql params, I never used sqlite/anything else before and have 0 experience with it. All I want is to store command in some sort of storage, but I don't know where to start. Any help will be much appreciated!
I have this code which chooses a random user and displays their name and what they won, the problem is it can also make the user who sent the giveaway message the winner and the same with bots. How can I make an exception for the msg.author?
if(msg.content.startsWith('-giveaway'))
{
const suggestion = msg.content.slice(10);
const user = msg.guild.members.random();
let embed = new Discord.RichEmbed()
.setTitle('Prize : ' + suggestion)
.addField('Host : ', msg.author)
.addField('Nyertes : ', user)
.setFooter('Verzió 1.1')
.setTimestamp()
msg.channel.send(embed);
console.log(`${user.user}`).catch(console.error);
}
You could filter out the message author from the user list before selecting a random user:
const userList = msg.guild.members.filter(user => user.id !== msg.author.id || !msg.author.bot || msg.member.roles.some(role => role.name === 'RoleName') || msg.member.roles.some(role => role.id === 'ROLE_ID'));
const user = userList.random();
Alright so heres my issue. I'm trying to delete a message that only contains an embed. However, the message wont delete. Here is what I've tried:
const embedMsg = message.embeds.find(msg => msg.title == 'Castle League Mafia');
if(embedMsg) {
message.delete();
return;
}
And I've just tried message.delete() once players is equal to 1 and that doesn't work either. It deletes my message (the one with the command for sending the embed)
Here is the place where I'm trying to do it: https://pastebin.com/DbuFx8Gs
Heres my full code: https://pastebin.com/6EJVTBFJ
Try this code here
// when you send the embed
const embed = message.channel.send(Embed)
// if (blah blah blah)
if (1 == 1) { // for testing
embed.delete()
}
in your case this should work
require('dotenv').config();
const discord = require("discord.js");
const client = new discord.Client();
const prefix = '!'
const footer = "Mafia Bot V1.0 - Spoon";
var players = 0;
client.login(process.env.BOT_TOKEN);
client.on('ready', () => {
console.log("Bot is logged in!");
client.user.setActivity('Mafia', {type: 'PLAYING'}).then(presence => console.log(`Activity set to ${presence.activities[0].name}`)).catch(console.error);
});
client.on('message', message => {
// Start Command
var embedMsg;
if (message.content === prefix + "newgame") {
let newEmbed = new discord.MessageEmbed()
.setTitle("Castle League Mafia")
.setDescription("**Everything here is going to be changed**\nReact to this message to join the mafia game!\n\n6 players in total are needed to play.\n\nIf you are the mafia, you will recieve a DM. If you do not recieve a DM, you are innocent.\n\n**" + players + "/6 Players**")
.setColor("PURPLE")
.setTimestamp()
.setFooter(footer);
embedMsg = message.channel.send(newEmbed);
}
// Add join reaction
if(message.author.bot) {
if(message.embeds) {
if(embedMsg) {
message.react('☑️');
return;
}
}
}
// When players react
client.on("messageReactionAdd", (reaction, user) => {
if(reaction.emoji.name === "☑️" && !user.bot) {
players += 1;
// When players join
switch (players) {
case 1:
console.log(players + " players are ready to play!");
if(embedMsg) {
embedMsg.delete();
return;
}
let startEmbed = new discord.MessageEmbed()
.setTitle("Game has started!")
.setDescription("**Mafia has been messaged!**")
.setColor("PURPLE")
.setTimestamp()
.setFooter(footer);
message.channel.send(startEmbed);
break;
case 2:
console.log(players + " players are ready to play!");
break;
case 3:
console.log(players + " players are ready to play!");
break;
default:
break;
}
return;
}
});
client.on("messageReactionAdd", (reaction, user) => {
if(reaction.emoji.name === "🔵") {
}
});
client.on("messageReactionRemove", (reaction, user) => {
if(reaction.emoji.name === "☑️" && !user.bot) {
players -= 1;
console.log(players + " players are ready to play!");
return;
}
})
});
I am making my first Discord Bot, using Discord.js - I can make it read a command !makeraid and the bot will ask the first question, and store the response into an array.
I want to be able to ask multiple questions like raid name, description, date, and time. I have not yet got this far, after the first question is asked, as a test i want the bot to create the embed message.
However, i cannot make it trigger/fire the next question.
client.on('message', message => {
if (message.content.toLowerCase().startsWith("!makeraid")) {
const filter = m => m.author.id === message.author.id;
var raid = {};
var color = ((1 << 24) * Math.random() | 0).toString(16);
var raidImages = {'DDS':'https://i.imgur.com/izsm8ri.jpg','GR':'https://i.imgur.com/4S9NKtF.jpg','CR':'https://i.imgur.com/EnYiWka.jpg','OR':'https://i.imgur.com/VOYDUlO.jpg'};
message.reply('Raid Name?').then(r => r.delete(10000));
message.channel.awaitMessages(filter, {
max: 1,
time: 10000,
errors: ['time'],
})
.then((collected) => {
raid.title = collected.first().content;
console.log(raid);
collected.first().delete(5000);
})
.catch(() => {
message.channel.send('Raid Cancelled - Too Slow!').then(r => r.delete(5000));
});
while ( Object.keys(raid).length > 0 ) {
message.reply('Do you want to create the raid? Yes or No.').then(r => r.delete(10000));
message.channel.awaitMessages(filter, {
max: 1,
time: 10000,
errors: ['time'],
})
.then((collected) => {
if (collected.first().content.toLowerCase() === "yes") {
collected.first().delete();
var raidEmbed = new Discord.RichEmbed()
.setColor('#'+color)
.setAuthor('Raid Bot', client.user.avatarURL)
.setTitle(':star::star: '+raid.title+' :star::star:')
.setThumbnail(client.user.avatarURL)
.setDescription('Some description here')
.addField('Date', 'Some value here', true)
.addField('Time', 'Some value here', true)
.setTimestamp()
.setFooter('Raid created by: '+ message.member.user.tag, message.member.user.avatarURL);
message.channel.send(raidEmbed).then(async embedMessage => {
await embedMessage.react('✅');
await embedMessage.react('❓');
await embedMessage.react('🇽');
});
} else {
collected.first().delete();
message.channel.send('Raid Cancelled').then(r => r.delete(5000));
}
})
.catch(() => {
message.channel.send('Raid Cancelled - Too Slow! (Make)').then(r => r.delete(5000));
});
}
message.delete();
} else if (message.content.toLowerCase().startsWith("!help")) {
message.reply('You Suck 😃').then(r => r.delete(10000));
message.delete();
}
});
No errors are coming up in the terminal, it just does nothing after the first response has been collected and push into the array.