Whenever somebody sends !setmainchannel, my program crashes. I am using Node.js with the package discord.js. This is the only problem I have. I don't and can't understand what's wrong, and I would extremely appreciate it if someone could help me out.
bot.js:
let Discord = require("discord.js");
let client = new Discord.Client();
let fs = require('fs');
let help = require("./helpembed.json");
var jsonRead = function(filePath){
fs.readFile(filePath, 'utf-8', (err, returnJson) => {
if(err){
console.log(err);
}
else{
let ret = JSON.parse(returnJson);
return ret;
}
})
}
var jsonWrite = function(filePath, objIn){
fs.writeFile(filePath, JSON.stringify(objIn), err => {
if(err){
console.log(err);
}
})
}
client.on("message", msg => {
let time = new Date();
let cstTimeStamp = `${time.getMonth() + 1}/${time.getDate()}/${time.getFullYear()} ${time.getHours() + 1}:${time.getMinutes()}:${time.getSeconds()}`
if(msg.content == "!setmainchannel"){
let mainChannel = msg.mentions.channels.first();
if(!mainChannel){
console.log(`${cstTimeStamp} #${msg.author.tag} requested to set a main channel but didn't provide a channel\n`);
msg.channel.send("There's no channel to set the main to");
}
else{
let currentSettings = jsonRead("./main-channel.json");
currentSettings.channel = mainChannel;
jsonWrite("./main-channel.json", currentSettings);
console.log(`${cstTimeStamp} #${msg.author.tag} set the main channel as ${currentSettings.channel}\n`);
msg.channel.send(`Set the main channel as ${currentSettings.channel}`);
}
}
})
client.once('ready', () => {
console.log('Bot is online\n');
});
client.login('Token hidden for safety reasons');
main-channel.json:
{
"channel":null
}
First, your bot does nothing because it only reacts if (msg.content == "!setmainchannel"). If you provide an argument, like a channel (!setmainchannel #ch-name), it won't run as the message's content is not exactly the prefix and the command.
You'll need to fix that first. By removing the prefix and chopping off the arguments, you can get the command itself and check if this exact command is used. (Again, you should not check the whole message.content)
Second, you don't wait for the callback inside readFile to run. It means, when you try to update currentSettings.channel, your jsonRead() function has just started to read the file and the currentSettings is undefined. You won't be able to update its channel property.
I've updated both your jsonWrite and jsonRead functions to return promises and make it easier to use. Check the working code below:
const Discord = require("discord.js");
const fs = require('fs');
const path = require('path');
const client = new Discord.Client();
const prefix = '!';
client.on('message', async (msg) => {
// create an args variable that slices off the prefix and splits it into an array
const args = msg.content.slice(prefix.length).split(/ +/);
// create a command variable by taking the first element in the array
// and removing it from args
const command = args.shift().toLowerCase();
const cstTimeStamp = new Date().toLocaleString();
if (command === 'setmainchannel') {
const mainChannel = msg.mentions.channels.first();
const filePath = path.resolve(__dirname, './main-channel.json');
if (!mainChannel) {
console.log(`${cstTimeStamp} ${msg.author.tag} requested to set a main channel but didn't provide a channel\n`);
return msg.channel.send("There's no channel to set the main to");
}
try {
const currentSettings = await jsonRead(filePath);
currentSettings.channel = mainChannel;
jsonWrite(filePath, currentSettings);
console.log(`${cstTimeStamp} ${msg.author.tag} set the main channel as ${currentSettings.channel}\n`);
msg.channel.send(`Set the main channel as ${currentSettings.channel}`);
} catch (err) {
console.log(err);
}
}
});
client.once('ready', () => {
console.log('Bot is online\n');
});
client.login('Token hidden for safety reasons');
function jsonRead(filePath) {
return new Promise((resolve, reject) => {
fs.readFile(filePath, 'utf-8', (err, content) => {
if (err) {
reject(err);
} else {
try {
const parsedContent = JSON.parse(content);
resolve(parsedContent);
} catch (err) {
reject(err);
}
}
});
});
}
function jsonWrite(filePath, data) {
return new Promise((resolve, reject) => {
fs.writeFile(filePath, JSON.stringify(data), (err) => {
if (err) {
reject(err);
}
resolve(true);
});
});
}
Alright, I see what's going on here. I made the logic react to ONLY !setmainchannel, whereas I should've done if(msg.content.startsWith("!setmainchannel")!
Related
This question already has answers here:
How do I fix CLIENT_MISSING_INTENTS error?
(5 answers)
Closed 1 year ago.
hey i've tried almost every tutorial in here but it still shows me uncaught typerror.. it keeps doing it even after i've seen and did what the others too had (i mean the same problem) but it just won't work
every thing hasn't worked i don't know what to do
i've also tried to put the intent thing but it says that the const client = new Discord.Client(); needs to be changed or idk what to do anymore any help would be really great for me.
my main script is this:
require('dotenv').config();
const Discord = require('discord.js');
const fs = require('fs');
if(!fs.existsSync('./data/servers.json')) {
console.log('servers.json does not exist');
console.log('Creating servers.json...');
fs.writeFileSync('./data/servers.json', '{}', err => {
console.error(err);
});
console.log('Success!');
}
if(!fs.existsSync('./data/config.json')) {
console.log('config.json does not exist');
console.log('Creating config.json...');
fs.writeFileSync('./data/config.json', '{"defaultPrefix": "!"}', err => {
console.error(err);
});
console.log('Success!');
}
if(!process.env.DISCORD_TOKEN) {
console.log('The DISCORD_TOKEN environment variable is not defined');
if(!fs.existsSync('./.env')) {
console.log('.env does not exist');
console.log('Creating .env...');
fs.writeFileSync('./.env', 'DISCORD_TOKEN=', err => {
console.error(err);
});
console.log('Success!');
}
console.log('Please, set the DISCORD_TOKEN environment variable or add it in .env');
}
const servers = require('../exports/exports.js');
const defaultPrefix = require('../data/config.json').defaultPrefix;
const client = new Discord.Client();
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.once('ready', () => {
client.user.setStatus('online');
client.user.setActivity(defaultPrefix + 'help', { type: 'LISTENING' });
console.log('Ready!');
});
client.on('message', message => {
if (message.author.bot) return;
let prefix = servers.getPrefix(message.guild.id);
if(message.content.toLowerCase().startsWith(prefix)) {
const args = message.content.toLowerCase().slice(prefix.length).split(' ');
if(!client.commands.has(args[0])) return;
try {
client.commands.get(args[0]).execute(message, args.slice(1, args.length), prefix);
}
catch(err) {
console.error(err);
message.reply('Something went wrong while executing that command');
}
}
else if(message.content.toLowerCase().startsWith(defaultPrefix + 'help')) {
const args = message.content.toLowerCase().slice(prefix.length).split(' ');
try {
client.commands.get('help').execute(message, args.slice(1, args.length), prefix);
}
catch(err) {
message.reply('Something went wrong while executing that command');
}
}
});
async function close() {
console.log('Received terminate signal');
console.log('Closing');
process.exit();
}
process.on('SIGINT', close);
process.on('SIGTERM', close);
client.login(process.env.DISCORD_TOKEN);
Really easy solution is:
const client = new Client({
intents: 32767
});
But you also need to have all intents enabled in your bot settings at https://discord.com/developers
Discord added these slash commands in v13, I have followed the discordjs.guide website on how to do it.
My code is:
//packages
const { Client, Collection, Intents } = require("discord.js");
const client = new Client({ intents: [Intents.FLAGS.GUILDS] });
const disbut = require("discord-buttons");
client.commands = new Collection();
const moment = require("moment");
const { MessageEmbed } = require("discord.js");
const AntiSpam = require("discord-anti-spam");
const ms = require("ms");
const { Slash } = require("discord-slash-commands");
const slash = new Slash(client);
const rtkn = ">r";
const { REST } = require("#discordjs/rest");
const { Routes } = require("discord-api-types/v9");
const { token, owner, bowner, clientid, guildid, prefix } = require("./config.json");
const fs = require("fs");
const commandFiles = fs.readdirSync("./commands").filter((file) => file.endsWith(".js"));
const commands = [];
const cmds = [];
disbut(client);
for (const file of commandFiles) {
const command = require(`./commands/${file}`);
commands.push(command.data.toJSON());
}
const commands = [];
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);
await interaction.reply({ content: "There was an error while executing this command!", ephemeral: true });
}
});
const rest = new REST({ version: "9" }).setToken(token);
(async () => {
try {
console.log("Started refreshing application (/) commands.");
await rest.put(Routes.applicationGuildCommands(clientId, guildId), { body: commands });
console.log("Successfully reloaded application (/) commands.");
} catch (error) {
console.error(error);
}
})();
const clean = (text) => {
if (typeof text === "string") return text.replace(/`/g, "`" + String.fromCharCode(8203)).replace(/#/g, "#" + String.fromCharCode(8203));
else return text;
};
client.on("message", (message) => {
const args = message.content.split(" ").slice(1);
if (message.content.startsWith(prefix + "eval")) {
if (message.author.id !== owner) return;
try {
const code = args.join(" ");
let evaled = eval(code);
if (typeof evaled !== "string") evaled = require("util").inspect(evaled);
message.channel.send(clean(evaled), { code: "xl" });
} catch (err) {
message.channel.send(`\`ERROR\` \`\`\`xl\n${clean(err)}\n\`\`\``);
}
}
});
client.on("message", (message) => {
const args = message.content.split(" ").slice(1);
if (message.content.startsWith(prefix + "eval")) {
if (message.author.id !== bowner) return;
try {
const code = args.join(" ");
let evaled = eval(code);
if (typeof evaled !== "string") evaled = require("util").inspect(evaled);
message.channel.send(clean(evaled), { code: "xl" });
} catch (err) {
message.channel.send(`\`ERROR\` \`\`\`xl\n${clean(err)}\n\`\`\``);
}
}
});
client.on("warn", (err) => console.warn("[WARNING]", err));
client.on("error", (err) => console.error("[ERROR]", err));
client.on("disconnect", () => {
console.warn("Disconnected!");
process.exit(0);
});
process.on("unhandledRejection", (reason, promise) => {
console.log("[FATAL] Possibly Unhandled Rejection at: Promise ", promise, " reason: ", reason.message);
});
client.login(token);
//ping.js contents below.
const { SlashCommandBuilder } = require("#discordjs/builders");
module.exports = {
data: new SlashCommandBuilder().setName("ping").setDescription("Replies with Pong!"),
async execute(interaction) {
await interaction.reply("Pong!");
},
};
My ping.js file is:
const { SlashCommandBuilder } = require("#discordjs/builders");
module.exports = {
data: new SlashCommandBuilder().setName("ping").setDescription("Replies with Pong!"),
async execute(interaction) {
return interaction.reply("Pong!");
},
};
When I run the code, it registers the slash commands fine, but when I run it, it says "interaction failed." Please help.
Your code is not well structured. You have a lot of deprecated modules and you declared commands twice. The problem however, is that you never call client.commands.set. In your for...of loop, you called commands.push instead of client.commands.set.
I don’t know how the SlashCommandBuilder function works, but I suspect the toJSON method would return something that looks like this:
{
name: 'commandName',
description: 'description',
options: []
}
You have to change your loop to look like this:
for (const file of commandFiles) {
const command = require(`./commands/${file}`);
const data = command.data.toJSON()
client.commands.set(data.name, data);
}
So when i warn a user it works perfectly, but when i try to warn again a person it replace the old string (the reason) but i want to make it add and keep the old string. (the reason) i tryed many things but still, fs is replacing automaticaly the old string (the reason).
And there is my javascript code :
const Discord = require("discord.js")
const fs = require("fs");
module.exports = {
name: "warn",
description: "Warn command",
async execute( message){
let config = require("../config.json")
let lang = JSON.parse(fs.readFileSync("./langs.json", "utf8"));
if(!lang[message.guild.id]){
lang[message.guild.id] = {
lang: config.lang
};
}
let correct1 = lang[message.guild.id].lang;
const ping = require(`../lang/${correct1}/warn.json`)
const response = ping
const messageArray = message.content.split(' ');
const args = messageArray.slice(1);
let sEmbed1 = new Discord.MessageEmbed()
.setColor("#FF0000")
.setTitle("Permission refused.")
.setDescription("<:dont:803357503412502588> | You don't have the permission for this command. (`MANAGE_ROLES`)");
if(!message.member.hasPermission("MANAGE_ROLES")) return message.reply(sEmbed1)
const user = message.mentions.users.first()
if(!user) {
return message.channel.send("<:dont:803357503412502588> | You need to mention a user.")
}
if(message.mentions.users.first().bot) {
return message.channel.send("<:dont:803357503412502588> | You can't warn a bot")
}
if(message.author.id === user.id) {
return message.channel.send("<:dont:803357503412502588> | You can't warn yourself!")
}
const reason = args.slice(1).join(" ")
if(!reason) {
return message.channel.send("<:dont:803357503412502588> | You need a reason")
}
const warnings = {
reason: `${reason}`,
guild_id: `${message.guild.id}`,
user_id: `${user.id}`,
moderator: `${message.author.username}`
}
const jsonString = JSON.stringify(warnings)
fs.writeFile('./warnings.json', jsonString, err => {
if (err) {
console.log('Error writing file', err)
} else {
console.log('Successfully wrote file')
}
})
}
}
const jsonString = JSON.stringify(warnings)
fs.writeFile('./warnings.json', jsonString, err => {
if (err) {
console.log('Error writing file', err)
} else {
console.log('Successfully wrote file')
}
})
Could you replace line 2 with fs.writeFileSync("./warnings.json", jsonString, {'flags': 'a'}, err => {
I want to know how to read/write from/to json files.
const Discord = require ('discord.js');
const client = new Discord.Client();
const {prefix, token,} = require('./config.json');
const fs = require ('fs');
client.login(token)
client.on('message', message => {
if(message.content.startsWith(prefix + "TC")) { //TC = team create
var args = message.content.split(' ').join(' ').slice(4);
if(!args) return message.channel.send("No")
var TeamCreate = `{"NameTeam": "${args}", "ManagerTeam": ${message.author.id}}`
fs.writeFile("./team.json", TeamCreate, (x) => {
if (x) console.error(x)
})}});
The json file will display :
{"NameTeam": "teste","ManagerTeam": 481117441955463169}
And I would like that each time we place the order, it gets added to the json file.
Example:
1 first order = {"NameTeam": "teste","ManagerTeam": 481117441955463169}
2 second order = {"NameTeam": "teste","ManagerTeam": 481117441955463169}, {"NameTeam": "teste2","ManagerTeam": 1234567890}
From what I understand, you want to make a json file that contains a list of teams.
The easy way to do that is to read and parse the json, make changes to it, and then stringify the jsonand update the file. Also, making json with strings is really messy and can lead to syntax errors, while in javascript turning js objects into json is as simple as doing JSON.stringify(javascriptObject)
Try something like this:
const Discord = require('discord.js');
const client = new Discord.Client();
const { prefix, token, } = require('./config.json');
const fs = require('fs');
client.login(token)
client.on('message', message => {
if (message.content.startsWith(prefix + "TC")) { //TC = team create
var args = message.content.split(' ').join(' ').slice(4);
if (!args) return message.channel.send("No")
var team = {
NameTeam: args,
ManagerTeam: message.author.id
}
fs.readFile("./team.json", (err, data) => {
if (!err && data) {
var parsedJson;
try {
parsedJson = JSON.parse(data);
//Make sure the parsedJson is an array
if (!(parsedJson instanceof Array)) {
parsedJson = [];
}
}
catch (e) {
console.log("Couldn't parse json.");
parsedJson = [];
}
finally {
//Add the newly created team to parsedJson
parsedJson.push(team);
//Write file, stringifying the json.
fs.writeFile("./team.json", JSON.stringify(parsedJson), (err) => {
if (!err) {
console.log("Successfully created team.");
}
else {
console.log("Error writing to file.")
}
});
}
}
else {
console.log("Error reading json");
}
});
}
});
Hope this helps and good luck.
The code below doesn't give any errors but I have a weird bug anyway. I have four streams to aggregate twitter feeds to a discord channel. 3 of those often work. but whenever I run the code there is always a feed not coming through, no line is getting executed in that stream. This often happens with the IntelFeed and/or covid-19feed. When I wait for some time or repeatedly rerun the code it starts working. I think it may be due to the structure of the code (not having enough time to fulfill the conditions) or due to the API. But I can't confirm the latter one.
const Discord = require('discord.js');
const botconfig = require("./botconfig.json");
const { Client, RichEmbed } = require('discord.js');
const twitterFeedsModel = require('./models/twitterFeedsModel');
const client = new Discord.Client();
const mongoose = require('mongoose', {useNewUrlParser: true}, { useUnifiedTopology: true });
mongoose.connect('mongodb://localhost/twitterFeedDatabeses');
const Twit = require('twit');
const T = new Twit({
consumer_key: botconfig.consumer_key,
consumer_secret: botconfig.consumer_key_secret,
access_token: botconfig.access_token,
access_token_secret: botconfig.access_token_secret,
});
client.on("ready", () => {
console.log(`Logged in as ${client.user.tag}!`);
//Newsfeed
const stream = T.stream("statuses/filter", { follow: ["5402612", "1652541", "831470472", "26792275", "380648579", "426802833", "144274618", "31696962", "1642135962", "16561457"]});
const scr_name = ['BBCbreaking', 'Reuters', 'pewglobal', 'ForeignPolicy', 'AFP', 'AP_Politics', 'economics', 'dw_europe', 'BBCNewsAsia', 'RadioFreeAsia']
stream.on("tweet", function (tweet) {
if(!scr_name.includes(tweet.user.screen_name)) return;
client.channels.get("646745474514026506").send(`https://twitter.com/${tweet.user.screen_name}/status/${tweet.id_str}`);
});
//Covid-19stream
const secondStream = T.stream("statuses/filter", {follow: "2985479932"});
const secondScr_name = "BNODesk"
secondStream.on("tweet", function (tweet){
console.log(tweet.user.screen_name)
if(secondScr_name.includes(tweet.user.screen_name)) {
const tweetContent = tweet.text.split(" ");
console.log(tweetContent)
const filteredWords = ['thank', 'Thank', 'you', 'you.', 'you!']
console.log("It does include Breakin: " + tweetContent.includes("BREAKING:"))
if(!filteredWords.some(word => tweet.text.includes(word))){
if(tweetContent.includes("BREAKING:")){
console.log("It does include breaking (after if-statement): " + tweetContent.includes("BREAKING:"))
client.channels.get("645733080061181965").send(`https://twitter.com/${tweet.user.screen_name}/status/${tweet.id_str}`)
client.channels.get('645733080061181965').send('I found out this tweet covers important news')
} else if(!tweet.text.startsWith("#")){
client.channels.get("645733080061181965").send(`https://twitter.com/${tweet.user.screen_name}/status/${tweet.id_str}`)
client.channels.get("645733080061181965").send(`Hello <#283206528004259850>, there is a new tweet!`)
}
}
}
});
//GRUNNstream
const thirdStream = T.stream("statuses/filter", { follow: ["14907733", "22465767", "18549902", "451432440", "97639259", "2343981858"]});
const thirdScr_name = ['rtvnoord', 'oogtv', 'dvhn_nl', 'P2000Groningen', 'polgroningen', 'Sikkom050']
thirdStream.on("tweet", function (tweet) {
if(thirdScr_name.includes(tweet.user.screen_name)) {
client.channels.get("632705489108729867").send(`https://twitter.com/${tweet.user.screen_name}/status/${tweet.id_str}`);
}
});
// intelstream
const fourthStream = T.stream("statuses/filter", {follow: ['3331851939', '2407993940', '1140336427550552000', '2790057867', '2315512764', '1517300821', '70529694', '62248461', '146958450', '85904241', '762565517026664400']});
const fourthScr_name = ['IntelCrab', 'IntelDoge', 'IntelAgencyNGO', 'lummideast', 'bellingcat', 'obretix', 'JanesINTEL', 'BarzanSadiq', 'ragipsoyly', 'leventkemal', 'OmerOzkizilcik']
fourthStream.on("tweet", function (tweet) {
if(fourthScr_name.includes(tweet.user.screen_name)) {
client.channels.get("646745512011235339").send(`https://twitter.com/${tweet.user.screen_name}/status/${tweet.id_str}`);
}
});
});
module.exports.run = client.on('message', message => {
if (!message.content.startsWith(botconfig.prefix) || message.author.bot) return;
const args = message.content.slice(botconfig.prefix.length).split(/ +/);
const command = args.shift().toLowerCase();
if (command.length === 0) {
return message.channel.send(`I ain't gonna fill the command in by myself fam`);
}
if (command === 'add_twitter_feed'){
if (!args.length){
return message.channel.send("Please enter a valid value!")};
var twitterUsername_feed = args;
T.get('users/show', { screen_name: twitterUsername_feed.join() }, function (err, data, response) {
console.log(data.id)
const twitterFeedVar = new twitterFeedsModel({
_id: mongoose.Types.ObjectId(),
twitterUsernameAddedToFeed: twitterUsername_feed.join(),
twitterUsername_idAddedToFeed: data.id,
})
twitterFeedVar.save()
.then(result => console.log(result))
.catch(err => console.log(err))
twitterFeedVar.find()
.then(doc => {
message.channel.send(doc)
})
})
}
/*if (command === `savelist`) {
Test.find()
.then(doc => {
message.channel.send(doc)
})
}
*/
if (command === 'twitter_user_id'){
if (!args.length){
return message.channel.send("Please enter a valid value!")};
var twitterUsername_lookup = args;
console.log(`${message.member.user.tag} requested the ID of the following user: ` + twitterUsername_lookup.join())
T.get('users/show', { screen_name: twitterUsername_lookup.join() }, function (err, data, response) {
console.log(data)
message.channel.send(`This is the ID of ` + twitterUsername_lookup.join() + `: ` + data.id)
if (!data.id) {
return message.channel.send(`Twitter user not found.`)
}
})
message.delete()
}
if (command === `hello`){
return message.channel.send("Hi there :)")
}
if (command === `feedlist`){
var scr_name2 = ['BBCbreaking', 'Reuters', 'pewglobal', 'ForeignPolicy', 'AFP', 'AP_Politics', 'economics', 'dw_europe', 'BBCNewsAsia', 'RadioFreeAsia']
return message.channel.send(scr_name2)
}
if (command === `reload`) {
message.channel.send(`Reloading...`)
console.clear();
client.destroy()
client.login(botconfig.token);
message.channel.send(`Bot reloaded succesfully!`);
return;
}
});
module.exports.help = {
name: "testtest"
}
client.login(botconfig.token);