Discord.js command that gives a role - javascript

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

Related

Cannot read property 'run' of undefined discord js

There was a post for this but it didn't seem to fix my problem. I'm writing a simple discord.js program and when I created a new command called forceverify, it gave the error "Cannot read property 'run' of undefined"
main.js:
const Discord = require('discord.js');
const client = new Discord.Client();
let fetch = require('node-fetch');
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('Loaded');
})
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 === 'help') {
client.commands.get('help').execute(message, args, Discord);
} else if (command === 'verify') {
client.commands.get('verify').execute(message, args, Discord);
} else if (command === 'forceverify') {
client.commands.get('forceverify').run(message, args, Discord);
}
})
client.on('guildMemberAdd', member => {
const welcomeChannel = client.channels.cache.find(ch => ch.name === 'member-log');
if (!welcomeChannel) {
console.log('No channel was found');
}
welcomeChannel.send(`Welcome!`);
client.login('The token is there');
forceverify.js
const { DiscordAPIError } = require("discord.js");
const fetch = require("node-fetch");
const packageData = require("../package.json");
module.exports = {
name: 'verify',
description: "Verify yourself to get access to the server",
execute(message, args, Discord) {
if (message.member.roles.cache.has('805210755800367104')) {
const clientUser = client.users.fetch(args[1]);
let myRole = message.guild.roles.cache.get("805531649131151390");
fetch(`https://api.sk1er.club/player/${args[0]}`)
.then(res => res.json())
.then(({ player }) => {
clientUser.member.setNickname(player.displayname).catch(console.error);
})
.catch(err => console.log(err));
} else {
message.channel.reply("You don't have sufficient permissions.");
}
}
}
Every other command works properly but for some reason, this one simply doesn't work. I tried what the other question said to do (which is add .execute to module.exports or change .execute to .run) neither worked probably because it simply can't find the file (everything was spelled correctly)
The export from forceverify.js has the name verify but it should be forceverify. So, the forceverify command isn't registered and client.commands.get('forceverify') returns undefined.
// commands/forceverify.js
module.exports = {
name: 'forceverify',
description: 'Force verify yourself to get access to the server',
execute(message, args, Discord) {
// do stuff
}
}
And you should call the execute function when invoking the command.
client.commands.get('forceverify').execute(message, args, Discord)
You can refactor your code to simplify the command invocation code.
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 (!client.commands.has(command)) {
return
}
client.commands.get(command).execute(message, args, Discord)
})

Discord.js doesn't do anything

My code worked fine but I changed some things and now it doesn't...
When I type !ping in the any channel it doesn't work.
the bot is on the server and an admin.
I changed the token down there
here's the code: Does anyone see something??
const Discord = require(`discord.js`),
client = new Discord.Client(),
prefix = `!`,
NO = `801418578069815297`
YES = `801418578300764180`
client.login(`bruh`)
client.once(`ready`, () => {
console.log(`online.`)
client.user.setPresence({
status: `online`,
game: {
name: `You`,
type: `WATCHING`
}
})
})
client.on(`message`, message =>{
if(!message.content.startsWith(prefix) || message.author.client) return
const args = message.content.slice(prefix.length).trim().split(` `)
const arg = args.toString().split(sep)
const command = args.shift().toLowerCase()
if(command === `ping`){
message.channel.send(`pong!`)
}
}
)
EDIT:
I put some log outputs in:
const Discord = require("discord.js");
let client = new Discord.Client();
let prefix = "!";
console.log("discord, client, prefix defined.")
client.login("bruh");
console.log("logged in.")
client.once("ready", () => {
console.log("online.");
client.user.setPresence({
status: "online",
game: {
name: "You",
type: "WATCHING"
}
});
});
client.on("message", message =>{
console.log("message recieved")
if(!message.content.startsWith(prefix) || message.author.client) return;
console.log("it's a command.")
const args = message.content.slice(prefix.length).trim().split(" ");
console.log("splitted.")
const arg = args.toString().split(sep);
console.log("args defined.")
const command = args.shift().toLowerCase();
console.log("command defined.")
if(command === "ping") {
console.log("command identified:"+command)
message.channel.send("pong!");
console.log("message sent.")
}
});
The output is:
logged in.
online.
message recieved
I looked at that closely but still didn't find anything...
The problem is, you're using commas where you should be using semicolons, so JS will be interepreting this strangely which will give you undefined behaviour. You should also preferably prefix your variables with let, var or const otherwise this could also lead to undefined behaviour. It is recommended to use let over var.
Try the code below to fix your problem:
const Discord = require(`discord.js`);
let client = new Discord.Client();
let prefix = '!';
let NO = "801418578069815297";
let YES = "801418578300764180";
client.login(`bruh`);
client.once(`ready`, () => {
console.log(`online.`);
client.user.setPresence({
status: `online`,
game: {
name: `You`,
type: `WATCHING`
}
});
});
client.on(`message`, message =>{
if(!message.content.startsWith(prefix) || message.author.client) return;
const args = message.content.slice(prefix.length).trim().split(' ');
const command = args.shift().toLowerCase();
if(command === `ping`) {
message.channel.send(`pong!`);
}
});
I've had problems in the past with using wrong quotation marks, that might be the case for you here as well
Try to replace all your ` with ' or "
I found a way to make it work. contact me on discord Moderpo#0172 if you wanna know the answer I'll have to find out what I did because I forgot lol

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

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')
}
}

How can I make a user specific channel in Discord.Js?

How can I make a user specific channel in Discord.Js?
So I am making a Discord bot where you click a reaction and it takes you into a private channel and nobody else can see the channel
This is what I have so far:
const Discord = require('discord.js');
const client = new Discord.Client();
const { bot } = require('./config.json');
const request = require('request');
client.on('message', message => {
var command = message.content.replace('t#', '');
var command = command.replace('t# ', '')
if(command.startsWith('post') === true){
message.delete();
var postEmbed = new Discord.RichEmbed();
postEmbed.setTitle('Twotter Post')
postEmbed.setAuthor(message.author.tag, message.author.avatarURL)
postEmbed.setDescription(command.replace('post ', ''))
postEmbed.setFooter('Created by Happy Fone on YouTube')
this.message = message;
message.channel.send(postEmbed).then(message => {
message.react('👍')
message.react('👎')
message.react('📲')
this.messageId = message.id;
});
}
});
client.on('messageReactionAdd', (messageReaction, user) => {
if(user.bot)return;
const { message, emoji } = messageReaction;
if(emoji.name == "📲") {
if(message.id == this.messageId) {
makeChannel(this.message)
}
}
});
function makeChannel(message){
var server = message.guild;
var name = message.author.username;
server.createChannel(name, "text");
}
client.login(bot.token)
I am trying to be as specific as possible for what I want. If you need any more info please say.
Since you need the user that reacted to the message in makeChannel(), you'll have to add a parameter for it. You don't actually need the relevant message in your function, so you can substitute that parameter for a Guild (which you do need).
function makeChannel(guild, user) {
const name = user.username;
...
}
// within messageReactionAdd listener
makeChannel(message.guild, user);
When creating the channel, you can pass in a ChannelData object containing permissions (PermissionResolvables) for it. By doing so, you can deny everyone (except for members with the Administrator permission) access to the channel except the user.
// within makeChannel()
guild.createChannel(name, {
type: 'text',
permissionOverwrites: [
{
id: guild.id, // shortcut for #everyone role ID
deny: 'VIEW_CHANNEL'
},
{
id: user.id,
allow: 'VIEW_CHANNEL'
}
]
})
.then(channel => console.log(`${name} now has their own channel (ID: ${channel.id})`))
.catch(console.error);
Refer to the examples in the Discord.js documentation for Guild#createChannel().
function makeChannel(message){
var server = message.guild;
var username = message.author.username;
server.createChannel(name, `${username}`);
var channel = server.find("name", `${username}`)
channel.overwritePermissions(message.author.id,{'VIEW_CHANNEL':true,'VIEW_CHANNEL':true}))
}
client.on('messageReactionAdd', (messageReaction, user) => {
if(user.bot)return;
const { message, emoji } = messageReaction;
if(emoji.name == "📲") {
if(message.id == this.messageId) { makeChannel(this.message) }
}
});
client.login(bot.token)
This piece of code is not yet tested, I'll do this later.

Working on a Discord bot with discord.js, tempmute won't work

making a discord bot in javascript with visual studio code but for some reason getting an error. I'll show you the code that is relevant first.
Overall trying to get a temporary mute function to work and I want to add it to the available commands which pops up when you hit !help. Table looks like this:
!help
classes I'm working with
Here is the index.js:
const { Client, Collection } = require("discord.js");
const { config } = require("dotenv");
const fs = require("fs");
const client = new Client({
disableEveryone: true
});
client.commands = new Collection();
client.aliases = new Collection();
client.categories = fs.readdirSync("./commands/");
config({
path: __dirname + "/.env"
});
["command"].forEach(handler => {
require(`./handlers/${handler}`)(client);
});
client.on("ready", () => {
console.log(`Hi, ${client.user.username} is now online!`);
client.user.setPresence({
status: "online",
game: {
name: "you get boosted❤️",
type: "Watching"
}
});
});
client.on("message", async message => {
const prefix = "!";
if (message.author.bot) return;
if (!message.guild) return;
if (!message.content.startsWith(prefix)) return;
if (!message.member) message.member = await message.guild.fetchMember(message);
const args = message.content.slice(prefix.length).trim().split(/ +/g);
const cmd = args.shift().toLowerCase();
if (cmd.length === 0) return;
let command = client.commands.get(cmd);
if (!command) command = client.commands.get(client.aliases.get(cmd));
if (command)
command.run(client, message, args);
});
client.login(process.env.TOKEN);
Here is tempmute:
bot.on('message', message => {
let args = message.content.substring(PREFIX.length).split(" ");
switch (args[0]) {
case 'mute':
var person = message.guild.member(message.mentions.users.first() || message.guild.members.get(args[1]));
if(!person) return message.reply("I CANT FIND THE USER " + person)
let mainrole = message.guild.roles.find(role => role.name === "Newbie");
let role = message.guild.roles.find(role => role.name === "mute");
if(!role) return message.reply("Couldn't find the mute role.")
let time = args[2];
if(!time){
return message.reply("You didnt specify a time!");
}
person.removeRole(mainrole.id)
person.addRole(role.id);
message.channel.send(`#${person.user.tag} has now been muted for ${ms(ms(time))}`)
setTimeout(function(){
person.addRole(mainrole.id)
person.removeRole(role.id);
console.log(role.id)
message.channel.send(`#${person.user.tag} has been unmuted.`)
}, ms(time));
break;
}
});
Here is the help.js which lists all commands
const { RichEmbed } = require("discord.js");
const { stripIndents } = require("common-tags");
module.exports = {
name: "help",
aliases: ["h"],
category: "info",
description: "Returns all commands, or one specific command info",
usage: "[command | alias]",
run: async (client, message, args) => {
if (args[0]) {
return getCMD(client, message, args[0]);
} else {
return getAll(client, message);
}
}
}
function getAll(client, message) {
const embed = new RichEmbed()
.setColor("RANDOM")
const commands = (category) => {
return client.commands
.filter(cmd => cmd.category === category)
.map(cmd => `- \`${cmd.name}\``)
.join("\n");
}
const info = client.categories
.map(cat => stripIndents`**${cat[0].toUpperCase() + cat.slice(1)}** \n${commands(cat)}`)
.reduce((string, category) => string + "\n" + category);
return message.channel.send(embed.setDescription(info));
}
function getCMD(client, message, input) {
const embed = new RichEmbed()
const cmd = client.commands.get(input.toLowerCase()) || client.commands.get(client.aliases.get(input.toLowerCase()));
let info = `No information found for command **${input.toLowerCase()}**`;
if (!cmd) {
return message.channel.send(embed.setColor("RED").setDescription(info));
}
if (cmd.name) info = `**Command name**: ${cmd.name}`;
if (cmd.aliases) info += `\n**Aliases**: ${cmd.aliases.map(a => `\`${a}\``).join(", ")}`;
if (cmd.description) info += `\n**Description**: ${cmd.description}`;
if (cmd.usage) {
info += `\n**Usage**: ${cmd.usage}`;
embed.setFooter(`Syntax: <> = required, [] = optional`);
}
return message.channel.send(embed.setColor("GREEN").setDescription(info));
}
ERROR:
Error message, bot not defined.
Overall trying to get a temporary mute function to work and I want to add it to the available commands which pops up when you hit !help. Table looks like this:
!help
I think the tempmute simply doesn't work because you use bot.on() instead of client.on(), which was defined in the index.js. I can't help you for the rest but everything is maybe related to this.

Categories

Resources