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.
Related
I've been working on this code for a discord bot that tracks a the voice channels of a server until a specific person joins which then the bot joins and then plays an audio. However whenever I start up my file, it keeps on saying
[nodemon] starting `node index.js`
[nodemon] clean exit - waiting for changes before restart
I have no clue why, I've looked online and I haven't seen any other people having the same issue as me, and if they did the answer didn't help.
Here is my code.
const { Client, GatewayIntentBits } = require('discord.js');
const { Lavalink } = require('discord.js-lavalink');
class MyBot {
// The Discord.js client object that represents our bot
client;
// The ID of the specific person we want to track
userIdToTrack;
// The audio file to play when the specific person joins
audioFile;
constructor(client, userIdToTrack, audioFile) {
// Save the client object and user ID and audio file for later use
this.client = "[bot token]";
this.userIdToTrack = '[discord id]';
this.audioFile = '[file name]';
}
onGuildVoiceJoin(event) {
// Get the member who just joined the voice channel
const member = event.member;
// If the member is the specific person we want to track...
if (member.id === this.userIdToTrack) {
// Get the voice channel that the member joined
const voiceChannel = event.channel;
// Join the voice channel with the bot
voiceChannel.guild.voice.channel.join();
// Play the audio file using Lavalink
lavalink.play(voiceChannel, {
track: '[file name]',
});
const client = new Client({
token: 'bot token]',
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.MessageContent,
GatewayIntentBits.GuildVoiceStates,
GatewayIntentBits.GuildPresences,
],
});
// Create a new instance of the Lavalink class and connect to the Lavalink nodes
const lavalink = new Lavalink({
client: client,
nodes: [
{ host: 'ratio-w', port: 2334, password: 'youshallnotpass' },
],
});
lavalink.connect();
client.on('ready', () => {
console.log('The bot is ready');
// Create a new instance of the bot, passing in the client object, user ID, and audio file
const bot = new MyBot("bot token", "user id", "file name");
// Listen for voice state update events, which are triggered when a user joins or leaves a voice channel
client.on('voiceStateUpdate', (oldState, newState) => {
// Check if the user we want to track has just joined a voice channel
if (newState.member.id === userIdToTrack && newState.channel) {
// Get the voice channel the user joined
const voiceChannel = newState.channel;
// Join the voice channel with the bot
voiceChannel.join().then(connection => {
// Play the audio file using Lavalink
lavalink.play(voiceChannel, {
track: audioFile,
});
});
}
});
client.on('messageCreate', message => {
if (message.content === 'ping') {
message.reply('hey <#user id>, you STINK!!!!111!');
}
});
client.on('messageCreate', message => {
if (message.content === 'shut up [redacted]') {
message.reply('yeah <#user id> shut up smelly');
}
});
client.on('messageCreate', message => {
if (message.content === 'stop being a nerd [redacted]') {
message.reply('<#user id> be like :nerd:');
}
});
});
process.on('unhandledRejection', (reason, promise) => {
console.log('Unhandled Rejection at:', reason.stack || reason)
// Recommended: send the information to sentry.io
// or whatever crash reporting service you use
})
client.login('[bot id]');}}}
I tried fixing any possible syntax errors, I've tried looking online but no help was found, I've properly started lavalink (I think), I've edited some of the code so that all possible parts are fixed. I've downloaded all possible directories like updating discord.js, node.js, lavalink.js, and more I think.
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 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
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:
Hi I'm creating a bot for my server and I was trying to make a member counter in voice channels and when I finished doing it I wrote in the terminal: node index.js and he started saying that the token was not available to my client.
ERROR:
(node:9596) UnhandledPromiseRejectionWarning: DiscordjsError: Request
to use token, but token was unavailable to the client. at RequestHandler.execute
Here is my code
Note: I did all the bot code in a file just to be able to use it in a .bat file.
It's because on line 6 where you try to fetch, you're not logged in. You're calling bot.login() later (and it's async)
const guild = bot.guilds.fetch('222078108977594368')
Check https://discordjs.guide/popular-topics/errors.html#request-to-use-token-but-token-was-unavailable-to-the-client
If you want to fetch it only once, you can probably move this to the ready state's handler:
const Discord = require('discord.js')
const { send, stdout } = require('process')
const bot = new Discord.Client()
const token = 'XXX'
const prefix = 'a!'
// use let, so you can change it later in bot.on('ready')
let guild = null
// this event will only trigger after logging in
bot.on('ready', () => {
const ping = new Date()
// fetch here
guild = bot.guilds.fetch('222078108977594368')
ping.setHours(ping.getHours() - 3)
console.log(`BOT INICIADO AS ${ping.getUTCHours()}:${ping.getUTCMinutes()}:${ping.getUTCSeconds()}`)
console.log('GuruGuru Está Online!')
bot.user.setActivity(`${bot.guilds.cache.size} servidores`, { type: 'WATCHING' });
})