I'm having problems with combining these two codes together: - discord.js

This is what I have tried: It only executes the first one.
client.on('message', message => {
if (!message.content.startsWith(prefix) || message.author.bot) return;
const roleName = message.member.roles.cache.find(r => r.name === "Owner")
if (roleName) {
return message.reply("Pog")
} else {
return message.reply("Sorry, an error occured.")
}
});
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 === 'ping') {
client.commands.get('ping').execute(message, args);
} else if (command == 'youtube') {
client.commands.get('youtube').execute(message, args);
} else if (command == 'clear') {
client.commands.get('clear').execute(message, args);
} else if (command == 'mute') {
client.commands.get('mute').execute(message, args);
} else if (command == 'unmute') {
client.commands.get('unmute').execute(message, args);
}
});
I'm new to js and I need help with combining these two codes together.
All I want to do is that the person using command needs to heve certan role, so that like members ...
can't use the mute command.

Yes you can do this, you just want to find the role first and then run an if statement to check if the user has this role before calling .execute(message, args);
This can be done like this:
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 === 'ping') {
client.commands.get('ping').execute(message, args);
} else if (command == 'youtube') {
client.commands.get('youtube').execute(message, args);
} else if (command == 'clear') {
client.commands.get('clear').execute(message, args);
} else if (command == 'mute') {
if (message.member.roles.cache.some(role => role.name == "Owner")) {
client.commands.get('mute').execute(message, args);
} else {
message.reply("You are unable to use this command");
}
} else if (command == 'unmute') {
if (message.member.roles.cache.some(role => role.name == "Owner")) {
client.commands.get('unmute').execute(message, args);
} else {
message.reply("You are unable to use this command");
}
}
});
You should avoid having multiple listeners for the same event and just use one. Also, note that there will be no member object in message if the message was sent in a DM

Related

discord.js command handling else if problem

I'm new to discord.js and I'm trying to make a really simple command with command handling.
The content of the bot.js file:
const Discord = require('discord.js');
const client = new Discord.Client();
const { prefix, token } = require("./config.json");
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('On!');})
client.on('message', async 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("Error");
}
The content of the lunedi1.js file:
const Discord = require('discord.js');
const fs = require("fs");
const client = new Discord.Client();
const { prefix, token } = require("../config.json");
module.exports = {
name: "lunedi1",
description: "Codici videolezioni, li puoi ottenere facendo '.<giorno> <ora>",
execute(message, args) {
if(message.content.startsWith(prefix + "lunedi1")){
return message.channel.send("Diritto, 1630027401")
}else if(message.content.startsWith(prefix + "lunedi2")){
return message.channel.send("Italiano, 959924441")
}else if(message.content.startsWith(prefix + "lunedi3")){
return message.channel.send("Italiano, 959924441")
}else if(message.content.startsWith(prefix + "lunedi4")){
return message.channel.send("Fisica LAB, 954071647" )
}else if(message.content.startsWith(prefix + "lunedi5")){
return message.channel.send("Informatica, 1213333512")
}else if(message.content.startsWith(prefix + "martedi1")){
return message.channel.send("Informatica, 1213333512")
}else if(message.content.startsWith(prefix + "martedi2")){
return message.channel.send("Georgrafia, 951609580")
}else if(message.content.startsWith(prefix + "martedi3")){
return message.channel.send("Chimica, 952232255")
}else if(message.content.startsWith(prefix + "martedi4")){
return message.channel.send("Chimica, 952232255")
}else if(message.content.startsWith(prefix + "martedi5")){
return message.channel.send("Inglese, 953894058")
}else if(message.content.startsWith(prefix + "martedi6")){
return message.channel.send("Storia, 959924441")
}else if(message.content.startsWith(prefix + "mercoledi1")){
return message.channel.send("Grafica, 954902455")
}else if(message.content.startsWith(prefix + "mercoledi2")){
return message.channel.send("Italiano, 959924441")
}else if(message.content.startsWith(prefix + "mercoledi3")){
return message.channel.send("Italiano, 959924441")
}else if(message.content.startsWith(prefix + "mercoledi4")){
return message.channel.send("Inglese, 953894058")
}else if(message.content.startsWith(prefix + "mercoledi5")){
return message.channel.send("Inglese, 953894058")
}else if(message.content.startsWith(prefix + "mercoledi6")){
return message.channel.send("Religione, 955444970")
}else if(message.content.startsWith(prefix + "giovedi1")){
return message.channel.send("Matematica, 957066907")
}else if(message.content.startsWith(prefix + "giovedi2")){
return message.channel.send("Matematica, 957066907")
}else if(message.content.startsWith(prefix + "giovedi3")){
return message.channel.send("Grafica, 954902455")
}else if(message.content.startsWith(prefix + "giovedi4")){
return message.channel.send("Grafica, 954902455")
}else if(message.content.startsWith(prefix + "giovedi5")){
return message.channel.send("Scienze della Terra, 1632151557")
}else if(message.content.startsWith(prefix + "venerdi1")){
return message.channel.send("Fisica, 1752593012")
}else if(message.content.startsWith(prefix + "venerdi2")){
return message.channel.send("Fisica, 1752593012")
}else if(message.content.startsWith(prefix + "venerdi3")){
return message.channel.send("Chimica, 952232255")
}else if(message.content.startsWith(prefix + "venerdi4")){
return message.channel.send("Storia, 959924441")
}else if(message.content.startsWith(prefix + "venerdi5")){
return message.channel.send("Educazione fisica, 140876521")
}else if(message.content.startsWith(prefix + "venerdi6")){
return message.channel.send("Educazione fisica, 140876521")
}else if(message.content.startsWith(prefix + "sabato1")){
return message.channel.send("Informatica, 1213333512")
}else if(message.content.startsWith(prefix + "sabato2")){
return message.channel.send("Diritto, 1630027401")
}else if(message.content.startsWith(prefix + "sabato3")){
return message.channel.send("Scienze della Terra, 1632151557")
}else if(message.content.startsWith(prefix + "sabato4")){
return message.channel.send("Matematica, 957066907")
}else if(message.content.startsWith(prefix + "sabato5")){
return message.channel.send("Matematica, 957066907")
}
},
};
As you can see it is really simple but when I want that when I do like ".martedi2" I don't get "Georgrafia, 951609580" but it only works with ".lunedi1", others don't work and like do other 30 commands will be rlly confusing. If you need more info I can give that. Thx to everyone that will help me :)
command name is lunedi1 thats why. other will not work because message content starting does not starts with other, you can use arguments to solve this problem
code:
const Discord = require('discord.js');
const client = new Discord.Client();
const { prefix, token } = require("../config.json");
module.exports = {
name: "info",
description: "Codici videolezioni, li puoi ottenere facendo '.<giorno> <ora>",
execute(message, args) {
if (!args[0]) return message.channel.send("please give name");
if (args[0] === "lunedi1") {
return message.channel.send("Diritto, 1630027401")
} else if (args[0] === "lunedi2") {
return message.channel.send("Italiano, 959924441")
} else {
return message.channel.send("?");
};
}
};
usage:
[Prefix]info
example:
!info lunedi1
you can do this for other.
Links:
Guide For Arguments

I cannot set while to work properly in for loops in ts

I want to get array of arrays with unique values, but at some point
while
gets missed or ignored (I presume because of the asynchronous nature of it). Can someone help with a adding a promise to this, or setting
async/await
structure or giving better advise how to check the arrays. I tried adding
async/await
but I get error and I am not sure where I can add a promise or use it. It is
getSeveralArrays() {
for (let index = 0; index < 50; index++) {
this.getValue();
}
}
getValue() {
this.i++;
this.array = [];
this.randomArray = [];
for (let index = 0; index < 4; index++) {
this.randomValue = this.getRandom();
if (this.array.length === 2) {
while ((this.array[0] === this.randomValue) || (this.array[1] === this.randomValue)) {
this.randomValue = this.getRandom();
}
this.array.push(this.randomValue);
} else if (this.array.length === 3) {
while ((this.array[0] === this.randomValue) || (this.array[1] === this.randomValue) || (this.array[2] === this.randomValue)) {
this.randomValue = this.getRandom();
}
this.array.push(this.randomValue);
} else {
this.array.push(this.randomValue);
}
console.log({...this.array});
this.randomArray.push({ind: this.i, val: this.array});
}
}
getRandom() {
const value = Math.floor(Math.random() * 4);
return value;
}
There is nothing asynchronous in all your code, so no need for async/await. Also, while is not asynchronous.
You were missing a case for the length of 1 though, so the second element could always be the same as the first.
class X {
getSeveralArrays() {
for (let index = 0; index < 50; index++) {
this.getValue();
}
}
getValue() {
this.i++;
this.array = [];
this.randomArray = [];
for (let index = 0; index < 4; index++) {
this.randomValue = this.getRandom();
if (this.array.length === 1) {
while (this.array[0] === this.randomValue) {
this.randomValue = this.getRandom();
}
this.array.push(this.randomValue);
} else if (this.array.length === 2) {
while (this.array[0] === this.randomValue || this.array[1] === this.randomValue) {
this.randomValue = this.getRandom();
}
this.array.push(this.randomValue);
} else if (this.array.length === 3) {
while (
this.array[0] === this.randomValue ||
this.array[1] === this.randomValue ||
this.array[2] === this.randomValue
) {
this.randomValue = this.getRandom();
}
this.array.push(this.randomValue);
} else {
this.array.push(this.randomValue);
}
console.log({ ...this.array });
this.randomArray.push({ ind: this.i, val: this.array });
}
}
getRandom() {
const value = Math.floor(Math.random() * 4);
return value;
}
}
console.log(new X().getSeveralArrays());
Also, all those checks can be simplified:
while (this.array.some(value => value === this.randomValue)) {
this.randomValue = this.getRandom();
}
And generally, just as a small code review: If you do not need to access something from another class method (or somewhere outside), you should not put all those values into class properties, but keep them as values inside your functions.
So this.randomValue and this.array should just be defined within your function with let or const.

Filter for nested objects to return all children elements

I have a filter that is on ng-repeat and compares strings of all objects (including nested ones) to a search string. If the search string is found in the object, it returns true.
I'm looking for a way to extend this functionality so that when the search string matches with a string in the object, the filter will return true for that object and will return true for all nested objects in the matching object (this is a tree view, I'm searching for a node and want to show all children nodes when matched).
How would I do that?
My filter looks like this:
.filter('deepFilter', function ($filter) {
return function(text) {
return function (value) {
if(text && text.length > 0) {
var searchTerm = text;
if (angular.isObject(value)) {
var found = false;
angular.forEach(value, function(v) {
found = found || $filter('deepFilter')(searchTerm)(v);
});
return found;
} else if (angular.isString(value)) {
if (value.indexOf(searchTerm) !== -1) {
return true;
} else {
return false;
}
}
} else {
return true;
}
};
};
});
The solution I found is by using a function in the isString part of the filter, and iterating over the collection. If I find the object, I look for it's children using a recursive function and set a visibleAsAChild property for these. Then, I've added a condition in the isObject evaluation to return true for these object that have visibleAsAChild prop.
I'm not sure if this is the most efficient way to do it, but it certainly works.
.filter('deepFilter', function ($filter) {
var currentObject;
var setChildrenToVisible = function(node) {
angular.forEach(node.nodes, function(node) {
if(node.nodes) {
setChildrenToVisible(node);
}
node.visibleAsAChild = true;
});
};
var lookupChildren = function(o, value) {
// console.log(o);
angular.forEach(o.nodes, function(node) {
if (node.name === value) {
setChildrenToVisible(node);
}
});
};
return function(text) {
return function (value) {
if(text && text.length > 0) {
var searchTerm = text;
if (angular.isObject(value)) {
var found = false;
angular.forEach(value, function(v) {
found = found || $filter('deepFilter')(searchTerm)(v);
});
if(found && value.hasOwnProperty('id')) {
currentObject = value;
}
if(value.hasOwnProperty('id') && value.visibleAsAChild) {
return true;
}
return found;
} else if (angular.isString(value)) {
if (value.indexOf(searchTerm) !== -1) {
if(currentObject){
lookupChildren(currentObject, value);
}
return true;
} else {
return false;
}
}
} else {
return true;
}
};
};

Equivalent of angular.equals in angular2

I am working on migration of angular 1 project to angular 2 . In angular 1 project I was using angular.equals for object comparison angular.equals($ctrl.obj1, $ctrl.newObj); , I searched online for equivalent method in angular 2 but could not find any matching result.
#Günter Yes you are right there is no equivalent in angular2 . While searching more I found third party library lodash which will do same job as angular.equals and syntax is same as angular one and this library solves my problem
Code example from lodash documentation
var object = { 'a': 1 };
var other = { 'a': 1 };
_.isEqual(object, other);
// => true
object === other;
// => false
I rewrote Ariels answer (thank you!) to be TSLINT-friendly. You can also save some continues by using else if, but I think this is more clear. Maybe someone else needs it too:
export function deepEquals(x, y) {
if (x === y) {
return true; // if both x and y are null or undefined and exactly the same
} else if (!(x instanceof Object) || !(y instanceof Object)) {
return false; // if they are not strictly equal, they both need to be Objects
} else if (x.constructor !== y.constructor) {
// they must have the exact same prototype chain, the closest we can do is
// test their constructor.
return false;
} else {
for (const p in x) {
if (!x.hasOwnProperty(p)) {
continue; // other properties were tested using x.constructor === y.constructor
}
if (!y.hasOwnProperty(p)) {
return false; // allows to compare x[ p ] and y[ p ] when set to undefined
}
if (x[p] === y[p]) {
continue; // if they have the same strict value or identity then they are equal
}
if (typeof (x[p]) !== 'object') {
return false; // Numbers, Strings, Functions, Booleans must be strictly equal
}
if (!deepEquals(x[p], y[p])) {
return false;
}
}
for (const p in y) {
if (y.hasOwnProperty(p) && !x.hasOwnProperty(p)) {
return false;
}
}
return true;
}
}
Instead of writing a function to iterate through the objects, you could just use JSON.stringify and compare the two strings?
Example:
var obj1 = {
title: 'title1',
tags: []
}
var obj2 = {
title: 'title1',
tags: ['r']
}
console.log(JSON.stringify(obj1));
console.log(JSON.stringify(obj2));
console.log(JSON.stringify(obj1) === JSON.stringify(obj2));
In Angular 2 you should use pure JavaScript/TypeScript for that so you can add this method to some service
private static equals(x, y) {
if (x === y)
return true;
// if both x and y are null or undefined and exactly the same
if (!(x instanceof Object) || !(y instanceof Object))
return false;
// if they are not strictly equal, they both need to be Objects
if (x.constructor !== y.constructor)
return false;
// they must have the exact same prototype chain, the closest we can do is
// test there constructor.
let p;
for (p in x) {
if (!x.hasOwnProperty(p))
continue;
// other properties were tested using x.constructor === y.constructor
if (!y.hasOwnProperty(p))
return false;
// allows to compare x[ p ] and y[ p ] when set to undefined
if (x[p] === y[p])
continue;
// if they have the same strict value or identity then they are equal
if (typeof (x[p]) !== "object")
return false;
// Numbers, Strings, Functions, Booleans must be strictly equal
if (!RXBox.equals(x[p], y[p]))
return false;
}
for (p in y) {
if (y.hasOwnProperty(p) && !x.hasOwnProperty(p))
return false;
}
return true;
}
You could just copy the original source code from angularjs for the angular.equals function. Usage: equals(obj1, obj2);
var toString = Object.prototype.toString;
function isDefined(value) {return typeof value !== 'undefined';}
function isFunction(value) {return typeof value === 'function';}
function createMap() {
return Object.create(null);
}
function isWindow(obj) {
return obj && obj.window === obj;
}
function isScope(obj) {
return obj && obj.$evalAsync && obj.$watch;
}
function isRegExp(value) {
return toString.call(value) === '[object RegExp]';
}
function simpleCompare(a, b) { return a === b || (a !== a && b !== b); }
function isDate(value) {
return toString.call(value) === '[object Date]';
}
function isArray(arr) {
return Array.isArray(arr) || arr instanceof Array;
}
function equals(o1, o2) {
if (o1 === o2) return true;
if (o1 === null || o2 === null) return false;
// eslint-disable-next-line no-self-compare
if (o1 !== o1 && o2 !== o2) return true; // NaN === NaN
var t1 = typeof o1, t2 = typeof o2, length, key, keySet;
if (t1 === t2 && t1 === 'object') {
if (isArray(o1)) {
if (!isArray(o2)) return false;
if ((length = o1.length) === o2.length) {
for (key = 0; key < length; key++) {
if (!equals(o1[key], o2[key])) return false;
}
return true;
}
} else if (isDate(o1)) {
if (!isDate(o2)) return false;
return simpleCompare(o1.getTime(), o2.getTime());
} else if (isRegExp(o1)) {
if (!isRegExp(o2)) return false;
return o1.toString() === o2.toString();
} else {
if (isScope(o1) || isScope(o2) || isWindow(o1) || isWindow(o2) ||
isArray(o2) || isDate(o2) || isRegExp(o2)) return false;
keySet = createMap();
for (key in o1) {
if (key.charAt(0) === '$' || isFunction(o1[key])) continue;
if (!equals(o1[key], o2[key])) return false;
keySet[key] = true;
}
for (key in o2) {
if (!(key in keySet) &&
key.charAt(0) !== '$' &&
isDefined(o2[key]) &&
!isFunction(o2[key])) return false;
}
return true;
}
}
return false;
}
a = { name: 'me' }
b = { name: 'me' }
a == b // false
a === b // false
JSON.stringify(a) == JSON.stringify(b) // true
JSON.stringify(a) === JSON.stringify(b) // true

Cakephp 2.4.9 authorization problems

I have two roles admin and member
Now I want that the member only can edit his records (Participant), but how I could to that?
And the admin can edit all records from Participant.
public function isAuthorized($user){
if(in_array($this->action, array('edit'))){
if($user['id'] != $this->Session->read('Auth.Participant.user_id')) {
return false;
}
}
return true;
}
But with my function, nobody can do something with edit:(
public function isAuthorized($user) {
// Admin can access every action
if (isset($user['role']) && $user['role'] === 'admin') {
return true;
}
if (isset($user['role']) && $user['role'] === 'member') {
if(in_array($this->action, array('edit'))){
if($user['id'] != $this->Session->read('Auth.Participant.user_id')) {
return false;
}
else{
return true;
}
}
}
//Default deny
return false;
}

Resources