I have a "Special User" which is equal to 'Client.users.fetch(Special User's ID)'.
Then the user has two event listeners attached to the it, 'message' and 'presenceUpdate',
The message event listener works perfects, although the presenceUpdate does not work at all,
All help is greatly appreciated!
require("dotenv").config();
const Discord = require(`discord.js`);
const Client = new Discord.Client();
Client.on("ready", () => {
console.log(`\tClient Ready`);
});
var SpecialUser = Client.users
.fetch(process.env.ID)
.then((User) => {
console.log(User.username);
// Working
User.client.addListener("message", (message) => {
console.log("message");
});
// Not Working
User.client.addListener("presenceUpdate", (Old, New) => {
console.log(`Presence Updated`);
});
})
.catch(console.error);
Client.on("message", (message) => {});
Client.login(process.env.TOKEN);
If the presenceUpdate event doesn't trigger, chances are you'll need to add the GUILD_PRESENCES intent either using the client options:
const Discord = require(`discord.js`);
const client = new Discord.Client({
intents: ['GUILDS', 'GUILD_MESSAGES', 'GUILD_PRESENCES'],
});
// rest of your code...
In your Discord dashboard; by choosing your bot then by clicking on the Bot settings:
Related
Im trying to detect when someone sends an message with this code. Sadly its not working for some reason. It should give an output in the console and send an reply but both doesnt happen.
const bot= new CommandClient(`Bot ${token}`, { intents: ['guilds'], maxShards: 'auto',restMode: true })
bot.on('message', (message) => {
message.reply('This is a reply!')
.then(() => console.log("test"))
.catch(console.error);
})
The const bot works with interaction so its probably not the problem.
Can anyone help me?
const { Client, GatewayIntentBits } = require('discord.js');
const bot = new Client({intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages, GatewayIntentBits.MessageContent]})
bot.on('messageCreate', async message => {
message.reply("This is a reply!")
.then(() => console.log("test"))
.catch(console.error);
})
I'm trying to make a simple Discord bot, but I haven't been able to get it to respond to any of my messages.
const Discord = require("discord.js");
const { GatewayIntentBits } = require('discord.js');
const client = new Discord.Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.MessageContent
]
});
client.on("ready", () => {
console.log(`Logged in as ${client.user.tag}!`)
})
client.on("messageCreate", msg => {
if(msg.content === "ping") {
msg.reply("pong");
}
})
const token = process.env['TOKEN']
client.login(token)
The bot is logging into discord, I'm not getting any errors in the console, and I've toggled on all the privileged gateway intents.
Edit
So, my previous answer was wrong, but is most definitely a better way to send messages.
There's not anything else that I can see is wrong with the code -- so I guess I'll try to debunk?
const { Client, GatewayIntentBits } = require("discord.js");
const client = new Client({ intents: [ GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages, GatewayIntentBits.MessageContent ]});
client.on("ready", async() => {
console.log(`${client.user.tag} logged in.`);
});
client.on("messageCreate", async(message) => {
if(message.content.toLowerCase() === "ping") {
message.reply({ content: "pong!" }); // or message.reply("pong!");
}
});
client.login(process.env.TOKEN);
This should be a runnable instance of your code. What you should do is see if you're even getting the messageCreate event at all, by running it like this:
client.on("messageCreate", (message) => {
console.log(`Received message!`);
});
If you do get something, then it is unable to correctly parse the message content. Are you ensuring it's the same capitalization wise? Is it spelt correctly?
If you don't get something, it's an issue with your Intents, or the way your event is structured.
Try adding parenthesis around your msg, though that shouldn't affect anything. Just a thought.
Incorrect Answer
In discord.js#13.x.x, the way to send messages has changed.
Formerly, you could do the following:
message.reply("Hello world!");
But now, to make formatting what provided property is what, it goes as follows:
message.reply({
content: "Hello world!",
});
You can also add things such as Embeds by using embeds: [], or Components by: components: [] (which requires Action Rows, not base Components).
Hope this helps.
I'm using the following code to create a quick database to store the ID of the user who called a bot via a slash command. I then want to compare this ID with the ID of the person interacting with the bot. My aim is to prevent anyone but the user that called the bot being able to interact with it.
The following code works but it's temperamental in that it fails without a clear reason on occasion (i.e. it returns the error which states that the person interacting isn't the person who sent the slash command even if they are).
I'm new to discord.js and quick.db tables so I'm hoping someone more competent than me has a better way of achieving this.
const { Client, Intents, MessageEmbed, MessageActionRow, MessageButton } = require('discord.js'),
client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES ] });
client.db = require("quick.db");
var quiz = require("./quiz.json");
client.login(config.token);
client.on('ready', () => {
console.log(`Logged in as ${client.user.tag}!`);
if ([null, undefined].includes(client.db.get(`quiz`))) client.db.set(`quiz`, {});
if ([null, undefined].includes(client.db.get(`quiz.spawns`))) client.db.set(`quiz.spawns`, {});
});
client.on('messageCreate', async (message) => {
if (!message.content.startsWith(config.prefix)) return;
const args = message.content.slice(config.prefix.length).trim().split(/ +/g);
const command = args.shift();
if (command == "unlock") {
message.delete();
const m = await message.channel.send(getMMenuPage());
client.db.set(`quiz.spawns.m${m.id}`, message.author.id);
}
});
client.on('interactionCreate', async (interaction) => {
if (interaction.isButton()) {
if (client.db.get(`quiz.spawns.m${interaction.message.id}`) != interaction.user.id) return interaction.reply(getMessagePermissionError(client.db.get(`quiz.spawns.m${interaction.message.id}`)));
const q = quiz;
Please let me know if you need more information.
Thanks.
Instead of using:
const db = require("quick.db");
You should be using:
const { QuickDB } = require("quick.db");
const db = new QuickDB();
Other than that I haven't see any problems.
I have this very basic code for a very basic discord bot
since the new discord.js version 13 you need to declare intents.
I tried doing that using the bitmap 32767 (basically declaring all intents), however the bot doesnt trigger the "messageCreate" event when a message is send
in the dms it only works in servers.
All privileged gateway intents on the developer site have been set to true.
What am I missing?
const Discord = require("discord.js");
const allIntents = new Discord.Intents(32767);
const client = new Discord.Client({ intents: allIntents });
require("dotenv").config();
const botName = "Miku";
client.once("ready", () => {
//gets executed once at the start of the bot
console.log(botName + " is online!");
});
client.on("messageCreate", (message) => {
console.log("got a message");
});
(async() => {
//bot connects with Discord api
client.login(process.env.TOKEN);
})();
You cannot listen for events in the Direct Messages unless they are direct responses/replies/reactions to the initial message.
For example, you can send a message to new members and wait for a response:
client.on('guildMemberAdd', member =>{
member.send("Welcome to the server!");
message.awaitReactions(filter, { max: 1, time: 60000, errors: ['time'] })
.then((collected) => {
//Now, write your code here that handles the reactions.
});
but there is no way to listen for events within the Direct Messages. As in, client.on... will never fire because of a DM event.
I copied the skeleton of another user, and tried editing a few things but I just can't get the bot to a spot where when I react with the message it automatically generates the code and sends it.
My intentions are to react to a permanent message and have the reactee receive a DM from the bot with a unique link. Ideally they can only receive the link one time, even if they leave and join the channel again. I'm sure I've got some big errors in here for my functionality, I'd appreciate some guidance!
const { Client, Intents } = require('discord.js');
const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES] });
const mySecret = process.env['token']
client.once('ready', () => {
console.log('I am awake');
});
client.on('message', message => {
if(reaction.message.name === "\:thumbsup:" || message.author.bot)
return;
const args = message.content.slice(prefix.length).split(' ');
const command = args.shift().toLowerCase();
const replyWithInvite = async (message) => {
let invite = await message.channel.createInvite(
{
maxAge: 10 * 60 * 1000, // maximum time for the invite, in milliseconds
maxUses: 1 // maximum times it can be used
},
`Requested with command by ${message.author.tag}`
)
.catch(console.log);
message.author.send(invite ? `Here's your invite: ${invite}` : "There has been an error during the creation of the invite.");
}
if (command === 'invite') {
replyWithInvite(message);
}
});
client.login(mySecret);```
The first problem in ur code is you're event. in
const { Client, Intents } = require('discordjs');
require('dotenv').config() // If u're using environment variables for ur token
const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MEMBERS, Intents.FLAGS.GUILD_BANS, Intents.FLAGS.GUILD_MESSAGES, Intents.FLAGS.GUILD_BANS], partials: ['MESSAGE', 'CHANNEL', 'REACTION'] });
client.once('ready', () => {
console.log('I am awake');
});
client.on('messageReactionAdd', async (reaction, user) => {
// Check if the reaction is on ur intended message or just some random message on the server
if (reaction.message.id != urMessageid) return;
//check if the reaction is thumbsup or not
if (reaction.emoji.name != 'thumbsup') return;
// Create the invite now
const defaultChannel = reaction.message.guild.channels.find(c=> c.permissionsFor(guild.me).has("SEND_MESSAGES"));
let invite = await defaultChannel.createInvite({
maxAge: 10 * 60 * 1000, // maximum time for the invite, in milliseconds
maxUses: 1 ,// maximum times it can be used
reason: `Requested with command by ${user.tag}`
}).then(invite => invite).catch(error => console.log(error));
user.send(`Here's your invite ${invite}`).catch(error => console.log(error));
});
client.login(process.env.TOKEN);
You can find some examples on reactions on the Discordjs V12 guide.
Also on a side note for future references you shouldnt use the message event since its deprecated. You can use client#messageCreate