Adding button functionality to my discord bot - discord

I want to make a button for my message embed. Can I do it this way? I looked at the documentation that showed making an async interaction function but just wanted to know if there was a way to make it like this.
embeds: [
new MessageEmbed()
.setColor("#0099ff")
.setTitle("Popo's Team Sorter")
.setDescription(`${message.author} has joined queue \nPlayers in queue currently:\n\n${playing_players}`),
],
components: [
new MessageActionRow().addComponents(
new MessageButton().setCustomId("primary").setLabel("Primary").setStyle("PRIMARY")
),
],
});

Related

Discordjs 14.7.1 Skips First Reaction

Problem is the Discord bot is skipping the first reaction emoji.
If I un-react and re-react with the same emoji, then the bot registers it.
I've been trying to figure this out for a while, and am stumped as to what I am missing in my logic or if I need to find another solution.
Intention:
Discord bot gathers and prints out all reactions to a message by a user
Relevant Information:
Discordjs 14.7.1
Discord Developer Website:
Presence Intent: Enabled
Server Members Intent: Enabled
Message Content Intent: Enabled
Code:
const { Client, Events, GatewayIntentBits, Partials } = require('discord.js');
const { token } = require('./includes/config.json');
// create a new discord client
const client = new Client({
intents: [
GatewayIntentBits.DirectMessageReactions,
GatewayIntentBits.DirectMessageTyping,
GatewayIntentBits.DirectMessages,
GatewayIntentBits.GuildMembers,
GatewayIntentBits.GuildMessageReactions,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.Guilds,
GatewayIntentBits.MessageContent,
],
partials: [
Partials.Channel,
Partials.GuildMember,
Partials.Message,
Partials.Reaction,
Partials.User,
]
});
// ready
client.once(Events.ClientReady, () => {
console.log('Ready!');
});
// if partial, fetch full
client.on(Events.MessageReactionAdd, async (reaction, user) => {
if (reaction.partial) {
try {
await reaction.fetch();
} catch (error) {
console.error(error);
return;
}
}
// define the message component
const message = reaction.message;
// all userReactions by user.id
const userReactions = await message.reactions.cache.filter(reaction => reaction.users.cache.has(user.id));
// print emojis
try {
for (const reaction of userReactions.values()) {
console.log(`Emoji: ${reaction.emoji}`);
}
} catch(error) {
console.error(error);
}
})
// login
client.login(token);
Problem:
The bot is not registering the first reaction placed
Example:
- I react to a message in this order: 😄❤️🔥
- the logfile shows:
Emoji: ❤️
Emoji: ❤️
Emoji: 🔥
Expected result:
Emoji: 😄
Emoji: 😄
Emoji: ❤️
Emoji: 😄
Emoji: ❤️
Emoji: 🔥
Observations:
I noticed that the bot works fine for all messages sent after it is running
The problematic behaviour is experienced only for messages sent before the bot was running
Conclusion:
MessageReactionAdd() does get called, as tested by placing 'console.log(test output); statements. I learned that it works on cached messages only, which I thought was mitigated by fetching the full reaction. Such was not the case. I tried testing by forcing a message fetch manually by channel.id and message.id, it still did not work.
My Solution:
Used an sqlite database to keep track of reactions.
From within MessageReactionAdd() I was able to check for the reactions I was interested in logging, and added them to an sqlite database.
Within an equivalent MessageReactionRemove() section, I was able to check for removal of the reactions and delete the pertinent row from the database.
Thank you for reading and assisting. :)

How can i fix this Discord.Js Client Intents initialization?

I want to send a private message to every Servermember.
If i use this intents its not working.
Also not working with Intents.ALL, Intents.Guild.ALL, ...
`const client = new Client({intents: [
Intents.all()
]});
client.guilds.cache.forEach(guild => {
guild.members.cache.forEach(member => {
member.send("hi").catch(console.error);
});
});`
Tried many different intents, yet not working.
Never use all intents, it significally slows down your bot and is a bad practise. You can read the guide on intents here and a list of intents here.
Here's an example from the guide:
const { Client, GatewayIntentBits } = require('discord.js');
const client = new Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.MessageContent,
GatewayIntentBits.GuildMembers,
],
});
In Discord.JS, all intents are PascalCase. Keep that in mind.

messageCreate event no longer firing after adding the interactionCreate event

To start: Yes I have intents setup. I have the "message content" intent enabled in the developer portal.
Recently I decided to setup slash commands for my bot. (That is all working fine, not the purpose of this question). Now however, I find that my "messageCreate" event is not firing at all. I've done some basic testing, including removing the "interactionCreate" event, and it still is non-functional. The only fix I've found is completely reverting to the previous version on my source control.
I haven't been able to find any solutions from the discord.js Discord so I decided to come here in the hopes someone can help. Thanks for your time! Client constructor and event code attached below.
Client:
const myIntents = new Intents(
Intents.FLAGS.GUILDS,
Intents.FLAGS.GUILD_MESSAGES,
Intents.FLAGS.DIRECT_MESSAGES,
Intents.FLAGS.GUILD_MESSAGE_REACTIONS,
Intents.FLAGS.DIRECT_MESSAGE_REACTIONS
);
const client = new Client({ intents: myIntents, partials: ["CHANNEL"] });
Events:
client.once('ready', () => {
// Works fine
});
client.on('interactionCreate', async interaction => {
// Works fine
});
client.on('messageCreate', async message => {
console.log('DEBUG') // Never triggers
// Other stuff
});
client.on("error", (e) => console.error(e));
client.on("warn", (e) => console.warn(e));
process.on('unhandledRejection', (e) => console.error(e));
console.log("client") // All events, including messageCreate, are visible in the resulting output
client.login(config.token);
I think you need the "MESSAGE" partial.
You can try and replace
const client = new Client({ intents: myIntents, partials: ["CHANNEL"] });
To
const client = new Client({ intents: myIntents, partials: ["CHANNEL", "MESSAGE"] });
Moreover, I had the same issue but I was very dumb because I didn't realize that my bot didn't have "READ MESSAGES" and "SEND MESSAGES" permissions in that channel, so that might be the issue.

guildMemberAdd event not working even with intents enabled. (discord.js)

I'm trying to set up a welcome message function on my discord bot, but no matter what I do, the bot doesn't seem to be able to use guildMemberAdd. I'm aware of the new update, and as suggested I've turned on both options under Private Giveaway Intents. But it still does not work. Here is my code:
client.on('guildMemberAdd', member => {
const emb = new MessageEmbed()
.setColor('#FFBCC9')
.setTitle("new member")
.setDescription("welcome to the server!")
member.guild.channels.get('780902470657376298').send(emb);
});
I have also found an answer online suggesting to use this:
const { Client, Intents } = require("discord.js");
const client = new Discord.Client({ ws: { intents: new Discord.Intents(Discord.Intents.ALL) }});
But no matter how I write that, my bot just won't even come online unless I use const client = new Discord.Client(); with nothing in the parentheses.
With v12 coming along, in order to get your full channels list you're only able to get the cached ones in your server. Hence why you should change this line:
member.guild.channels.get('780902470657376298').send(emb);
to:
member.guild.channels.cache.get('780902470657376298').send(emb);
You passed in the intents params wrong. Here is the correct way to do it.
const { Client, Intents } = require("discord.js");
const client = new Discord.Client({ ws: { intents: ['GUILDS', 'GUILD_MESSAGES', 'GUILD_MEMBERS', 'GUILD_PRESENCES'] } });
If you use this the guildMemberAdd event will emit.
Make sure you have intents turned on in the developer portal. As Shown in this image https://i.imgur.com/WfBLtXY.png.

Send DMed files and links to channel in server

Okay. This might be a strange question, but I need help as I could not find anything online. I have a discord bot and server that is hosts a competition, and users submit their submissions by Direct Messaging me a link or file of their submission. I would like to change this to them DMing the bot instead, and the bot posting the links and files in a certain channel in the server. I have absolutely no clue how to achieve this as I am kind of a novice when it comes to this sort of thing. Please comment if I need to change my wording or need to clarify anything!
Replace channel id with the actual id of the channel that you want to send the submissions to.
For Discord.js v12/v13 (the latest version):
client.on('message', ({attachments, author, content, guild}) => {
// only do this for DMs
if (!guild) {
// this will simply send all the attachments, if there are any, or the message content
// you might also want to check that the content is a link as well
const submission = attachments.size
? {files: [...attachments.values()], content: `${author}`}
: {content: `${content}\n${author}`}
client.channels.cache.get('channel id').send(submission)
}
})
For Discord.js v11 replace
client.channels.cache.get('channel id').send(submission)
with
client.channels.get('channel id').send(submission)
In the message event, you can check if the message is in a dm channel then you can take the message content and send it to a specific channel as an embed.
Your solution would be:
client.on('message', (message) => {
if (message.channel.type === 'dm') {
const channel = client.guilds.cache.get("GUILD_ID").channels.cache.get("CHANNEL_ID");
const embed = new Discord.MessageEmbed()
.setAuthor(message.author.tag, message.author.avatarURL())
.setColor('RANDOM')
.setDescription(message.content)
channel.send(embed);
if (message.attachments.array().length) {
message.attachments.forEach((attachment) => channel.send({ files: [ attachment ] }))
}
}
})

Resources