How would I loop through a json file? - javascript

I'm making a verification system where people link their accounts on two different platforms. I've got the code working, but now I need to check if the code is valid. I'm using .forEach on the json file, yet I keep getting the error:
client.verificationCodes.forEach is not a function
and it crashes.
Here is what the json file looks like:
my json file
Here is my code:
const Discord = require('discord.js')
const rbx = require('noblox.js')
const fs = require("fs")
const express = require("express")
const app = express()
app.use(express.json())
const client = new Discord.Client()
client.verificationCodes = require("./codes.json")
require("dotenv").config()
const port = process.env.PORT
const serverKey = process.env.SERVER_KEY
const cookie = process.env.COOKIE
function randomString(length, chars) {
var result = '';
for (var i = length; i > 0; --i) result += chars[Math.floor(Math.random() * chars.length)];
return result;
}
client.on("ready", () => {
console.log("Client is ready.")
})
app.post("/getVerificationCode", function(req,res,next) {
console.log("Recieved")
if (req.body.serverKey !== serverKey) {
console.log("Invalid serverKey supplied.")
return res.status(403).json({
error: "You do not have permission to use this."
})
}
let verificationCode = randomString(4,'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ').toUpperCase()
const userID = parseInt(req.body.userid)
console.log(verificationCode)
client.verificationCodes[userID] = {
code: verificationCode
}
fs.writeFile("./codes.json", JSON.stringify(client.verificationCodes,null,4), err => {
if (err) throw err
})
return res.status(200).json({
VerificationCode: verificationCode
})
})
app.get("/*", function(req,res,next) {
return res.status(200).json({})
})
client.on("message", (message) => {
if (message.content.toLowerCase().startsWith("!verify")) {
let args = message.content.split(" ")
if (!args[1]) {
message.reply("You must specify a code.")
return
}
client.verificationCodes.forEach(vCode => {
if (vCode.Code === args[1]) {
let username = rbx.getUsernameFromId(vCode)
message.member.setNickname(username)
}
})
}
})
app.listen(port)
console.log(`App listening on port ${port}`)
function rbxLogin(newCookie) {
try {
rbx.setCookie(newCookie)
} catch(err) {
console.log(`Invalid cookie supplied, or expired. ${err}`)
}
}
// rbxLogin(cookie)
client.login(process.env.BOT_TOKEN)
I appreciate help!

You had a syntax error because .forEach doesn't work on objects but on array and since that client.verificationCodes is an object then you need to use Object.entries to convert that to array of key, value.
I've refactored the block causing this error please use this:
Object.entries(client.verificationCodes).forEach(([key, vCode]) => {
if (vCode.Code === args[1]) {
let username = rbx.getUsernameFromId(vCode)
message.member.setNickname(username)
}
})
which will make your whole code like this:
const Discord = require('discord.js')
const rbx = require('noblox.js')
const fs = require("fs")
const express = require("express")
const app = express()
app.use(express.json())
const client = new Discord.Client()
client.verificationCodes = require("./codes.json")
require("dotenv").config()
const port = process.env.PORT
const serverKey = process.env.SERVER_KEY
const cookie = process.env.COOKIE
function randomString(length, chars) {
var result = '';
for (var i = length; i > 0; --i) result += chars[Math.floor(Math.random() * chars.length)];
return result;
}
client.on("ready", () => {
console.log("Client is ready.")
})
app.post("/getVerificationCode", function(req,res,next) {
console.log("Recieved")
if (req.body.serverKey !== serverKey) {
console.log("Invalid serverKey supplied.")
return res.status(403).json({
error: "You do not have permission to use this."
})
}
let verificationCode = randomString(4,'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ').toUpperCase()
const userID = parseInt(req.body.userid)
console.log(verificationCode)
client.verificationCodes[userID] = {
code: verificationCode
}
fs.writeFile("./codes.json", JSON.stringify(client.verificationCodes,null,4), err => {
if (err) throw err
})
return res.status(200).json({
VerificationCode: verificationCode
})
})
app.get("/*", function(req,res,next) {
return res.status(200).json({})
})
client.on("message", (message) => {
if (message.content.toLowerCase().startsWith("!verify")) {
let args = message.content.split(" ")
if (!args[1]) {
message.reply("You must specify a code.")
return
}
Object.entries(client.verificationCodes).forEach(([key, vCode]) => {
if (vCode.Code === args[1]) {
let username = rbx.getUsernameFromId(vCode)
message.member.setNickname(username)
}
})
}
})
app.listen(port)
console.log(`App listening on port ${port}`)
function rbxLogin(newCookie) {
try {
rbx.setCookie(newCookie)
} catch(err) {
console.log(`Invalid cookie supplied, or expired. ${err}`)
}
}
// rbxLogin(cookie)
client.login(process.env.BOT_TOKEN)

Related

discord.js 12.5.3 can't send message, but status online

Index.js
const Discord = require("discord.js");
const client = new Discord.Client({ disableMentions: 'everyone' });
require('dotenv').config();
const Eco = require("quick.eco");
client.eco = new Eco.Manager();
client.db = Eco.db;
client.config = require("./config");
client.commands = new Discord.Collection();
client.aliases = new Discord.Collection();
const fs = require("fs");
fs.readdir("./events/", (err, files) => {
if (err) return console.error(err);
files.forEach(f => {
if (!f.endsWith(".js")) return;
const event = require(`./events/${f}`);
let eventName = f.split(".")[0];
client.on(eventName, event.bind(null, client));
});
});
fs.readdir("./commands/", (err, files) => {
if (err) return console.error(err);
files.forEach(f => {
if (!f.endsWith(".js")) return;
let command = require(`./commands/${f}`);
client.commands.set(command.help.name, command);
command.help.aliases.forEach(alias => {
client.aliases.set(alias, command.help.name);
});
});
});
client.login(process.env.TOKEN);
Message.js
const { MessageEmbed } = require('discord.js');
const fs = require('fs');
let visitor = require('../database/visitor.json');
let level = require('../database/level.json');
let place = require('../database/place.json');
let money = require('../database/money.json');
module.exports = async (client, message) => {
if (message.content === "market") {
message.reply(`yup, what?`);
}
if(!visitor[message.author.id]){
visitor[message.author.id] = {
totalvis: 0,
totalbuyer: 0
};
}
if(!level[message.author.id]){
level[message.author.id] = {
level: 1,
exp: 0
};
}
if(!place[message.author.id]){
place[message.author.id] = {
pla: "Hongria"
};
}
if(!money[message.author.id]){
money[message.author.id] = {
balance: 20
};
}
if(level[message.author.id].exp > 300) {
let amount = Math.floor(Math.random() * 60) + 20;
money[message.author.id].balance = money[message.author.id].balance + amount;
level[message.author.id].level++;
level[message.author.id].exp = 0;
let embed = new MessageEmbed()
.setTitle(`${message.author.username} Level Up`)
.addField(`Rewards`, `+ ${amount} Money`)
.setColor("#E5E5E5")
.setTimestamp()
message.channel.send(embed);
}
fs.writeFile('./database/visitor.json', JSON.stringify(visitor, null, 2), (err) => {
if (err) console.log(err);
});
fs.writeFile('./database/level.json', JSON.stringify(level, null, 2), (err) => {
if (err) console.log(err);
});
fs.writeFile('./database/place.json', JSON.stringify(place, null, 2), (err) => {
if (err) console.log(err);
});
fs.writeFile('./database/money.json', JSON.stringify(money, null, 2), (err) => {
if (err) console.log(err);
});
if (!message.guild || message.author.bot) return;
if (message.channel.id === client.config.countChannel) require("../counter")(message, client);
client.prefix = client.db.fetch(`prefix_${message.guild.id}`) ? client.db.fetch(`prefix_${message.guild.id}`) : client.config.prefix;
if (!message.content.startsWith(client.prefix)) return;
let args = message.content.slice(client.prefix.length).trim().split(" ");
let commandName = args.shift().toLowerCase();
let command = client.commands.get(commandName) || client.commands.get(client.aliases.get(commandName));
if (!command) return;
client.ecoAddUser = message.author.id;
command.execute(client, message, args);
};
Command.js
const { MessageEmbed } = require("discord.js");
const fs = require('fs');
exports.execute = async (client, message, args) => {
if (!client.config.admins.includes(message.author.id)) return;
message.channel.send("**Rebooting system..**").then(m => {
setTimeout(() => {
m.edit("**Wait a sec...**").then(ms => {
setTimeout(() => {
ms.edit("**Done.**")
}, 3000)
})
}, 3000);
})
.then(message => process.exit())
.then(() => client.login(process.env.TOKEN))
}
exports.help = {
name: "reboot",
aliases: ["rb"],
usage: `reboot`
}
I use Discord.js version 12.5.3, my discord bot status is online, but if I try some command, my bot not send any message but in console, no errors. I used to be able to use this method, but now I want to try to make a discord bot again, and I use the same code without changing anything, but now my bot can't send any messages
I turn Privileged Gateway Intents in Discord Developer Portal, and it work!

Discord slash command "interaction failed" V13

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);
}

Startup TypeError: Cannot read property 'Collection' of undefined

So I've had multiple problems one after another. The first being;
TypeError [CLIENT_MISSING_INTENTS]: Valid intents must be provided for the Client
Which I solved by changing up my code from:
const Discord = require("discord.js");
const bot = new Discord.Client();
To:
const { Client, Intents, Discord } = require("discord.js");
const bot = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES] });
But now I am running into a seperate issue. Where I keep getting this error;
Startup TypeError: Cannot read property 'Collection' of undefined
This is really frustrated because I've been at this problem for a couple of hours. Any help would be massively appreciated!
All essential code:
const { Client, Intents } = require("discord.js");
const bot = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES] });
const { prefix, token, mongoPath } = require("./jsonFiles/config.json");
const mongoose = require("mongoose");
const mongo = require("./utility/mongo.js");
const fs = require("fs");
const Levels = require("discord-xp");
bot.login(token);
bot.commands = new Discord.Collection();
bot.cooldowns = new Discord.Collection();
const commandFolders = fs.readdirSync("./commands");
for (const folder of commandFolders) {
//Finds the name of the command
const commandFiles = fs
.readdirSync(`./commands/${folder}`)
.filter((file) => file.endsWith(".js"));
for (const file of commandFiles) {
const command = require(`./commands/${folder}/${file}`);
bot.commands.set(command.name, command);
}
}
bot.on("ready", async () => {
console.log("Connect as " + bot.user.tag);
//levels(bot);
await mongo().then(() => {
try {
console.log("Connected to mongo!");
} finally {
mongoose.connection.close();
}
});
bot.user.setActivity(".help", {
type: "WATCHING",
});
});
bot.on("message", async (message) => {
try {
await mongo().then(async (mongoose) => {
Levels.setURL(mongoPath);
if (!message.guild) return;
if (message.author.bot) return;
const randomAmountOfXp = Math.floor(Math.random() * 20) + 1; // Min 1, Max 30
const hasLeveledUp = await Levels.appendXp(
message.author.id,
message.guild.id,
randomAmountOfXp
);
if (hasLeveledUp) {
const user = await Levels.fetch(message.author.id, message.guild.id);
message.channel.send(
`${message.author}, congratulations! You have leveled up to **${user.level}** in \`${message.guild.name}\` :sunglasses:`
);
}
});
if (!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).trim().split(/ +/);
const commandName = args.shift().toLowerCase();
const command =
bot.commands.get(commandName) ||
bot.commands.find((cmd) => cmd.aliases && cmd.aliases.includes(commandName));
if (!command) return;
if (command.guildOnly && message.channel.type === "dm")
return message.reply("I can't execute that command inside DMs!");
if (command.permissions) {
const authorPerms = message.channel.permissionsFor(message.author);
if (!authorPerms || !authorPerms.has(command.permissions)) {
if (message.author.id !== "344834268742156298") {
return message.reply("YOU DO NOT HAVE PERMISSION (git gud scrub)");
}
}
}
if (command.creator === true && message.author.id !== "344834268742156298")
return message.reply("Wait what, you are not creator man, you cannot use the command!!!!!");
if (command.args === true && !args.length) {
let reply = `You didn't provide a valid arguments, ${message.author}!`;
if (command.usage) {
reply += `\nThe proper usage would be: \`${prefix}${command.name} ${command.usage}\``;
}
message.delete({
timeout: 25 * 1000,
});
return message.channel.send(reply).then((message) => {
message.delete({
timeout: 25 * 1000,
});
});
}
const { cooldowns } = bot;
if (!cooldowns.has(command.name)) {
cooldowns.set(command.name, new Discord.Collection());
}
const now = Date.now();
const timestamps = cooldowns.get(command.name);
const cooldownAmount = (command.cooldown ?? 1.5) * 1000;
if (timestamps.has(message.author.id)) {
const expirationTime = timestamps.get(message.author.id) + cooldownAmount;
if (now < expirationTime) {
const timeLeft = (expirationTime - now) / 1000;
return message.reply(
`please wait ${timeLeft.toFixed(1)} more second(s) before reusing the \`${
command.name
}\` command.`
);
}
}
timestamps.set(message.author.id, now);
setTimeout(() => timestamps.delete(message.author.id), cooldownAmount);
const maxArguments = command.maxArgs || null;
if (
args.length < command.minArgs ||
(maxArguments !== null && command.args === "true" && args.length > command.maxArgs)
) {
let reply = `\nThe proper usage would be: \`${prefix}${command.name} ${command.usage}\``;
return message.channel.send(reply);
}
try {
command.execute(message, args, message.guild);
} catch (err) {
console.log(err);
}
} catch (err) {
console.log(err);
}
});
At the top you never defined Discord properly. You are trying to access the non-existant Discord property of the discord.js module with object destructuring. There are 2 quick fixes for this, the first one will be faster however.
//at the top change the declaration of Client
const Discord = {
Client,
Intents
} = require('discord.js')
//Discord is module discord.js
Or you can do
const {
Collection,
Client,
Intents
} = require('discord.js')
//use new Collection() instead of new Discord.Collection()
Try instead of:
const { Client, Intents } = require("discord.js");
Try:
const Discord = require("discord.js"), { Client, Intents } = Discord;
Or you can also import Collection from discord:
const { Client, Intents, Collection } = require("discord.js");
and replace:
new Discord.Collection() with new Collection()

Discord.js A different js file for each command

Hello so I am learning javascript and can't figure out how to have multiple .js files for each command I have some code that I followed online however it does not seem to work for me (I am on discord.js v12.2)
const Discord = require('discord.js');
const client = new Discord.Client();
const fs = require('fs');
const { prefix, token } = require('./config.json');
client.commands = new Discord.Collection();
client.on('ready', () => {
console.log(`Logged in as ${client.user.tag}!`);
client.user.setActivity("Type ~help for commands")
});
fs.readdir('./cmds', (err,files) => {
if (err) {
console.log(err);
}
let cmdFiles = files.filter(f => f.split(".").pop() === "js");
if (cmdFiles.length === 0){
console.log("No files found");
return;
}
cmdFiles.forEach((f,i) => {
let props = require(`./cmds/${f}`);
console.log(`${i+1}: ${f} loaded`);
client.commands.set(props.help.name, props);
})
})
client.on('message',msg => {
if (msg.channel.type === "dm") return;
if (msg.author.bot) return;
if (msg.channel.type === "dm") return;
if (msg.author.bot) return;
let msg_array = msg.content.split(" ");
let args1 = msg.content.slice(prefix.length).trim().split(' ');
let args = msg_array.slice(1);
let cmd = args1.shift().toLowerCase();
let command = client.commands.get(cmd);
if (!msg.content.startsWith(prefix)) return;
if (client.commands.has(cmd)) {
command = client.commands.get(cmd);
if (cmd){
command.run(client,msg,args,args1);
}
}
});
client.login(token);
The error message I am getting with this code is
TypeError: Cannot read property 'name' of undefined
at C:\Users\rubyn\Desktop\AlexLearning\index.js:27:40
at Array.forEach (<anonymous>)
at C:\Users\rubyn\Desktop\AlexLearning\index.js:24:14
at FSReqCallback.oncomplete (fs.js:164:23)
Thank you for taking time to read this :)
You need to require all of your "cmds" first at the top. You can create an object with those "cmds" that you can later reference in the forEach. Have the key for each "cmd" in the object be the value of ${f};
UPDATE
const Discord = require('discord.js');
const client = new Discord.Client();
const fs = require('fs');
const { prefix, token } = require('./config.json');
// Require all your individual cmd files
const cmd1 = require(`./cmds/cmd1`);
const cmd2 = require(`./cmds/cmd2`);
const cmd3 = require(`./cmds/cmd3`);
const cmd4 = require(`./cmds/cmd4`);
// create an object to reference them later
const cmdObj = {
cmd1,
cmd2,
cmd3,
cmd4
};
client.commands = new Discord.Collection();
client.on('ready', () => {
console.log(`Logged in as ${client.user.tag}!`);
client.user.setActivity("Type ~help for commands")
});
fs.readdir('./cmds', (err,files) => {
if (err) {
console.log(err);
}
let cmdFiles = files.filter(f => f.split(".").pop() === "js");
if (cmdFiles.length === 0){
console.log("No files found");
return;
}
cmdFiles.forEach((f,i) => {
// Dynamically reference an object property
let props = cmdObj[f];
console.log(`${i+1}: ${f} loaded`);
client.commands.set(props.help.name, props);
})
})
client.on('message',msg => {
if (msg.channel.type === "dm") return;
if (msg.author.bot) return;
if (msg.channel.type === "dm") return;
if (msg.author.bot) return;
let msg_array = msg.content.split(" ");
let args1 = msg.content.slice(prefix.length).trim().split(' ');
let args = msg_array.slice(1);
let cmd = args1.shift().toLowerCase();
let command = client.commands.get(cmd);
if (!msg.content.startsWith(prefix)) return;
if (client.commands.has(cmd)) {
command = client.commands.get(cmd);
if (cmd){
command.run(client,msg,args,args1);
}
}
});
client.login(token);

Chunks of code being ignored. No errors, no logs. Might be API related

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);

Categories

Resources