Issues with dming a user if they send a command - javascript

I am trying to create a discord bot that can serve a multitude of purposes. Right now, I need some help with dming the user if they use the !help prefix. I tried multiple ways of dming the user & they lead to nowhere.
Here is my code:
const Discord = require("discord.js");
const config = require("./config.json");
const client = new Discord.Client({intents: ["GUILDS", "GUILD_MESSAGES"]});
const prefix = "!";
client.on("messageCreate", function(message) {
if (message.author.bot) return;
if (!message.content.startsWith(prefix)) return;
const commandBody = message.content.slice(prefix.length);
const args = commandBody.split(' ');
const command = args.shift().toLowerCase();
if (command === "") {
const timeTaken = Date.now() - message.createdTimestamp;
message.reply("e")
}
});
client.on('message', message => {
if (message.content === 'help') {
messageCreate.author.send('Help')
}
});
client.login(config.BOT_TOKEN);

Note your code here:
if (message.content === 'help') {
messageCreate.author.send('Help')
}
What is messageCreate defined as? Try replacing messageCreate with just message in the above excerpt.

Related

Discord.js Replit, cannot get my bot to respond to commands

I am currently developing a Discord bot for replit, and I am able to get it to post and even get it to send an intro message when joining a server, however whenever I try to get it to respond to a command I type it won't respond. The message for the first one client.on guild create works. However the client.on for async message will not work.
This is what I have so far.
const { Client } = require('discord.js');
const client = new Client({ intents: 32767 });
//const Discord = require('discord.js');
const keepAlive = require('./server');
require("dotenv").config();
//const client = new Discord.Client();
//const fetch = require('node-fetch');
const config = require('./package.json');
const prefix = '!';
const guild = "";
client.once('ready', () => {
console.log('Jp Learn Online');
});
// let defaultChannel = "";
// guild.channels.cache.forEach((channel) => {
// if(channel.type == "text" && defaultChannel == "") {
// if(channel.permissionsFor(guild.me).has("SEND_MESSAGES")) {
// defaultChannel = channel;
// }
// }
// })
//defaultChannel.send("This is a test message I should say this message when I join");
//if(guild.systemChannelId != null) return guild.systemChannel.send("This is a test message I should say this message when I join"), console.log('Bot entered new Server.')
// client.on('guildCreate', (g) => {
// const channel = g.channels.cache.find(channel => channel.type === 'GUILD_TEXT' && channel.permissionsFor(g.me).has('SEND_MESSAGES'))
// channel.send("This is a test message I should say this message when I join");
// });
client.on('guildCreate', guild => {
guild.systemChannel.send('this message wil print')
});
client.on('message', async message => {
if (!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).split(/ +/); // This splits our code into to allow multiple commands.
const command = args.shift().toLowerCase();
if (command === 'jhelp') {
message.channel.send('こんにちは、私はDiscordロボットです。始めたいなら、!jhelp タイプしてください。 \n\n Hello I am a discord bot built to help learn the Japanese language! \n\n If you want to access a japanese dictionary type !dictionary \n\n If you would like to learn a random Japanese Phrase type !teachme \n\n If you would like to answer a challenge question type !challenge1 through 5 each different numbered challnege will ask a different question \n (ie. !challenge1) this will ask the first question.')
}
please note. the lower parts of the code are simply commands. That expand further from jhelp I want to know mainly why my second client.on with messages wont work specifically in the context of working with replit.
Thanks for the help in advance.
I expected that maybe changing intents might work, I even went into the discord developer portal, and enabled options, and am still not able to get it working.
After Discord separated out the message intent as a privileged one, the bit field you need to use for all intents has changed. You need to use 131071.
I.e.
const { Client } = require('discord.js');
const client = new Client({ intents: 131071 });
//const Discord = require('discord.js');
const keepAlive = require('./server');
require("dotenv").config();
//const client = new Discord.Client();
//const fetch = require('node-fetch');
const config = require('./package.json');
const prefix = '!';
const guild = "";
client.once('ready', () => {
console.log('Jp Learn Online');
});
// let defaultChannel = "";
// guild.channels.cache.forEach((channel) => {
// if(channel.type == "text" && defaultChannel == "") {
// if(channel.permissionsFor(guild.me).has("SEND_MESSAGES")) {
// defaultChannel = channel;
// }
// }
// })
//defaultChannel.send("This is a test message I should say this message when I join");
//if(guild.systemChannelId != null) return guild.systemChannel.send("This is a test message I should say this message when I join"), console.log('Bot entered new Server.')
// client.on('guildCreate', (g) => {
// const channel = g.channels.cache.find(channel => channel.type === 'GUILD_TEXT' && channel.permissionsFor(g.me).has('SEND_MESSAGES'))
// channel.send("This is a test message I should say this message when I join");
// });
client.on('guildCreate', guild => {
guild.systemChannel.send('this message wil print')
});
client.on('messageCreate', async message => {
if (!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).split(/ +/); // This splits our code into to allow multiple commands.
const command = args.shift().toLowerCase();
if (command === 'jhelp') {
message.channel.send('こんにちは、私はDiscordロボットです。始めたいなら、!jhelp タイプしてください。 \n\n Hello I am a discord bot built to help learn the Japanese language! \n\n If you want to access a japanese dictionary type !dictionary \n\n If you would like to learn a random Japanese Phrase type !teachme \n\n If you would like to answer a challenge question type !challenge1 through 5 each different numbered challnege will ask a different question \n (ie. !challenge1) this will ask the first question.')
}
Yes! its the problem with your intents, for guildMemberAdd/Remove you require GuildMembers intents

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 not processing the command

I was adding some new commands to my discord v12 bot. But it's not responding to the code I typed. Any help is appreciated.
This section is inside index.js
client.admins = new discord.Collection();
const admins = fs.readdirSync('./custom/admin').filter(file => file.endsWith('.js'));
for (const file of admins) {
const admin = require(`./custom/admin/${file}`);
client.admins.set(admin.name.toLowerCase(), admin);
};
This is the code to process the above lines
if (message.author.bot || message.channel.type === 'dm') return;
const prefix = client.config.discord.prefix;
if (message.content.indexOf(prefix) !== 0) return;
const args = message.content.slice(prefix.length).trim().split(/ +/g);
const admin = args.shift().toLowerCase();
const adm = client.admins.get(admin) || client.admins.find(adm => adm.aliases && adm.aliases.includes(admin));
if (adm) adm.execute(client, message, args);
And the function which I am trying the bot to do is named delete.js
module.exports = {
name: 'snap' ,
aliases: [],
category: 'admin',
utilisation: '{prefix}snap [number]',
execute(message, args) {
if(isNaN(args)) return message.reply("Bruh,Specify how much message should I delete")
if(args>99) return message.reply("You ain't making me do that much work boi")
if (message.member.hasPermission('ADMINISTRATOR') ){
const {MessageAttachment} = require('discord.js');
const snaping = new MessageAttachment('./snap.gif')
message.channel.send(snaping)
setTimeout(snapCommand , 9000 ,args, message)
}
else
{
message.channel.send("-_- you are not an admin,Then why are you trying to use admin commands");
}
function snapCommand(args, message){
var del= args ;
del = parseInt(del , 10)
message.channel.bulkDelete(del+2);
}
}
}
when I launch the bot it shows no error msg, So that's a good sign I think, but when I use !snap 5
'!' which is my prefix. The bot does nothing. No error in the console also. Does anyone have any idea to solve this?
Never mind, I fixed it by adding client to the delete.js code
execute(client, message, args) {
if(isNaN(args)) return message.reply("Bruh,Specify how much message should I delete")
if(args>99) return message.reply("You ain't making me do that much work boi")

Discord Bot Logging in Over 1000 Times

I suspect this is happening due to the code below. It's the only bot of 3 with this code. The code itself hasn't been working 100% of the time when the bot is logged in. It's supposed to give anyone that is live streaming a "streaming" role. Some people it adds the role onto and for others it doesn't.
I'd like help for both issues if possible. Mostly the logging issue since I can't even keep the bot online anymore
The code below shows the entire index.js file. The code talked about above is the "presenceUpdate" section of code.
const fs = require('fs');
const Discord = require('discord.js');
const {prefix, token} = require('./config.json');
const welcomeGif = require('./welcomeGifs.json');
const client = new Discord.Client();
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);
}
client.once('ready', () => {
console.log(`${client.user.username} is online!`);
});
client.on('guildMemberAdd', gif => {
gif = new Discord.Attachment(welcomeGif[Math.floor(Math.random() * welcomeGif.length)]);
client.channels.get('614134721533968494').send(gif);
});
client.on('presenceUpdate', (oldPresence, newPresence) => {
const guild = newPresence.guild;
const streamingRole = guild.roles.cache.find(role => role.id === '720050658149138444');
if (newPresence.user.bot || newPresence.presence.clientStatus === 'mobile' || oldPresence.presence.status !== newPresence.presence.status) return;
const oldGame = oldPresence.presence.activities ? oldPresence.presence.activities.streaming: false;
const newGame = newPresence.presence.activities ? newPresence.presence.activities.streaming: false;
if (!oldGame && newGame) { // Started playing.
newPresence.roles.add(streamingRole)
.then(() => console.log(`${streamingRole.name} added to ${newPresence.user.tag}.`))
.catch(console.error);
} else if (oldGame && !newGame) { // Stopped playing.
newPresence.roles.remove(streamingRole)
.then(() => console.log(`${streamingRole.name} removed from ${newPresence.user.tag}.`))
.catch(console.error);
}
});
// This is the start of the main function when the bot is turned on
client.on('message', message => {
// The bot will not respond if there is no prefix,
// the user that typed it was a bot,
// or if it was not sent from in the server
if (!message.content.startsWith(prefix) || message.author.bot || !message.guild) return;
// Creates the arguments variable and separates it with a space
// and creates the command variable
const args = message.content.slice(prefix.length).split(' ');
const commandName = args.shift().toLowerCase();
if (!client.commands.has(commandName)) return;
const command = client.commands.get(commandName);
if (command.guildOnly && message.channel.type !== 'text') {
return message.reply('I can\'t execute that command inside DMs!');
}
try {
command.execute(message, args);
}
catch (error) {
console.error(error);
message.channel.send('There was an error trying to execute that command!\nCheck the console for details.');
}
});
// This logs in the bot with the specified token found in config
client.login(token);
Ok I'm getting closer and closer I think. I think the issue is that upon the bot logging in, it crashes from an error I found. When it crashes it is set to automatically restart so when it restarts it crashes again and repeats the cycle. The error I found is "clientStatus" is undefined which is in the presenceUpdate section.

"ready" event is never called

I'm programming my first Discord bot and I programmed it to output something to the console whenever it starts up, or in other words whenever client.on("ready") is called. However, I can't get it to actually fire and I don't know why. I have all Node dependencies installed, the bot is in the server and is able to send messages, and the first few lines of the program run fine.
What is the problem?
Here is the source:
console.log("Launching bot...\n");
const Discord = require("discord.js");
const client = new Discord.Client();
const config = require("./config.json");
client.on("ready", () => {
console.log(`Bot has started, with
${client.users.size} users, in
${client.channels.size} channels of
${client.guilds.size} guilds.`);
client.user.setActivity(`Serving
${client.guilds.size} servers`);
});
client.on("message", async message => {
if(message.authot.bot) return;
if(message.content.indexOf(config.prefix) !== 0)
return;
const args =
message.content
.slice(config.prefix.length).trim().split(/ +
/g);
const command = args.shift().toLowerCase();
if(command === "ping") {
let m = await message.channel.send("Ping?");
m.edit(`Pong! Latency is ${m.createdTimestamp -
message.createdTimestamp}ms. API Latency is
${Math.round(client.ping)}ms`);
}
});
You forgot to use the .login method for your client, that's the reason why your ready event doesn't get triggered!
Here is the updated code, you just have to insert your top secret key from https://discordapp.com/developers/applications/
console.log("Launching bot...\n");
const Discord = require("discord.js");
const client = new Discord.Client();
const config = require("./config.json");
client.on("ready", () => {
console.log(`Bot has started, with
${client.users.size} users, in
${client.channels.size} channels of
${client.guilds.size} guilds.`);
client.user.setActivity(`Serving
${client.guilds.size} servers`);
});
client.on("message", async message => {
if(message.authot.bot) return;
if(message.content.indexOf(config.prefix) !== 0)
return;
const args =
message.content
.slice(config.prefix.length).trim().split(/ +
/g);
const command = args.shift().toLowerCase();
if(command === "ping") {
let m = await message.channel.send("Ping?");
m.edit(`Pong! Latency is ${m.createdTimestamp -
message.createdTimestamp}ms. API Latency is
${Math.round(client.ping)}ms`);
}
});
client.login("YOUR TOP SECRET KEY")

Categories

Resources