Discord js, Bot can only find itself until someone else send a message - discord.js

I was trying to get all the members of a role but i can only get the bot until someone else send a message then i can see them too
here is my code
const matches = require("../differents-matches")
module.exports = (client) => {
setInterval(async () => {
/*const allmatch = await matches.
where('_notified').exists(false).
where('_startDate').lt(Date.now()).
where('_endDate').gt(Date.now())
allmatch.forEach(element => {
})*/
console.log(client.guilds.cache.get('1050150840813498401').roles.cache.get('1050889003110506516').members.map(m => m.user.id))
//
}, 5000)
}
i tried the solution proposed in this post but the problem is still here
i have all the intents needed :
const client = new Client({ intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages, GatewayIntentBits.MessageContent, GatewayIntentBits.GuildMembers], fetchAllMembers: true });
and i did activate the server member intent in the bot options, i can't find any other thing to try. If you have an idea of what is the problem please leave a message.

It is expected, actually the fetchAllMembers client option disappeared with Discord.js v13.
You should now fetch the guild members manually:
const matches = require("../differents-matches")
module.exports = (client) => {
setInterval(async () => {
/*const allmatch = await matches.
where('_notified').exists(false).
where('_startDate').lt(Date.now()).
where('_endDate').gt(Date.now())
allmatch.forEach(element => {
})*/
const guild = client.guilds.cache.get('1050150840813498401');
await guild.members.fetch(); // do what fetchAllMembers previously did
console.log(guild.roles.cache.get('1050889003110506516').members.map(m => m.user.id))
//
}, 5000)
}

Related

Embed stated not being sent to channel

const { Client, GatewayIntentBits } = require('discord.js');
const client = new Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMessages,
]
});
const { EmbedBuilder } = require('discord.js');
// All partials are loaded automatically
//const Discord = require('discord.js');
client.on('ready', async () => {
console.log(`${client.user.username} is ready!`);
})
client.on('guildCreate', (g) => {
const channel = g.channels.cache.find(channel => channel.type === 'GUILD_TEXT' && channel.permissionsFor(g.me).has('SEND_MESSAGES'))
channel.send("Thanks for inviting flappy dank! Please run the command !run to get started!");
})
client.on("messageCreate", async (message) => {
if (message.content == '!testcmd') {
const illla = new EmbedBuilder()
.setColor(FF0000)
.setTitle('Members Generator 2.0!')
.setDescription('testing testing 123 123')
.setTimestamp()
.setFooter({ text: 'wow a footer'});
message.channel.send(illla)
}
})
I have tried the code above, when I run the command ‘!testcmd’, it does not output any embed. i have searched online for solutions, but none working. I expect and embed to be outputted, yet it doesn’t return any errors. Any advice would be appreciated!
You're using discord.js v14. There's a changes about sending Embeds
const illla = new EmbedBuilder()
.setColor(FF0000)
.setTitle('Members Generator 2.0!')
.setDescription('testing testing 123 123')
.setTimestamp()
.setFooter({ text: 'wow a footer'});
message.channel.send(illla) //The Changes is in here
The comment line should change as:
message.channel.send({embeds: [illla] });
Click here to see more about EmbedBuilder

Discord bot not coming online despite no error messages?

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.

How to Pin a Message in Discord

I am trying to make a discord bot for a small server that I am in, and I want it to pin a certain message to the channel that it was sent in. I have done a few bots before, but it seems that the syntax has changed since I last used it, and code that I was going to reuse no longer works. I have managed to get around some of those changes (like the intents,) but when I try to check for a sent message, it just does nothing. My current code
const { Client, Intents } = require("discord.js");
const { token } = require("./config.json");
const client = new Client({ intents: [Intents.FLAGS.GUILDS] });
client.once("ready", () => {
console.log(`Logged in as ${client.user.tag}!`);
});
client.on("message", (msg) => {
if (msg.content == "something goes here") {
msg.pin()
}
});
client.login(token);
I have tried supplementing messageCreate for message like I have seen a few people recommend, but it still seems to do nothing. Even changing the msg.pin() to console.log(msg) still shows nothing in the console
client.on("messageCreate", (msg) => {
if (msg.content == "something goes here") {
console.log(msg)
}
});
I do have the privileged intent toggle enabled, so I don't think that that is the problem
[privileged toggles]
Does anybody know what the problem here is, and how I could fix it? Any help is appreciated, thanks!
First of all, you have not enabled the GUILD_MESSAGES intent in your client so you need to add that by doing this:
const client = new Client({
intents: [
Intents.FLAGS.GUILDS
Intents.FLAGS.GUILD_MESSAGES
]
});
Other than that, the .pin() function is still there and there is no change in it. You can provide a reason as well. The .pin() function also returns a promise, so you will have to use .then() or await, so your final code might look like this:
const { Client, Intents } = require("discord.js");
const { token } = require("./config.json");
const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES] });
client.once("ready", () => {
console.log(`Logged in as ${client.user.tag}!`);
});
client.on("message", (msg) => {
if (msg.content == "something goes here") {
msg.pin().then(() => console.log)
}
});
client.login(token);
You can learn more about the .pin() function here => pin | discord.js
For Discord.js v13 use the following:
const { Client } = require("discord.js");
const { token } = require("./config.json");
const client = new Client({
intents: new Intents(32767)
});
client.login(token)
client.on("message", (ctx) => {
if (ctx.content == "something goes here") {
ctx.pin(ctx.id, "Pinned")
}
});

DM Specific User ID on Discord.js Bot

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

How can a Discord bot reply to only certain users?

I am looking for a way to make a Discord bot which either reacts or replies to only certain users. It can choose the user by either role or ID, but I can not seem to get it working. This is what I have tried:
if (message.author.id === 'myDiscordID') {
message.reply('hello!').then(r => {
});
}
I am coding in Discord JS, if that helps. This is the entire index.js file:
const Discord = require('discord.js');
const { prefix, token } = require('./config.json');
const client = new Discord.Client();
client.once('ready', () => {
console.log('Ready!');
});
client.on('message', message => {
if (message.author.id === 'myDiscordID') {
message.reply('hello!').then(r => {
});
}
});
client.login(token);
The file runs fine, the bot comes online, and then it prints 'Ready!' to the console, however, the rest of the code doesn't seem to work.
I`ts look like this must work.
Are you sure bot in your server and have permissions to read message ?
Try this ready block
client.once('ready', () => {
console.log('Ready!');
const guildList = client.guilds.cache.map(guild => guild.name)
console.join(`Bot go online in ${guildList.length}`)
console.log(guildList.join('\n'))
});
And some solutin to check user.id or roles includes:
console.log(message.content) for check is this event triggeret.
client.on('message', message => {
console.log(message.content)
if (message.author.id === '') {
message.reply('author contain')
}
if (message.member.roles.cache.has('ROLE ID')) {
message.reply('role contain')
}
if(message.member.roles.cache.some(role => ['ID1', 'ID2'].includes(role.id)) {
message.reply('some role contain')
}
});
I was also having a problem with that. Here is the solution that worked for me.
const userID = "The_user's_id";
bot.on("message", function(message) {
if(message.author.id === userID) {
message.react('emoji name or id');
}
});
Note: to find the id of a user, just right click him and press "copy ID".

Resources