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);
}
Related
Im trying to create a discord bot, theres one command that returns the ping when /ping is typed, and another one im trying to add that restarts the bot when /restart is typed. But when I type /restart, it functions like I typed /ping and replied with the ping. I cannot find a solution to my problem so any help is appreciated. If you need more information on this please reply to me.
Here is a file called "handleCommands" with its code:
const { REST } = require('discord.js');
const { Routes } = require('discord-api-types/v9');
const fs = require('fs');
const pingCommand = require(`./src/commands/tools/ping.js`);
const restartCommand = require('../../commands/tools/restart.js');
module.exports = (client) => {
client.handleCommands = async () => {
const commandFolders = fs.readdirSync('./src/commands');
for (const folder of commandFolders) {
const commandFiles = fs
.readdirSync(`./src/commands/${folder}`)
.filter((file) => file.endsWith(".js"));
const { commands, commandArray } = client;
for (const file of commandFiles) {
const command = require(`../../commands/${folder}/${file}`);
if (command.data.name !== 'restart') {
commands.set(command.data.name, command);
commandArray.push(command.data.toJSON());
} else {
commands.set(restartCommand.data.name, restartCommand);
commandArray.push(restartCommand.data.toJSON());
}
}
}
const clientId = '(BotsClientIdWentHere)';
const guildId = '(ServersClientIdWentHere';
const rest = new REST({ version: '9' }).setToken(process.env.token);
try {
console.log('Started refreshing application (/) commands.');
await rest.put(
Routes.applicationGuildCommands(clientId, guildId), {
body: client.commandArray,
});
console.log('Successfully reloaded application (/) commands.')
} catch (error) {
console.error(error);
}
};
};
Here is code from restart.js:
const { SlashCommandBuilder } = require('discord.js');
module.exports = {
data: new SlashCommandBuilder()
.setName('restart')
.setDescription('Restarts the bot (Debug)'),
async execute(interaction, client) {
// Shut down the bot
await client.destroy();
// Log the bot back in to Discord
await client.login(MyBotsTokenWentHere);
// Send a message to confirm that the bot has been restarted
await interaction.editReply({
content: 'Bot restarted successfully'
});
}
}
A file called "interactionCreate":
module.exports = {
name: "interactionCreate",
async execute(interaction, client) {
console.log("Received interaction event:", interaction);
if (interaction.isChatInputCommand()) {
console.log("Received chat input command:", interaction.commandName);
const { commands } = client;
const { commandName } = interaction;
const command = commands.get(commandName);
if (!command) return;
try {
await command.execute(interaction, client);
} catch (error) {
console.error(error);
await interaction.reply({
content: `Something went wrong.. Please try again later. If this issue persists, please message my creator.`,
ephermeral: true,
});
}
}
},
};
And bot.js:
require("dotenv").config();
const { token } = process.env;
const { Client, Collection, GatewayIntentBits } = require("discord.js");
const fs = require("fs");
const client = new Client({ intents: GatewayIntentBits.Guilds });
client.commands = new Collection();
client.commandArray = [];
const functionFolders = fs.readdirSync(`./src/functions`);
for (const folder of functionFolders) {
const functionFiles = fs
.readdirSync (`./src/functions/${folder}`)
.filter((file) => file.endsWith('.js'));
for (const file of functionFiles)
require(`./functions/${folder}/${file}`)(client);
}
client.handleEvents();
client.handleCommands();
client.login(token);
Here is also the ping file code:
const { SlashCommandBuilder } = require('discord.js');
module.exports = {
data: new SlashCommandBuilder()
.setName('ping')
.setDescription('Returns the bots ping (Debug)'),
async execute(interaction, client) {
const message = await interaction.deferReply({
fetchReply: true
});
const currentTime = Date.now();
const responseTime = currentTime - interaction.createdTimestamp;
const responseTimeSeconds = responseTime / 1000; // convert to seconds
const newMessage = `API Latency: ${client.ws.ping}\nClient Ping: ${message.createdTimestamp - interaction.createdTimestamp}\nTime: ${responseTimeSeconds} seconds`
await interaction.editReply({
content: newMessage
});
}
}
And here I attacked a picture of the file heirarchy.
enter image description here
I tried to add functions that were supposed to add the function to table and add logs to the console to try to see what its printing but in the end the last error was "ReferenceError: (MyBotsTokenWentHere) is not defined". Any help appreciated.
Edit: Problem solved. Here is the updated restart.js and handleCommands files:
const { SlashCommandBuilder } = require('discord.js');
module.exports = {
data: new SlashCommandBuilder()
.setName('restart')
.setDescription('Restarts the bot (Debug)'),
async execute(interaction, client) {
// Send a reply to the command message
await interaction.deferReply({
content: 'Restarting the bot...'
});
// Shut down the bot
await client.destroy();
// Log the bot back in to Discord
await client.login(MyBotsTokenWentHere);
// Edit the reply to confirm that the bot has been restarted
await interaction.editReply({
content: 'Bot restarted successfully'
});
}
}
handleCommands:
const { REST } = require('discord.js');
const { Routes } = require('discord-api-types/v9');
const fs = require('fs');
const pingCommand = require(`../../commands/tools/ping.js`);
const restartCommand = require('../../commands/tools/restart.js');
module.exports = (client) => {
client.handleCommands = async () => {
const commandFolders = fs.readdirSync('./src/commands');
for (const folder of commandFolders) {
const commandFiles = fs
.readdirSync(`./src/commands/${folder}`)
.filter((file) => file.endsWith(".js"));
const { commands, commandArray } = client;
for (const file of commandFiles) {
const command = require(`../../commands/${folder}/${file}`);
//console.log(`loading ${command.data.name} from commands/${folder}/${file}`)
if (command.data.name !== 'restart') {
commands.set(command.data.name, command);
commandArray.push(command.data.toJSON());
} else {
commands.set(restartCommand.data.name, restartCommand);
commandArray.push(restartCommand.data.toJSON());
}
}
}
const clientId = '(ClientIdWentHere)';
const guildId = '(GuildIdWentHere)';
const rest = new REST({ version: '9' }).setToken(process.env.token);
try {
console.log('Started refreshing application (/) commands.');
await rest.put(
Routes.applicationGuildCommands(clientId, guildId), {
body: client.commandArray,
});
console.log('Successfully reloaded application (/) commands.')
} catch (error) {
console.error(error);
}
};
};
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!
I've been at this for 4h now... I'm making a discord bot that should take a user's input and define the word using an API call. I have an index.js that should call my urban.js file and define a word a user inputs. For example, if a user inputs "/urban cow," the bot should put the definition of a cow. However, right now it cannot read the option after "/urban" no matter what I try.
// THIS IS MY urban.js FILE
const {
SlashCommandBuilder,
SlashCommandStringOption
} = require('#discordjs/builders');
const {
request
} = require('undici');
const {
MessageEmbed
} = require('discord.js');
const wait = require('node:timers/promises').setTimeout;
const trim = (str, max) => (str.length > max ? `${str.slice(0, max - 3)}...` : str);
async function getJSONResponse(body) {
let fullBody = '';
for await (const data of body) {
fullBody += data.toString();
}
return JSON.parse(fullBody);
}
module.exports = {
data: new SlashCommandBuilder()
.setName('urban')
.setDescription('Replies with definition!')
.addStringOption(option =>
option.setName('input')
.setDescription('word to define')
.setRequired(true)),
async execute(interaction) {
const term = interaction.options.getString('input')
console.log(term);
const query = new URLSearchParams({
term
});
const dictResult = await request(`https://api.urbandictionary.com/v0/define?${query}`);
const {
list
} = await getJSONResponse(dictResult.body);
if (!list.length) {
return interaction.editReply(`No results found for **${term}**.`);
}
const [answer] = list;
const embed = new MessageEmbed()
.setColor('#EFFF00')
.setTitle(answer.word)
.setURL(answer.permalink)
.addFields({
name: 'Definition',
value: trim(answer.definition, 1024)
}, {
name: 'Example',
value: trim(answer.example, 1024)
}, {
name: 'Rating',
value: `${answer.thumbs_up} thumbs up. ${answer.thumbs_down} thumbs down.`,
}, );
interaction.editReply({
embeds: [embed]
});
},
};
// THIS IS THE INDEX JS FILE. It's not a filepath issue.
const {
token
} = require('./config.json');
const fs = require('node:fs');
const path = require('node:path');
const {
Client,
Collection,
Intents,
MessageEmbed,
DiscordAPIError
} = require('discord.js');
const wait = require('node:timers/promises').setTimeout;
const client = new Client({
intents: [Intents.FLAGS.GUILDS]
});
client.commands = new Collection();
const commandsPath = path.join(__dirname, 'commands');
const commandFiles = fs.readdirSync(commandsPath).filter(file => file.endsWith('.js'));
const eventsPath = path.join(__dirname, 'events');
const eventFiles = fs.readdirSync(eventsPath).filter(file => file.endsWith('.js'));
for (const file of eventFiles) {
const filePath = path.join(eventsPath, file);
const event = require(filePath);
if (event.once) {
client.once(event.name, (...args) => event.execute(...args));
} else {
client.on(event.name, (...args) => event.execute(...args));
}
}
for (const file of commandFiles) {
const filePath = path.join(commandsPath, file);
const command = require(filePath);
// Set a new item in the Collection
// With the key as the command name and the value as the exported module
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);
await interaction.deferReply({
ephemeral: true
});
await wait(4000);
if (!command) return;
try {
await command.execute(interaction);
} catch (error) {
console.error(error);
}
});
console.log(token)
client.login(token)
When I console.log(interaction.options.getString('input'))
it just gives me null.
when I console.log interaction it gives me a detailed account of the command and everything else like the user that sent it. But none of the information from the SlashCommand data. Please help.
Im new to Discod.js v13. I get this error
(async () => {
^
TypeError: (intermediate value) is not a function
This is the code i think its the problem
const rest = new REST({
version: "9"
}).setToken("MyToken")
(async () => {
If you need the full code:
const { Client, Intents, Collection } = require("discord.js")
const fs = require("fs")
const {REST} = require("#discordjs/rest");
const {Routes} = require("discord-api-types/v9");
const client = new Client({
intents:[
Intents.FLAGS.GUILDS,
Intents.FLAGS.GUILD_MESSAGES
]
})
const BotName = "TestBot"
const commandFiles = fs.readdirSync("./commands").filter(file => file.endsWith(".js"));
const commands = []
client.commands = new Collection()
for(const file of commandFiles){
const command = require("./commands/"+file)
commands.push(command.data.toJSON());
client.commands.set(command.data.name, command)
}
client.once("ready", applicationId =>{
console.log(`${BotName} is now online`)
const CLIENT_ID = client.user.id
const rest = new REST({
version: "9"
}).setToken("MyToken")
(async () => {
try{
if(process.env.ENV === "production"){
await rest.put(Routes.applicationCommands(CLIENT_ID), {
body: commands
})
console.log("Success command register globally")
}else{
await rest.put(Routes.applicationGuildCommands(CLIENT_ID, process.env.GUILD_ID), {
body: commands
})
console.log("Success command register locally")
}
}catch(err){
console.log(err)
}
})();
})
client.on("interaction", async interaction =>{
if(!interaction.isCommand()) return
const command = client.commands.get(interaction.commandName)
if(!command) return
try{
await command.execute(interaction);
}catch(err){
console.log(err)
await interaction.reply({
content: "ERROR" + err,
ephemeral:true
})
}
})
client.login("MyToken")
As said in my comment, this is a ASI (automatic semicolon insertion) related error. I checked it, and after putting a semicolon after }).setToken("MyToken"); it worked fine.
Always use semicolons to avoid these mistakes.
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);