This is the code, I want it to write user's name and then auction word (p.s I am new to this)
const Discord = require('discord.js')
const client = new Discord.Client()
const { MessageEmbed } = require('discord.js');
const channel = client.channels.cache.get('889459156782833714');
client.on("ready", () => {
console.log(`Logged in as ${client.user.tag}!`)
})
client.on("message", msg => {
var message = new Discord.MessageEmbed()
.setColor('#FF0000')
.setTitle() // want user's name + "Auction"
.addField('Golden Poliwag', 'Very Pog', true)
.setImage('https://graphics.tppcrpg.net/xy/golden/060M.gif')
.setFooter('Poliwag Auction')
if (msg.content === "d.test") {
msg.reply(message)
}
})
You can access the user's username by using msg.author.tag. So. the way to use the user's tag in an embed would be:
const { MessageEmbed, Client } = require("discord.js");
const client = new Client();
const channel = client.channels.cache.get("889459156782833714");
client.on("ready", () => {
console.log(`Logged in as ${client.user.tag}!`);
});
client.on("message", (msg) => {
var message = new Discord.MessageEmbed()
.setColor("#FF0000")
.setTitle(`${msg.author.tag} Auction`)
.addField("Golden Poliwag", "Very Pog", true)
.setImage("https://graphics.tppcrpg.net/xy/golden/060M.gif")
.setFooter("Poliwag Auction");
if (msg.content === "d.test") {
msg.reply(message);
}
});
I suggest you to read the discord.js documentation, almost all you need to interact with Discord API is from there.
You can't control the bot if you don't login to it. Get the bot's token from Developer Portal and login to your bot by adding client.login('<Your token goes here>') in your project.
You can't get the channel if it's not cached in the client. You need to fetch it by using fetch() method from client's channels manager:
const channel = await client.channels.fetch('Channel ID goes here');
P/s: await is only available in async function
message event is deprecated if you are using discord.js v13. Please use messageCreate event instead.
You are able to access user who sent the message through msg object: msg.author. If you want their tag, you can get the tag property from user: msg.author.tag, or username: msg.author.username or even user ID: msg.author.id. For more information about discord message class read here.
The reply options for message is not a message. You are trying to reply the message of the author with another message which is wrong. Please replace the reply options with an object that includes embeds:
msg.reply({
embeds: [
// Your array of embeds goes here
]
});
From all of that, we now have the final code:
const { Client, MessageEmbed } = require('discord.js');
const client = new Client();
client.on("ready", () => {console.log(`Logged in as ${client.user.tag}!`)});
client.on("messageCreate", async (msg) => {
const channel = await client.channels.fetch('889459156782833714');
const embed = new Discord.MessageEmbed()
.setColor('#FF0000')
.setTitle(`${msg.author.tag} Auction`)
.addField('Golden Poliwag','Very Pog',true)
.setImage('https://graphics.tppcrpg.net/xy/golden/060M.gif')
.setFooter('Poliwag Auction');
if (msg.content === "d.test") {
msg.reply({
embeds: [ embed ],
});
}
});
client.login('Your bot token goes here');
Now your bot can reply to command user with an rich embed.
Related
i have multiple commands that work perfectly fine but i always get this message in return.
here is the code for that command. it works perfectly fine i guess it just doesn't respond to the interaction even though i feel like it should be?
how can i get it to ignore this message or reply properly?
const Discord = require('discord.js');
const { EmbedBuilder, SlashCommandBuilder } = require('discord.js');
module.exports = {
data: new SlashCommandBuilder()
// command name
.setName('totalfrozencheckouts')
// command description
.setDescription('Add up every message in the frozen checkouts channel after a specific message ID')
.addStringOption(option =>
option.setName('messageid')
.setDescription('The message ID')
.setRequired(true)),
async execute(interaction) {
const channel = '<#' + process.env.FROZENCHECKOUTS + '>';
const messageId = interaction.options.getString("messageid");
// Check if the channel mention is valid
if (!channel.startsWith('<#') || !channel.endsWith('>')) {
return interaction.channel.send(`Invalid channel mention. Please use the format: ${this.usage}`);
}
// Extract the channel ID from the channel mention
const channelId = channel.slice(2, -1);
// Try to fetch the messages from the requested channel and message ID
interaction.guild.channels.cache.get(channelId).messages.fetch({ after: messageId })
.then(messages => {
// Create an array of the message contents that are numbers
const numbers = messages.map(message => message.content).filter(content => !isNaN(content));
// Check if there are any messages
if (numbers.length === 0) {
return interaction.channel.send(`No messages were found in ${channel} after message ID https://discord.com/channels/1059607354678726666/1060019655663689770/${messageId}`);
}
// Adds up the messages
const sum = numbers.reduce((accumulator) => accumulator + 1, 1);
// Create an embed object
const embed = new EmbedBuilder()
.setColor(0x4bd8c1)
.setTitle(`Total Checkouts in #frozen-checkouts for today is:`)
.addFields(
{name: 'Total Checkouts', value: sum.toString() , inline: true},
)
.setThumbnail('https://i.imgur.com/7cmn8uY.png')
.setTimestamp()
.setFooter({ text: 'Frozen ACO', iconURL: 'https://i.imgur.com/7cmn8uY.png' });
// Send the embed object
interaction.channel.send({embeds: [embed]});
})
.catch(error => {
console.error(error);
interaction.channel.send('An error occurred while trying to fetch the messages. Please try again later.');
});
}
}
I don't really know what to try because it literally works I just don't know how to get it to either ignore that message or respond with nothing. It doesn't break the bot its just annoying to look at.
Use interaction.reply instead of interaction.channel.send to reply.
How can I have it so that the bot sends a message to a specific channel, while using .deferReply and .editReply? Currently, I'm getting an error saying that suggestionChannel.deferReply is not a function. Here's my code:
const { SlashCommandBuilder } = require("#discordjs/builders");
const { MessageEmbed } = require("discord.js");
module.exports = {
data: new SlashCommandBuilder()
.setName("suggest")
.setDescription("Send your suggestion to the specified channel")
.addStringOption((option) =>
option
.setName("suggestion")
.setDescription("Your suggestion")
.setRequired(true)
),
async execute(interaction, client) {
var suggestionChannelID = "900982140504793109";
var suggestionChannel = client.channels.cache.get(suggestionChannelID);
const embed = new MessageEmbed()
.setColor("#0099ff")
.setTitle(`New suggestion by ${interaction.member.displayName}`)
.setDescription(`${interaction.options.getString("suggestion")}`);
await suggestionChannel.deferReply();
await suggestionChannel
.editReply({
embeds: [embed],
})
.then(function (interaction) {
interaction.react(`👍`).then(interaction.react(`👎`));
});
},
};
How can I have it so that the bot sends a message to a specific
channel, while using .deferReply and .editReply?
Well, the short answer is; you can't. But you can do this:
As the error already says, deferReply() is not a method of the TextBasedChannels class, defined by your suggestionChannel.
Instead, try sending a message to the channel instead of replying. Replies can only be executed in the interaction's channel:
var suggestionChannelID = "900982140504793109";
var suggestionChannel = client.channels.cache.get(suggestionChannelID);
const embed = new MessageEmbed()
.setColor("#0099ff")
.setTitle(`New suggestion by ${interaction.member.displayName}`)
.setDescription(`${interaction.options.getString("suggestion")}`);
// use this instead
await suggestionChannel.send({
embeds: [embed],
});
P.S side note, deferReply() starts a 15-minute timer before the interaction expires and triggers that 'x is thinking...' text to appear when the client is calculating stuff, so try to call it as soon as possible. By default, interactions expire after 3 seconds, so if your bot fails to finish whatever it needs to accomplish within that timeframe, that interaction will fail.
I'm trying to code a discord bot that send a message to all users in a list. I am having problems using the client.users.fetch(); method on discord.js. The error message says something about DiscordAPIError: Unknown user, Unhandled promise rejection, and DiscordAPIError: Cannot send messages to this user, even though I am in the same guild as the bot.
Here is the code I have so far:
const Discord = require('discord.js');
const client = new Discord.Client();
const ownerId = 'YOUR-ID'
const users = ['YOUR-ID']
client.on('ready', () => {
console.log('Bot is online!');
});
client.on('message', async message => {
if (message.content.includes("test")) {
if (message.author.id == ownerId) {
message.channel.send("ok!")
var userID
var user
for (let i = 0; i < users.length; i++) {
userID = users[i];
user = client.users.fetch(userID.toString(), true);
client.user.send('works');
}
}
}
});
client.login('YOUR-TOKEN');
There are several issues in your code.
Firstly, client.users.fetch(...) is an asynchronous function therefore it requires an await.
Secondly, client.user.send(...) will actually send a message to the bot which is impossible. So you'll want to replace it with either message.channel.send(...) which will send the message in the same channel the message was received in or message.author.send(...) which will send a message to the author of the message.
Below is an example fix:
const Discord = require('discord.js'); // Define Discord
const client = new Discord.Client(); // Define client
const ownerId = 'your-discord-user-id';
const users = [] // Array of user ID's
client.on('ready', () => { // Ready event listener
console.log('Bot is online!'); // Log that the bot is online
});
client.on('message', async message => { // Message event listener
if (message.content.includes("test")) { // If the message includes "test"
if (message.author.id == ownerId) { // If the author of the message is the bot owner
message.channel.send("ok!"); // Send a message
// Define variables
let userID;
let user;
for (let i = 0; i < users.length; i++) { // Loop through the users array
userID = users[i]; // Get the user ID from the array
user = await client.users.fetch(userID.toString()); // Await for the user to be fetched
message.channel.send('works'); // Send a message to tell the message author the command worked
}
}
}
});
client.login('YOUR-TOKEN'); // Login your bot
I wanted to use the command "-ava #(user)" to display the avatar of the specified user. I created this code but I'm not sure why when I type the command in discord where the bot is, nothing is returned. This is the following code for my discord bot:
const BaseCommand = require('../../utils/structures/BaseCommand');
const Discord = require('discord.js');
module.exports = {
name: 'ava',
description: 'Provide user with certain avatar as requested.',
execute(message, args) {
if (args[0]) {
const user = message.mentions.users.first();
if (!user) return message.reply('Please mention a user to access their avatar');
const otherIconEmbed = new Discord.RichEmbed()
.setTitle(`${user.username}'s Avatar`)
.setImage(user.displayAvatarURL);
message.channel.send(otherIconEmbed).catch(err => console.log(err));
}
const myIconEmbed = new Discord.RichEmbed()
.setTitle(`${message.author.username}'s avatar!`)
.setImage(message.author.displayAvatarURL);
message.channel.send(myIconEmbed).catch(err => console.log(err));
}
}
Simply you have to put () after displayAvatarURL so it gives displayAvatarURL () and if you want to make it animated you must put displayAvatarURL ({dynamic: true}) 🙂
I'm trying to get a role without using messages, like:
const Discord = require('discord.js');
const Bot = new Discord.Client();
const Role = Discord.roles.find('name,'Exemple')
Role.delete()
Is this possible to do that?
Using that way of Collection#find("key", "value") in Discord.JS is deprecated by the way,
You should use Collection#find(Obj => Obj.key == "value") instead.
Yes you can but you will need to have the guild id you want to get the role from. Also, you should put that part in the ready event.
const discord = require("discord.js");
const client = new discord.Client();
client.on("ready", () => {
console.log("Bot online!");
const guild = client.guilds.get("The_server_id");
const role = guild.roles.find("name", "Your_role_name");
console.log(`Found the role ${role.name}`);
})
I tried with the posted solution but client.guilds.get was not recognized as a function:
UnhandledPromiseRejectionWarning: TypeError: client.guilds.get is not a function at Client.
Checking the content of client.guilds I found 'cache' object:
GuildManager {
cacheType: [Function: Collection],
cache: Collection [Map] {
'<discord server id>' => Guild {
members: [GuildMemberManager],
channels: [GuildChannelManager],
(...)
}
}
}
The solution was:
const Discord = require('discord.js');
const client = new Discord.Client();
client.once('ready', () => {
const myGuild = client.guilds.cache.get('<discord server id>');
const myRole = myGuild.roles.cache.find(role => role.name === '<role name>');
console.log(`Found the role ${myRole.name}`);
});
Guild doesn't work unless you have it set up on the server. People keep suggesting this but you have to already have infrastructure set up in your discord server.
const role = guild.roles.cache.get('role_id');
This seems to be working in the latest API version.
To get an specific role i use this code.
Replace SERVER_ID with your server id and ROLE_NAME with the name of the role
const guild = client.guilds.cache.get("SERVER_ID");
const role = guild.roles.cache.find((r) => r.name === "ROLE_NAME");
console.log(`Found the role ${role.name}`);
console.log(`Found the role ${role.id}`);