Discord bot not sending message - javascript

I am creating a Discord bot that sends a message when the user's message contains a certain string.
For example, if the user says 'ping', the bot should reply with 'pong'. However, this is not currently working as intended.
The bot itself is online and in the server I am testing, and I am using the correct login token. The code itself does not produce any errors, but it does not function as expected. I am looking for a solution to this issue.
Heres the code:
Ive removed the token just for this post.
const Discord = require('discord.js');
const { Client, GatewayIntentBits } = Discord;
// Create a new client
const client = new Client({
// Set the intents to include guilds and guild messages
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.MessageContent,
GatewayIntentBits.GuildMembers,
]
});
client.on('ready', () => {
console.log(`Logged in as ${client.user.tag}!`);
});
client.on('message', message => {
if (message.content === 'ping') {
message.reply('Pong!');
}
});
// Log in to Discord using the bot's token
client.login('REMOVED FOR STACK OVERFLOW POST');
Heres my bots permissions

As Zsolt Meszaros pointed out the client on function should use
https://stackoverflow.com/users/6126373/zsolt-meszaros
client.on('messageCreate', message => {
if (message.content === 'ping') {
message.reply('Pong!');
}
});
instead of
client.on('message', message => {
if (message.content === 'ping') {
message.reply('Pong!');
}
});

Related

Discord bot not giving reply [duplicate]

This question already has an answer here:
message.content doesn't have any value in Discord.js
(1 answer)
Closed last month.
Can someone help me out? I'm actually stuck. This the the source code for a bot I made to send GIFs when requesed by a user in a server. The bot is online and connecting to the Discord API.
Discord bot getting online image
The bot should be activated when typed !gif , in keyword the user can type any categorie or emotion they want and the bot would get the gif.
There are no errors shown yet but the bot is still not replying.
No reply image
Bot online image
I am also getting valid reply when used the giphy api url.
const Discord = require('discord.js');
require('dotenv').config();
const client = new Discord.Client({ intents: ["GUILDS", "GUILD_MESSAGES"] });
client.on('ready', () => {
console.log(`Logged in as ${client.user.tag}!`);
});
client.on("messageCreate", async (message) => {
const tokens = message.content.split(" ");
if (tokens[0] == "!gif") {
const keywords = tokens.slice(1, tokens.length).join(" ");
const url = `http://api.giphy.com/v1/gifs/search?q=tag&api_key=token&limit=5`;
const response = await fetch(url);
const result = await response.json();
const index = Math.floor(Math.random() * result.results.length);
message.channel.send(result.results[index].url);
}
});
client.login(process.env.DISCORD_BOT_TOKEN);
I tried many online fixes none worked I also tried changing version of Discord.js, node-fetch as well as dotenv but none worked.
Discord.js v14
const { Client, GatewayIntentBits, Events } = require('discord.js')
require('dotenv').config()
const client = new Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.MessageContent,
GatewayIntentBits.GuildMembers,
GatewayIntentBits.GuildMessages,
],
})
client.on(Events.MessageCreate, async (message) => {
if (message.author.id === client.user.id) return
const token = message.content.split(' ')
if (token[0] === '!gif')
message.channel.send({
content: `<#${message.author.id}>`,
files: ['https://media.tenor.com/fTTVgygGDh8AAAAM/kitty-cat-sandwich.gif'],
})
})
client.on(Events.ShardReady, () => {
console.log(`Logged in as ${client.user.tag}!`)
})
client.login(process.env.TOKEN)

Discord Bot gets online but doesn't respond to messages [duplicate]

This question already has an answer here:
message.content doesn't have any value in Discord.js
(1 answer)
Closed 3 months ago.
const Discord = require("discord.js")
const client = new Discord.Client({
intents: [
Discord.GatewayIntentBits.Guilds,
Discord.GatewayIntentBits.GuildMessages
]
});
client.on("ready", () => {
console.log(`Logged in as ${client.user.tag}!`)
})
client.on("messageCreator", (msg) => {
if (msg.content === "ping") {
msg.reply("pong");
}
})
client.on("message", Message => {
if (msg.content === "hi") {
msg.reply("hello");
}
})
client.login(process.env.TOKEN)
Hi, im tryng learn how to make a discord bot for my server and i dont know much of js. I've been reading some tutorials but isnt working.
Seems like you're trying to listen to 2 message events, messageCreator and message.
The event messageCreator doesn't exist. You need to replace it with messageCreate.
The event message has been deprecated. (Also, you've named your message instance Message but you're referring to it as msg.)
const Discord = require("discord.js");
const client = new Discord.Client({
intents: [Discord.GatewayIntentBits.Guilds, Discord.GatewayIntentBits.GuildMessages],
});
client.on("ready", () => {
console.log(`Logged in as ${client.user.tag}!`);
});
client.on("messageCreate", (msg) => {
if (msg.content === "ping") {
msg.reply("pong");
}
});
client.login(process.env.TOKEN);

Bot isn't replying to any message

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 am trying to make a discord bot automatically send a one-time-use invite when a user reacts to my message. I'm a bit new and could use help :)

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

Why doesn't my message.reply command not work?

My bot has connected to the server, it becomes online when I start the code, but i can't seem to figure out why the message.reply command doesnt work
Code:
const Discord = require('discord.js');
const bot = new Discord.Client();
bot.on('Message', (message) => {
if(message.content == 'ping') {
message.reply('pong');
}
});
Am i missing something? i'm coding using visual studio code
Client's events are case-sensitive, therefore, "Message" and "message" are completely two different things.
Replace "Message" with "message" on line 5 to fix your code.
const Discord = require('discord.js');
const bot = new Discord.Client();
bot.on('message', (message) => {
if (message.content == 'ping') {
message.reply('pong');
}
});

Categories