Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 days ago.
Improve this question
image
the script :
const { Client, ActivityType, WebhookClient, EmbedBuilder } = require("discord.js");
const chalk = require('chalk');
const mongoose = require('mongoose');
module.exports = {
name: 'ready',
once: true,
/**
*
#param (Client) client
*/
execute (client) {
console.log(chalk.gray(${String(new Date).split(" ", 5).join(" ")}) + chalk.white('[') + chalk.green('WAIFU_INFO') + chalk.white(']') + chalk.green( ${client.user.tag} (${client.user.id})) + chalk.white( is Ready!));
console.log(chalk.gray(${String(new Date).split(" ", 5).join(" ")}) + chalk.white('[') + chalk.green('WAIFU_INFO') + chalk.white(']') + chalk.green( ${client.guilds.cache.size} | ${client.users.cache.size} | ${client.channels.cache.size}) + chalk.white( Goods));
const embed = new EmbedBuilder()
.setDescription("**Account has been**: `Online and Ready!`")
.setColor(client.important.MAIN_COLOR);
client.channels.cache.get(client.important.CHANNEL).send({ embeds: [embed] })
let guilds = client.guilds.cache.size;
let users = client.users.cache.size;
let channels = client.channels.cache.size;
// const activities = [
// `${users} users`,
// `/help <cmd-name>`,
// `${guilds} servers | ${channels} channels`,
// `/play <search>`,
// ];
client.user.setPresence({
activities: [{ name: `/help <cmd-name> | /play <search>`, type: 2 }],
status: 'online',
});
mongoose.set('strictQuery', false);
mongoose.connect(client.important.MONGO_DB, {
}).then(() => console.log(chalk.gray(` ${String(new Date).split(" ", 5).join(" ")} `) + chalk.white('[') + chalk.green('MONGO_DB') + chalk.white(']') + chalk.green(` is now connected!`)))
}
}
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 am trying to create and initialize candy machine config account from web application but transaction failed with following error:
Are there some special need why every tutorial is based on node,js and just minting is on web?
Here is code snippet with following steps:
Create authority account and airdrop some lamports
Create candy machine config account
Initialize candy machine config account (fail)
Log:
Transaction simulation failed: Error processing Instruction 1: custom program error: 0x8f
Program 11111111111111111111111111111111 invoke [1]
Program 11111111111111111111111111111111 success
Program cndyAnrLdpjq1Ssp1z8xxDsB8dxe7u4HL5Nxi2K5WXZ invoke [1]
Program log: Custom program error: 0x8f
Program cndyAnrLdpjq1Ssp1z8xxDsB8dxe7u4HL5Nxi2K5WXZ consumed 6437 of 200000 compute units
Program cndyAnrLdpjq1Ssp1z8xxDsB8dxe7u4HL5Nxi2K5WXZ failed: custom program error: 0x8f
import { Keypair, PublicKey } from "#solana/web3.js"
import { useWorkspace } from "#/composables/useWorkspace"
import { SYSVAR_RENT_PUBKEY, CONFIG_ARRAY_START, CONFIG_LINE_SIZE, CANDY_MACHINE_PROGRAM_ID, SYSTEM_PROGRAM_ID } from "./constants"
import BN from "bn.js"
import * as anchor from '#project-serum/anchor';
let anchorWallet = null;
let solanaConnection = null;
let candyMachineProgram = null;
export const init = () => {
const { wallet, connection, candyMachine } = useWorkspace();
anchorWallet = wallet;
solanaConnection = connection;
candyMachineProgram = candyMachine;
}
const candyMachineAccountSpace = (numLines) => {
return CONFIG_ARRAY_START + 4 + numLines * CONFIG_LINE_SIZE + 4 + Math.ceil(numLines / 8.0)
};
export const mintNft = async (metadata) => {
let candyMachineConfig = Keypair.generate();
let authority = Keypair.generate();
await airdrop(authority.publicKey, 1);
await initializeCandyMachineAccount(metadata, candyMachineConfig, authority);
}
const createAccount = async (account) => {
let minimumAmountForRent = await solanaConnection.getMinimumBalanceForRentExemption(
candyMachineAccountSpace(1),
);
console.log("Account space need: " + candyMachineAccountSpace(1))
console.log("Minimum rent for config account: " + minimumAmountForRent);
console.log("From account: " + anchorWallet.value.publicKey);
console.log("To account: " + account.publicKey);
return anchor.web3.SystemProgram.createAccount({
fromPubkey: anchorWallet.value.publicKey,
newAccountPubkey: account.publicKey,
space: candyMachineAccountSpace(1),
lamports: minimumAmountForRent,
programId: new PublicKey(CANDY_MACHINE_PROGRAM_ID),
});
}
const airdrop = async (address, amount) => {
return await solanaConnection.requestAirdrop(address, amount);
}
const initializeCandyMachineAccount = async (metadata, candyMachineConfig, authority) => {
let cmuuid = candyMachineConfig.publicKey.toBase58().slice(0, 6) //;
console.log("cmuuid: " + cmuuid);
console.log("Symbol: " + metadata.symbol);
console.log("Seller fee: " + metadata.sellerFeeBasisPoints);
console.log("Rent: " + new PublicKey(SYSVAR_RENT_PUBKEY));
console.log("Wallet: ");
candyMachineProgram.value.rpc.initializeConfig(
{
uuid: cmuuid,
maxNumberOfLines: new BN(1),
symbol: metadata.symbol,
sellerFeeBasis: metadata.sellerFeeBasisPoints,
isMutable: true,
maxSupply: new BN(1),
retainAuthority: true,
creators: [
{
address: anchorWallet.value.publicKey,
share: 100
}
]
},
{
accounts: {
config: candyMachineConfig.publicKey,
authority: authority.publicKey,
payer: authority.publicKey,
systemProgram: SYSTEM_PROGRAM_ID,
rent: new PublicKey(SYSVAR_RENT_PUBKEY),
},
preInstructions: [
//await createAccount(authority), // created by airdrop
await createAccount(candyMachineConfig)
],
signers: [candyMachineConfig, authority],
}
)
}
I get the following message via mqtt:
{"7801":{"teste":"teste888"}}
I need to get the information and update it in the teste field, like:
colection.update({
"teste":"teste888"
})
How can I get this information straight from the string in JSON format?
My code:
//mqtt
const mqtt = require('mqtt')
client = mqtt.connect({
host: 'xxx.xxx.xxx.xxx',
port: 1883,
username: 'xxxxxxx',
password: 'xxxxxxxx'
});
// firestore
const admin = require('firebase-admin');
const serviceAccount = require('./firestore/firestoreTeste.json');
admin.initializeApp({
credential: admin.credential.cert(serviceAccount)
});
const db = admin.firestore();
//client mqtt
client.on('connect', () => {
let documents = db.collection('place2').get()
.then(snapshot => {
snapshot.forEach(doc => {
var namePlace = [];
namePlace = doc.id.toString();
client.subscribe(namePlace + "/locker/testex/update")
client.subscribe(namePlace + "/booking/testex/update")
});
});
});
client.on('message', (topic, message) => {
console.log('JSON: ', message.toString());
const namePlace = topic.split("/")[0];
console.log("Name place: ", namePlace);
const nameCol = topic.split("/")[1]
console.log("Name colection: ", nameCol)
const key = message.toString().substr(2,4);
console.log("ID: ", key);
const colection = db.collection("place2").doc(namePlace).collection(nameCol).doc(key);
const teste = JSON.parse(message)
console.log("teste: ", teste)
colection.update({
//teste
})
})
Thank you!
I think you're looking for:
colection.update({
teste: teste["7801"]
})
This will take property 7801 from your JSON, and write that value to the teste field in the database.
If you don't know the name of the 7801 field, you can use a loop to get the values from all top-level properties:
let value = "";
Object.keys(teste).forEach((key) => {
value += test[key];
});
colection.update({
teste: value
})
Here I just concatenated the values, but you may want to do something more specific to your use-case.
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.