Command Restrictions - discord

I'm trying to make a command won't work if it's not in a certain channel. When I run my code, I get this error: SyntaxError: Unexpected token '!'
module.exports = {
name: "kill",
desciprtion: "idk",
if (!message.channel.id === '794303555975643136') return;
const { member } = message;
member.roles.add('794308638125981726')
}

In JavaScript and most other languages, you could refer to ! in functions as not.
For example, let's take message.member.hasPermission().
If we add ! at the start, giving us:
if (!message.member.hasPermission('ADMINISTRATOR') return
We're basically telling the client, if the message member does **not** have the administrator permission, return the command.
Now, let's take your if statement, saying if (!message.channel.id === 'id') return, you're basically telling the client if not message id equals to id return the command, which let's face it makes totally no sense.
When we want to compare a variable with a certain value, we would want to tell the client if the variable is **not** equal to value, return the command.
Hence why, you should fix your if statement into saying:
if (message.channel.id !== '794303555975643136') return;
Sorry for the pretty long answer, felt like giving a little lesson to someone :p

Related

Discord.js checking for mention in args

Hey so I am making a discord bot and when I use this to check for mention: message.mentions.members.first(); it will look for mention in whole message user has sent. I am trying to work this out because if user send message ?ban bla bla bla #user it will work. I want to check for mention only in args[0]. Is that possible? I am using discord v12. Thanks!
this is what i found to work...
if(args[0].slice(2).slice(0, -1) !== message.mentions.users.first()?.id) {
return message.reply("Please start with a user...")
}
the args[0].slice(2).slice(0, -1) if a mention... will be the id of the first mention... and if the mention is the first arg, it will also be the first mention. So what I did was took ID of the first mention and compared it to the sliced args[0] to see if they match, else it will return telling them to please start with a user... Make sure to keep the ? in message.mentions.users.first()?.id just in the case of no mention in the message, it will not cause an error to the process and will also return the please start with a user message.
Mentions
USERS_PATTERN uses RegEx for checking if string mentions about a User. If string matches with the pattern it returns true, otherwise returns false.
const { MessageMentions: { USERS_PATTERN } } = require('discord.js');
...
if (!args[0].match(USERS_PATTERN)) return message.channel.send("Please mention a user");
...

How to check if message contains emojis discord.js

I need to check if a message sent by user contains emojis because my database can't store this type of data. So I thought that I'll use a message.content.match() or message.content.includes() but when I use it, it still is not enough. I was thinking about making something like blacklist but for emojis and then I realized that I need to save a blacklist of all emojis so I gave up on that. My question for you is, do you know any easier way to make this? I was searching for solution to my problem but I didn't find anything.
Thank you a lot for any help.
if(message.author.id!='botid' && message.author.id===userdbId && message.content.match(/<a?:.+?:\d+>/)){
const name = args.join(" ");
const username = name.slice(0);
conn.query(`UPDATE users SET ignick='`+username+`' WHERE userID='${message.author.id}'`);
console.log(username);
message.channel.send("success message");
conn.end(err => {
if(err){
throw error;
}
console.log('Disconnected from database');
})
}
else{
console.log('bot has been stopped from adding his message to database');
}```
At top of this code i made a connect function and two constructors to pull from database userId
Whenever an emote is used in a message, it follows this format: <:OmegaStonks:723370807308582943>, where the name of the emote is "OmegaStonks" and the id links to the link to the image, like so: https://cdn.discordapp.com/emojis/723370807308582943.png
Detecting this pattern is pretty easy using regex.
<a?:.+?:\d+>
which takes any character from the first : to the second : (and I used a ? to make the wildcard . stop as soon as possible). You also can't have colons in emote names, so it won't abruptly stop there.
Source
Here is how you could do it
client.on('message', msg => {
if(msg.content.match(/<a?:.+?:\d+>/)) return; //or whatever action(s) you want to do
})

Error when console.log the displayname of the message owner

I get this Error:
TypeError: Cannot read property 'displayName' of null
This is the code that should console-log the command and the username of the user who used it:
client.on('message', (message) => {
const { content, member } = message
const autor = member.displayName || member.username
aliases.forEach((alias) => {
const command = `${prefix}${alias}`
if (content.startsWith(`${command}`) || content === command) {
console.log(`${autor} used: ${command}`)
callback(message)
}
})
})
In the console I get the username but it still gives an error. It only gives this error if I use a specific command. The command sends an embed of the message. Then it sends a copy of the message to the user who sent it.
if (message.content.includes('...'))
{message.delete({timeout: 800})
.then(message.member.send(message.content))
message.channel.send(embed)
Thank you for your help
If you want to use the nickname primarily, you can make your bot default to the username if the nickname is unavailable.
For your first section, you can use a ternary operator.
const autor = member ? member.displayName : message.author.username
If member returns null, it'll instead use the username property of the author which is never null.
For the second part of your code, you might as well replace message.member.send() with message.author.send() since then former provides no advantages over the latter and instead only leads to instances such as this one.
As from the documentation about message.member:
Represents the author of the message as a guild member. Only available if the message comes from a guild where the author is still a member
That means the error you are having may happen if the user is not a member of the server/guild anymore, or is a private message.
You can use message.author if you just want the username. Or you can return the function when message.member is null.

cant make an error statement to dm users discord.js

I tried putting a catch error if the user didn't get the message but for some reason, I get an error
client.on('guildMemberAdd', member => {
const linkId = pool.createLink(member.id);
const embed = new Discord.MessageEmbed()
.setTitle('reCAPTCHA Verification')
.setDescription(`To gain access to this server you must solve a captcha. The link will expire in 15 minutes.\nhttp://${domain == '' ? 'localhost:8050' : domain}/verify/${linkId}`)
.setColor('YELLOW');
member.send(embed)
} catch (e) {
console.log(`Error adding role to user ${discordId}.`)
}
get an error missing ","
added "," }, catch (e) {
and then I get Argument expression expected.
The Problem
The error is probably because your code is not formatted properly at all? You have a function member => {} and then you have a catch immediately following the function, and you never even close your client.on() parentheses.
Your program properly understanding entirely incorrect syntax is as infeasible as speaking gibberish to someone who speaks a different language and expecting them to understand you. When learning a new language, you need to be aware of new grammar rules, vocabulary, and more that may differ immensely from your own primary language. This is true of programming languages as well; javascript is very flexible, but your program will not be able to decipher immensely inaccurate syntax (which is the equivalent of gibberish to the program).
Please try to learn more about try/catch statements, javascript functions, syntax errors, and proper syntax. This is an immensely simple formatting issue, and questions like this one really should not be present on StackOverflow. Looking at some basic javascript tutorials, doing some quick research (perhaps even looking at some bot examples), and/or doing a single Google search could have solved your problem within seconds.
The Solution
This is the proper, more accurate syntax:
client.on('guildMemberAdd', member => {
const linkId = pool.createLink(member.id);
const embed = new Discord.MessageEmbed()
.setTitle('reCAPTCHA Verification')
.setDescription(`To gain access to this server you must solve a captcha. The link will expire in 15 minutes.\nhttp://${domain == '' ? 'localhost:8050' : domain}/verify/${linkId}`)
.setColor('YELLOW');
member.send(embed).catch(() => {console.log("Couldn't send message.")});
});
This is, of course, assuming that the formatting was the actual issue and you didn't just format it poorly when adding the code to your question. If it was only poorly formatted in your question and properly formatted in your actual code, then the issue isn't even present in the code you provided (in which case your question cannot even be answered, unless you provide the proper code).
i am getting an error
DiscordAPIError: Cannot send messages to this user
at RequestHandler.execute (C:\Users\Administrator\Desktop\GRPIL-BOT\src\DiscordVerification-master\DiscordVerification-master\node_modules\discord.js\src\rest\RequestHandler.js:154:13)
at processTicksAndRejections (node:internal/process/task_queues:93:5)
at async RequestHandler.push (C:\Users\Administrator\Desktop\GRPIL-BOT\src\DiscordVerification-master\DiscordVerification-master\node_modules\discord.js\src\rest\RequestHandler.js:39:14) {
method: 'post',
path: '/channels/790342794140975115/messages',
code: 50007,
httpStatus: 403
}
which
try {
const linkId = pool.createLink(member.id);
const embed = new Discord.MessageEmbed()
.setTitle('reCAPTCHA Verification')
.setDescription(`To gain access to this server you must solve a captcha. The link will expire in 15 minutes.\nhttp://${domain == '' ? 'localhost:8050' : domain}/verify/${linkId}`)
.setColor('YELLOW');
member.send(embed)
} catch (e) {
console.log(`Error adding role to user ${discordId}.`)
}
should avoid the error

Discord js TypeError: Cannot read property members

Hello i have this code,
user = message.guild.members.fetch(id2).then((use,err)
And i have this error
TypeError: Cannot read property 'members' of null
Please can yuo help me ?
Thank you
message.guild is not initialized. You could check if it is null before use eg
if(message.guild){
user = message.guild.members.fetch(id2).then((use,err) ...
}else{
//do something when it is not initialized
}
Your error occurs because the message object refers to a message that was received as a DM. Because of how DMs work, there is no guild or member property for such message (they are left as nulls).
To avoid that, you should handle direct messages slightly differently. The easiest and most commonly used way is to completely stop direct messages from running your message event code. This can be done by adding
if (message.channel.type === 'dm') return;
at the very top of your event.
As that makes it impossible to initiate commands in DMs, even if they don't need to be executed in a guild to work (like ping command for example), this might be not what you want. In such case, you should implement a way to determine if command someone tried to run in DM is "allowed" to be executed there. Implementations for that vary depending on command handling implementation, but snippet below is basic princinple.
client.on('message', message => {
if (message.author.bot || !message.startsWith(prefix)) return;
const args = message.content.slice(prefix.length).split(/ /g);
const command = args.shift().toLowerCase();
if (command === 'memberinfo') {
if (message.channel.type === 'dm') return message.reply('this command cannot be run in DMs.');
// Actual command code
}
});

Resources