"Cannot read property 'cache' of undefined" when I check a member role - discord.js

I want to make a mute command for my Discord bot but that create errors:
C:\Program Files\nodejs\node.exe .\index.js
|------ Bot on ------|
index.js:22
Uncaught TypeError: Cannot read property 'cache' of undefined
No debugger available, can not send 'variables'
Process exited with code 1
I want to check if the user who is mentionned has already the mute role and if the executor has an admin role. But that create this error.
My code:
bot.on("message", async message => {
if(message.content.startsWith(prefix + "mute")){
let User = message.mentions.users.first();
let time = message.content.split(" ").slice(2)
let reason = message.content.split(" ").slice(3)
if(!reason){ let reason = "aucune"}
if(!time || !User) return message.reply("Veuillez entrer une commande valide !\n" + prefix + "mute #user <temps> <raison>")
let dUser = User.id
if(dUser == message.author.id) return message.reply("Vous ne pouvez pas vous mute vous même !")
if(isNaN(time[0]) || time < 1) return message.reply("Veuillez entrer une valeur chiffrée et supérieur à 1 !")
let muterole = "793840735266013205"
che
if(User.roles.cache.has(muterole)) return message.reply("Ce membre est déjà mute !")
if(!message.author.roles.cache.has("783758067111428126" || "783758066138218577")) return message.reply("Vous n'avez pas la permission d'utiliser cette commande !")
if(User.roles.cache.has("783758067111428126" || "783758066138218577")) return message.reply("Vous ne pouvez pas mute un membre du staff !")
let emb = new Discord.MessageEmbed()
.setTitle(Mute)
.setDescription(User.username + " a bien été mute par " + message.author.username + " pendant " + time[0] + " secondes pour la raison suivante : " + reason)
.setColor("#E74C3C")
pendant " + time[0] + " secondes pour la raison suivante : " + reason)
User.roles.add(muterole)
setTimeout(() => {
User.roles.remove(muterole)
let reply = new Discord.MessageEmbed()
.setDescription(User + " a bien été unmute !")
.setColor("#E74C3C")
message.guild.channels.cache.get("795063422386569298").send(reply)
let mp = new Discord.MessageEmbed()
.setDescription("Vous avez été unmute de " + guild)
.setColor("#E74C3C")
message.author.send(mp)
}, time[0] = 60000
)}
})
Don’t worry about French words.

Your code is not going to do what you want it to do, because you messed up some parts. User will be the first mentioned user that can be found in your arguments. So if you mention the user right at the first position of your arguments, it will be at index 0. That is because the arguments get stored in an array and arrays always starts at index 0. That means now your following arguments have to be at index 1 and 2. So you can change your time and reason into:
let time = message.content.split(" ").slice(1);
let reason = message.content.split(" ").slice(2).join(" ");
Make sure you use .join(" ") at your reason, that will allow you to add multiple words for the reason. The next mistake is in the if-statement where you ask if there is no reason. You create a new variable inside the statement, which makes no sense. You just have to do:
if(!reason){ reason = "aucune"; }
Now if there is no reason provided the reason will be aucune.
If you want to ask if a user has the mute role already, you can use a GuildMember Object. That would look like this:
if(message.guild.member(User).roles.cache.has(muterole)) return message.reply("Ce membre est déjà mute !")
After that if-statement you ask if a user has certain roles and if he don't has this roles, he has no permission. Something like that should always be the first line of code of such a command and it should look like this:
if(!message.author.roles.cache.has("783758067111428126") || !message.author.roles.cache.has("783758066138218577")) return message.reply("Vous n'avez pas la permission d'utiliser cette commande !")
The same procedure with the following if-statement:
if(User.roles.cache.has("783758067111428126") || User.roles.cache.has("783758066138218577")) return message.reply("Vous ne pouvez pas mute un membre du staff !")
Then in your embed you are using time[0], although time is not an array. It just has to be time.
Your code should look like this now:
bot.on("message", async message => {
if(message.content.startsWith(prefix + "mute")){
if(!message.author.roles.cache.has("783758067111428126") || !message.author.roles.cache.has("783758066138218577")) return message.reply("Vous n'avez pas la permission d'utiliser cette commande !")
let User = message.mentions.users.first();
if(User.roles.cache.has("783758067111428126") || User.roles.cache.has("783758066138218577")) return message.reply("Vous ne pouvez pas mute un membre du staff !")
let time = message.content.split(" ").slice(2)
let reason = message.content.split(" ").slice(3)
if(!reason){ reason = "aucune"; }
if(!time || !User) return message.reply("Veuillez entrer une commande valide !\n" + prefix + "mute #user <temps> <raison>")
let dUser = User.id
if(dUser == message.author.id) return message.reply("Vous ne pouvez pas vous mute vous même !")
if(isNaN(time) || time < 1) return message.reply("Veuillez entrer une valeur chiffrée et supérieur à 1 !")
let muterole = "793840735266013205"
if(message.guild.member(User).roles.cache.has(muterole)) return message.reply("Ce membre est déjà mute !")
let emb = new Discord.MessageEmbed()
.setTitle(Mute)
.setDescription(User.username + " a bien été mute par " + message.author.username + " pendant " + time + " secondes pour la raison suivante : " + reason)
.setColor("#E74C3C")
User.roles.add(muterole)
setTimeout(() => {
User.roles.remove(muterole)
let reply = new Discord.MessageEmbed()
.setDescription(User + " a bien été unmute !")
.setColor("#E74C3C")
message.guild.channels.cache.get("795063422386569298").send(reply)
let mp = new Discord.MessageEmbed()
.setDescription("Vous avez été unmute de " + message.guild)
.setColor("#E74C3C")
message.author.send(mp)
}, time
)}
})

Related

How to not process commands in discord.py if the channel if private?

My code :
#commands.Cog.listener()
async def on_message(self, message):
if message.author.id == self.bot.user.id:
return
if message.channel.type == discord.ChannelType.private:
await message.channel.send("Vous devez être dans un serveur pour realiser cette commande !")
return
but it doesn't work, it's recognise that is was a private channel and it send the right message but it also process the command and send the answer ...
Don't include bot.process_commands(message) in the if code block which runs if the channel is private. Try this:
#commands.Cog.listener()
async def on_message(self, message):
if message.author.id == self.bot.user.id:
bot.process_commands(message)
return
if message.channel.type == discord.ChannelType.private:
await message.channel.send("Vous devez être dans un serveur pour realiser cette commande !")
return
#Don't add bot.process_commands(message) here.
Don't add bot.process_commands(message) outside the if block because if you do then it will run even if it is private.

ZAPIER CODE STEP HTTP REQUEST

I need generate the following request in zapier with a code step. I use webhook function but for some reason the answer is a separated comma value and i need the full json. I try in postman and works perfect. But i dont unterstand so fine how i can do with code. I use postman to format the code in nodejs the code run but dont geck back anything. Somebody can help so fin the problem? thans so much. (i´m a basic user for that reason i dont untersant all)
The request:
curl -X POST \
'https://gateway.watsonplatform.net/personality-insights/api/v3/profile?version=2017-10-13&consumption_preferences=false&raw_scores=true' \
-H 'accept: application/json' \
-H 'accept-language: es' \
-H 'authorization: Basic here is the token' \
-H 'cache-control: no-cache' \
var http = require("https");
var options = {
"method": "POST",
"hostname": "gateway.watsonplatform.net",
"port": null,
"path": "/personality-insights/api/v3/profile?version=2017-10-13&consumption_preferences=false&raw_scores=false",
"headers": {
"content-type": "application/json",
"accept": "application/json",
"authorization": "Basic HEREISTHETOKEN==",
"accept-language": "es",
"cache-control": "no-cache",
}
};
var req = http.request(options, function (res) {
var chunks = [];
res.on("data", function (chunk) {
chunks.push(chunk);
});
res.on("end", function () {
var body = Buffer.concat(chunks);
console.log(body.toString());
});
});
req.write(JSON.stringify({ contentItems:
[ { content: 'Wow, I liked #TheRock before, nowLa evaluada aseguró que no adulteró, falsificó u omitió intencionalmente alguna información en su solicitud de empleo, dice que toda la información suministrada en este proceso de selección es completamente legal y en cualquier momento se puede validar. I really SEE how special he is. The daughterIndicó que consume licor solo en ocasiones especiales, las bebidas que acostumbra a consumir son: cerveza, teniendo un consumo máximo por ocasión de 5 cervezas. Aseguró no haber tenido dependencia de las sustancias alcohólicas e indicó no tener antecedentes de alcoholismo en la familia. Agregó no haber tenido incumplimientos o problemas laborales a causa del licor. story was IT for me. So great! #MasterClass So great! #MasterClasWow, I liked #TheRock before, nowLa evaluada aseguró que no adulteró, falsificó u omitió intencionalmente alguna información en su solicitud de empleo, dice que toda la información suministrada en este proceso de selección es completamente legal y en cualquier momento se puede validar. I really SEE how special he is. The daughterIndicó que consume licor solo en ocasiones especiales, las bebidas que acostumbra a consumir son: cerveza, teniendo un consumo máximo por ocasión de 5 cervezas. Aseguró no haber tenido dependencia de las sustancias alcohólicas e indicó no tener antecedentes de alcoholismo en la familia. Agregó no haber tenido incumplimientos o problemas laborales a causa del licor. story was IT for me. So great! #MasterClasss',
contenttype: 'text/plain',
created: 1447639154000,
id: '666073008692314113',
language: 'es' } ] }));
req.end();
return {DATA: http.text};

What is wrong when I call this array from a variable?

I have been do it a template page for Wordpress Theme. In it, have to filter some tags from an user field.
But for test, I do it that:
$user_id = get_current_user_id();
$contexto = get_user_meta($user_id, 'contexto', true);
$contexto = '"' . $contexto . '"';
$array = array (
"Buscando mi nicho​" => "buscando-mi-nicho",
"Montando mi blog" => "montando-mi-plataforma",
"Buscando lectores" => "buscando-lectores",
"Construyendo mi lista de correo​" => "construyendo-mi-lista-de-correo",
"Vendiendo mi primer producto/servicio​" => "vendiendo-mi-primer-productoservicio",
"Buscando más clientes​​​" => "escalar-ventas",
"A punto de dar el gran salto (para vivir de mi blog)​" => "a-punto-de-dar-el-gran-salto-para-vivir-de-mi-blog",
"Ya soy Knowmada Full Time​" => "ya-soy-knowmada-full-time"
);
$etiqueta = $array[$contexto];
$user_first = get_user_meta( $user_id, 'first_name', true );
echo '<p>Hola '. $user_first . '. Queremos ayudarte a progresar, y tu etapa actual es <strong>' . $contexto . '</strong>, por eso, te recomendamos los siguientes contenidos con la etiqueta <b>' . $etiqueta . '</b></p>';
And I get:
Hola Javier. Queremos ayudarte a progresar, y tu etapa actual es "Montando mi blog", por eso, te recomendamos los siguientes contenidos con la etiqueta
You can see, that I don't get the variable $etiqueta.
If I put, for example:
$etiqueta = $array["Montando mi blog"];
I get:
Hola Javier. Queremos ayudarte a progresar, y tu etapa actual es "Montando mi blog", por eso, te recomendamos los siguientes contenidos con la etiqueta montando-mi-plataforma
So I get $etiqueta.
What is wrong whit:
$etiqueta = $array[$contexto];
It is because the keys in your array to not have the double quotes ("). Remove the line:
$contexto = '"' . $contexto . '"';
and it should work.

FB.UI callback with scopes on Backbone

var obj={
method: 'feed',
name: 'Je viens de créer son premier domaine : "' + this.model.attributes.name + '"',
caption: 'Entrez dans l\'univers du vin avec Vinoga',
description: (
'Ayez un domaine plus grand, plus beau ou plus prestigieux que vos amis. Challengez vos amis à travers de nombreux mini-jeux et rendez-leur visite '
),
link: 'http://www.vinoga.com',
picture: 'https://twimg0-a.akamaihd.net/profile_images/3095682321/79e5bb5014d6b118b08c5b11bd2a81e8.jpeg'
};
function callback(response)
{
this.model.setActivation(); // HERE
alert('toto');
}
FB.ui(obj, callback);
},
I got an error about this.model.setActivation is undefined ...
Do you have any idea how to solve this?
Thanks in Advance
Pierre
You can use underscore's bind helper to set the context for the callback.
FB.ui(obj, _.bind(callback, this));

Cakephp Data validation - This field cannot be left blank

I'm using cakephp and I get a strange behavior with it.
Here is my validation rule in the Model:
public $validate = array(
'flyer' => array(
'rule' => array('fileValidation', 'flyer', array('image/jpeg', 'image/pjpeg'), NULL, TRUE)
)
// Other rules...
);
Here is the fileValidation method (yes I'm french =) )
public function fileValidation(array $check, $field, array $allowedMimeTypes = NULL, $maxFileSize = NULL, $allowEmpty = FALSE)
{
$file = array_shift($check);
$message = NULL;
if($file['error'] === UPLOAD_ERR_OK){
// checking uploaded file
if(empty($file['tmp_name']) || empty($file['tmp_name']) || $file['tmp_name'] === 'none' || !is_uploaded_file($file['tmp_name'])){
$message = "Une erreur est survenue lors de l'envoi du fichier, veuillez réessayer à nouveau. Si le problème persiste, merci de contacter le support technique.";
}
// checking mimeTypes if required
elseif(!empty($allowedMimeTypes) && !in_array($file['type'], $allowedMimeTypes)){
$message = "Le type de fichier envoyé n'est pas celui attendu.";
}
// checking file size if required
elseif(!empty($maxFileSize) && $file['size'] > $maxFileSize){
$message = "Le fichier envoyé est trop volumineux, réduisez sa taille et réessayez.";
}
else{
return TRUE;
}
}
elseif($file['error'] === UPLOAD_ERR_NO_FILE){
// validates if no upload is allowed
if(!$allowEmpty){
$message = "Une erreur est survenue lors de l'envoi du fichier, veuillez réessayer à nouveau. Si le problème persiste, merci de contacter le support technique.";
}
else{
return TRUE;
}
}
elseif($file['error'] === UPLOAD_ERR_INI_SIZE){
$message = "Le fichier envoyé est trop volumineux, réduisez sa taille et réessayez.";
}
elseif($file['error'] === UPLOAD_ERR_FORM_SIZE){
$message = "Le fichier envoyé est trop volumineux, réduisez sa taille et réessayez.";
}
elseif($file['error'] === UPLOAD_ERR_PARTIAL){
$message = "Une erreur est survenue lors de l'envoi du fichier, le serveur n'a reçu qu'une partie du fichier, veuillez réessayer à nouveau.";
}
elseif($file['error'] >= UPLOAD_ERR_NO_TMP_DIR){
$message = "Une erreur interne est survenue, veuillez réessayer à nouveau. Si le problème persiste, merci de contacter le support technique.";
}
// Here is the problem
$this->validationErrors[$field][] = $message;
return FALSE;
}
So far so good, my Validation rule seems to work correctly but when à get an error, I have two messages: "My custom message" and "This file cannot be left blank".
How to remove this message, where am I wrong?
Thanks in advance.
May be it will works for you
$this->validationErrors[$field][] = $message; // comment this Line
return FALSE // comment this Line
And Add the following line at last of your fileValidation function
return implode("\n", $message);
Cakephp.Saint's solution doesn't work because $message is a string, not an array but this works fine:
return $message;

Resources