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")
Related
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
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.
Im created a bot for discord using Discord.js, and every time I try to run my Bal command through my command handler it rejects it with the error Cannot read property 'run' of undefined
here is my code for Index.js
const Discord = require('discord.js');
const db = require("#replit/database")
const client = new Discord.Client();
const token = process.env.TOKEN;
const keep_alive = require('./keep_alive.js')
const PREFIX = "orb ";
const fs = require('fs');
const activities_list = [
"orb help.",
`${client.guilds.cache.size} servers!`,
"n 3^o7 !"
];
client.commands = new Discord.Collection();
const ecocommandFiles = fs.readdirSync('./ecocommands/').filter(file => file.endsWith('.js'));
for(const file of ecocommandFiles){
const command = require(`./ecocommands/${file}`);
client.commands.set(command.name, command);
}
client.on('ready', () => {
console.log("Orbitus online");
setInterval(() => {
const index = Math.floor(Math.random() * (activities_list.length - 1) + 1);
client.user.setActivity(activities_list[index], { type: 'WATCHING' });
}, 30000);
});
//Command Handler\\
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();
if(command === 'bal'){
client.commands.get('bal').run(message, args, Discord);
}
});
client.login(token);
And here is my code for Bal.js
module.exports.run = async (message, args, Discord) => {
if(!message.content.startsWith(PREFIX))return;
let user = message.mentions.members.first() || message.author;
let bal = db.fetch(`money_${message.guild.id}_${user.id}`)
if (bal === null) bal = 0;
let bank = await db.fetch(`bank_${message.guild.id}_${user.id}`)
if (bank === null) bank = 0;
let moneyEmbed = new Discord.RichEmbed()
.setColor("#FFFFFF")
.setDescription(`**${user}'s Balance**\n\nPocket: ${bal}\nBank: ${bank}`);
message.channel.send(moneyEmbed)
};
I really need help because I want to continue development on my bot.
Thanks for your time
so uuh , i think you should follow the official guide:
https://discordjs.guide/command-handling/
your's seems bit similar but maybe got from yt (etc)
anyway the issue is
you dont export name from Bal.js only run (function)
module.exports.run = .....
and as name is undefined
your here setting undefined as the key with your run function to client.commands (collection)
for(const file of ecocommandFiles){
const command = require(`./ecocommands/${file}`);
client.commands.set(command.name, command);
^^^^^^^^
}
now only key in the client.commands collection is undefined
client.commands.get('bal') this will come undefined as there is not command called bal in your collection (only undefined)
what you could do is add
module.exports.name = 'bal' into bal.js
every command from now on should have this (if you decide to use this way)
Again I would suggest you read the discord.js official guide as it very beginner friendly and has a command handler and dynamic command handling tutorials with additional features, I will leave the links down below if you need them :)
Links
Official-docs: Click-here
official guide (this is the official guide for beginners with d.js): Click-here
Command-Handling (guide): Click-here
Dynamic-Command-Handling(guide) : Click-here
Additional-Features) (guide): Click-here
Other guides:
Event handling (from the same official guide): Click-here
An-idiots-Guide (use jointly with the official guide): Click-here
I am using node.js for my bot, and I, like the question stated, need to find the last message in the channel that matches the criteria specified in the code. For example, the command would say, ?joe, and it would find the last message that has "joe" in it, and return the member that sent it. In the server I am going to use it in, the message is very frequent, so I don't think it will hit any message reading limitations.
I did the code in main.js and the commands in separate js files, like this,
const Discord = require('discord.js');
const client = new Discord.Client();
const prefix = '?'
const fs = require('fs');
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('AbidBot is online!!');
});
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();
if(command === 'ping'){
client.commands.get('ping').execute(message, args);
}
});
client.login();
The ping command looks like this:
module.exports = {
name: 'ping',
description: "this is a ping command!",
execute(message, args){
message.channel.send('pong!')
}
}
Thanks for your help!
EDIT #1
Thanks, but it does not seem to be working for me #Lioness100. Can you take a look?
module.exports = {
name: 'joe',
description: "find joe",
execute(message, args){
message.channel.messages.fetch().then((messages) => {
// find the message that has 'joe' in it
const author = messages.find({ content } => content.includes(' joe ')).author.tag;
message.channel.send(author);
}
});
}
You can use MessageManager.fetch() and Collection.find()
// fetch the last 100 messages in the channel
message.channel.messages.fetch({ limit: 100 }).then((messages) => {
// find the message that has 'joe' in it
const msg = messages.find(({ content }) => content.includes(' joe '));
return msg
? message.channel.send(msg)
: message.channel.send('None of the last 100 messages include the word `joe`!');
});
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.