I have a selfbot project for Discord (I know it's against the ToS, but this is just an experiment I'm not going to use it)
I want the selfbot to send a message like "this is an example message" every hour in a specific channel with the ID (783651779207626752)
What and where should I add something in the code?
const Discord = require("discord.js")
const client = new Discord.Client()
const { prefix, token } = require("./config.json")
const fs = require("fs")
const { table, getBorderCharacters } = require("table")
const commands = new Discord.Collection();
let commandFiles
function loadCommands() {
console.log("loading commands..")
const startTime = new Date().getTime()
commandFiles = fs.readdirSync("./commands/").filter(file => file.endsWith(".js"));
const failedTable = []
if (commands.size > 0) {
for (command of commands.keyArray()) {
delete require.cache[require.resolve(`./commands/${command}.js`)]
}
commands.clear()
}
for (file of commandFiles) {
let command
try {
command = require(`./commands/${file}`);
let enabled = true;
if (!command.name || !command.description || !command.run) {
enabled = false;
}
if (enabled) {
commands.set(command.name, command);
} else {
failedTable.push([file, "❌"])
}
} catch (e) {
failedTable.push([file, "❌"])
}
}
}
loadCommands()
exports.reloadCommands = loadCommands
client.once("ready", () => {
console.log("logged in as " + client.user.username + "#" + client.user.discriminator)
})
function runCommand(cmd, message, args) {
args.shift()
try {
commands.get(cmd).run(message, args)
} catch(e) {
console.log(e)
}
}
setTimeout(() => {
client.login(token)
}, 1500)
You can make another file called globalFunctions.js
Add anything that you want to be running globally as an IFFE
This will insure that every IFFE has its own block of code
globalFunctions.js
export default globalFunctions(client, channel){
/*
IFFE
*/
(function(){
setInterval(()=>{
channel.send('some message')
}, /*Time you want*/)
})()
// and so on
}
OR "I recommend this if you want to scale"
you can add other files for each global function and add then to global function file
/*Import other functions*/
import periodicMessage from 'PATH'
export default globalFunctions(client, channel){
periodicMessage(client, channel);
}
and just import this function to the main file and run it after the server runs
main.js
import globalFunctions from 'PATH'
client.once('ready', () => {
// Your code
globalFunctions(client, channel)
})
Related
I'm Creating a discord bot for a pc game that will run /setup command that will automate some other commands using setInterval(). I'm using a class to group the commands into their own subclass. I wanted to make a command that will run a few certain commands every few secs or hours. I've tried everything I can think, tried to google it but nothin came up.
Here is the Index.js file (main file)
require ('dotenv').config();
const { Client, GatewayIntentBits, Partials, Routes, Collection } = require('discord.js')
const Discord = require('discord.js')
const client = new Client({
intents:[
GatewayIntentBits.GuildMessages,
GatewayIntentBits.Guilds,
GatewayIntentBits.MessageContent
],
rest: {version: '10'},
partials: [Partials.Channel]
});
const {TOKEN, APP, GUILD} = process.env;
const {registerCommands} = require('./handler/registercommand');
client.rest.setToken(TOKEN);
client.on('interactionCreate', (interaction) => {
if (interaction.isChatInputCommand()) {
const {commandName} = interaction;
console.log(commandName)
const cmd = client.slashCommands.get(commandName);
if (cmd) {
cmd.execute(client, interaction);
}
else {
interaction.reply({content: 'Error running this slash command'});
}
}
});
async function main() {
try {
client.slashCommands = new Collection;
await registerCommands(client, '../commands');
//console.log(client.slashCommands);
const slashCommandsJson = client.slashCommands.map((cmd) => cmd.getSlashCommandJSON());
console.log(slashCommandsJson);
await client.rest.put(Routes.applicationCommands(APP), {
body: slashCommandsJson,
});
const registeredSlashCommands = await client.rest.get(
Routes.applicationCommands(APP)
);
console.log(registeredSlashCommands);
await client.login(TOKEN);
}
catch(err) {
console.log(err)
}
}
main()
One of the commands I want to automate which in this case is /arbitrations
const unirest = require("unirest");
const { EmbedBuilder, AttachmentBuilder, SlashCommandBuilder } = require("discord.js");
const SlashCommands = require('../handler/slashcommands');
file = new AttachmentBuilder();
module.exports = class arbitration extends SlashCommands {
constructor() {
super('arbitration');
}
async execute(client, interaction) {
const api = unirest("GET", "https://api.warframestat.us/pc/arbitration");
const moment = require("moment");
api.end(function (response) {
//gathers the data from the get request
if (response.error) throw new Error(response.error); // throws(logs) the error
const jsonResponse = response.body; // grabs the body from the response
const jsonEmbed = new EmbedBuilder()
.setTitle("Current Arbitration:")
.setColor("#BF40BF") // sets the color of the embed
.setFooter({ text: "Arbitration" }) // sets the footer text of the embed
if (jsonResponse['enemy'] === 'Grineer'){
file = new AttachmentBuilder('./assets/grineer.jpg')
jsonEmbed.setThumbnail('attachment://grineer.jpg')
}
else if (jsonResponse['enemy'] === 'Corpus'){
file = new AttachmentBuilder('./assets/corpus.jpg')
jsonEmbed.setThumbnail('attachment://corpus.jpg')
}
else if (jsonResponse['enemy'] === 'Corrupted'){
file = new AttachmentBuilder('./assets/corrupted.jpg')
jsonEmbed.setThumbnail('attachment://corrupted.jpg')
}
else {
file = new AttachmentBuilder('./assets/infested.jpg')
jsonEmbed.setThumbnail('attachment://infested.jpg')
}
var d = new Date(jsonResponse["expiry"]);
let date = moment(d, "MMM-DD").format("MMM:DD"); // returns the month and day
date = date.replace(":", " "); // replaces the : with a space
let final = moment(d, "HH:mm:ss").format("h:mm:ss A");
jsonEmbed.addFields({
name: `${jsonResponse["type"]}, \`${jsonResponse["node"]}\``,
value: `\n**Expires on:** \n${date} at ${final}`,`
});
interaction.reply({ embeds: [jsonEmbed], files: [file] });
});
}
getSlashCommandJSON(){
return new SlashCommandBuilder()
.setName(this.name)
.setDescription('Shows current Arbitration')
.toJSON();
}
};
Then the /setup command that will automate certain commands depending on the user's answer, I'm trying to execute /arbitrations command inside the SetInterval() on line 22:
const SlashCommands = require('../handler/slashcommands');
const { EmbedBuilder, Discord, SlashCommandBuilder } = require("discord.js");
module.exports = class setup extends SlashCommands {
constructor() {
super('setup');
}
async execute(client, interaction){
console.log("in the command")
const filter = (m) => m.author.id === interaction.user.id
interaction.channel.send("Would you like to automate the Arbitration command?")
console.log("sent Question")
interaction.channel
.awaitMessages({filter ,max: 1, time: 1000 * 20})
.then((collected) => {
const msg = collected.first()
if (msg.content.toLowerCase() === "yes" || msg.content.toLowerCase() === "y") {
console.log("setting setInterval()")
setInterval(() => {
var minutes = new Date().getMinutes()
if (minutes === 51) {
SlashCommands.get(`arbitrations`).execute(client, interaction)
}
}, 1000 * 5)
interaction.channel.send("Arbitration is Automated")
}
else if (msg.content.toLowerCase() === "no" || msg.content.toLowerCase() === "n") {
interaction.channel.send("Automation for Arbitration is canceled")
}
else {
interaction.channel.send("An error has occured please run again")
}
})
.catch((err) => console.log(err))
}
getSlashCommandJSON(){
return new SlashCommandBuilder()
.setName(this.name)
.setDescription('Automates commands')
.toJSON();
}
}
FYI: first time using this site so sorry if this doesn't look right
I already tried the code that's currently on line 25 and I get error "SlashCommands.get is not a function"
Is it possible to detect errors before the code starts to run?
I have a Discord bot, and I would like the command handler that prints all loaded commands to the console to show the status for errors in advance.
Command handler at the moment:
const { readdirSync } = require("fs");
const ascii = require("ascii-table");
const list = new ascii('Commands');
list.setHeading('Command', 'Loaded');
module.exports = (bot) => {
let commands = readdirSync(`./commands/`).filter(file => file.endsWith(".js"));
for (let file of commands) {
let command = require(`../commands/${file}`);
if (command.name) {
bot.commands.set(command.name, command);
list.addRow(file, '✅');
} else {
list.addRow(file, '❌');
continue;
}
}
console.log(list.toString());
}
You can simply use the try and catch statements of Javascript. In this way, if an error occurs still it will not break your code or bot. It will continue running without any problem.
If you don't want to show anything and want to continue running the bot:
try {
const { readdirSync } = require("fs");
const ascii = require("ascii-table");
const list = new ascii("Commands");
list.setHeading("Command", "Loaded");
module.exports = (bot) => {
let commands = readdirSync(`./commands/`).filter((file) =>
file.endsWith(".js")
);
for (let file of commands) {
let command = require(`../commands/${file}`);
if (command.name) {
bot.commands.set(command.name, command);
list.addRow(file, "✅");
} else {
list.addRow(file, "❌");
continue;
}
}
console.log(list.toString());
};
} catch (e) {
// Don't do anything
}
Incase you want to print out the error to the console and continue running the bot. Then you can add a console.log() under the catch statement:
try {
const { readdirSync } = require("fs");
const ascii = require("ascii-table");
const list = new ascii("Commands");
list.setHeading("Command", "Loaded");
module.exports = (bot) => {
let commands = readdirSync(`./commands/`).filter((file) =>
file.endsWith(".js")
);
for (let file of commands) {
let command = require(`../commands/${file}`);
if (command.name) {
bot.commands.set(command.name, command);
list.addRow(file, "✅");
} else {
list.addRow(file, "❌");
continue;
}
}
console.log(list.toString());
};
} catch (e) {
console.log(e)
}
I'm trying to get a little familiar with the slash command handler, but I get an error when trying to grab the member id, this happens with just about everything I try to grab.
Here at the top is directly my command, where I try to send a message with the content "user.id".
this is my command:
const { SlashCommandBuilder } = require("#discordjs/builders");
module.exports = {
data: new SlashCommandBuilder()
.setName("avatar")
.setDescription("SERVUSSS")
.addUserOption(option => option.setName("member").setDescription("memberdings").setRequired(true)),
async execute(interaction) {
const user = interaction.options.getUser('target');
await interaction.reply(`${user.id}`);
}
}
this is my deploy file:
require("dotenv").config();
const fs = require("fs");
const { REST } = require("#discordjs/rest");
const { Routes } = require("discord-api-types/v9");
const commands = [];
const commandFiles = fs.readdirSync("./src/commands").filter(file => file.endsWith(".js"));
commandFiles.forEach(commandFile => {
const command = require(`./commands/${commandFile}`);
commands.push(command.data.toJSON());
});
const restClient = new REST({version: "9"}).setToken(process.env.TOKEN);
restClient.put(Routes.applicationGuildCommands(process.env.APPLICATION_ID, process.env.GUILD_ID),
{body: commands }).then(() => console.log("success")).catch(console.error);
my index file:
require("dotenv").config();
const { Client, Collection } = require("discord.js");
const fs = require("fs");
const client = new Client({intents: []});
client.commands = new Collection();
const commandFiles = fs.readdirSync("./src/commands").filter(file => file.endsWith(".js"));
commandFiles.forEach(commandFile => {
const command = require(`./commands/${commandFile}`);
client.commands.set(command.data.name, command);
});
client.once("ready", () => {
console.log("ready!!");
});
client.on("interactionCreate", async (interaction) => {
if(!interaction.isCommand()) return;
const command = client.commands.get(interaction.commandName)
if(command) {
try {
await command.execute(interaction)
} catch(error) {
console.log(error)
if(interaction.deferred || interaction.replied) {
interaction.editReply("error")
} else {
interaction.reply("error")
}
}
}
})
client.login(process.env.TOKEN)
I actually stick to it pretty much all the time
https://discordjs.guide/ just do not understand what I'm doing wrong
Since option name is member then it's going to be
const user = interaction.options.getUser('member');
In your command file, the name for the option is given as member, but when you are using interaction.options.getUser(), you are passing the name as 'target'. So all you have to do is change the line where you are declaring the user to: const user = interaction.options.getUser('member')
I have a piece of code that automatically runs every 4 hours to send a set message to a specific discord channel on my discord server but I would like to have this function start upon command and I would like that command to be in a separate file from my main index code if someone could give me a template for this code as a slash command I would greatly appreciate it you would be saving me days possibly weeks of tedious research and trial and error I need code that is up to date with v13 of discord.js and that will be compatible with my main index file code which will be set below the specific function that I want accomplished.
setInterval(() => {
client.channels.cache.get("916642101989617684").send("!stats");
}, (1000 * 60) * 240);
const fs = require('fs');
const { Client, Collection, Intents } = require('discord.js');
const { token } = require('./config.json');
const client = new Client({ intents: [Intents.FLAGS.GUILDS] });
client.commands = new 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.data.name, command);
}
const eventFiles = fs.readdirSync('./events').filter(file => file.endsWith('.js'));
for (const file of eventFiles) {
const event = require(`./events/${file}`);
if (event.once) {
client.once(event.name, (...args) => event.execute(...args));
} else {
client.on(event.name, (...args) => event.execute(...args));
}
}
client.once('ready', () => {
console.log('Ready!');
});
setInterval(() => {
client.channels.cache.get("916642101989617684").send("!stats");
}, (1000 * 60) * 240);
client.on('interactionCreate', async interaction => {
if (!interaction.isCommand()) return;
const command = client.commands.get(interaction.commandName);
if (!command) return;
try {
await command.execute(interaction);
} catch (error) {
console.error(error);
return interaction.reply({ content: 'There was an error while executing this command!', ephemeral: true });
}
});
client.login(token);
Simply put it in an interactionCreate event, but make sure it's once so that it doesn't constantly make more intervals
client.once("interactionCreate", async (interaction) => {
if (interaction.commandName === "register") { //or whatever name the command should be
//the code you want to start here
})
I am working on making an npm module and it keeps responding with a "is not a constructor error". Here is my code:
const Discord = require('discord.js')
module.exports = function () {
this.Client = function () {
new Discord.Client()
}
this.Client.whenEvent = function (event, callback) {
const client = this.Client();
client.on(event, callback)
}
this.Client.login = function (token) {
const client = this.Client()
client.login(token)
}
}
and here is my testing code if you need it as well
const diss = require('./index.js')
const client = new diss.Client()
client.whenEvent('ready', () => {
console.log('IM READY!')
})
client.whenEvent('message', message => {
if (message.content == "test") {
message.channel.send('diss.js worked! NOW ADD STUFF!')
}
})
client.login(TOKEN)