Check if first argument is a mention - javascript

I'm coding a discord bot and I'm trying to make a kick command right now. I managed to find how to check if there's any mention in the command message with message.mentions.members.first() but I couldn't find anything to check if a specific argument is a mention.
Code I have so far:
module.exports = {
name: "kick",
category: "moderation",
permissions: ["KICK_MEMBERS"],
devOnly: false,
run: async ({client, message, args}) => {
if (args[0]){
if(message.mentions.members.first())
message.reply("yes ping thing")
else message.reply("``" + args[0] + "`` isn't a mention. Please mention someone to kick.")
}
else
message.reply("Please specify who you want to kick: g!kick #user123")
}
}
I looked at the DJS guide but couldn't find how.

MessageMentions has a USERS_PATTERN property that contains the regular expression that matches the user mentions (like <#!813230572179619871>). You can use it with String#match, or RegExp#test() to check if your argument matches the pattern.
Here is an example using String#match:
// make sure to import MessageMentions
const { MessageMentions } = require('discord.js')
module.exports = {
name: 'kick',
category: 'moderation',
permissions: ['KICK_MEMBERS'],
devOnly: false,
run: async ({ client, message, args }) => {
if (!args[0])
return message.reply('Please specify who you want to kick: `g!kick #user123`')
// returns null if args[0] is not a mention, an array otherwise
let isMention = args[0].match(MessageMentions.USERS_PATTERN)
if (!isMention)
return message.reply(`First argument (_\`${args[0]}\`_) needs to be a member: \`g!kick #user123\``)
// kick the member
let member = message.mentions.members.first()
if (!member.kickable)
return message.reply(`You can't kick ${member}`)
try {
await member.kick()
message.reply('yes ping thing')
} catch (err) {
console.log(err)
message.reply('There was an error')
}
}
}

Related

How can i use global slash command in discord.js v13?

I've created a simple slash command. It works on the only guild. before that, I was using v12. Now I wanna switch to v13.
Now how can I make these global slash commands?
Code
client.on ("ready", () => {
console.log(`${client.user.tag} Has logged in`)
client.user.setActivity(`/help | ${client.user.username}`, { type: "PLAYING" })
const guildId = "914573324485541928"
const guild = client.guilds.cache.get(guildId)
let commands
if (guild) {
commands = guild.commands
} else {
commands = client.application.commands
}
commands.create({
name: 'ping',
description: 'Replies with pong'
})
commands.create({
name: 'truth',
description: 'Replies with truth'
})
});
client.on('interactionCreate', async (interaction) => {
if(!interaction.isCommand()){
return
}
const { commandName, options } = interaction
if (commandName === 'ping'){
interaction.reply({
content: 'pong'
})
}
```
I'm new in v13 so please explain it simply :|
Simply change the guild declaration. Your code checks if guild is truthy, and uses the guild if it is. Otherwise, it will use global commands
const guild = null
// any falsy value is fine (undefined, false, 0, '', etc.)

How to add permissions to user to channel by command? Discord.js

How to give permissions to a specific channel by command? Sorry, I’m new at discord.js so any help would be appreciated.
const Discord = require('discord.js');
module.exports = {
name: 'addrole',
run: async (bot, message, args) => {
//!addrole #user RoleName
let rMember =
message.guild.member(message.mentions.users.first()) ||
message.guild.members.cache.get(args[0]);
if (!rMember) return message.reply("Couldn't find that user, yo.");
let role = args.join(' ').slice(22);
if (!role) return message.reply('Specify a role!');
let gRole = message.guild.roles.cache.find((r) => r.name === role);
if (!gRole) return message.reply("Couldn't find that role.");
if (rMember.roles.has(gRole.id));
await rMember.addRole(gRole.id);
try {
const oofas = new Discord.MessageEmbed()
.setTitle('something')
.setColor(`#000000`)
.setDescription(`Congrats, you have been given the role ${gRole.name}`);
await rMember.send(oofas);
} catch (e) {
message.channel.send(
`Congrats, you have been given the role ${gRole.name}. We tried to DM `
);
}
},
};
You can use GuildChannel.updateOverwrites() to update the permissions on a channel.
// Update or Create permission overwrites for a message author
message.channel.updateOverwrite(message.author, {
SEND_MESSAGES: false
})
.then(channel => console.log(channel.permissionOverwrites.get(message.author.id)))
.catch(console.error);
(From example in the discord.js docs)
Using this function, you can provide a User or Role Object or ID of which to update permissions (in your case, you can use gRole).
Then, you can list the permissions to update followed by true, to allow, or false, to reject.
Here is a full list of permission flags you can use
This method is outdated and doesn't work on V13+ the new way is doing this:
channel.permissionOverwrites.edit(role, {SEND_MESSAGES: true }
channel.permissionOverwrites.edit(member, {SEND_MESSAGES: true }

Discord bot mute command by mention

I want to add few moderation commands to the bot, but I get stuck with "mute" command:
module.exports = {
name: 'mute',
description: 'command to mute members',
execute(message, args){
if(message.member.roles.cache.some(r => r.name === "Siren")){
const role = message.guild.roles.cache.find(r => r.name === "Muted");
const user = message.mentions.members.first().id;
user.roles.add(role);
}
}
}
I keep getting error:
TypeError: Cannot read property 'add' of undefined
I've been reading various guides and going through documentation and I keep failing on finding where I have made a mistake or what even causes this error.
At the first you try add role to member id, not a member. If no members mention in message, you will get empty mention collection and try get id of undefined, because message.mentions.members.first() of empty collection return undefined.
Second, try not use role names, use role ID for this, its more secure. And change your if code from if (statment) then do something to if (!statment) return reject reason this will help avoid unnecessary nesting of code.
module.exports = {
name: 'mute',
description: 'command to mute members',
execute(message, args){
if(!message.member.roles.cache.has('2132132131213')) return message.reply('You can`t use mute command')
const role = message.guild.roles.cache.get('21321321312');
if (!role) return message.reply('can`t get a role')
const member = message.mentions.members.first()
if (!member) return message.reply('Pls mention a member')
member.roles.add(role).then(newMember => {
message.channel.send(`successfully muted member ${member.user}`)
})
}
}

Discord.js Embed error Cannot send an empty message

so I'm trying to make a help command with list of commands showed in embed. My code kinda works but it throws an error "DiscordAPIError: Cannot send an empty message" and I've tried already everything I know and what I've found but I can't fix it.
Here's the code
const Discord = require('discord.js');
const { prefix } = require('../config.json');
module.exports = {
name: 'help',
description: 'List all of my commands or info about a specific command.',
aliases: ['commands', 'cmds'],
usage: '[command name]',
cooldown: 5,
execute(msg, args) {
const data = [];
const { commands } = msg.client;
if (!args.length) {
const helpEmbed = new Discord.MessageEmbed()
.setColor('YELLOW')
.setTitle('Here\'s a list of all my commands:')
.setDescription(commands.map(cmd => cmd.name).join('\n'))
.setTimestamp()
.setFooter(`You can send \`${prefix}help [command name]\` to get info on a specific command!`);
msg.author.send(helpEmbed);
return msg.author.send(data, { split: true })
.then(() => {
if (msg.channel.type === 'dm') return;
msg.reply('I\'ve sent you a DM with all my commands!');
})
.catch(error => {
console.error(`Could not send help DM to ${msg.author.tag}.\n`, error);
msg.reply('it seems like I can\'t DM you! Do you have DMs disabled?');
});
}
const name = args[0].toLowerCase();
const command = commands.get(name) || commands.find(c => c.aliases && c.aliases.includes(name));
if (!command) {
return msg.reply('that\'s not a valid command!');
}
data.push(`**Name:** ${command.name}`);
if (command.aliases) data.push(`**Aliases:** ${command.aliases.join(', ')}`);
if (command.description) data.push(`**Description:** ${command.description}`);
if (command.usage) data.push(`**Usage:** ${prefix}${command.name} ${command.usage}`);
data.push(`**Cooldown:** ${command.cooldown || 3} second(s)`);
msg.channel.send(data, { split: true });
},
};
You should try replace this line :
msg.channel.send(data, { split: true });
with
msg.channel.send(data.join(' '), { split: true }); since your data variable is an array and not a string
The problem is as the error states. You are trying to send an empty message somewhere.
You can try replacing msg.channel.send(data) with msg.channel.send(data.join('\n')), since the data variable is an array.
I don't see why sending an array doesn't work though.

How to fix a complex Discord command in JS based off of webhooks and roles

I'm working on a command where when you do the command, d!woa the following happens
A webhook gets created with a certain name, Then a role gets created with the channel name, after that the bot watches if there's a webhook with that certain name for the channel, and just sees if anyone sends a message in that channel. If it does, then the bot will add that role with the certain name.
The problem is that there's this error : TypeError: Cannot read property 'guild' of undefined
The error will most likely appear at the end of the code provided.
I've tried rearranging the code, defining guild, and defining message. It does not seem to work even after trying all of this. I only want it to rely off of the ID instead of Name to be accurate for this command.
const Discord = require('discord.js');
const commando = require('discord.js-commando');
class woa extends commando.Command
{
constructor(client) {
super(client, {
name: 'watchoveradd',
group: 'help',
memberName: 'watchoveradd',
description: 'placeholder',
aliases: ['woa'],
})
}
async run(message, args){
if (message.channel instanceof Discord.DMChannel) return message.channel.send('This command cannot be executed here.')
else
if(!message.member.guild.me.hasPermission(['MANAGE_WEBHOOKS'])) return message.channel.send('I don\'t have the permissions to make webhooks, please contact an admin or change my permissions!')
if(!message.member.guild.me.hasPermission(['MANAGE_ROLES'])) return message.channel.send('I don\'t have the permissions to make roles, please contact an admin or change my permissions!')
if (!message.member.hasPermission(['MANAGE_WEBHOOKS'])) return message.channel.send('You need to be an admin or webhook manager to use this command.')
if (!message.member.hasPermission(['MANAGE_ROLES'])) return message.channel.send('You need to be an admin or role manager to use this command.')
const avatar = `...`;
const name2 = "name-1.0WOCMD";
let woaID = message.mentions.channels.first();
if(!woaID) return message.channel.send("Channel is nonexistant or command was not formatted properly. Please do s!woa #(channelname)");
let specifiedchannel = message.guild.channels.find(t => t.id == woaID.id);;
specifiedchannel.send('test');
const hook = await woaID.createWebhook(name2, avatar).catch(error => console.log(error))
await hook.edit(name2, avatar).catch(error => console.log(error))
message.channel.send("Please do not tamper with the webhook or else the command implied before will no longer function with this channel.")
setTimeout(function(){
message.channel.send('Please wait...');
}, 10);
setTimeout(function(){
var role = message.guild.createRole({
name: `Name marker ${woaID.name} v1.0`,
color: 0xcc3b3b,}).catch(console.error);
if(role.name == "name marker") {
role.setMentionable(false, 'SBW Ping Set.')
role.setPosition(10)
role.setPermissions(['CREATE_INSTANT_INVITE', 'SEND_MESSAGES'])
.then(role => console.log(`Edited role`))
.catch(console.error)};
}, 20);
var sbwrID = member.guild.roles.find(`Synthibutworse marker ${woaID} v1.0`);
let specifiedrole = message.guild.roles.find(r => r.id == sbwrID.id)
setTimeout(function(){
message.channel.send('Created Role... Please wait.');
}, 100);
message.guild.specifiedchannel.replacePermissionOverwrites({
overwrites: [
{
id: specifiedrole,
denied: ['SEND_MESSAGES'],
allowed: ['VIEW_CHANNEL'],
},
],
reason: 'Needed to change permissions'
});
var member = client.user
var bot = message.client
bot.on('message', function(message) { {
if(message.channel.id == sbwrID.id) {
let bannedRole = message.guild.roles.find(role => role.id === specifiedrole);
message.member.addRole(bannedRole);
}
}})
}};
module.exports = woa;
I expect a command without the TypeError, and the command able to create a role and a webhook (for a marker), and the role is automatically set so that the user that has the role won't be able to speak in the channel, and whoever speaks in the channel will get the role.
The actual output is a TypeError: Cannot read property 'guild' of undefined but a role and webhook are created.
You have var sbwrID = member.guild...
You did not define member. Use message.member.guild...
You can setup a linter ( https://discordjs.guide/preparations/setting-up-a-linter.html ) to find these problems automatically.

Categories