changed constant for config.calls

function for calls (see #24)
re-beautified code
This commit is contained in:
Stephen Vanderwarker 2022-04-29 20:20:34 -04:00
parent 4f8d74c7e3
commit 2462dce4f8
Signed by: stephen
GPG Key ID: EF429EF847868C14

268
index.js
View File

@ -17,7 +17,7 @@ try {
// check if user debugging is enabled // check if user debugging is enabled
const debugging = config.debug; const debugging = config.debug;
// check if user wants phone calls with commands are run // check if user wants phone calls with commands are run
const callme = config.calls; const calls_enabled = config.calls;
// Asterisk config // Asterisk config
const asterisk_callfrom = config.asterisk.callfrom; const asterisk_callfrom = config.asterisk.callfrom;
@ -113,45 +113,59 @@ try {
// setup friends list // setup friends list
const friends = Object.keys(config.friends); const friends = Object.keys(config.friends);
xmpp.on('online', function(data, to) { xmpp.on('online', function (data, to) {
// once we're online, we'll send a message alerting xmpp admins // once we're online, we'll send a message alerting xmpp admins
console.log('Connected with JID: ' + bot_jid); console.log('Connected with JID: ' + bot_jid);
xmpp.send(user_jid, "[ONLINE]", false); xmpp.send(user_jid, "[ONLINE]", false);
// send mqtt online message // send mqtt online message
client.publish(mqtt_topic, mqtt_message); client.publish(mqtt_topic, mqtt_message);
// toot online message // toot online message
/* /*
M.post('statuses', { M.post('statuses', {
status: `${mastodon_toot}` status: `${mastodon_toot}`
}); });
*/ */
}); });
// wait for incoming messages // wait for incoming messages
xmpp.on('chat', function(from, message) { xmpp.on('chat', function (from, message) {
// check for debugging // check for debugging
function call(call_data) {
if (calls_enabled === '1') {
ami.action({
'action': 'originate',
'channel': 'SIP/' + asterisk_callfrom,
'context': asterisk_context,
'callerID': asterisk_callerID,
'data': 'googletts.agi,' + call_data,
'application': 'agi'
});
}
}
function debug() { function debug() {
if (debugging === '1') { if (debugging === '1') {
console.log('[DEBUG]'); console.log('[DEBUG]');
console.log(message); console.log(message);
console.log(from); console.log(from);
}; };
} }
function resError(error,res){
if (!error && res.statusCode == 401) { function resError(error, res) {
console.log('Invalid credentials'); if (!error && res.statusCode == 401) {
xmpp.send(from, 'Invalid credentials'); console.log('Invalid credentials');
} xmpp.send(from, 'Invalid credentials');
if (!error && res.statusCode == 404) { }
console.log('Record not found'); if (!error && res.statusCode == 404) {
xmpp.send(from, 'Record not found'); console.log('Record not found');
} xmpp.send(from, 'Record not found');
if (!error && res.statusCode == 500) { }
console.log('Server error.'); if (!error && res.statusCode == 500) {
xmpp.send(from, 'Server error. Please ping admin'); console.log('Server error.');
} xmpp.send(from, 'Server error. Please ping admin');
}
}; };
// setup gotify url // setup gotify url
let gotifyURL = `${gotify_api_url}/message?token=${gotify_key}&message=${from} ${gotify_message}&title=${gotify_title}&priority=${gotify_priority}`; let gotifyURL = `${gotify_api_url}/message?token=${gotify_key}&message=${from} ${gotify_message}&title=${gotify_title}&priority=${gotify_priority}`;
let gotifyEUrl = encodeURI(gotifyURL); let gotifyEUrl = encodeURI(gotifyURL);
// HELP // HELP
@ -175,7 +189,7 @@ try {
weekday[5] = "Friday"; weekday[5] = "Friday";
weekday[6] = "Saturday"; weekday[6] = "Saturday";
var n = weekday[d.getDay()]; var n = weekday[d.getDay()];
// get latest unlocks // get latest unlocks
request(unlocks_api_url + "?columns=" + n, (error, res, body) => { request(unlocks_api_url + "?columns=" + n, (error, res, body) => {
if (error) { if (error) {
return console.log(error) return console.log(error)
@ -186,54 +200,55 @@ try {
var unlockBodyMatch = body.match(unlockBody); var unlockBodyMatch = body.match(unlockBody);
const unlockFinalMessage = user_name + " has " + unlockBodyMatch[1] + " unlocks for " + n; const unlockFinalMessage = user_name + " has " + unlockBodyMatch[1] + " unlocks for " + n;
xmpp.send(from, unlockFinalMessage); xmpp.send(from, unlockFinalMessage);
call(unlockFinalMessage);
} }
resError(error,res); resError(error, res);
}); });
debug(); debug();
} }
} }
// Toot Unlocks // Toot Unlocks
else if (message === '!tootunlocks') { else if (message === '!tootunlocks') {
if (from != user_jid) { if (from != user_jid) {
xmpp.send(from, pc); xmpp.send(from, pc);
} else { } else {
var d = new Date(); var d = new Date();
var weekday = new Array(7); var weekday = new Array(7);
weekday[0] = "Sunday"; weekday[0] = "Sunday";
weekday[1] = "Monday"; weekday[1] = "Monday";
weekday[2] = "Tuesday"; weekday[2] = "Tuesday";
weekday[3] = "Wednesday"; weekday[3] = "Wednesday";
weekday[4] = "Thursday"; weekday[4] = "Thursday";
weekday[5] = "Friday"; weekday[5] = "Friday";
weekday[6] = "Saturday"; weekday[6] = "Saturday";
var n = weekday[d.getDay()]; var n = weekday[d.getDay()];
// get latest unlocks // get latest unlocks
request(unlocks_api_url + "?columns=" + n, (error, res, body) => { request(unlocks_api_url + "?columns=" + n, (error, res, body) => {
if (error) { if (error) {
return console.log(error) return console.log(error)
}; };
if (!error && res.statusCode == 200) { if (!error && res.statusCode == 200) {
var unlockBody = new RegExp(':(.*)}'); var unlockBody = new RegExp(':(.*)}');
var unlockBodyMatch = body.match(unlockBody); var unlockBodyMatch = body.match(unlockBody);
const unlockFinalMessage = "@" + config.mastodon.user + " has " + unlockBodyMatch[1] + " unlocks for " + n; const unlockFinalMessage = "@" + config.mastodon.user + " has " + unlockBodyMatch[1] + " unlocks for " + n;
M.post('statuses', { M.post('statuses', {
status: unlockFinalMessage status: unlockFinalMessage
});
debug();
}
resError(error,res);
}); });
debug(); debug();
} }
} resError(error, res);
});
debug();
}
}
// Tuya light control // Tuya light control
else if (message === '!lights') { else if (message === '!lights') {
if (from != user_jid) { if (from != user_jid) {
xmpp.send(from, pc); xmpp.send(from, pc);
} else { } else {
// get current light status // get current light status
request(tuya_status_url, (error, res, body) => { request(tuya_status_url, (error, res, body) => {
if (error) { if (error) {
return console.log(error) return console.log(error)
@ -253,7 +268,7 @@ try {
console.log("Tuya API: Unknown reply!"); console.log("Tuya API: Unknown reply!");
} }
} }
resError(error,res); resError(error, res);
}); });
debug(); debug();
} }
@ -261,7 +276,7 @@ try {
if (from != user_jid) { if (from != user_jid) {
xmpp.send(from, pc); xmpp.send(from, pc);
} else { } else {
// refresh tokens for Tuya API // refresh tokens for Tuya API
request(tuya_reauth_url, (error, res, body) => { request(tuya_reauth_url, (error, res, body) => {
if (error) { if (error) {
return console.log(error) return console.log(error)
@ -270,7 +285,7 @@ try {
if (!error && res.statusCode == 200) { if (!error && res.statusCode == 200) {
xmpp.send(from, 'Refreshing Tuya API auth keys'); xmpp.send(from, 'Refreshing Tuya API auth keys');
} }
resError(error,res); resError(error, res);
}); });
debug(); debug();
} }
@ -278,7 +293,7 @@ try {
if (from != user_jid) { if (from != user_jid) {
xmpp.send(from, pc); xmpp.send(from, pc);
} else { } else {
// turn on light // turn on light
request(tuya_toggle_url + "?stat=true&devname=" + tuya_name, (error, res, body) => { request(tuya_toggle_url + "?stat=true&devname=" + tuya_name, (error, res, body) => {
if (error) { if (error) {
return console.log(error) return console.log(error)
@ -289,7 +304,7 @@ try {
xmpp.send(from, stat); xmpp.send(from, stat);
console.log(stat); console.log(stat);
} }
resError(error,res); resError(error, res);
}); });
debug(); debug();
} }
@ -297,7 +312,7 @@ try {
if (from != user_jid) { if (from != user_jid) {
xmpp.send(from, pc); xmpp.send(from, pc);
} else { } else {
// turn off light // turn off light
request(tuya_toggle_url + "?stat=false&devname=" + tuya_name, (error, res, body) => { request(tuya_toggle_url + "?stat=false&devname=" + tuya_name, (error, res, body) => {
if (error) { if (error) {
return console.log(error) return console.log(error)
@ -307,7 +322,7 @@ try {
xmpp.send(from, stat); xmpp.send(from, stat);
console.log(stat); console.log(stat);
} }
resError(error,res); resError(error, res);
}); });
debug(); debug();
} }
@ -317,7 +332,7 @@ try {
} else { } else {
var per = message.substring(message.indexOf("brightness") + 10); var per = message.substring(message.indexOf("brightness") + 10);
var perc = (per * 10) var perc = (per * 10)
// get brightness of light // get brightness of light
request(tuya_bright_url + "?brite=" + perc + "&devname=" + tuya_name, (error, res, body) => { request(tuya_bright_url + "?brite=" + perc + "&devname=" + tuya_name, (error, res, body) => {
if (error) { if (error) {
return console.log(error) return console.log(error)
@ -326,7 +341,7 @@ try {
if (!error && res.statusCode == 200) { if (!error && res.statusCode == 200) {
xmpp.send(from, tuya_name + " set to " + per + "%"); xmpp.send(from, tuya_name + " set to " + per + "%");
} }
resError(error,res); resError(error, res);
}); });
if (config.debug === '1') { if (config.debug === '1') {
console.log('lights turned to ' + per + "%"); console.log('lights turned to ' + per + "%");
@ -336,7 +351,7 @@ try {
if (from != user_jid) { if (from != user_jid) {
xmpp.send(from, pc); xmpp.send(from, pc);
} else { } else {
// change light color // change light color
request(tuya_toggle_url + "?stat=true&devname=" + tuya_name, (error, res, body) => {}) request(tuya_toggle_url + "?stat=true&devname=" + tuya_name, (error, res, body) => {})
var color = message.substring(message.indexOf("color") + 6); var color = message.substring(message.indexOf("color") + 6);
var colorRgb = rgbcolor(color); var colorRgb = rgbcolor(color);
@ -354,7 +369,7 @@ try {
xmpp.send(from, tuya_name + "set to " + color); xmpp.send(from, tuya_name + "set to " + color);
console.log(tuya_name + "set to " + color); console.log(tuya_name + "set to " + color);
} }
resError(error,res); resError(error, res);
}); });
if (config.debug === '1') { if (config.debug === '1') {
console.log(tuya_name + "set to " + color); console.log(tuya_name + "set to " + color);
@ -363,27 +378,21 @@ try {
} }
// Ping a user to let them know you would like to communicate // Ping a user to let them know you would like to communicate
else if (message === '!ping') { else if (message === '!ping') {
// send xmpp ping message to message author // send xmpp ping message to message author
xmpp.send(from, "Pinging " + user_name + "! Please stand by."); xmpp.send(from, "Pinging " + user_name + "! Please stand by.");
// send xmpp ping message to admin // send xmpp ping message to admin
xmpp.send(user_jid, from + " has pinged you!"); xmpp.send(user_jid, from + " has pinged you!");
// send mqtt ping message // send mqtt ping message
client.publish(mqtt_topic, from + ' has pinged you!'); client.publish(mqtt_topic, from + ' has pinged you!');
// set gotify ping message to admin // set gotify ping message to admin
request.post(gotifyEUrl, function(err, response, body) { request.post(gotifyEUrl, function (err, response, body) {
if (err) { if (err) {
console.log('error:', err); console.log('error:', err);
} }
}); });
// call admin alerting of authors ping // call admin alerting of authors ping
ami.action({ call_data = "hello. " + from + " has pinged you!"
'action': 'originate', call(call_data);
'channel': 'SIP/' + asterisk_callfrom,
'context': asterisk_context,
'callerID': asterisk_callerID,
'data': 'googletts.agi, \"hello. ' + from + ' has pinged you!\"',
'application': 'agi'
});
debug(); debug();
} }
@ -392,32 +401,24 @@ try {
if (from != user_jid) { if (from != user_jid) {
xmpp.send(from, pc); xmpp.send(from, pc);
} else { } else {
// check current weather // check current weather
request(weather_url, function(err, response, body) { request(weather_url, function (err, response, body) {
if (err) { if (err) {
console.log('error:', err); console.log('error:', err);
} else { } else {
let w = JSON.parse(body); let w = JSON.parse(body);
let wm = weather_city_name + " Weather: Tempature: " + w.main.temp + " degrees. Conditions: " + w.weather[0].main + ". Pressure: " + let wm = weather_city_name + " Weather: Tempature: " + w.main.temp + " degrees. Conditions: " + w.weather[0].main + ". Pressure: " +
w.main.pressure + ". Wind Direction: " + getDirection(w.wind.deg) + ". Wind Speed: " + w.wind.speed + " miles per hour \r\n"; w.main.pressure + ". Wind Direction: " + getDirection(w.wind.deg) + ". Wind Speed: " + w.wind.speed + " miles per hour \r\n";
// send weather to mqtt // send weather to mqtt
client.publish('weather/temp', '' + w.main.temp + ''); client.publish('weather/temp', '' + w.main.temp + '');
client.publish('weather/conditions', '' + w.weather[0].main + ''); client.publish('weather/conditions', '' + w.weather[0].main + '');
client.publish('weather/pressure', '' + w.main.pressure + ''); client.publish('weather/pressure', '' + w.main.pressure + '');
client.publish('weather/wind/direction', '' + getDirection(w.wind.deg) + ''); client.publish('weather/wind/direction', '' + getDirection(w.wind.deg) + '');
client.publish('weather/wind/speed', '' + w.wind.speed + ''); client.publish('weather/wind/speed', '' + w.wind.speed + '');
// send weather to xmpp admin // send weather to xmpp admin
xmpp.send(from, wm); xmpp.send(from, wm);
// call admin with latest weather report // call admin with latest weather report
ami.action({ call(wm);
'action':'originate',
'channel':'SIP/' + asterisk_callfrom,
'context': asterisk_context,
'callerID' : asterisk_callerID,
'data': 'googletts.agi,' + wm,
'application': 'agi'
});
} }
}); });
debug(); debug();
@ -431,17 +432,16 @@ try {
} }
// Share-A-Command which was #13, but kinda turned into a different command // Share-A-Command which was #13, but kinda turned into a different command
// This will generate a private channel, and add the users in the friends // This will generate a private channel, and add the users in the friends
// secion from config.ini // secion from config.ini
// Please note this section requires you to have an Ejabberd server. // Please note this section requires you to have an Ejabberd server.
// I am welcome to pull requests for other servers (maybe set type in config.ini) // I am welcome to pull requests for other servers (maybe set type in config.ini)
else if (message === '!meet') { else if (message === '!meet') {
if (from != user_jid) { if (from != user_jid) {
xmpp.send(from, pc); xmpp.send(from, pc);
} else { } else {
// Create private XMPP room // Create private XMPP room
const createRoom = { const createRoom = {
method: 'POST', method: 'POST',
url: xmpp_api_url + '/create_room_with_opts', url: xmpp_api_url + '/create_room_with_opts',
@ -471,18 +471,18 @@ try {
}, },
json: true json: true
}; };
// send request to create room // send request to create room
request(createRoom, function(error, response, body) { request(createRoom, function (error, response, body) {
if (error) throw new Error(error); if (error) throw new Error(error);
console.log(body); console.log(body);
}); });
// wait 2 seconds until room has been created (http issues) // wait 2 seconds until room has been created (http issues)
setTimeout(() => { setTimeout(() => {
// loop through friends, authorize users, and send invites // loop through friends, authorize users, and send invites
for (const key in config.friends) { for (const key in config.friends) {
// send xmpp message to friends alerting of new room // send xmpp message to friends alerting of new room
xmpp.send(key, "Meeting started"); xmpp.send(key, "Meeting started");
// authorize users // authorize users
const addMember = { const addMember = {
method: 'POST', method: 'POST',
url: xmpp_api_url + 'set_room_affiliation', url: xmpp_api_url + 'set_room_affiliation',
@ -498,7 +498,7 @@ try {
}, },
json: true json: true
}; };
// invite users // invite users
const inviteMember = { const inviteMember = {
method: 'POST', method: 'POST',
url: xmpp_api_url + '/send_direct_invitation', url: xmpp_api_url + '/send_direct_invitation',
@ -515,11 +515,11 @@ try {
}, },
json: true json: true
}; };
request(addMember, function(error, response, body) { request(addMember, function (error, response, body) {
if (error) throw new Error(error); if (error) throw new Error(error);
console.log(body); console.log(body);
}); });
request(inviteMember, function(error, response, body) { request(inviteMember, function (error, response, body) {
if (error) throw new Error(error); if (error) throw new Error(error);
console.log(body); console.log(body);
}); });
@ -534,7 +534,7 @@ try {
if (from != user_jid) { if (from != user_jid) {
xmpp.send(from, pc); xmpp.send(from, pc);
} else { } else {
// end meeting (delete private xmpp room) // end meeting (delete private xmpp room)
const endMeeting = { const endMeeting = {
method: 'POST', method: 'POST',
url: xmpp_api_url + '/destroy_room', url: xmpp_api_url + '/destroy_room',
@ -548,13 +548,13 @@ try {
}, },
json: true json: true
}; };
// send room delete request // send room delete request
request(endMeeting, function(error, response, body) { request(endMeeting, function (error, response, body) {
if (error) throw new Error(error); if (error) throw new Error(error);
console.log(body); console.log(body);
}); });
for (const key in config.friends) { for (const key in config.friends) {
// alert friends meeting has ended // alert friends meeting has ended
xmpp.send(key, "Meeting ended"); xmpp.send(key, "Meeting ended");
} }
} }
@ -565,12 +565,12 @@ try {
else if (message === "sudo shutdown now -h") { else if (message === "sudo shutdown now -h") {
if (from != user_jid) { if (from != user_jid) {
xmpp.send(from, from + " is not in the sudoers file. This incident will be reported."); xmpp.send(from, from + " is not in the sudoers file. This incident will be reported.");
console.log(from + ' tried to shut me down!'); console.log(from + ' tried to shut me down!');
} else { } else {
// send shutdown message // send shutdown message
xmpp.send(from, "Alrighty, shutting down. Goodbye!"); xmpp.send(from, "Alrighty, shutting down. Goodbye!");
debug(); debug();
// kill bot // kill bot
process.exit(1); process.exit(1);
} }
} }
@ -580,8 +580,8 @@ try {
if (from != user_jid) { if (from != user_jid) {
xmpp.send(from, pc); xmpp.send(from, pc);
} else { } else {
// get user_jid vcard (profile info) // get user_jid vcard (profile info)
xmpp.getVCard(from, function(vcard) { xmpp.getVCard(from, function (vcard) {
xmpp.send(from, vcard); xmpp.send(from, vcard);
console.log(vcard) console.log(vcard)
}) })
@ -596,7 +596,7 @@ try {
}); });
// Catch and log XMPP errors // Catch and log XMPP errors
xmpp.on('error', function(err) { xmpp.on('error', function (err) {
console.error(err); console.error(err);
}); });
@ -610,21 +610,21 @@ try {
host: bot_hostname, host: bot_hostname,
port: bot_port port: bot_port
}); });
// subscribe to friends // subscribe to friends
xmpp.on('subscribe', function(from) { xmpp.on('subscribe', function (from) {
if (from in config.friends == true) { if (from in config.friends == true) {
console.log('accepting subsciption request from ' + from); console.log('accepting subsciption request from ' + from);
// accept pending subscription requests // accept pending subscription requests
xmpp.acceptSubscription(from); xmpp.acceptSubscription(from);
// check for incoming subscription requests // check for incoming subscription requests
xmpp.getRoster(); xmpp.getRoster();
// subscribe to any incoming subscription requests // subscribe to any incoming subscription requests
console.log('requesting subscription to ' + from); console.log('requesting subscription to ' + from);
xmpp.subscribe(from); xmpp.subscribe(from);
} else { } else {
console.log('denied subscription request from: ' + from + " as they are not in the friends section of config.ini"); console.log('denied subscription request from: ' + from + " as they are not in the friends section of config.ini");
} }
}); });
} catch (e) { } catch (e) {
console.log("Please create a config.ini"); console.log("Please create a config.ini");