Bot not responding - javascript

I'm trying to make my bot in discord on javascript, the bot goes online, shows in the console, but does not respond to messages
const Discord = require("discord.js")
const TOKEN = "MY TOKEN"
const client = new Discord.Client({
intents: [
"Guilds",
"GuildMessages"
]
})
client.on("ready", () => {
console.log(`Logged in as ${client.user.tag}`)
})
client.on("message", message => {
if (message.content.includes('ping'))
if (userCooldown[message.author.id]) {
userCooldown[message.author.id] = false;
message.reply('Pong');
setTimeout(() => {
userCooldown[message.author.id] = true;
}, 5000) // 5 sec
}
})
client.login(TOKEN)

Alright, there are a few issues at play here. Before I start, I should say that discord bots are moving away from reading message content and towards slash commands. If you have the opportunity to, please move towards slash commands. If you're looking for an up-to-date tutorial check out https://discordjs.guide.
With that being said, let me go through each issue one by one.
You're not asking for the MessageContent intent. You will not be able to check if the user's message contains ping
const client = new Discord.Client({
intents: [
"Guilds",
"GuildMessages",
"MessageContent"
]
})
I don't know if this is because this code has been shortened or not, but you're not defining userCooldown anywhere.
const userCooldown = {}
message doesn't exist as an event anymore. Use messageCreate instead
Your cooldown logic doesn't really work. I would flip the boolean around
client.on("messageCreate", message => {
if (message.content.includes('ping')) {
if (!userCooldown[message.author.id]) {
userCooldown[message.author.id] = true;
message.reply('Pong');
setTimeout(() => {
userCooldown[message.author.id] = false;
}, 5000) // 5 sec
}
}
})
You might have forgotten to enable this in the discord developer portal.
The complete code I used to make it work is below. I wish you luck on your discord developer journey.
const Discord = require("discord.js")
const TOKEN = "TOKEN_HERE"
const client = new Discord.Client({
intents: [
"Guilds",
"GuildMessages",
"MessageContent"
]
})
client.on("ready", () => {
console.log(`Logged in as ${client.user.tag}`)
})
const userCooldown = {}
client.on("messageCreate", message => {
if (message.content.includes('ping')) {
if (!userCooldown[message.author.id]) {
userCooldown[message.author.id] = true;
message.reply('Pong');
setTimeout(() => {
userCooldown[message.author.id] = false;
}, 5000) // 5 sec
}
}
})
client.login(TOKEN)

Related

Discord channel category name not found even though it exists

Im using the lastest Discord.js 14 and trying to create a new channel in the support category.
I manually created the category so I know it exists.
There are no channels in this category at present and this new channel the bot is trying to create will be the first one.
When I run this code console.log(supportCategory) the terminal shows undefined
Why?
// Require the necessary discord.js classes
const { Client, Events, GatewayIntentBits, ChannelTypes } = require('discord.js');
const { token } = require('./config.json');
// Create a new client instance
const client = new Client({ intents: [GatewayIntentBits.Guilds] });
// When the client is ready, run this code (only once)
// We use 'c' for the event parameter to keep it separate from the already defined 'client'
client.once(Events.ClientReady, c => {
console.log(`Ready! Logged in as ${c.user.tag}`);
});
client.on('ready', async () => {
console.log(`Logged in as ${client.user.tag}!`);
const guild = client.guilds.cache.first();
const supportCategory = guild.channels.cache.find(channel => channel.type === 'GUILD_CATEGORY' && channel.name === 'Support');
console.log(supportCategory) //this produces undefined
try {
const channel = await guild.channels.create('new-channel-name', {
type: 'GUILD_TEXT',
parent: supportCategory.id,
permissionOverwrites: [
{
id: guild.roles.everyone.id,
deny: ['VIEW_CHANNEL'],
},
],
});
console.log(`Channel created: ${channel.name}`);
} catch (error) {
console.error(error);
}
});
// Log in to Discord with your client's token
client.login(token);
You need to use the ChannelType enum to check a channel's category.
const supportCategory = guild.channels.cache.find(channel => channel.type === ChannelType.GuildCategory && channel.name === 'Support');

How do i make my discord bot respond to a message with prefix?

What I'm trying to do is set up a discord autoresponse bot that responds if someone says match prefix + respondobject like "!ping". I don't know why it doesn't come up with any response in the dispute. I've attached a picture of what it does. I can't figure out why it's not showing up with any responses in discord.
const Discord = require('discord.js');
const client = new Discord.Client({intents: ["GUILDS", "GUILD_MESSAGES"]});
const prefix = '!'
client.on('ready', () => {
let botStatus = [
'up!h or up!help',
`${client.users.cache.size} citizens!`,
`${client.guilds.cache.size} servers!`
]
setInterval(function(){
let status = botStatus[Math.floor(Math.random() * botStatus.length)]
client.user.setActivity(status, {type: 'WATCHING'})
}, 15000);
console.log(client.user.username);
});
client.on('message', message => {
if(!message.content.startsWith(prefix) || message.author.bot) return
const args = message.content.slice(prefix.length).split(/ +/)
const command = args.shift().toLowerCase()
const responseObject = {
"ping": `🏓 Latency is ${msg.createdTimestamp - message.createdTimestamp}ms. API Latency is ${Math.round(client.ws.ping)}ms`
};
if (responseObject[message.content]) {
message.channel.send('Loading data...').then (async (msg) =>{
msg.delete()
message.channel.send(responseObject[message.content]);
}).catch(err => console.log(err.message))
}
});
client.login(process.env.token);
Your main issue is that you're trying to check message.content against 'ping', but require a prefix. Your message.content will always have a prefix, so you could try if (responseObject[message.content.slice(prefix.length)]).
Other alternatives would be to add the prefix to the object ("!ping": "Latency is...")
Or, create a variable that tracks the command used.
let cmd = message.content.toLowerCase().slice(prefix.length).split(/\s+/gm)[0]
// then use it to check the object
if (responseObject[cmd]) {}

Discord bot is not replying to messages [duplicate]

This question already has answers here:
message event listener not working properly
(2 answers)
Closed 1 year ago.
I have been trying to set up a discord bot and by following the docs, I have been able to set up a slash command but have not been able to get the bot to reply to messages on the server.
Here is the code I used to set up slash command from docs.
const { REST } = require('#discordjs/rest');
const { Routes } = require('discord-api-types/v9');
const commands = [{
name: 'ping',
description: 'Replies with Pong!'
}];
const rest = new REST({ version: '9' }).setToken('token');
(async () => {
try {
console.log('Started refreshing application (/) commands.');
await rest.put(
Routes.applicationGuildCommands(CLIENT_ID, GUILD_ID),
{ body: commands },
);
console.log('Successfully reloaded application (/) commands.');
} catch (error) {
console.error(error);
}
})();
After this I set up the bot with this code:
const { Client, Intents } = require('discord.js');
const client = new Client({ intents: [Intents.FLAGS.GUILDS] });
client.once('ready', () => {
console.log('Ready!');
console.log(`Logged in as ${client.user.tag}!`);
});
client.on('interactionCreate', async interaction => {
// console.log(interaction)
if (!interaction.isCommand()) return;
if (interaction.commandName === 'ping') {
await interaction.reply('Pong!');
// await interaction.reply(client.user + '💖');
}
});
client.login('BOT_TOKEN');
Now I am able to get a response of Pong! when I say /ping.
But after I added the following code from this link I didn't get any response from the bot.
client.on('message', msg => {
if (msg.isMentioned(client.user)) {
msg.reply('pong');
}
});
I want the bot to reply to messages not just slash commands. Can someone help with this. Thanks!!🙂
First of all you are missing GUILD_MESSAGES intent to receive messageCreate event.
const client = new Discord.Client({ intents: ["GUILDS", "GUILD_MESSAGES"] });
Secondly the message event is deprecated, use messageCreate instead.
client.on("messageCreate", (message) => {
if (message.mentions.has(client.user)) {
message.reply("Pong!");
}
});
At last, Message.isMentioned() is no logner a function, it comes from discord.js v11. Use MessageMentions.has() to check if a user is mentioned in the message.
Tested using discord.js ^13.0.1.

Discord.js fired several times

The code that I made is fired several times, I have tried to add returns but it doesn't matter. I'm running the code with a raspberry pi 3.
const Discord = require('discord.js');
const { prefix, token } = require('./config.json');
const client = new Discord.Client();
client.once('ready', () => {
console.log('Ready!')
})
client.on('error', console.error);
client.on('message', message =>{
if (message.channel.id == '...........') {
console.log(message.content);
}
if (message.content.startsWith(`${prefix}ping`)) {
if (message.member.roles.some(role => role.name === '⚙️ | Manager'))
{message.channel.send('Pong!');} else {
message.channel.send('Not enough rights! :no_entry:');
}}
if (message.content.startsWith(`${prefix}test`)) {
if (message.author.id == '.........') {
const role = message.guild.roles.find('name', 'test');
message.member.addRole(role);
message.channel.send('test');
}}});
client.login(token);
I expect it to output it onces, but I don't get it to work.
This is the output:
I want him to do it only once.
Yeah I've had that problem before, simply turn off the bot from everything you're hosting it on, you were probably logged in on it multiple times, that might be because you're running it on a raspberry pi and did not properly shut it.

How to tell if a message mentions any user on the server?

I want to, with discord.js, tell if any given message mentions any user on the server.
Message.mentions is what you're looking for: you can either check .users or .members. If there's at least one element in one of these collections, then someone has been mentioned:
client.on('message', message => {
if (message.mentions.members.first()) // there's at least one mentioned user
else // there's no mentioned user
});
Keep a map of users and match with incoming messages
const Discord = require('discord.js')
const client = new Discord.Client()
const map = {}
client.on('message', msg => {
if (msg.content.indexOf('#') !== -1) {
const users = msg.content.match(/#[a-z\d]+/ig)
users.forEach((user) => {
if (map[users.slice(1)]) {
console.log(`${users.slice(1)} mentioned in server`)
}
})
}
})
client.on('ready', () => {
setInterval (function (){
for(u in Bot.users){
map[client.users[u].username] = true
}
}, 10000)
})
client.login('token')

Categories

Resources