So I've been trying to make a Discord Bot in Node.js, Im fetching data from an external api and using the BOT to display the data, problem is that when I call the function, its showing one by one instead of everything in one message.
I want to display everything in one message.
const token = 'my discord token is here';
const Discord = require('discord.js');
const axios = require('axios');
const client = new Discord.Client();
client.on('ready', () => {
console.log(`Logged in as ${client.user.tag}!`)
})
client.on('message', async msg => {
if (msg.content === '!inventario') {
let getInv = async () => {
let response = await axios.get('my api link where im getting the info is here')
let inventario = response.data
return inventario
}
let inventarioValue = await getInv ()
var inv = inventarioValue.total_inventory_count
msg.channel.send(`Total de Itens no inventário: ${inventarioValue.total_inventory_count} \nSkins:\n`);
for (var i=0;i<inv;i++)
{
var itens = inventarioValue.descriptions[i].market_name
msg.channel.send(itens);
}
}
});
client.login(token);
I want to execute this inventarioValue.descriptions[i].market_name, then after executing showing the full result instead of showing one by one.
Thanks
You can map object array element and add to message. For a better visual reflection, you can add them to embed.
const token = 'my discord token is here';
const Discord = require('discord.js');
const axios = require('axios');
const client = new Discord.Client();
client.on('ready', () => {
console.log(`Logged in as ${client.user.tag}!`)
})
client.on('message', async msg => {
if (msg.content === '!inventario') {
let getInv = async () => {
let response = await axios.get('my api link where im getting the info is here')
let inventario = response.data
return inventario
}
let inventarioValue = await getInv()
var inv = inventarioValue.total_inventory_count
let embed = new Discord.MessageEmbed()
embed.setDescription(`${inventarioValue.descriptions.map(val => val.market_name).join('\n')}`)
msg.channel.send(`Total de Itens no inventário: ${inventarioValue.total_inventory_count} \nSkins:\n`, embed);
}
});
client.login(token);
Related
I have recently spent a long time making a discord ticket bot, and all of a sudden now, it isnt turning on. There are no error messages when I turn the bot on, and the webview says the bot is online. I am hosting on repl.it
Sorry for the long code, but any genius who could work this out would be greatly appreciated. Thanks in advance.
const fs = require('fs');
const client = new Discord.Client();
const prefix = '-'
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);
}
require('./server.js')
client.on("ready", () => {
console.log('Bot ready!');
client.user.setActivity('-help', { type: "LISTENING"} ).catch(console.error)
})
client.on("message", async (message) => {
if (message.author.bot) return;
const filter = (m) => m.author.id === message.author.id;
if (message.content === "-ticket") {
let channel = message.author.dmChannel;
if (!channel) channel = await message.author.createDM();
let embed = new Discord.MessageEmbed();
embed.setTitle('Open a Ticket')
embed.setDescription('Thank you for reaching out to us. If you have a question, please state it below so I can connect you to a member of our support team. If you a reporting a user, please describe your report in detail below.')
embed.setColor('AQUA')
message.author.send(embed);
channel
.awaitMessages(filter, {max: 1, time: 1000 * 300, errors: ['time'] })
.then ( async (collected) => {
const msg = collected.first();
message.author.send(`
>>> ✅ Thank you for reaching out to us! I have created a case for your inquiry with out support team. Expect a reply soon!
❓ Your question: ${msg}
`);
let claimEmbed = new Discord.MessageEmbed();
claimEmbed.setTitle('New Ticket')
claimEmbed.setDescription(`
New ticket created by ${message.author.tag}: ${msg}
React with ✅ to claim!
`)
claimEmbed.setColor('AQUA')
claimEmbed.setTimestamp()
try {
let claimChannel = client.channels.cache.find(
(channel) => channel.name === 'general',
);
let claimMessage = await claimChannel.send(claimEmbed);
claimMessage.react('✅');
const handleReaction = (reaction, user) => {
if (user.id === '923956860682399806') {
return;
}
const name = `ticket-${user.tag}`
claimMessage.guild.channels
.create(name, {
type: 'text',
}).then(channel => {
console.log(channel)
})
claimMessage.delete();
}
client.on('messageReactionAdd', (reaction, user) => {
const channelID = '858428421683675169'
if (reaction.message.channel.id === channelID) {
handleReaction(reaction, user)
}
})
} catch (err) {
throw err;
}
})
.catch((err) => console.log(err));
}
})
client.login(process.env['TOKEN'])
Your problem could possibly be that you have not put any intents. Intents look like this:
const { Client } = require('discord.js');
const client = new Client({
intents: 46687,
});
You can always calculate your intents with this intents calculator: https://ziad87.net/intents/
Side note:
If you are using discord.js v14 you change client.on from message to messageCreate.
I've tried multiple ways to try to get it to send but it shows no error and doesn't send into channel.
const { MessageEmbed } = require('discord.js');
client.on("ready", async () => {
const embed = new MessageEmbed()
.setTitle(`Bot Status!`)
.setDescription(`${client.user.username} **Is Online!**`)
const channel = client.channels.cache.get('1006667208371490946')
channel.send({embeds: [embed]})
})
in the latest Discord.js version (V14) the correct way is
const { EmbedBuilder } = require('discord.js');
client.on("ready", async () => {
const embed = new EmbedBuilder()
.setTitle(`Bot Status!`)
.setDescription(`${client.user.username} **Is Online!**`);
const channel = client.channels.cache.get('1006667208371490946')
channel.send({embeds: [embed]})
});
If this is not solving your issue,
try to add a console.log(channel) just before channel.send({embeds: [embed]})
If the result is undefined, the problem is the bot can't get in your cache the channel you want. In that case you can fetch (Link to a post speaking about this)
In the other case the bot can't send a message in the channel, could be a permission issue but you can add a .then() / .catch() to see if error is showed or not.
Hope this can helps you
I think the problem is that you don't have the client to call.
const { MessageEmbed } = require('discord.js');
client.on("ready", async (/*client not found in here*/) => {
const embed = new MessageEmbed()
.setTitle(`Bot Status!`)
.setDescription(`${client.user.username} **Is Online!**`)
const channel = client.channels.cache.get('1006667208371490946')
channel.send({embeds: [embed]})
})
So try to add client
const { MessageEmbed } = require('discord.js');
client.on("ready", async(client) => {
const embed = new MessageEmbed()
.setTitle(`Bot Status!`)
.setDescription(`${client.user.username} **Is Online!**`)
const channel = client.channels.cache.get('1006667208371490946')
channel.send({embeds: [embed]})
})
i'm new to coding bots and i need help on how to add a command on messaging a certain person a customized message. this is what i have so far. what should i do?
const Discord = require('discord.js');
const config = require("./Data/config.json")
const client = new Discord.Client({ intents: ["GUILDS", "GUILD_MESSAGES"] })
client.once('ready', () => {
console.log('Ready!');
});
client.login('TOKEN');
client.on('message', async message => {
if (message.author.bot) return;
let prefix = '??'
if (!message.content.startsWith(prefix)) return;
let args = message.content.slice(prefix.length).trim().split("/ +/g");
let msg = message.content.toLowerCase();
let cmd = args.shift().toLowerCase();
if (msg.startsWith(prefix + 'ping')) {
message.channel.send('pong');
}
if (msg.startsWith(prefix + 'hello')) {
message.channel.send('hewwo uwu');
}
});
To fetch a user by id, you can use bot.users.fetch()
To direct message a user, you can use User.send():
const user = await client.users.fetch(userId);
user.send("This is a DM!");
This simple function will easily resolve the user (you can provide a user object or user ID so it’s very helpful)
async function DMUser(resolvable, content, client) {
const user = client.users.resolve(resolvable)
return user.send(content)
}
//returns: message sent, or error
//usage: DMUser(UserResolvable, "content", client)
Related links:
UserManager.resolve
User.send
UserResolvable
I currently have my bot sending an embed then reacting to it.
I was wondering how I would go on removing all reactions from this message.
Code:
const { Client, MessageEmbed} = require('discord.js');
const client = new Client();
let prefix = '~';
client.on('message', async message => {
if (message.content.toLowerCase() === prefix + 'help'
const embed = new MessageEmbed()
.setTitle('Help Cmd')
.setDescription('example')
let msg = await message.channel.send(embed);
await msg.react('▶');
await msg.react('◀');
setTimeout(() => {
//Removing all reactions from msg
}, 5000);
}
You can use msg.reactions.removeAll();.
const Discord = require ('discord.js');
const bot = new Discord.Client();
const token = 'TOKEN';
bot.on('ready', () =>{
console.log('Online');
if(msg.includes('hi')) {
message.delete();
message.author.send('hello')
}
})
bot.login(token);
You need to put your code into a .on() function. For example, to listen for messages:
const Discord = require ('discord.js');
const bot = new Discord.Client();
const token = 'TOKEN';
bot.on('ready', () =>{
console.log('Online');
})
bot.on('message', (message) => {
if(message.includes('hi')) {
message.delete();
message.author.send('hello')
}
})
bot.login(token);
Note you can't use msg and message, you must choose one variable name.