verify command in a specific channel, and a specific message without prefix - javascript

I'm basically trying to code something where you need to send a message to a specific channel, and a specific message to send to get a specific role, basically like verifying as such but without the prefix but an error keeps popping up and i cant get rid of it.
The script i am trying to fix:
bot.on("message", async message => {
if(message.channel.id === '753928667427635230'){
if(message.content == 'test'){
let role = message.guild.roles.cache.find('757964609222344744')
let member = message.author.id
member.roles.add(role)
message.channel.send('script works')
}
}
The error code below:
(node:14284) UnhandledPromiseRejectionWarning: TypeError: fn is not a function
at Map.find (C:\Users\haxor\Desktop\HardWareProject\node_modules\#discordjs\collection\dist\index.js:161:17)
at Client.<anonymous> (C:\Users\haxor\Desktop\HardWareProject\main.js:37:50)
at Client.emit (events.js:315:20)
at MessageCreateAction.handle (C:\Users\haxor\Desktop\HardWareProject\node_modules\discord.js\src\client\actions\MessageCreate.js:31:14)
at Object.module.exports [as MESSAGE_CREATE] (C:\Users\haxor\Desktop\HardWareProject\node_modules\discord.js\src\client\websocket\handlers\MESSAGE_CREATE.js:4:32)
my entire script:
const Discord = require('discord.js')
const bot = new Discord.Client()
const botsettings = require('./botsettings.json')
const fs = require('fs')
bot.commands = new Discord.Collection();
bot.aliases = new Discord.Collection();
fs.readdir("./commands/", (err, files) => {
if(err) console.log(err);
let jsfile = files.filter(f => f.split('.').pop() === 'js');
if(jsfile.length <= 0){
console.log('Commands aren\'t found!');
return;
}
jsfile.forEach((f) => {
let props = require(`./commands/${f}`);
console.log(`${f} loaded!`)
bot.commands.set(props.help.name, props);
props.help.aliases.forEach(alias => {
bot.aliases.set(alias, props.help.name);
})
})
})
bot.on("ready", async () => {
console.log(`Logged in as ${bot.user.username}`);
bot.user.setActivity(`HardLies`, {type: 'WATCHING' });
})
// Where the current error is at
bot.on("message", async message => {
if(message.channel.id === '753928667427635230'){
if(message.content == 'test'){
let role = message.guild.roles.cache.find('757964609222344744')
let member = message.author.id
member.roles.add(role)
message.channel.send('script works')
}
}
if(message.channel.type === 'dm') return;
if(message.author.bot) return;
let prefix = botsettings.prefix;
if(!message.content.startsWith(prefix)) return;
let args = message.content.slice(prefix.length).trim().split(/ +/g);
let cmd;
cmd = args.shift().toLowerCase();
let command;
let commandFile = bot.commands.get(cmd.slice(prefix.length));
if(commandFile) commandFile.run(bot, message, args);
if(bot.commands.has(cmd)){
command = bot.commands.get(cmd);
} else if(bot.aliases.has(cmd)){
command = bot.commands.get(bot.aliases.get(cmd));
}
try {
command.run(bot, message, args);
} catch (e){
return;
}
});
bot.login(botsettings.token);

The error "fn is not a function" is when you used .find(value) but this is an incorrect use. Try .find(u => u.id ==== ID) (for members .find(m => m.user.id === ID) or a better way you can just use .get(ID)
Second, you are trying to add a role to a User object. Wich is not possible. You'll have to use a GuildMember object (the difference) So instead use :
const user = message.member
And last, to add a role you'l have to use cache before the add function
member.roles.cache.add(role)
Your code should look list :
bot.on("message", async message => {
if(message.channel.id === '753928667427635230'){
if(message.content == 'test'){
let role = message.guild.roles.cache.get('757964609222344744')
let member = message.author.id
member.roles.cache.add(role)
message.channel.send('script works')
}
}

Related

TypeError: command.execute is not a function. (After typing !rps on discord channel)

When I try to use !rps, discord shows me that there is no command and I get somethink like that in the console
I don`t know do I need to change something in my index.js code or in my rps.js code
https://imgur.com/sGjGR4t
const Discord = require('discord.js');
const fs = require('fs');
const client = new Discord.Client({ intents: [Discord.Intents.FLAGS.GUILDS, Discord.Intents.FLAGS.GUILD_MESSAGES] });
client.command = new Discord.Collection();
const commandFolders = fs.readdirSync('./commands');
for (const folder of commandFolders) {
const commandFiles = fs.readdirSync(`./commands/${folder}/`).filter(file => file.endsWith('.js'));
for (const file of commandFiles) {
const command = require(`./commands/${folder}/${file}`);
client.command.set(command.name, command);
}
}
const prefix = '!';
client.once('ready', () => {
console.log('Bot jest online');
client.user.setActivity('Minecraft')
});
client.on('messageCreate', async message => {
if (!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).trim().split(/ +/);
const commandName = args.shift().toLowerCase();
if (!client.command.has(commandName)) return;
const command = client.command.get(commandName);
try {
command.execute(message, args);
} catch (error) {
console.error(error);
message.reply('Nie ma takiej komendy!')
}
});
client.login("TOKEN");
And the rps.js code, I tried to move rps.js to other folder but it does not solve the problem
const Discord = require('discord.js')
module.exports = {
name: "rps",
description: "rock paper scissors command",
usage: "!rps",
async run(bot, message, args) {
let embed = new Discord.MessageEmbed()
.setTitle("RPS")
.setDescription("React to play!")
.setTimestamp()
let msg = await message.channel.send(embed)
await msg.react("🗻")
await msg.react("✂")
await msg.react("📝")
const filter = (reaction, user) => {
return ['🗻', '✂', '📝'].includes(reaction.emoji.name) && user.id === message.author.id;
}
const chices = ['🗻', '✂', '📝']
const me = choices[Math.floor(Math.random() * choices.lenght)]
msg.awaitReactions(filter, { max: 1, time: 60000, error: ["time"] }).then(async (collected) => {
const reaction = collected.first()
let result = new Discord.MessageEmbed()
.setTitle("Result")
.addFields("Your Choice", `${reaction.emoji.name}`)
.addField("Bots choice", `${me}`)
await msg.edit(result)
if ((me === "🗻" && reaction.emoji.name === "✂") ||
(me === "✂" && reaction.emoji.name === "📝") ||
(me === "📝" && reaction.emoji.name === "🗻")) {
message.reply('You lost!');
} else if (me === react.emoji.name) {
return message.reply(`It's a tie!`);
} else {
return message.reply('You won!');
}
})
.catch(collected => {
message.reply('Process has been canceled, you failed to respond in time!');
})
}
}
In your rps.js file, you are defining the function to be run as run but in your index.js file, you are using the execute function so you can either change how you run the command in your main file or you can change the function name in your command file. Another place where you could get an error is the arguments you pass. In your main file, you are passing two arguments to your command file, message and args while in your command file, you are expecting three, bot, message and args. So you can either change the order of the arguments you pass or you can just remove the bot parameter in the command file:

TypeError: Cannot read property 'get' of undefined - Discord bot

(novice in coding, i just follow tutorials and try to understand and learn at the same time)
I recently wanted to code my own Discord bot but i had an issue with the event handler part so i tried another method but now i have another issue.
Instead of responding "pong" to "p!ping", it says :
client.commands.get('ping').execute(message, args);
^
TypeError: Cannot read property 'get' of undefined
at Object.execute (.../events/message.js:18:23)
at Client.<anonymous (.../main.js:19:44)
I also tried to replace
client.commands.get('ping').execute(message, args); with
client.commands.cache.get('ping').execute(message, args); or even client.commands.find('ping').execute(message, args); but it says "TypeError: Cannot read property 'get' of undefined - Discord bot" or even
Main file :
const Discord = require('discord.js');
const config = require('./config.json');
const {prefix, token} = require('./config.json')
const client = new Discord.Client();
client.commands = new Discord.Collection();
const eventFiles = fs.readdirSync('./events').filter(file => file.endsWith('.js'));
for (const file of eventFiles) {
const event = require(`./events/${file}`);
if (event.once) {
client.once(event.name, (...args) => event.execute(...args));
} else {
client.on(event.name, (...args) => event.execute(...args));
}
};
const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js'));
for (const file of commandFiles) {
const command = require(`./commands/${file}`);
// set a new item in the Collection
// with the key as the command name and the value as the exported module
client.commands.set(command.name, command);
};
client.on('message', message => {
if (!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).trim().split(/ +/);
const command = args.shift().toLowerCase();
if (!client.commands.has(command)) return;
try {
client.commands.get(command).execute(message, args);
} catch (error) {
console.error(error);
message.reply('there was an error trying to execute that command!');
}
});
client.login(token);
client.on("ready", () => {
client.user.setPresence({
activity: {
name: 'p!',
type: 'WATCHING'
},status: 'idle'
});
});
Message.js:
const client = new Discord.Client();
const prefix = 'p!';
module.exports = {
name: 'message',
execute(message) {
console.log(`${message.author.tag} in #${message.channel.name} sent: ${message.content}`);
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);
} else if (command === 'help'){
client.commands.get('trick').execute(message, args);
}
}
};
ping.js:
module.exports = {
name: 'ping',
description: 'Ping!',
execute(message, args) {
message.channel.send('pong');
},
};
I hope that the informations i provided were helpful. If it's a small mistake such as a missing ; i'm sorry for wasting your time. Thank you in advance
I changed the
if (command === 'ping'){ with
if (command === `${prefix}ping`){
and it works, i think i just have to do that with all the commands.
If you have an easier solution please feel free to share it or if you found the issue with the code please tell me. (because before it worked without this modification),
thank you
found an easier way like that theres no need to type a new line ( if (command === 'ping'){ client.commands.get('ping').execute(message, args);)
this is what my
Message.js file looks like now :
const client = new Discord.Client();
client.commands = new Discord.Collection();
module.exports = (Discord, client, message) => {
const {prefix} = require('../config.json');
if(!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).trim().split(/ +/);
const cmd = args.shift().toLowerCase ();
const command = client.commands.get(cmd) || client.commands.find (a => a.aliases && a.aliases.includes(cmd));
if(command) command.execute(client, message, args, Discord);
};

How do I pass module.exports in my index.js / discord.js

So I made a "mute" and "warn" command for my discord bot and when I try to run them I get an error. This error is because in all my previous commands I used ".execute(message, args)" in my command code, so when I wanted to get the command from my index.js I just had to pass client.commands.get('name').execute(message, args). Now, I don't have this in my command, so how do I get it from index.js. I hope you understand what I'm saying.
Here's index.js:
const Discord = require('discord.js');
const { Client, Collection } = require ('discord.js');
const client = new Discord.Client();
const token = 'TOKEN';
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.on('ready', () =>{
console.log('Compass is online');
client.user.setActivity('GameCore', {type: 'WATCHING'}).catch(console.error);
})
client.on('message', message=>{
if (!message.content.startsWith(PREFIX)) return;
else {
const args = message.content.slice(PREFIX.length).split(/ +/);
const command = args.shift().toLowerCase();
if(command === 'help') {
client.commands.get('help').execute(message, args);
}
if(command === 'kick') {
client.commands.get('kick').execute(message, args);
}
if(command === 'ban') {
client.commands.get('ban').execute(message, args);
}
if(command === 'slowmode') {
client.commands.get('slowmode').execute(message, args);
}
if(command === 'warn') {
client.commands.get('warn').execute(message, args);
}
if(command === 'mute') {
client.commands.get('mute').execute(message, args);
}
}
})
client.login(token);
mute.js (warn.js is build in a similar format):
var Discord = require('discord.js');
var ms = require('ms');
module.export = async(message, args) => {
if(!message.member.hasPemission('MANAGE_MESSAGES')) return message.channel.send(':x:***You do not have permissions to run this command!***')
var user = message.mentions.users.first();
if(!user) return message.channel.send(':x:***Please mention a user!***')
var member;
try {
member = await message.guild.members.fetch(user);
} catch(err) {
member = null;
}
if(!member) return message.channel.send(':x:***Please mention a user!***');
if(member.hasPermission('MANAGE_MESSAGES')) return message.channel.send(':x:***You cannot mute that person!***')
var rawTime = args[1];
var time = ms(rawTime)
if(!time) return message.channel.send('You didn\'t specify a time!')
var reason = args.splice(2).join(' ');
if(!reason) return message.reply('You need to give a mute reason!');
var channel = message.guild.channels.catch.find(c => c.name === 'potato');
var log = new Discord.MessageEmbed()
.setTitle(':white_check_mark:***This user has been muted.***')
.addField('User:', user, true)
.addField('By:', message.author, true)
.addField('Expires:', rawTime)
.addField('Reason:', reason)
channel.send(log);
var embed = new Discord.MessageEmbed()
.setTitle('You have been muted!')
.addField('Expires:', rawTime, true)
.addField('Reason:', reason, true);
try {
user.send(embed);
} catch(err) {
console.warn(err);
}
var role = msg.guild.roles.cache.find(r => r.name === 'Muted');
member.roles.add(role);
setTimeout(async() => {
member.roles.remove(role);
}, time);
message.channel.send(`**${user}** has been muted by **${message.author}** for **${rawTime}**!`)
}
And the error I get when I type "-mute" or "-warn":
client.commands.get('mute').execute(message, args);
^
TypeError: Cannot read property 'execute' of undefined
at Client.<anonymous> (G:\Alexis\Desktop\Compass\index.js:46:40)
at Client.emit (events.js:315:20)
at MessageCreateAction.handle (G:\Alexis\Desktop\Compass\node_modules\discord.js\src\client\actions\MessageCreate.js:31:14)
at Object.module.exports [as MESSAGE_CREATE] (G:\Alexis\Desktop\Compass\node_modules\discord.js\src\client\websocket\handlers\MESSAGE_CREATE.js:4:32)
at WebSocketManager.handlePacket (G:\Alexis\Desktop\Compass\node_modules\discord.js\src\client\websocket\WebSocketManager.js:384:31)
at WebSocketShard.onPacket (G:\Alexis\Desktop\Compass\node_modules\discord.js\src\client\websocket\WebSocketShard.js:444:22)
at WebSocketShard.onMessage (G:\Alexis\Desktop\Compass\node_modules\discord.js\src\client\websocket\WebSocketShard.js:301:10)
at WebSocket.onMessage (G:\Alexis\Desktop\Compass\node_modules\ws\lib\event-target.js:125:16)
at WebSocket.emit (events.js:315:20)
at Receiver.receiverOnMessage (G:\Alexis\Desktop\Compass\node_modules\ws\lib\websocket.js:797:20)
When exporting module you should use module.exports instead of module.export.
Also you are now trying to read nameand command properties from your module but there is none.
const command = require(`./commands/${file}`);
client.commands.set(command.name, command);
So if you want to use approach like this your command module should look something like this:
module.exports.name = 'mute';
module.exports.command = async (message, args) { ... };
or you can use your file name and export only function from your module
in index.js
const path = require('path');
...
for(const file of commandFiles){
const command = require(`./commands/${file}`);
client.commands.set(path.parse(file).name, command);
}
...
and in mute.js
...
module.exports = async (message, args) => { ... };
Learn basics of nodejs modules from https://www.tutorialsteacher.com/nodejs/nodejs-module-exports

TypeError: db.collection is not a function (Firestore and Discord.js)

I am trying to utilize Google's Firestore to store the tickets generated by users in our Discord as well as future features. I followed Google's documentation for setting up and adding data to the database. My initial test worked. When I utilized it to store data from a discord message, I am getting the following TypeError:
TypeError: db.collection is not a function
at Object.module.exports.run (D:\Projects\support-ticket-bot\commands\add-user.js:4:21)
at Client.<anonymous> (D:\Projects\support-ticket-bot\index.js:93:11)
at Client.emit (events.js:315:20)
at MessageCreateAction.handle (D:\Projects\support-ticket-bot\node_modules\discord.js\src\client\actions\MessageCreate.js:31:14)
at Object.module.exports [as MESSAGE_CREATE] (D:\Projects\support-ticket-bot\node_modules\discord.js\src\client\websocket\handlers\MESSAGE_CREATE.js:4:32)
at WebSocketManager.handlePacket (D:\Projects\support-ticket-bot\node_modules\discord.js\src\client\websocket\WebSocketManager.js:384:31)
at WebSocketShard.onPacket (D:\Projects\support-ticket-bot\node_modules\discord.js\src\client\websocket\WebSocketShard.js:444:22)
at WebSocketShard.onMessage (D:\Projects\support-ticket-bot\node_modules\discord.js\src\client\websocket\WebSocketShard.js:301:10)
at WebSocket.onMessage (D:\Projects\support-ticket-bot\node_modules\ws\lib\event-target.js:125:16)
at WebSocket.emit (events.js:315:20)
I have gone back to my initial test and it still works. I have retraced my steps and compared files and cannot find a valid reason that I get this error.
Here is my index.js file:
const fs = require('fs');
const Discord = require('discord.js');
const { prefix, token } = require('./config.json');
// firebase stuff
const firebase = require('firebase/app');
const admin = require('firebase-admin');
const serviceAccount = require('./ServiceAccount.json');
admin.initializeApp({
// eslint-disable-next-line comma-dangle
credential: admin.credential.cert(serviceAccount),
});
const db = admin.firestore();
// end firestore stuff
const client = new Discord.Client();
client.commands = new Discord.Collection();
fs.readdir('./commands/', (err, files) => {
if (err) {
console.log(err);
}
const commandFiles = files.filter((f) => f.split('.').pop() === 'js');
for (const file of commandFiles) {
const command = require(`./commands/${file}`);
client.commands.set(command.help.name, command);
}
commandFiles.forEach((f, i) => {
const command = require(`./commands/${f}`);
console.log(`${i + 1}: ${f} loaded!`);
client.commands.set(command.help.name, command);
});
});
client.once('ready', () => {
console.log('Ready!');
});
client.on('message', (message) => {
if (!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content
.slice(prefix.length)
.trim()
.split(/ +/);
const commandName = args.shift().toLowerCase();
const command =
client.commands.get(commandName) ||
client.commands.find(
(cmd) => cmd.help.aliases && cmd.help.aliases.includes(commandName)
);
if (!command) return;
if (command.help.guildOnly && message.channel.type === 'dm') {
return message.reply("I can't execute that command inside DMs!");
}
if (command.help.args && !args.length) {
let reply = `You didn't provide any arguments, ${message.author}!`;
if (command.help.usage) {
reply += `\nThe proper usage would be: \`${prefix}${command.name} ${command.usage}\``;
}
return message.channel.send(reply);
}
try {
command.run(client, message, db, args);
} catch (error) {
console.error(error);
message.reply('there was an error trying to execute that command!');
}
});
client.login(token);
and my add-user.js
/* eslint-disable comma-dangle */
module.exports.run = async (client, message, args, db) => {
try {
const docRef = db.collection('users').doc('test');
await docRef.set({
test: 'Test Again',
});
} catch (error) {
console.log('Something went wrong again!');
console.log(error);
}
};
module.exports.help = {
name: 'add-user',
description: 'beta command!',
args: true,
};
// db.collection('users').doc('alovelace');
Any help is greatly appreciated! Thanks!
Your arguments are in the wrong order. They are declared like this:
async (client, message, args, db)
But passed like this:
command.run(client, message, db, args);
db and args are swapped.

Discord.js command that gives a role

so I'm trying to make a command that where you type $test and it gives you, for example, a "Test" role. This is my current code but I keep getting an error: "Cannot read property 'addRole' of undefined"
const Discord = require("discord.js");
const { send } = require("process");
const { clear } = require("console");
const client = new Discord.Client();
var prefix = "$";
client.login("token");
//TEST COMMAND
client.on("message", message => {
if (message.content.startsWith(prefix + "test")) {
message.channel.send("You have been given `Need to be tested` role! You will be tested shortly!")
client.channels.get("701547440310059059").send(` please test ${message.author}!`)
const member = message.mentions.members.first();
let testRole = message.guild.roles.find(role => role.id == "609021049375293460")
member.addRole(testRole)
}})
client.on('ready',()=>{
console.log(`[READY] Logged in as ${client.user.tag}! ID: ${client.user.id}`);
let statuses = [
" status "
]
setInterval(function(){
let status = statuses[Math.floor(Math.random() * statuses.length)];
client.user.setActivity(status, {type:"WATCHING"})
}, 3000) //Seconds to Random
});
Please let me know how I can do this easily or something.
In discord.js v12, GuildMember does not have a function .addRole, you need to use GuildMemberRoleManager's .add, also you need to add .cache when getting roles from server, like this:
const member = message.mentions.members.first();
let testRole = message.guild.roles.cache.find(role => role.id == "609021049375293460")
member.roles.add(testRole)
Okay, you are getting the error Cannot read property 'addRole' of undefined.
This means that the member variable is undefined, which could be caused by the fact that you didn't mention a member.
In this line, you put const member = message.mentions.members.first(); which means when you run the command, you have to mention someone to add the role to.
Hope this helps.
In newest version of discord.js you can try the following code:
// Where '799617378904178698' is your role id
message.guild.roles.fetch('799617378904178698')
.then(role => {
console.log(`The role color is: ${role.color}`);
console.log(`The role name is: ${role.name}`);
let member = message.mentions.members.first();
member.roles.add(role).catch(console.error);
})
.catch(console.error);
Works in case you're trying to add a certain role. You ought to call it like that:
(prefix)commandName #member
Found one more solution in case you want to give any role to any user (except bot)
main.js (or index.js whatever you have):
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('Bot is online');
});
client.on('message', message => {
if (!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).split(/ +/);
console.log(args);
const command = args.shift().toLowerCase();
if (command == 'giveany') {
const role = args[1].slice(3, args[1].length - 1);
client.commands.get('giveany').execute(message, args, role);
}
});
client.login('token');
giveany.js :
module.exports = {
name: 'giveany',
description: 'adds any role to a member',
execute(message, args, role) {
console.log(role);
message.guild.roles.fetch(role)
.then(r => {
console.log(`The role color is: ${r.color}`);
console.log(`The role name is: ${r.name}`);
let member = message.mentions.members.first();
if (member != undefined) {
console.log('member=' + member);
member.roles.add(r).catch(console.error);
} else {
message.channel.send('You cannot give a role to a user that is either bot or undefined');
}
}).catch( (error) => {
console.error(error);
message.channel.send('Could not find given role: ' + args[1]);
});
}
}
Calling: +giveany #Username #Role

Categories

Resources