Node module.exports pattern - Is this correct? - javascript

I'm new to JS and I am currently working on an IRC bot. I have produced the following module which I want to use for creating bot commands.
/***
* Module contains available bot commands including
* access levels to view/utilise command and help text.
*
* Usage example: commands.tg.play(payload);
*
***/
module.exports = commands = {
tg: {
reg: '^[. - !]tg',
help: 'some help text for tg',
play: function(payload){tg(payload);}
},
help: {
reg: '^[. - !]help',
description: 'some help text for intel',
play: function(payload){help(payload);}
}
};
function tg(payload){
//Example: msg_route: pm msg_from: munkee msg_data: .tg munkee testing message via tg command msg_match: .tg msg_method: .
console.log("msg_route:" + payload.msg_route + ' msg_from: ' + payload.msg_from + ' msg_data: ' + payload.msg_data + ' msg_match: ' + payload.msg_match + ' msg_method: ' + payload.msg_method);
return;
}
function help(payload){
var output='Available commands: ';
for (var i in commands){
output=output+ ' ' + i.toString();
}
return console.log(output);
}
As you can see I am currently defining some methods within my commands object. In order to try and keep things a bit cleaner I define the functions to actually be run below the commands object. I can access these easily via commands.help.play(payload). However I wanted to know whether there is a better way to do this or is the direction I am going correct? At the moment the commands are very skeleton and will be carrying out quite a bit more work but I just wanted to post something to give the general idea.

I don't like the extra fn call you're making: play:function(payload){tg(payload);} should be just play:tg since functions are first-order citizens in js. I do also prefer to assign to module.exports at the end of the file.
/***
* Module contains available bot commands including
* access levels to view/utilise command and help text.
*
* Usage example: commands.tg.play(payload);
*
***/
var commands = {};
function tg(payload){
//Example: msg_route: pm msg_from: munkee msg_data: .tg munkee testing message via tg command msg_match: .tg msg_method: .
console.log("msg_route:" + payload.msg_route + ' msg_from: ' + payload.msg_from + ' msg_data: ' + payload.msg_data + ' msg_match: ' + payload.msg_match + ' msg_method: ' + payload.msg_method);
return;
}
function help(payload){
var output='Available commands: ';
for (var i in commands){
output=output+ ' ' + i.toString();
}
return console.log(output);
}
// export
module.exports = commands = {
tg: {
reg: '^[. - !]tg',
help: 'some help text for tg',
play: tg;
},
help: {
reg: '^[. - !]help',
description: 'some help text for intel',
play: help}
}
};

It is about my personal prefrence but i will go for this one. Singleton pattern with Constructor
function Commands(){
this.commands = {};
this.tg = function (payload){
//Example: msg_route: pm msg_from: munkee msg_data: .tg munkee testing message via tg command msg_match: .tg msg_method: .
console.log("msg_route:" + payload.msg_route + ' msg_from: ' + payload.msg_from + ' msg_data: ' + payload.msg_data + ' msg_match: ' + payload.msg_match + ' msg_method: ' + payload.msg_method);
return;
};
this.help = function (payload){
var output='Available commands: ';
for (var i in commands){
output=output+ ' ' + i.toString();
}
}
this.commands.tg= {
reg: '^[. - !]tg',
help: 'some help text for tg',
play: this.tg
};
this.commands.help= {
reg: '^[. - !]help',
description: 'some help text for intel',
play: this.help
};
}
if(!!obj)
obj = new Commands();
module.exports = obj;

Related

TypeError: makeUser is not a function discord js V12

(node:9436) UnhandledPromiseRejectionWarning: TypeError: makeUser is not a function
Hello I tried to make a command for when the person does the command automatically adds 1 line in a cfg called users.json but this gives me this error.
Again, as I was updating my bot to discord.js V12 I got an error:
TypeError: makeUser is not a function
Here is a part the code:
if (!config.servers.servidores.includes(args[4])) {
console.log(yellow + "[" + moment.tz("America/Sao_Paulo").format('HH:mm A') + "] " + red + `[DB]` + reset + ` ${msg.author.username} ` + l7yellow + `->` + lightred + ` Configuração Errada` + reset + ` Status: ` + red + `Servidor` + reset)
const metodoembed = new Discord.RichEmbed()
.setColor("#ff0000")
.setTitle("Database Editor -> Atom")
.setDescription("An `error` was identified when\nmodifying the database.")
.addField('**Type:**', '```http\n' + 'Server' + '```', true)
.addField('Solution:', 'Check the available\nservers in the database', true)
.setThumbnail(`${msg.author.displayAvatarURL}`)
.setTimestamp()
.setFooter(`${msg.author.username}`, `${msg.author.displayAvatarURL}`);
return msg.channel.send(metodoembed); }
//
function updategive(file, json) {
fs.writeFile(file, JSON.stringify(json, null, 2), "utf8", function(err) {
console.log(purple + "[" + reset + moment.tz("America/Sao_Paulo").format('HH:mm A') + purple + "] " + `[🧮] Banco de Dados atualizado.`);
});
}
if (!users[person]) {
makeUser(person);
}
users[person].attackTime = time;
users[person].concurrents = conc;
users[person].servers = servers;
users[person].expire = moment(expire).unix();
updategive("users.json", users);
return msg.channel.send(responsegive);
}
The error is occuring in this line:
if (!users[person]) {
makeUser(person);
}
Hello seems like you are using a function that is not existing. Create a function with the name makeUser and the parameter user. So it should look like this function makeUser(user) {...}.
Also if you are using discord.js v12, make sure you replace RichEmbed with MessageEmbed.

Can't attach frida function to android native lib function

I'm building a frida js script that reads a json object containing directives to where to attach frida functions inside a native lib in an android APK. If I hardcode the libname and function name I can successfully attach to the function when it runs inside the app but for some reason I don't know why when I read the names from the json object the attachment doesn't occur. Assuming that I want to attach to a function named Java_sg_vantagepoint_uncrackable3_CodeCheck_bar inside libfoo.so.
The code that runs successfully:
Interceptor.attach(Module.findExportByName("libfoo.so", "Java_sg_vantagepoint_uncrackable3_CodeCheck_bar"), {
onEnter: function(args){
console.log('libfoo.so::Java_sg_vantagepoint_uncrackable3_CodeCheck_bar')
// this is logged when the function runs in the APP
if(args){
for(var arg in args){
console.log('args[' + arg + ']:')
console.log('Java_sg_vantagepoint_uncrackable3_CodeCheck_bar::args[arg] ' + args[arg])}
}
},
onLeave: function(args){
console.log('Leaving Java_sg_vantagepoint_uncrackable3_CodeCheck_bar...')
}
}
)
The code that doesn't work:
var params = {
"libs": ["libfoo.so"]
}
for(var lib in params.libs)
{
const currentLib = params.libs[lib]
Module.ensureInitialized(currentLib)
console.log('current lib: ' + currentLib)
var libExports = Module.load(currentLib).enumerateExports()
for(var i in libExports)
{
var currentLibExport = libExports[i]
if(currentLibExport.name.toLowerCase().includes('java'))
{
console.log('attaching to export: ' + currentLib + '::' + currentLibExport.name + ' at address: ' + currentLibExport.address)
Interceptor.attach(currentLibExport.address, {
onEnter: function(args){
console.log('onEnter ' + currentLib + '::' + currentLibExport.name)
if(args){
for(var arg in args){
console.log(currentLib + '::' + currentLibExport.name + '::args[arg] ' + args[arg])
}
} else
{
console.log('no args for ' + currentLib + '::' + currentLibExport.name)
}
},
onLeave: function(args){
console.log('onLeave ' + currentLib + '::' + currentLibExport.name )
}
}
)
}
}
}
Not only this doesn't attach to the function named Java_sg_vantagepoint_uncrackable3_CodeCheck_bar but even stranger during runtime it is logged the following:
onEnter libfoo.so::main
onLeave libfoo.so::main
which for me makes no sense because I didn't attach to the main function
Reference: https://www.frida.re/docs/javascript-api/#module

Cannot read property 'toUpperCase' of null (Google Chrome)

So I'm trying to run a simple "conditional statement exercise" with a few questions, but in my Google Chrome it keeps giving me an error. Other applications aren't giving me any errors. I also have the most updated version of Google Chrome
Warning the js is going to launch when you go to the link
Check out my js fiddle
var counter = 0;
var questions = 5;
var ready = false;
alert("I have " + questions + " questions to ask you?");
var name = prompt("What is your name?");
alert("Hello " + name + "!");
alert("Here we go!");
var answer1 = prompt(name + "What color is the sky?");
if (answer1.toUpperCase() === 'BLUE') {
counter += 1;
alert('Congrates ' + name + ' you were right!');
} else {
alert('Sorry' + ' ' + name + 'but that was wrong.');
}
I'm not seeing that error. You can try wrapping that conditional in a value check conditional:
var answer1 = prompt(name + "What color is the sky?");
if (answer1) {
if (answer1.toUpperCase() === 'BLUE') {
counter += 1;
alert('Congrates ' + name + ' you were right!');
} else {
alert('Sorry' + ' ' + name + 'but that was wrong.');
}
}

$.post and $.get only letting title be changed, not logging?

In the following snippet of my code, I post to a link, from which it allows me to change the title, but will not call the function info() with the argument supplied, nor will it log in the console, please help with this code, thanks. Also, please note all the variables are defined and this code works 100% besides this, and it won't work with $.get rather than $.post either.
function info(text, state) {
$("<h4>"+text+"</h4>").appendTo("body");
if (state != "run") {
$("h2").text(text).fadeIn("slow").delay(30000).fadeOut();
}
$.post(buy, function(r) {
diff = event.timeStamp - last;
$(document).prop('title', 'Purchased '+info['itemName']+'!');
info('Purchased '+info['itemName']+' for '+info['expectedPrice']+' in '+diff+' milliseconds!');
console.log('Purchased '+info['itemName']+' for '+info['expectedPrice']+' in '+diff+' milliseconds!');
})
--EDIT--
If I put console.log above info, the code works excluding the info() function, so the problem is possibly there
Try (this pattern)
// var last = $.now();
function info(text, state) {
$("<h4>" + text + "</h4>").appendTo("body");
if (state != "run") {
$("h2").text(text).fadeIn("slow").delay(30000).fadeOut();
}
// missing closing `{` at OP
};
$.post(buy, function (_info) {
// `_info` : return json object
// `info` : function declaration name
// diff = $.now() - last;
$(document).prop('title', 'Purchased ' + _info['itemName'] + '!');
info('Purchased '
+ _info['itemName'] + ' for '
+ _info['expectedPrice'] + ' in '
+ diff + ' milliseconds!'
, "run");
console.log('Purchased '
+ _info['itemName'] + ' for '
+ _info['expectedPrice'] + ' in '
+ diff + ' milliseconds!');
});
jsfiddle http://jsfiddle.net/guest271314/7vxb7336/

Sharepoint 2013 Access denied. You do not have permission to perform this action or access this resource. - get_siteGroups()

Here is my Javascript code to get all the users from a sharepoint 2013 (office 365). But I get a error what I don't have permissions. Am I missing a trick?
It is used in a sharepoint hosted APP.
function retrieveAllUsersAllGroups() {
var clientContext = Context;
this.collGroup = clientContext.get_web().get_siteGroups();
clientContext.load(collGroup);
clientContext.load(collGroup, 'Include(Users)');
clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
}
function onQuerySucceeded() {
var userInfo = '';
var groupEnumerator = collGroup.getEnumerator();
while (groupEnumerator.moveNext()) {
var oGroup = groupEnumerator.get_current();
var collUser = oGroup.get_users();
var userEnumerator = collUser.getEnumerator();
while (userEnumerator.moveNext()) {
var oUser = userEnumerator.get_current();
this.userInfo += '\nGroup ID: ' + oGroup.get_id() +
'\nGroup Title: ' + oGroup.get_title() +
'\nUser: ' + oUser.get_title() +
'\nLogin Name: ' + oUser.get_loginName();
}
}
alert(userInfo);
}
function onQueryFailed(sender, args) {
alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}
Use PersonProperties object to get info about SharePoint users, such as display name, email, title, and other business and personal information.

Categories

Resources