init commit

This commit is contained in:
zino
2021-02-16 23:07:41 +01:00
parent ec3fc78e0f
commit 12b4ef5db4
5000 changed files with 2596132 additions and 0 deletions

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,358 @@
/*
* Copyright (C) 2016-2020 phantombot.github.io/PhantomBot
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* commandCoolDown.js
*
* Manage cooldowns for commands
*
* To use the cooldown in other scipts use the $.coolDown API
*/
(function() {
var defaultCooldownTime = $.getSetIniDbNumber('cooldownSettings', 'defaultCooldownTime', 5),
modCooldown = $.getSetIniDbBoolean('cooldownSettings', 'modCooldown', false),
defaultCooldowns = {},
cooldowns = {};
$.raffleCommand = null;
/*
* @class Cooldown
*
* @param {String} command
* @param {Number} seconds
* @param {Boolean} isGlobal
*/
function Cooldown(command, seconds, isGlobal) {
this.isGlobal = isGlobal;
this.command = command;
this.seconds = seconds;
this.cooldowns = [];
this.time = 0;
}
/*
* @function loadCooldowns
*/
function loadCooldowns() {
var commands = $.inidb.GetKeyList('cooldown', ''),
json,
i;
for (i in commands) {
json = JSON.parse($.inidb.get('cooldown', commands[i]));
cooldowns[commands[i]] = new Cooldown(json.command, json.seconds, json.isGlobal.toString().equals('true'));
}
}
/*
* @function canIgnore
*
* @param {String} username
* @param {Boolean} isMod
* @return {Boolean}
*/
function canIgnore(username, isMod) {
return (!modCooldown && isMod) || $.isAdmin(username);
}
/*
* @function isSpecial
*
* @param {String} command
* @return {Boolean}
*/
function isSpecial(command) {
return command == 'bet' ||
command == 'tickets' ||
command == 'bid' ||
command == 'adventure' ||
command == 'vote' ||
command == 'joinqueue' ||
command == $.raffleCommand;
}
/*
* @function get
*
* @export $.coolDown
* @param {String} command
* @param {String} username
* @param {Boolean} isMod
* @return {Number}
*/
function get(command, username, isMod) {
var cooldown = cooldowns[command];
if (isSpecial(command)) {
if (command == 'adventure' && defaultCooldowns[command] !== undefined && defaultCooldowns[command] > $.systemTime()) {
return defaultCooldowns[command];
} else {
return 0;
}
} else {
if (cooldown !== undefined && cooldown.seconds > 0) {
if (cooldown.isGlobal) {
if (cooldown.time > $.systemTime()) {
return (canIgnore(username, isMod) ? 0 : cooldown.time);
} else {
return set(command, true, cooldown.seconds, isMod);
}
} else {
if (cooldown.cooldowns[username] !== undefined && cooldown.cooldowns[username] > $.systemTime()) {
return (canIgnore(username, isMod) ? 0 : cooldown.cooldowns[username]);
} else {
return set(command, true, cooldown.seconds, isMod, username);
}
}
} else {
if (defaultCooldowns[command] !== undefined && defaultCooldowns[command] > $.systemTime()) {
return (canIgnore(username, isMod) ? 0 : defaultCooldowns[command]);
} else {
return set(command, false, defaultCooldownTime, isMod);
}
}
}
}
/*
* @function getSecs
*
* @export $.coolDown
* @param {String} command
* @param {String} username
* @return {Number}
*/
function getSecs(username, command, isMod) {
var cooldown = cooldowns[command];
if (cooldown !== undefined && cooldown.seconds > 0) {
if (cooldown.isGlobal) {
if (cooldown.time > $.systemTime()) {
return (cooldown.time - $.systemTime() > 1000 ? Math.ceil(((cooldown.time - $.systemTime()) / 1000)) : 1);
} else {
return set(command, true, cooldown.seconds, isMod);
}
} else {
if (cooldown.cooldowns[username] !== undefined && cooldown.cooldowns[username] > $.systemTime()) {
return (cooldown.cooldowns[username] - $.systemTime() > 1000 ? Math.ceil(((cooldown.cooldowns[username] - $.systemTime()) / 1000)) : 1);
}
}
} else {
if (defaultCooldowns[command] !== undefined && defaultCooldowns[command] > $.systemTime()) {
return (defaultCooldowns[command] - $.systemTime() > 1000 ? Math.ceil(((defaultCooldowns[command] - $.systemTime()) / 1000)) : 1);
} else {
return set(command, false, defaultCooldownTime, isMod);
}
}
return 0;
}
/*
* @function set
*
* @export $.coolDown
* @param {String} command
* @param {Boolean} hasCooldown
* @param {Number} seconds
* @param {Boolean} isMod
* @param {String} username
* @return {Number}
*/
function set(command, hasCooldown, seconds, isMod, username) {
seconds = (seconds > 0 ? ((parseInt(seconds) * 1e3) + $.systemTime()) : 0);
if (hasCooldown) {
if (username === undefined) {
cooldowns[command].time = seconds;
} else {
cooldowns[command].cooldowns[username] = seconds;
}
} else {
defaultCooldowns[command] = seconds;
}
return 0;
}
/*
* @function add
*
* @export $.coolDown
* @param {String} command
* @param {Number} seconds
* @param {Boolean} isGlobal
*/
function add(command, seconds, isGlobal) {
// Make sure we have the right type.
if (typeof seconds !== 'number') {
seconds = (parseInt(seconds + ''));
}
if (cooldowns[command] === undefined) {
cooldowns[command] = new Cooldown(command, seconds, isGlobal);
$.inidb.set('cooldown', command, JSON.stringify({
command: String(command),
seconds: String(seconds),
isGlobal: String(isGlobal)
}));
} else {
cooldowns[command].isGlobal = isGlobal;
cooldowns[command].seconds = seconds;
$.inidb.set('cooldown', command, JSON.stringify({
command: String(command),
seconds: String(seconds),
isGlobal: String(isGlobal)
}));
}
}
/*
* @function remove
*
* @export $.coolDown
* @param {String} command
*/
function remove(command) {
$.inidb.del('cooldown', command);
if (cooldowns[command] !== undefined) {
delete cooldowns[command];
}
}
/*
* @function clear
*
* @export $.coolDown
* @param {String} command
*/
function clear(command) {
if (cooldowns[command] !== undefined) {
cooldowns[command].time = 0;
}
}
/*
* @event command
*/
$.bind('command', function(event) {
var sender = event.getSender(),
command = event.getCommand(),
args = event.getArgs(),
action = args[0],
subAction = args[1],
actionArgs = args[2];
/*
* @commandpath coolcom [command] [seconds] [type (global / user)] - Sets a cooldown for a command, default is global. Using -1 for the seconds removes the cooldown.
*/
if (command.equalsIgnoreCase('coolcom')) {
if (action === undefined || isNaN(parseInt(subAction))) {
$.say($.whisperPrefix(sender) + $.lang.get('cooldown.coolcom.usage'));
return;
}
actionArgs = (actionArgs !== undefined && actionArgs == 'user' ? false : true);
action = action.replace('!', '').toLowerCase();
subAction = parseInt(subAction);
if (subAction > -1) {
$.say($.whisperPrefix(sender) + $.lang.get('cooldown.coolcom.set', action, subAction));
add(action, subAction, actionArgs);
} else {
$.say($.whisperPrefix(sender) + $.lang.get('cooldown.coolcom.remove', action));
remove(action);
}
clear(command);
return;
}
if (command.equalsIgnoreCase('cooldown')) {
if (action === undefined) {
$.say($.whisperPrefix(sender) + $.lang.get('cooldown.cooldown.usage'));
return;
}
/*
* @commandpath cooldown togglemoderators - Toggles if moderators ignore command cooldowns.
*/
if (action.equalsIgnoreCase('togglemoderators')) {
modCooldown = !modCooldown;
$.setIniDbBoolean('cooldownSettings', 'modCooldown', modCooldown);
$.say($.whisperPrefix(sender) + $.lang.get('cooldown.set.togglemodcooldown', (modCooldown ? $.lang.get('common.enabled') : $.lang.get('common.disabled'))));
return;
}
/*
* @commandpath cooldown setdefault [seconds] - Sets a default global cooldown for commands without a cooldown.
*/
if (action.equalsIgnoreCase('setdefault')) {
if (isNaN(parseInt(subAction))) {
$.say($.whisperPrefix(sender) + $.lang.get('cooldown.default.usage'));
return;
} else if (parseInt(subAction) < 5) {
$.say($.whisperPrefix(sender) + $.lang.get('cooldown.coolcom.err'));
return;
}
defaultCooldownTime = parseInt(subAction);
$.setIniDbNumber('cooldownSettings', 'defaultCooldownTime', defaultCooldownTime);
$.say($.whisperPrefix(sender) + $.lang.get('cooldown.default.set', defaultCooldownTime));
}
}
});
/*
* @event initReady
*/
$.bind('initReady', function() {
$.registerChatCommand('./core/commandCoolDown.js', 'coolcom', 1);
$.registerChatCommand('./core/commandCoolDown.js', 'cooldown', 1);
$.registerChatSubcommand('cooldown', 'togglemoderators', 1);
$.registerChatSubcommand('cooldown', 'setdefault', 1);
loadCooldowns();
});
/*
* @event webPanelSocketUpdate
*/
$.bind('webPanelSocketUpdate', function(event) {
if (event.getScript().equalsIgnoreCase('./core/commandCoolDown.js')) {
if (event.getArgs()[0] == 'add') {
add(event.getArgs()[1], event.getArgs()[2], event.getArgs()[3].equals('true'));
} else if (event.getArgs()[0] == 'update') {
defaultCooldownTime = $.getIniDbNumber('cooldownSettings', 'defaultCooldownTime', 5);
modCooldown = $.getIniDbBoolean('cooldownSettings', 'modCooldown', false);
} else {
remove(event.getArgs()[1]);
}
}
});
/* Export to the $. API */
$.coolDown = {
remove: remove,
clear: clear,
get: get,
set: set,
add: add,
getSecs: getSecs
};
})();

View File

@@ -0,0 +1,114 @@
/*
* Copyright (C) 2016-2020 phantombot.github.io/PhantomBot
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* commandPause.js
*
* Pause using ANY command
*/
(function() {
var isActive = $.getSetIniDbBoolean('commandPause', 'commandsPaused', false),
defaultTime = $.getSetIniDbNumber('commandPause', 'defaultTime', 300),
timerId = -1;
/**
* @function pause
* @export $.commandPause
* @param {Number} [seconds]
*/
function pause(seconds) {
seconds = (seconds ? seconds : defaultTime);
if (isActive) {
clearTimeout(timerId);
} else {
$.setIniDbBoolean('commandPause', 'commandsPaused', true);
isActive = true;
}
timerId = setTimeout(function() {
unPause();
}, seconds * 1e3);
$.say($.lang.get('commandpause.initiated', $.getTimeString(seconds)));
};
/**
* @function isPaused
* @export $.commandPause
* @returns {boolean}
*/
function isPaused() {
return isActive;
};
/**
* @function clear
* @export $.commandPause
*/
function unPause() {
if (timerId > -1) {
clearTimeout(timerId);
$.setIniDbBoolean('commandPause', 'commandsPaused', false);
isActive = false;
timerId = -1;
$.say($.lang.get('commandpause.ended'));
}
};
/**
* @event event
*/
$.bind('command', function(event) {
var command = event.getCommand(),
args = event.getArgs();
/**
* @commandpath pausecommands [seconds] - Pause all command usage for the given amount of time. If [seconds] is not present, uses a default value
* @commandpath pausecommands clear - Unpause commands
*/
if (command.equalsIgnoreCase('pausecommands')) {
if (args[0] != undefined || args[0] != null) {
if (args[0] == 'clear') {
unPause();
return;
}
if (!isNaN(parseInt(args[0]))) {
pause(parseInt(args[0]));
} else {
pause();
}
} else {
$.say($.lang.get('pausecommands.usage'));
}
}
});
/**
* @event initReady
*/
$.bind('initReady', function() {
if ($.bot.isModuleEnabled('./core/commandPause.js')) {
$.registerChatCommand('./core/commandPause.js', 'pausecommands', 2);
}
});
/** Export functions to API */
$.commandPause = {
pause: pause,
isPaused: isPaused,
unPause: unPause,
};
})();

View File

@@ -0,0 +1,358 @@
/*
* Copyright (C) 2016-2020 phantombot.github.io/PhantomBot
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* commandRegister.js
*
* Register and keep track of commands.
*
* NOTE: You will have to register ANY command you implement!
* The commandEvent will not get fired to your module if the registry does not know about it!
*/
(function() {
var commands = {},
aliases = {};
/*
* @function registerChatCommand
*
* @param {String} script
* @param {String} command
* @param {String} groupId
*/
function registerChatCommand(script, command, groupId) {
// If groupId is undefined set it to 7 (viewer).
groupId = (groupId === undefined ? 7 : groupId);
if (commandExists(command)) {
return;
}
// This is for the panel commands.
if (groupId == 30) {
if ($.inidb.exists('permcom', command)) {
$.inidb.del('permcom', command);
}
commands[command] = {
groupId: groupId,
script: script,
subcommands: {}
};
return;
}
// Handle disabled commands.
if ($.inidb.exists('disabledCommands', command)) {
$.inidb.set('tempDisabledCommandScript', command, script);
return;
}
// Get and set the command permission.
groupId = $.getSetIniDbNumber('permcom', command, groupId);
commands[command] = {
groupId: groupId,
script: script,
subcommands: {}
};
}
/*
* @function registerChatSubcommand
*
* @param {String} command
* @param {String} subcommand
* @param {String} groupId
*/
function registerChatSubcommand(command, subcommand, groupId) {
// If groupId is undefined set it to 7 (viewer).
groupId = (groupId === undefined ? 7 : groupId);
if (!commandExists(command) || subCommandExists(command, subcommand)) {
return;
}
// Get and set the command permission.
groupId = $.getSetIniDbNumber('permcom', (command + ' ' + subcommand), groupId);
commands[command].subcommands[subcommand] = {
groupId: groupId
}
}
/*
* @function registerChatAlias
*
* @param {String} alias
*/
function registerChatAlias(alias) {
if (!aliasExists(alias)) {
aliases[alias] = true;
}
}
/*
* @function unregisterChatCommand
*
* @param {String} command
*/
function unregisterChatCommand(command) {
if (commandExists(command)) {
delete commands[command];
delete aliases[command];
}
$.inidb.del('permcom', command);
$.inidb.del('pricecom', command);
$.inidb.del('cooldown', command);
$.inidb.del('paycom', command);
$.inidb.del('disabledCommands', command);
}
/*
* @function tempUnRegisterChatCommand
*
* @param {String} command
*/
function tempUnRegisterChatCommand(command) {
$.inidb.set('tempDisabledCommandScript', command, commands[command].script);
if (commandExists(command)) {
delete commands[command];
delete aliases[command];
}
}
/*
* @function unregisterChatSubcommand
*
* @param {String} command
* @param {String} subcommand
*/
function unregisterChatSubcommand(command, subcommand) {
if (subCommandExists(command, subcommand)) {
delete commands[command].subcommands[subcommand];
}
$.inidb.del('permcom', command + ' ' + subcommand);
$.inidb.del('pricecom', command + ' ' + subcommand);
}
/*
* @function getCommandScript
*
* @param {String} command
* @return {String}
*/
function getCommandScript(command) {
if (commands[command] === undefined) {
return "Undefined";
}
return commands[command].script;
}
/*
* @function commandExists
*
* @param {String} command
* @return {Boolean}
*/
function commandExists(command) {
return (commands[command] !== undefined);
}
/*
* @function aliasExists
*
* @param {String} command
*/
function aliasExists(alias) {
return (aliases[alias] !== undefined);
}
/*
* @function subCommandExists
*
* @param {String} command
* @param {String} subcommand
* @return {Boolean}
*/
function subCommandExists(command, subcommand) {
if (commandExists(command)) {
return (commands[command].subcommands[subcommand] !== undefined);
}
return false;
}
/*
* @function getCommandGroup
*
* @param {String} command
* @return {Number}
*/
function getCommandGroup(command) {
if (commandExists(command)) {
return commands[command].groupId;
}
return 7;
}
/*
* @function getCommandGroupName
*
* @param {String} command
* @return {String}
*/
function getCommandGroupName(command) {
var group = '';
if (commandExists(command)) {
if (commands[command].groupId == 0) {
group = 'Caster';
} else if (commands[command].groupId == 1) {
group = 'Administrator';
} else if (commands[command].groupId == 2) {
group = 'Moderator';
} else if (commands[command].groupId == 3) {
group = 'Subscriber';
} else if (commands[command].groupId == 4) {
group = 'Donator';
} else if (commands[command].groupId == 5) {
group = 'VIP';
} else if (commands[command].groupId == 6) {
group = 'Regular';
} else if (commands[command].groupId == 7) {
group = 'Viewer';
}
return group;
}
return 'Viewer';
}
/*
* @function getSubcommandGroup
*
* @param {String} command
* @param {String} subcommand
* @return {Number}
*/
function getSubcommandGroup(command, subcommand) {
if (commandExists(command)) {
if (subCommandExists(command, subcommand)) {
return commands[command].subcommands[subcommand].groupId;
}
return getCommandGroup(command);
}
return 7;
}
/*
* @function getSubCommandGroupName
*
* @param {String} command
* @param {String} subcommand
* @return {String}
*/
function getSubCommandGroupName(command, subcommand) {
var group = '';
if (subCommandExists(command, subcommand)) {
if (commands[command].subcommands[subcommand].groupId == 0) {
group = 'Caster';
} else if (commands[command].subcommands[subcommand].groupId == 1) {
group = 'Administrator';
} else if (commands[command].subcommands[subcommand].groupId == 2) {
group = 'Moderator';
} else if (commands[command].subcommands[subcommand].groupId == 3) {
group = 'Subscriber';
} else if (commands[command].subcommands[subcommand].groupId == 4) {
group = 'Donator';
} else if (commands[command].subcommands[subcommand].groupId == 5) {
group = 'VIP';
} else if (commands[command].subcommands[subcommand].groupId == 6) {
group = 'Regular';
} else if (commands[command].subcommands[subcommand].groupId == 7) {
group = 'Viewer';
}
return group;
}
return 'Viewer';
}
/*
* @function updateCommandGroup
*
* @param {String} command
* @param {Number} groupId
*/
function updateCommandGroup(command, groupId) {
if (commandExists(command)) {
commands[command].groupId = groupId;
}
}
/*
* @function updateSubcommandGroup
*
* @param {String} command
* @param {String} subcommand
* @param {Number} groupId
*/
function updateSubcommandGroup(command, subcommand, groupId) {
if (subCommandExists(command, subcommand)) {
commands[command].subcommands[subcommand].groupId = groupId;
}
}
/*
* @function getSubCommandFromArguments
*
* @param {String} command
* @param {String[]} args
*/
function getSubCommandFromArguments(command, args) {
if (!commandExists(command) || args[0] === undefined) {
return '';
} else {
var subCommand = args[0].toLowerCase();
if (subCommandExists(command, subCommand)) {
return subCommand;
}
return '';
}
}
/** Export functions to API */
$.registerChatCommand = registerChatCommand;
$.registerChatSubcommand = registerChatSubcommand;
$.unregisterChatCommand = unregisterChatCommand;
$.unregisterChatSubcommand = unregisterChatSubcommand;
$.commandExists = commandExists;
$.subCommandExists = subCommandExists;
$.getCommandGroup = getCommandGroup;
$.getCommandGroupName = getCommandGroupName;
$.getSubcommandGroup = getSubcommandGroup;
$.getSubCommandGroupName = getSubCommandGroupName;
$.updateCommandGroup = updateCommandGroup;
$.updateSubcommandGroup = updateSubcommandGroup;
$.getCommandScript = getCommandScript;
$.aliasExists = aliasExists;
$.registerChatAlias = registerChatAlias;
$.tempUnRegisterChatCommand = tempUnRegisterChatCommand;
$.getSubCommandFromArguments = getSubCommandFromArguments;
})();

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,345 @@
/*
* Copyright (C) 2016-2020 phantombot.github.io/PhantomBot
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* fileSystem.js
*
* Export general file management to th $ API
*/
(function() {
var JFile = java.io.File,
JFileInputStream = java.io.FileInputStream,
JFileOutputStream = java.io.FileOutputStream,
Paths = Packages.java.nio.file.Paths,
executionPath = Packages.tv.phantombot.PhantomBot.GetExecutionPath(),
fileHandles = [],
validPaths = [
'./addons',
'./config/audio-hooks',
'./config/gif-alerts',
'./logs',
'./scripts'
];
/**
* @function readFile
* @export $
* @param {string} path
* @returns {Array}
*/
function readFile(path) {
var lines = [];
if (!fileExists(path)) {
return lines;
}
if (invalidLocation(path)) {
$.consoleLn('Blocked readFile() target outside of validPaths:' + path);
return lines;
}
try {
var fis = new JFileInputStream(path),
scan = new java.util.Scanner(fis);
for (var i = 0; scan.hasNextLine(); ++i) {
lines[i] = scan.nextLine();
}
fis.close();
} catch (e) {
$.log.error('Failed to open \'' + path + '\': ' + e);
}
return lines;
}
/**
* @function mkDir
* @export $
* @param {string} path
* @returns {boolean}
*/
function mkDir(path) {
if (invalidLocation(path)){
$.consoleLn('Blocked mkDir() target outside of validPaths:' + path);
return false;
}
var dir = new JFile(path);
return dir.mkdir();
}
/**
* @function moveFile
* @export $
* @param {string} file
* @param {string} path
*/
function moveFile(file, path) {
var fileO = new JFile(file),
pathO = new JFile(path);
if (invalidLocation(file) || invalidLocation(path)) {
$.consoleLn('Blocked moveFile() source or target outside of validPaths:' + file + ' to ' + path);
return;
}
if ((fileO != null && pathO != null) || (file != "" && path != "")) {
try {
org.apache.commons.io.FileUtils.moveFileToDirectory(fileO, pathO, true);
} catch (ex) {
$.log.error("moveFile(" + file + ", " + path + ") failed: " + ex);
}
}
}
/**
* @function saveArray
* @export $
* @param {Array} array
* @param {string} path
* @param {boolean} append
*/
function saveArray(array, path, append) {
if (invalidLocation(path)) {
$.consoleLn('Blocked saveArray() target outside of validPaths:' + path);
return;
}
try {
var fos = new JFileOutputStream(path, append),
ps = new java.io.PrintStream(fos),
l = array.length;
for (var i = 0; i < l; ++i) {
ps.println(array[i]);
}
fos.close();
} catch (e) {
$.log.error('Failed to write to \'' + path + '\': ' + e);
}
}
/**
* @function closeOpenFiles
*/
function closeOpenFiles() {
var dateFormat = new java.text.SimpleDateFormat('MM-dd-yyyy'),
date = dateFormat.format(new java.util.Date());
for (var key in fileHandles) {
if (!fileHandles[key].startDate.equals(date)) {
fileHandles[key].fos.close();
delete fileHandles[key];
}
}
}
/**
* @function writeToFile
* @export $
* @param {string} line
* @param {string} path
* @param {boolean} append
*/
function writeToFile(line, path, append) {
var dateFormat = new java.text.SimpleDateFormat('MM-dd-yyyy'),
date = dateFormat.format(new java.util.Date()),
fos,
ps;
if (invalidLocation(path)){
$.consoleLn('Blocked writeToFile() target outside of validPaths:' + path);
return;
}
closeOpenFiles();
if (fileHandles[path] !== undefined && append) {
fos = fileHandles[path].fos;
ps = fileHandles[path].ps;
} else {
fos = new JFileOutputStream(path, append);
ps = new java.io.PrintStream(fos);
fileHandles[path] = {
fos: fos,
ps: ps,
startDate: date
};
}
try {
ps.println(line);
fos.flush();
} catch (e) {
$.log.error('Failed to write to \'' + path + '\': ' + e);
}
}
/**
* @function touchFile
* @export $
* @param {string} path
*/
function touchFile(path) {
if (invalidLocation(path)) {
$.consoleLn('Blocked touchFile() target outside of validPaths:' + path);
return;
}
try {
var fos = new JFileOutputStream(path, true);
fos.close();
} catch (e) {
$.log.error('Failed to touch \'' + path + '\': ' + e);
}
}
/**
* @function deleteFile
* @export $
* @param {string} path
* @param {boolean} now
*/
function deleteFile(path, now) {
if (invalidLocation(path)) {
$.consoleLn('Blocked deleteFile() target outside of validPaths:' + path);
return;
}
try {
var f = new JFile(path);
if (now) {
f['delete']();
} else {
f.deleteOnExit();
}
} catch (e) {
$.log.error('Failed to delete \'' + path + '\': ' + e);
}
}
/**
* @function fileExists
* @export $
* @param {string} path
* @returns {boolean}
*/
function fileExists(path) {
if (invalidLocation(path)) {
$.consoleLn('Blocked fileExists() target outside of validPaths:' + path);
return false;
}
try {
var f = new JFile(path);
return f.exists();
} catch (e) {
return false;
}
}
/**
* @function findFiles
* @export $
* @param {string} directory
* @param {string} pattern
* @returns {Array}
*/
function findFiles(directory, pattern) {
if (invalidLocation(directory)) {
$.consoleLn('Blocked findFiles() target outside of validPaths:' + directory);
return [];
}
try {
var f = new JFile(directory),
ret = [];
if (f.isDirectory()) {
var files = f.list();
for (var i = 0; i < files.length; i++) {
if (files[i].indexOf(pattern) != -1) {
ret.push(files[i]);
}
}
return ret;
}
} catch (e) {
$.log.error('Failed to search in \'' + directory + '\': ' + e);
}
return [];
}
/**
* @function isDirectory
* @export $
* @param {string} path
* @returns {boolean}
*/
function isDirectory(path) {
if (invalidLocation(path)) {
$.consoleLn('Blocked isDirectory() target outside of validPaths:' + path);
return false;
}
try {
var f = new JFile(path);
return f.isDirectory();
} catch (e) {
return false;
}
}
/**
* @function findSize
* @export $
* @param {string} file
* @returns {Number}
*/
function findSize(file) {
if (invalidLocation(file)) {
$.consoleLn('Blocked findSize() target outside of validPaths:' + file);
return 0;
}
var fileO = new JFile(file);
return fileO.length();
}
function invalidLocation(path) {
var p = Paths.get(path);
for (var x in validPaths) {
if (p.toAbsolutePath().startsWith(Paths.get(executionPath, validPaths[x]))) {
return false;
}
}
return true;
}
/** Export functions to API */
$.deleteFile = deleteFile;
$.fileExists = fileExists;
$.findFiles = findFiles;
$.findSize = findSize;
$.isDirectory = isDirectory;
$.mkDir = mkDir;
$.moveFile = moveFile;
$.readFile = readFile;
$.saveArray = saveArray;
$.touchFile = touchFile;
$.writeToFile = writeToFile;
})();

View File

@@ -0,0 +1,180 @@
/*
* Copyright (C) 2016-2020 phantombot.github.io/PhantomBot
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* gameMessages.js
*
* An API for predefined game result messages
* Use the $.gameMessages API
*/
(function() {
var lastRandom = -1,
winMessageCount = {
roll: 0,
gamble: 0,
slot: 0
},
lostMessagesCount = {
roll: 0,
gamble: 0,
slot: 0
};
/**
* @function loadResponses
*/
function loadResponses() {
var i;
// Load up messages for the roll command.
for (i = 1; $.lang.exists('roll.win.' + i); i++) {
winMessageCount.roll++;
}
// Load up messages for the roll command.
for (i = 1; $.lang.exists('roll.lost.' + i); i++) {
lostMessagesCount.roll++;
}
// Load up messages for the slot command.
for (i = 1; $.lang.exists('slot.win.' + i); i++) {
winMessageCount.slot++;
}
// Load up messages for the slot command.
for (i = 1; $.lang.exists('slot.lost.' + i); i++) {
lostMessagesCount.slot++;
}
// Load up messages for the gamble command.
for (i = 1; $.lang.exists('gamble.win.' + i); i++) {
winMessageCount.gamble++;
}
// Load up messages for the gamble command.
for (i = 1; $.lang.exists('gamble.lost.' + i); i++) {
lostMessagesCount.gamble++;
}
}
/**
* @function getWin
*
* @export $.gameMessages
* @param {string} username
* @param {string} game
* @returns {string}
*/
function getWin(username, game) {
var rand;
switch (game) {
case 'roll':
if (winMessageCount.roll === 0) {
return '';
} else {
do {
rand = $.randRange(1, winMessageCount.roll);
} while (rand == lastRandom);
}
lastRandom = rand;
return $.lang.get(game + '.win.' + rand, $.resolveRank(username));
case 'gamble':
if (winMessageCount.gamble === 0) {
return '';
} else {
do {
rand = $.randRange(1, winMessageCount.gamble);
} while (rand == lastRandom);
}
lastRandom = rand;
return $.lang.get(game + '.win.' + rand, $.resolveRank(username));
case 'slot':
if (winMessageCount.slot === 0) {
return '';
} else {
do {
rand = $.randRange(1, winMessageCount.slot);
} while (rand == lastRandom);
}
lastRandom = rand;
return $.lang.get(game + '.win.' + rand, $.resolveRank(username));
default:
return '';
}
}
/**
* @function getLose
* @export $.gameMessages
* @param {string} username
* @returns {string}
*/
function getLose(username, game) {
var rand;
switch (game) {
case 'roll':
if (lostMessagesCount.roll === 0) {
return '';
} else {
do {
rand = $.randRange(1, lostMessagesCount.roll);
} while (rand == lastRandom);
}
lastRandom = rand;
return $.lang.get(game + '.lost.' + rand, $.resolveRank(username));
case 'gamble':
if (lostMessagesCount.gamble === 0) {
return '';
} else {
do {
rand = $.randRange(1, lostMessagesCount.gamble);
} while (rand == lastRandom);
}
lastRandom = rand;
return $.lang.get(game + '.lost.' + rand, $.resolveRank(username));
case 'slot':
if (lostMessagesCount.slot === 0) {
return '';
} else {
do {
rand = $.randRange(1, lostMessagesCount.slot);
} while (rand == lastRandom);
}
lastRandom = rand;
return $.lang.get(game + '.lost.' + rand, $.resolveRank(username));
default:
return '';
}
}
/**
* @event initReady
*/
$.bind('initReady', function() {
if ($.bot.isModuleEnabled('./core/gameMessages.js')) {
loadResponses();
}
});
/** Export functions to API */
$.gameMessages = {
getWin: getWin,
getLose: getLose
};
})();

View File

@@ -0,0 +1,377 @@
/*
* Copyright (C) 2016-2020 phantombot.github.io/PhantomBot
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
(function() {
var bot = $.botName.toLowerCase();
/*
* @event command
*/
$.bind('command', function(event) {
var sender = event.getSender(),
command = event.getCommand(),
argsString = event.getArguments(),
args = event.getArgs(),
action = args[0],
subAction = args[1];
if (command.equalsIgnoreCase(bot)) {
if (action === undefined) {
$.say($.whisperPrefix(sender) + $.lang.get('init.usage', bot));
return;
}
/*
* @commandpath botName disconnect - Removes the bot from your channel.
*/
if (action.equalsIgnoreCase('disconnect')) {
$.say($.whisperPrefix(sender) + $.lang.get('init.disconnect', 'irc-ws.chat.twitch.tv'));
setTimeout(function() {
java.lang.System.exit(0);
}, 1000);
}
/*
* @commandpath botName moderate - Forces the bot to detect its moderator status.
*/
if (action.equalsIgnoreCase('moderate')) {
$.session.getModerationStatus();
}
/*
* @commandpath botName setconnectmessage [message] - Sets a message that will be said once the bot joins the channel.
*/
if (action.equalsIgnoreCase('setconnectmessage')) {
if (subAction === undefined) {
$.say($.whisperPrefix(sender) + $.lang.get('init.connected.msg.usage', bot));
return;
}
var message = args.slice(1).join(' ');
$.setIniDbString('settings', 'connectedMsg', message);
$.say($.whisperPrefix(sender) + $.lang.get('init.connected.msg', message));
}
/*
* @commandpath botName removeconnectmessage - Removes the message said when the bot joins the channel.
*/
if (action.equalsIgnoreCase('removeconnectmessage')) {
$.inidb.del('settings', 'connectedMsg');
$.say($.whisperPrefix(sender) + $.lang.get('init.connected.msg.removed'));
}
/*
* @commandpath botName togglepricecommods - Toggles if moderators and higher pay for commands.
*/
if (action.equalsIgnoreCase('togglepricecommods')) {
var toggle = !$.getIniDbBoolean('settings', 'pricecomMods', false);
$.setIniDbBoolean('settings', 'pricecomMods', toggle);
$.say($.whisperPrefix(sender) + (toggle ? $.lang.get('init.mod.toggle.on.pay') : $.lang.get('init.mod.toggle.off.pay')));
}
/*
* @commandpath botName togglepermcommessage - Toggles if the no permission message is said in the chat.
*/
if (action.equalsIgnoreCase('togglepermcommessage')) {
var toggle = !$.getIniDbBoolean('settings', 'permComMsgEnabled', false);
$.setIniDbBoolean('settings', 'permComMsgEnabled', toggle);
$.say($.whisperPrefix(sender) + (toggle ? $.lang.get('init.mod.toggle.perm.msg.on') : $.lang.get('init.mod.toggle.perm.msg.off')));
}
/*
* @commandpath botName togglepricecommessage - Toggles if the cost message is said in the chat.
*/
if (action.equalsIgnoreCase('togglepricecommessage')) {
var toggle = !$.getIniDbBoolean('settings', 'priceComMsgEnabled', false);
$.setIniDbBoolean('settings', 'priceComMsgEnabled', toggle);
$.say($.whisperPrefix(sender) + (toggle ? $.lang.get('init.mod.toggle.price.msg.on') : $.lang.get('init.mod.toggle.price.msg.off')));
}
/*
* @commandpath botName togglecooldownmessage - Toggles if the cooldown message is said in the chat.
*/
if (action.equalsIgnoreCase('togglecooldownmessage')) {
var toggle = !$.getIniDbBoolean('settings', 'coolDownMsgEnabled', false);
$.setIniDbBoolean('settings', 'coolDownMsgEnabled', toggle);
$.say($.whisperPrefix(sender) + (toggle ? $.lang.get('init.toggle.cooldown.msg.on') : $.lang.get('init.toggle.cooldown.msg.off')));
}
}
if (command.equalsIgnoreCase('module')) {
if (action === undefined) {
$.say($.whisperPrefix(sender) + $.lang.get('init.module.usage'));
return;
}
/*
* @commandpath module delete [path] - Removes a module from the modules list. This does not remove the module itself.
*/
if (action.equalsIgnoreCase('delete')) {
if (subAction === undefined) {
$.say($.whisperPrefix(sender) + $.lang.get('init.module.delete.usage'));
return;
} else if ($.getIniDbString('modules', subAction, undefined) === undefined) {
$.say($.whisperPrefix(sender) + $.lang.get('init.module.delete.404', subAction));
return;
}
$.inidb.del('modules', subAction);
$.say($.whisperPrefix(sender) + $.lang.get('init.module.delete.success', subAction));
}
/*
* @commandpath module list - Gives a list of all the modules with their current status.
*/
if (action.equalsIgnoreCase('list')) {
var keys = Object.keys($.bot.modules),
modules = $.bot.modules,
temp = [],
i;
for (i in keys) {
if (modules[keys[i]].scriptName.indexOf('./core') !== -1 || modules[keys[i]].scriptName.indexOf('./lang') !== -1) {
continue;
}
temp.push(modules[keys[i]].scriptName + (modules[keys[i]].isEnabled ? ' (' + $.lang.get('common.enabled') + ')' : ' (' + $.lang.get('common.disabled') + ')'));
}
var totalPages = $.paginateArray(temp, 'init.module.list', ', ', true, sender, (isNaN(parseInt(subAction)) ? 1 : parseInt(subAction)));
if (totalPages > 0) {
$.say($.whisperPrefix(sender) + $.lang.get('init.module.list.total', totalPages));
}
}
/*
* @commandpath module status [module path] - Retrieve the current status (enabled/disabled) of the given module
*/
if (action.equalsIgnoreCase('status')) {
if (subAction === undefined) {
$.say($.whisperPrefix(sender) + $.lang.get('init.module.usage.status'));
return;
}
var module = $.bot.getModule(subAction);
if (module !== undefined) {
if (module.isEnabled) {
$.say($.whisperPrefix(sender) + $.lang.get('init.module.check.enabled', module.getModuleName()));
} else {
$.say($.whisperPrefix(sender) + $.lang.get('init.module.check.disabled', module.getModuleName()));
}
} else {
$.say($.whisperPrefix(sender) + $.lang.get('init.module.404'));
}
}
/*
* @commandpath module enable [module path] - Enable a module using the path and name of the module
*/
if (action.equalsIgnoreCase('enable')) {
if (subAction === undefined) {
$.say($.whisperPrefix(sender) + $.lang.get('init.module.usage.enable'));
return;
}
if (subAction.indexOf('./core') !== -1 || subAction.indexOf('./lang') !== -1) {
return;
}
var module = $.bot.getModule(subAction);
if (module !== undefined) {
$.setIniDbBoolean('modules', module.scriptName, true);
$.bot.loadScript(module.scriptName);
$.bot.modules[module.scriptName].isEnabled = true;
var hookIndex = $.bot.getHookIndex($.bot.modules[module.scriptName].scriptName, 'initReady');
try {
if (hookIndex !== -1) {
$.bot.getHook(module.scriptName, 'initReady').handler();
}
$.say($.whisperPrefix(sender) + $.lang.get('init.module.enabled', module.getModuleName()));
} catch (ex) {
$.log.error('Unable to call initReady for enabled module (' + module.scriptName + '): ' + ex);
$.consoleLn("Sending stack trace to error log...");
Packages.com.gmt2001.Console.err.printStackTrace(ex.javaException);
}
} else {
$.say($.whisperPrefix(sender) + $.lang.get('init.module.404'));
}
}
/*
* @commandpath module disable [module path] - Disable a module using the path and name of the module
*/
if (action.equalsIgnoreCase('disable')) {
if (subAction === undefined) {
$.say($.whisperPrefix(sender) + $.lang.get('init.module.usage.disable'));
return;
}
if (subAction.indexOf('./core') !== -1 || subAction.indexOf('./lang') !== -1) {
return;
}
var module = $.bot.getModule(subAction);
if (module !== undefined) {
$.setIniDbBoolean('modules', module.scriptName, false);
$.bot.modules[module.scriptName].isEnabled = false;
$.say($.whisperPrefix(sender) + $.lang.get('init.module.disabled', module.getModuleName()));
if (module.scriptName.equalsIgnoreCase('./systems/pointSystem.js')) {
var modules = ['./games/adventureSystem.js', './games/roll.js', './games/slotMachine.js', './systems/ticketraffleSystem.js', './systems/raffleSystem.js', './games/gambling.js'],
i;
for (i in modules) {
module = $.bot.getModule(modules[i]);
$.bot.modules[modules[i]].isEnabled = false;
$.setIniDbBoolean('modules', module.scriptName, false);
}
$.say($.whisperPrefix(sender) + $.lang.get('init.module.auto-disabled'));
}
} else {
$.say($.whisperPrefix(sender) + $.lang.get('init.module.404'));
}
}
/*
* Panel command.
*/
if (action.equalsIgnoreCase('enablesilent')) {
if (subAction === undefined) {
return;
}
if (subAction.indexOf('./core') !== -1 || subAction.indexOf('./lang') !== -1) {
return;
}
var module = $.bot.getModule(subAction);
if (module !== undefined) {
$.setIniDbBoolean('modules', module.scriptName, true);
$.bot.loadScript(module.scriptName);
$.bot.modules[module.scriptName].isEnabled = true;
var hookIndex = $.bot.getHookIndex(module.scriptName, 'initReady');
try {
if (hookIndex !== -1) {
$.bot.getHook(module.scriptName, 'initReady').handler();
}
} catch (ex) {
$.log.error('Unable to call initReady for enabled module (' + module.scriptName + '): ' + ex);
$.consoleLn("Sending stack trace to error log...");
Packages.com.gmt2001.Console.err.printStackTrace(ex.javaException);
}
}
}
/*
* Panel command.
*/
if (action.equalsIgnoreCase('disablesilent')) {
if (subAction === undefined) {
return;
}
if (subAction.indexOf('./core') !== -1 || subAction.indexOf('./lang') !== -1) {
return;
}
var module = $.bot.getModule(subAction);
if (module !== undefined) {
$.setIniDbBoolean('modules', module.scriptName, false);
$.bot.modules[module.scriptName].isEnabled = false;
if (module.scriptName.equalsIgnoreCase('./systems/pointSystem.js')) {
var modules = ['./games/adventureSystem.js', './games/roll.js', './games/slotMachine.js', './systems/ticketraffleSystem.js', './systems/raffleSystem.js', './games/gambling.js'],
i;
for (i in modules) {
module = $.bot.getModule(modules[i]);
$.bot.modules[module.scriptName].isEnabled = false;
$.setIniDbBoolean('modules', module.scriptName, false);
}
}
}
}
}
/*
* Panel command.
*/
if (command.equalsIgnoreCase('reconnect')) {
if ($.isBot(sender)) {
$.session.reconnect();
}
}
/*
* Panel command.
*/
if (command.equalsIgnoreCase('disconnect')) {
if ($.isBot(sender)) {
java.lang.System.exit(0);
}
}
/*
* @commandpath echo [message] - Send a message as the bot.
*/
if (command.equalsIgnoreCase('chat') || command.equalsIgnoreCase('echo')) {
if (argsString.length() > 0) {
$.say(argsString);
}
}
});
/*
* @event initReady
*/
$.bind('initReady', function() {
$.registerChatCommand('./core/initCommands.js', 'chat', 1);
$.registerChatCommand('./core/initCommands.js', 'module', 1);
$.registerChatCommand('./core/initCommands.js', 'echo', 1);
$.registerChatCommand('./core/initCommands.js', 'reconnect', 1);
$.registerChatCommand('./core/initCommands.js', 'disconnect', 1);
$.registerChatCommand('./core/initCommands.js', bot, 2);
$.registerChatSubcommand(bot, 'disconnect', 1);
$.registerChatSubcommand(bot, 'reconnect', 1);
$.registerChatSubcommand(bot, 'moderate', 2);
// Say the connected message.
if ($.inidb.exists('settings', 'connectedMsg')) {
$.say($.inidb.get('settings', 'connectedMsg'));
}
});
})();

View File

@@ -0,0 +1,110 @@
/*
* Copyright (C) 2016-2020 phantombot.github.io/PhantomBot
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* jsTimers.js
*
* A general javascript module to replace Rhino's crappy timer functions
*/
var setTimeout,
clearTimeout,
setInterval,
clearInterval;
(function() {
var counter = 1,
registry = {};
/**
* @function setTimeout
* @param {Function} fn
* @param {Number} delay
* @param {String} name
* @returns {Number}
*/
setTimeout = function(fn, delay, name) {
var id = counter++,
timer;
if (name !== undefined) {
timer = new java.util.Timer(name);
} else {
timer = new java.util.Timer();
}
registry[id] = new JavaAdapter(java.util.TimerTask, {
run: fn
});
timer.schedule(registry[id], delay);
return id;
};
/**
* @function setInterval
* @param {Function} fn
* @param {Number} interval
* @param {String} name
*
* @returns {Number}
*/
setInterval = function(fn, interval, name) {
var id = counter++,
timer;
if (name !== undefined) {
timer = new java.util.Timer(name);
} else {
timer = new java.util.Timer();
}
registry[id] = new JavaAdapter(java.util.TimerTask, {
run: fn
});
timer.schedule(registry[id], interval, interval);
return id;
};
/**
* @function clearTimeout
* @param {Number} id
*/
clearTimeout = function(id) {
if (id == undefined) {
return;
}
if (registry[id] != undefined) {
try {
registry[id].cancel();
} catch (ex) {
// Cannot cancel since timer is already over.
// Ignore this.
}
}
delete registry[id];
};
/**
* @type {clearTimeout}
*/
clearInterval = clearTimeout;
})();

View File

@@ -0,0 +1,134 @@
/*
* Copyright (C) 2016-2020 phantombot.github.io/PhantomBot
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* keywordCoolDown.js
*
* Manage cooldowns for keywords
*
* To use the cooldown in other scipts use the $.coolDownKeywords API
*/
(function() {
var modCooldown = $.getIniDbBoolean('cooldownSettings', 'modCooldown', false),
cooldown = [];
/**
* @function permCheck
* @param username
* @return boolean
*/
function permCheck(username) {
return (!modCooldown && $.isMod(username)) || $.isAdmin(username);
};
/**
* @function getCooldown
* @param keyword
* @return number
*/
function getCooldown(keyword) {
if ($.inidb.exists('coolkey', keyword.toLowerCase())) {
return parseInt($.inidb.get('coolkey', keyword.toLowerCase()));
} else if ($.inidb.exists('coolkey', keyword)) { // ignore case
return parseInt($.inidb.get('coolkey', keyword));
} else {
return 0;
}
};
/**
* @function set
* @export $.coolDownKeywords
* @param keyword
* @param time
* @param username
*/
function set(keyword, hasCooldown, time, username) {
if (time == null || time == 0 || time == 1 || isNaN(time)) {
return;
}
time = ((time * 1000) + $.systemTime());
keyword = keyword.toLowerCase();
cooldown.push({
keyword: keyword,
time: time
});
$.consoleDebug('Pushed keyword ' + keyword + ' to cooldown.');
};
/**
* @function get
* @export $.coolDownKeywords
* @param keyword
* @param username
* @return number
*/
function get(keyword, username) {
var hasCooldown = $.inidb.exists('coolkey', keyword.toLowerCase()) || $.inidb.exists('coolkey', keyword), // ignore case.
i;
if (!hasCooldown)
return 0;
for (i in cooldown) {
if (cooldown[i].keyword.equalsIgnoreCase(keyword)) {
if ((cooldown[i].time - $.systemTime()) > 0) {
if (permCheck(username)) return 0;
return parseInt(cooldown[i].time - $.systemTime());
}
}
}
set(keyword, hasCooldown, getCooldown(keyword));
return 0;
};
/**
* @function clear
* @export $.coolDownKeywords
* @param keyword
*/
function clear(keyword) {
var i;
for (i in cooldown) {
if (cooldown[i].keyword.equalsIgnoreCase(keyword)) {
cooldown.splice(i, 1);
return;
}
}
};
/**
* @function clearAll
*/
function clearAll() {
var i;
for (i in cooldown) {
cooldown.splice(i, 1);
}
};
/** EXPORT TO $. API*/
$.coolDownKeywords = {
set: set,
get: get,
clear: clear,
};
})();

View File

@@ -0,0 +1,198 @@
/*
* Copyright (C) 2016-2020 phantombot.github.io/PhantomBot
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* lang.js
*
* Provide a language API
* Use the $.lang API
*
* NOTE: Reading from/writing to the lang data directly is not possbile anymore!
* Use the register(), exists() and get() functions!
*/
(function() {
var data = [],
curLang = ($.inidb.exists('settings', 'lang') ? $.inidb.get('settings', 'lang') : 'english');
/**
* @function load
*/
function load(force) {
$.bot.loadScriptRecursive('./lang/english', true, (force ? force : false));
if (curLang != 'english') {
$.bot.loadScriptRecursive('./lang/' + curLang, true, (force ? force : false));
}
if ($.isDirectory('./scripts/lang/custom')) {
$.bot.loadScriptRecursive('./lang/custom', true, (force ? force : false));
}
// Set "response_@chat" to true if it hasn't been set yet, so the bot isn't muted when using a fresh install
if (!$.inidb.exists('settings', 'response_@chat')) {
$.setIniDbBoolean('settings', 'response_@chat', true);
}
}
/**
* @function register
* @export $.lang
* @param {string} key
* @param {string} string
*/
function register(key, string) {
if (key && string) {
data[key.toLowerCase()] = string;
}
if (key && string.length === 0) {
data[key.toLowerCase()] = '<<EMPTY_PLACEHOLDER>>';
}
}
/**
* @function get
* @export $.lang
* @param {string} key
* @returns {string}
*/
function get(key) {
var string = data[key.toLowerCase()],
i;
if (string === undefined) {
$.log.warn('Lang string for key "' + key + '" was not found.');
return '';
}
if (string == '<<EMPTY_PLACEHOLDER>>') {
return '';
}
for (i = 1; i < arguments.length; i++) {
while (string.indexOf("$" + i) >= 0) {
string = string.replace("$" + i, arguments[i]);
}
}
return string;
}
/**
* @function paramCount
* @export $.lang
* @param {string} key
* @returns {Number}
*/
function paramCount(key) {
var string = data[key.toLowerCase()],
i,
ctr = 0;
if (!string) {
return 0;
}
for (i = 1; i < 99; i++) {
if (string.indexOf("$" + i) >= 0) {
ctr++;
} else {
break;
}
}
return ctr;
}
/**
* @function exists
* @export $.lang
* @param {string} key
* @returns {boolean}
*/
function exists(key) {
return (data[key.toLowerCase()]);
}
/**
* @event command
*/
$.bind('command', function(event) {
var sender = event.getSender().toLowerCase(),
command = event.getCommand(),
args = event.getArgs(),
action = args[0],
inversedState;
/**
* @commandpath lang [language name] - Get or optionally set the current language (use folder name from "./lang" directory);
*/
if (command.equalsIgnoreCase('lang')) {
if (!action) {
$.say($.whisperPrefix(sender) + get('lang.curlang', curLang));
} else {
action = action.toLowerCase();
if (!$.fileExists('./scripts/lang/' + action + '/main.js')) {
$.say($.whisperPrefix(sender) + get('lang.lang.404'));
} else {
$.inidb.set('settings', 'lang', action);
curLang = action;
load(true);
$.say($.whisperPrefix(sender) + get('lang.lang.changed', action));
}
}
}
/**
* @commandpath mute - Toggle muting the bot in the chat
*/
if (command.equalsIgnoreCase('mute')) {
inversedState = !$.getIniDbBoolean('settings', 'response_@chat');
$.setIniDbBoolean('settings', 'response_@chat', inversedState);
$.reloadMisc();
$.say($.whisperPrefix(sender) + (inversedState ? get('lang.response.enabled') : get('lang.response.disabled')));
}
/**
* @commandpath toggleme - Toggle prepending chat output with "/me".
*/
if (command.equalsIgnoreCase('toggleme')) {
inversedState = !$.getIniDbBoolean('settings', 'response_action');
$.setIniDbBoolean('settings', 'response_action', inversedState);
$.reloadMisc();
$.say($.whisperPrefix(sender) + (inversedState ? get('lang.response.action.enabled') : get('lang.response.action.disabled')));
}
});
/**
* @event initReady
*/
$.bind('initReady', function() {
$.registerChatCommand('./core/lang.js', 'lang', 1);
$.registerChatCommand('./core/lang.js', 'mute', 1);
$.registerChatCommand('./core/lang.js', 'toggleme', 1);
});
/** Export functions to API */
$.lang = {
exists: exists,
get: get,
register: register,
paramCount: paramCount
};
// Run the load function to enable modules, loaded after lang.js, to access the language strings immediatly
load();
})();

View File

@@ -0,0 +1,404 @@
/*
* Copyright (C) 2016-2020 phantombot.github.io/PhantomBot
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* logging.js
*
* Provide and API for logging events and errors
* Use the $ API for log functions
* Use the $.logging API for getting log-like date and time strings
*/
(function() {
var logDays = $.getSetIniDbNumber('settings', 'log_rotate_days', 30),
logs = {
file: $.getSetIniDbBoolean('settings', 'log.file', true),
event: $.getSetIniDbBoolean('settings', 'log.event', true),
error: $.getSetIniDbBoolean('settings', 'log.error', true)
},
cmdLogEnabled = $.getSetIniDbBoolean('discordSettings', 'customCommandLogs', false),
cmdDiscordLogChannel = $.getSetIniDbString('discordSettings', 'modLogChannel', '');
/*
* @event webPanelSocketUpdate
*/
$.bind('webPanelSocketUpdate', function(event) {
if (event.getScript().equalsIgnoreCase('./core/logging.js')) {
cmdLogEnabled = $.getSetIniDbBoolean('discordSettings', 'customCommandLogs', false);
cmdDiscordLogChannel = $.getSetIniDbString('discordSettings', 'modLogChannel', '');
}
});
/*
* function reloadLogs()
*/
function reloadLogs() {
$.getIniDbNumber('settings', 'log_rotate_days');
logs.file = $.getIniDbBoolean('settings', 'log.file');
logs.event = $.getIniDbBoolean('settings', 'log.event');
logs.error = $.getIniDbBoolean('settings', 'log.error');
}
/*
* @function getLogDateString
*
* @export $.logging
* @param {Number} timeStamp
* @return {String}
*/
function getLogDateString(timeStamp) {
var now = (timeStamp ? new Date(timeStamp) : new Date()),
pad = function(i) {
return (i < 10 ? '0' + i : i);
};
return pad(now.getDate()) + '-' + pad(now.getMonth() + 1) + '-' + now.getFullYear();
}
/*
* @function getLogTimeString
*
* @export $.logging
* @param {Number} timeStamp
* @return {String}
*/
function getLogTimeString(timeStamp) {
if (timeStamp) {
return (new Date(timeStamp)).toLocaleTimeString('en-GB').replace(' ', '_');
} else {
return (new Date()).toTimeString();
}
}
/*
* @function getLogEntryTimeDateString
*
* @export $.logging
* @return {String}
*/
function getLogEntryTimeDateString() {
var dateFormat = new java.text.SimpleDateFormat("MM-dd-yyyy @ HH:mm:ss.SSS z");
dateFormat.setTimeZone(java.util.TimeZone.getTimeZone(($.inidb.exists('settings', 'timezone') ? $.inidb.get('settings', 'timezone') : 'GMT')));
return dateFormat.format(new Date());
}
/*
* @function logCustomCommand
*
* @param {object} info
*/
function logCustomCommand(info) {
var lines = Object.keys(info).map(function(key) {
return '**' + $.lang.get('discord.customcommandlogs.' + key) + '**: ' + info[key];
});
$.log.file('customCommands', lines.join('\r\n'));
if (!$.hasDiscordToken && cmdLogEnabled && cmdDiscordLogChannel) {
$.discordAPI.sendMessageEmbed(cmdDiscordLogChannel, 'blue', lines.join('\r\n\r\n'));
}
}
/*
* @function logfile
*
* @export $
* @param {String} filePrefix
* @param {String} message
* @param {String} sender
*/
function logfile(filePrefix, message, sender) {
if (logs.file === false || message.indexOf('.mods') !== -1) {
return;
}
if (!$.isDirectory('./logs/' + filePrefix + '/')) {
if (!$.isDirectory('./logs/')) {
$.mkDir('./logs');
}
$.mkDir('./logs/' + filePrefix);
}
$.writeToFile('[' + getLogEntryTimeDateString() + '] ' + message, './logs/' + filePrefix + '/' + getLogDateString() + '.txt', true);
}
/*
* @function logEvent
*
* @export $
* @param {string} message
*/
function logEvent(message) {
if (logs.event === false || message.indexOf('specialuser') !== -1) {
return;
}
if (!$.isDirectory('./logs/events')) {
if (!$.isDirectory('./logs/')) {
$.mkDir('./logs');
}
$.mkDir('./logs/event');
}
try {
throw new Error('eventlog');
} catch (e) {
sourceFile = e.stack.split('\n')[1].split('@')[1];
}
$.writeToFile('[' + getLogEntryTimeDateString() + '] [' + sourceFile.trim() + '] ' + message, './logs/event/' + getLogDateString() + '.txt', true);
}
/*
* @function logError
*
* @export $
* @param {String} message
*/
function logError(message) {
if (logs.error === false) {
return;
}
if (!$.isDirectory('./logs/error/')) {
if (!$.isDirectory('./logs/')) {
$.mkDir('./logs');
}
$.mkDir('./logs/error');
}
try {
throw new Error('errorlog');
} catch (e) {
sourceFile = e.stack.split('\n')[1].split('@')[1];
}
$.writeToFile('[' + getLogEntryTimeDateString() + '] [' + sourceFile.trim() + '] ' + message, './logs/error/' + getLogDateString() + '.txt', true);
Packages.com.gmt2001.Console.err.printlnRhino(java.util.Objects.toString('[' + sourceFile.trim() + '] ' + message));
}
/*
* @function logWarning
*
* @export $
* @param {String} message
*/
function logWarning(message) {
if (logs.error === false) {
return;
}
if (!$.isDirectory('./logs/warning/')) {
if (!$.isDirectory('./logs/')) {
$.mkDir('./logs');
}
$.mkDir('./logs/warning');
}
try {
throw new Error('warninglog');
} catch (e) {
sourceFile = e.stack.split('\n')[1].split('@')[1];
}
$.writeToFile('[' + getLogEntryTimeDateString() + '] [' + sourceFile.trim() + '] ' + message, './logs/warning/' + getLogDateString() + '.txt', true);
Packages.com.gmt2001.Console.warn.printlnRhino(java.util.Objects.toString(message));
}
/*
* @function logRotate
*/
function logRotate() {
var logFiles,
idx,
logFileDate,
logDirs = ['chat', 'chatModerator', 'core', 'core-debug', 'core-error', 'error', 'event', 'patternDetector', 'pointSystem', 'private-messages'],
logDirIdx,
datefmt = new java.text.SimpleDateFormat('dd-MM-yyyy'),
date,
rotateDays = $.getIniDbNumber('settings', 'log_rotate_days') * 24 * 60 * 6e4,
checkDate = $.systemTime() - rotateDays;
if (rotateDays === 0) {
return;
}
$.log.event('Starting Log Rotation');
for (logDirIdx = 0; logDirIdx < logDirs.length; logDirIdx++) {
logFiles = $.findFiles('./logs/' + logDirs[logDirIdx], 'txt');
for (idx = 0; idx < logFiles.length; idx++) {
logFileDate = logFiles[idx].match(/(\d{2}-\d{2}-\d{4})/)[1];
date = datefmt.parse(logFileDate);
if (date.getTime() < checkDate) {
$.log.event('Log Rotate: Deleted ./logs/' + logDirs[logDirIdx] + '/' + logFiles[idx]);
$.deleteFile('./logs/' + logDirs[logDirIdx] + '/' + logFiles[idx], true);
}
}
}
$.log.event('Finished Log Rotation');
}
/*
* @event ircChannelMessage
*/
$.bind('ircChannelMessage', function(event) {
logfile('chat', '' + event.getSender() + ': ' + event.getMessage());
});
/*
* @event ircPrivateMessage
*/
$.bind('ircPrivateMessage', function(event) {
var sender = event.getSender().toLowerCase(),
message = event.getMessage().toLowerCase();
if (message.startsWith('specialuser')) {
return;
}
if (message.indexOf('the moderators if this room') === -1) {
logfile('private-messages', '' + sender + ': ' + message);
}
if (sender.equalsIgnoreCase('jtv')) {
if (message.equalsIgnoreCase('clearchat')) {
logfile('private-messages', '' + $.lang.get('console.received.clearchat'));
} else if (message.indexOf('clearchat') !== -1) {
logEvent($.lang.get('console.received.purgetimeoutban', message.substring(10)));
} else if (message.indexOf('now in slow mode') !== -1) {
logfile('private-messages', '' + $.lang.get('console.received.slowmode.start', message.substring(message.indexOf('every') + 6)));
} else if (message.indexOf('no longer in slow mode') !== -1) {
logfile('private-messages', '' + $.lang.get('console.received.slowmode.end'));
} else if (message.indexOf('now in subscribers-only') !== -1) {
logfile('private-messages', '' + $.lang.get('console.received.subscriberonly.start'));
} else if (message.indexOf('no longer in subscribers-only') !== -1) {
logfile('private-messages', '' + $.lang.get('console.received.subscriberonly.end'));
} else if (message.indexOf('now in r9k') !== -1) {
logfile('private-messages', '' + $.lang.get('console.received.r9k.start'));
} else if (message.indexOf('no longer in r9k') !== -1) {
logfile('private-messages', '' + $.lang.get('console.received.r9k.end'));
} else if (message.indexOf('hosting') !== -1) {
var target = String(message).replace(/now hosting /ig, '').replace(/\./ig, '');
if (target.equalsIgnoreCase('-')) {
$.bot.channelIsHosting = null;
logfile('private-messages', '' + $.lang.get('console.received.host.end'));
} else {
$.bot.channelIsHosting = target;
logfile('private-messages', '' + $.lang.get('console.received.host.start', target));
}
} else {
logfile('private-messages', '' + sender + ': ' + message);
}
}
});
/*
* @event command
*/
$.bind('command', function(event) {
var command = event.getCommand(),
sender = event.getSender(),
args = event.getArgs(),
action = args[0];
if (command.equalsIgnoreCase('log')) {
if (action === undefined) {
$.say($.whisperPrefix(sender) + $.lang.get('logging.usage'));
return;
}
/**
* @commandpath log rotatedays [days] - Display or set number of days to rotate the logs. 0 to disable log rotation.
*/
if (action.equalsIgnoreCase('rotatedays')) {
if (args[1] === undefined) {
$.say($.whisperPrefix(sender) + $.lang.get('logging.rotatedays.usage', $.getIniDbNumber('settings', 'log_rotate_days')));
return;
}
if (isNaN(args[1])) {
$.say($.whisperPrefix(sender) + $.lang.get('logging.rotatedays.usage', $.getIniDbNumber('settings', 'log_rotate_days')));
return;
}
if (parseInt(args[1]) === 0) {
$.say($.whisperPrefix(sender) + $.lang.get('logging.rotatedays.success.off'));
} else {
$.say($.whisperPrefix(sender) + $.lang.get('logging.rotatedays.success', args[1]));
}
$.inidb.set('settings', 'log_rotate_days', args[1]);
return;
}
/**
* @commandpath log files - Toggle the logging of files
*/
if (action.equalsIgnoreCase('files')) {
logs.file = !logs.file;
$.setIniDbBoolean('settings', 'log.file', logs.file);
$.say($.whisperPrefix(sender) + (logs.file ? $.lang.get('logging.enabled.files') : $.lang.get('logging.disabled.files')));
return;
}
/**
* @commandpath log events - Toggle the logging of events
*/
if (action.equalsIgnoreCase('events')) {
logs.event = !logs.event;
$.setIniDbBoolean('settings', 'log.event', logs.event);
$.say($.whisperPrefix(sender) + (logs.event ? $.lang.get('logging.enabled.event') : $.lang.get('logging.disabled.event')));
return;
}
/**
* @commandpath log errors - Toggle the logging of errors
*/
if (action.equalsIgnoreCase('errors')) {
logs.error = !logs.error;
$.setIniDbBoolean('settings', 'log.error', logs.error);
$.say($.whisperPrefix(sender) + (logs.error ? $.lang.get('logging.enabled.error') : $.lang.get('logging.disabled.error')));
}
}
});
var interval = setInterval(function() {
logRotate();
}, 24 * 60 * 6e4, 'scripts::core::logging.js');
/*
* @event initReady
*/
$.bind('initReady', function() {
$.registerChatCommand('./core/logging.js', 'log', 1);
logRotate();
});
/* Export functions to API */
$.logging = {
getLogEntryTimeDateString: getLogEntryTimeDateString,
getLogDateString: getLogDateString,
getLogTimeString: getLogTimeString
};
$.log = {
file: logfile,
event: logEvent,
error: logError,
warn: logWarning
};
$.reloadLogs = reloadLogs;
$.logCustomCommand = logCustomCommand;
})();

View File

@@ -0,0 +1,821 @@
/*
* Copyright (C) 2016-2020 phantombot.github.io/PhantomBot
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
(function () {
var currentHostTarget = '',
respond = getSetIniDbBoolean('settings', 'response_@chat', true),
action = getSetIniDbBoolean('settings', 'response_action', false),
secureRandom = new java.security.SecureRandom(),
reg = new RegExp(/^@\w+,\s?$/),
timeout = 0;
/*
* @function reloadMisc
*/
function reloadMisc() {
respond = getIniDbBoolean('settings', 'response_@chat');
action = getIniDbBoolean('settings', 'response_action');
}
/**
** This function sometimes does not work. So only use it for stuff that people dont use much
* @function hasKey
* @export $.list
* @param {Array} list
* @param {*} value
* @param {Number} [subIndex]
* @returns {boolean}
*/
function hasKey(list, value, subIndex) {
var i;
if (subIndex > -1) {
for (i in list) {
if (list[i][subIndex].equalsIgnoreCase(value)) {
return true;
}
}
} else {
for (i in list) {
if (list[i].equalsIgnoreCase(value)) {
return true;
}
}
}
return false;
}
/*
* @function getMessageWrites
*/
function getMessageWrites() {
return parseInt($.session.getWrites());
}
/**
* @function isKnown
* @export $.user
* @param {string} username
* @returns {boolean}
*/
function isKnown(username) {
return $.inidb.exists('visited', username.toLowerCase());
}
/**
* @function sanitize
* @export $.user
* @param {string} username
* @returns {string}
*/
function sanitize(username) {
return (username == null ? username : String(username).replace(/\W/g, '').toLowerCase());
}
/**
* @function isFollower
* @export $.user
* @param {string} username
* @returns {boolean}
*/
function isFollower(username) {
var userFollowsCheck;
if ($.inidb.exists('followed', username.toLowerCase())) {
return true;
} else {
userFollowsCheck = $.twitch.GetUserFollowsChannel(username.toLowerCase(), $.channelName.toLowerCase());
if (userFollowsCheck.getInt('_http') == 200) {
$.inidb.set('followed', username.toLowerCase(), true);
return true;
}
}
return false;
}
/**
* @function getCurrentHostTarget
* @export $
* @returns {string}
*/
function getCurrentHostTarget() {
return currentHostTarget.toLowerCase();
}
/**
* @function strlen
* @export $
* @param {string} str
* @returns {Number}
*/
function strlen(str) {
if (str == null) {
return 0;
}
if ((typeof str.length) instanceof java.lang.String) {
if ((typeof str.length).equalsIgnoreCase('number')) {
return str.length;
} else {
return str.length;
}
} else {
if ((typeof str.length) == 'number') {
return str.length;
} else {
return str.length;
}
}
}
function equalsIgnoreCase(str1, str2) {
try {
return str1.equalsIgnoreCase(str2);
} catch (e) {
try {
return str1.toLowerCase() == str2.toLowerCase();
} catch (e) {
return false;
}
}
return false;
}
/**
* @function say
* @export $
* @param {string} message
*/
function say(message) {
if (reg.test(message)) {
return;
}
if (respond && !action) {
$.session.say(message);
} else {
if (respond && action) {
// If the message is a Twitch command, remove the /me.
if (message.startsWith('.') || message.startsWith('/')) {
$.session.say(message);
} else {
$.session.say('/me ' + message);
}
}
if (!respond) {
$.consoleLn('[MUTED] ' + message);
$.log.file('chat', '[MUTED] ' + $.botName.toLowerCase() + ': ' + message);
return;
}
}
$.log.file('chat', '' + $.botName.toLowerCase() + ': ' + message);
}
/**
* @function say
* @export $
* @param {string} message
* @param {boolean} run
*/
function sayWithTimeout(message, run) {
if (((timeout + 10000) > systemTime()) || !run) {
return;
}
timeout = systemTime();
say(message);
}
/**
* @function systemTime
* @export $
* @returns {Number}
*/
function systemTime() {
return parseInt(java.lang.System.currentTimeMillis());
}
/**
* @function systemTimeNano
* @export $
* @returns {Number}
*/
function systemTimeNano() {
return parseInt(java.lang.System.nanoTime());
}
/**
* @function rand
* @export $
* @param {Number} max
* @returns {Number}
*/
function rand(max) {
if (max == 0) {
return max;
}
return (Math.abs(secureRandom.nextInt()) % max);
}
/**
* @function randRange
* @export $
* @param {Number} min
* @param {Number} max
* @returns {Number}
*/
function randRange(min, max) {
if (min == max) {
return min;
}
return parseInt(rand(max - min + 1) + min);
}
/**
* @function randElement
* @export $
* @param {Array} array
* @returns {*}
*/
function randElement(array) {
if (array == null) {
return null;
}
return array[randRange(0, array.length - 1)];
}
/**
* @function arrayShuffle
* @param {Array} array
* @returns {Array}
*/
function arrayShuffle(array) {
for (var i = array.length - 1; i > 0; i--) {
var j = Math.floor(Math.random() * (i + 1));
var temp = array[i];
array[i] = array[j];
array[j] = temp;
}
return array;
}
/**
* @function randInterval
* @export $
* @param {Number} min
* @param {Number} max
* @returns {Number}
*/
function randInterval(min, max) {
return Math.floor(Math.random() * (max - min + 1) + min);
}
/**
* @function trueRandRange
* @export $
* @param {Number} min
* @param {Number} max
* @returns {Number}
*/
function trueRandRange(min, max) {
if (min == max) {
return min;
}
try {
var HttpRequest = Packages.com.gmt2001.HttpRequest,
HashMap = Packages.java.util.HashMap,
JSONObject = Packages.org.json.JSONObject,
json = new JSONObject('{}'),
parameters = new JSONObject('{}'),
header = new HashMap(1),
id = rand(65535),
request;
header.put('Content-Type', 'application/json-rpc');
parameters
.put('apiKey', '0d710311-5840-45dd-be83-82904de87c5d')
.put('n', 1)
.put('min', min)
.put('max', max)
.put('replacement', true)
.put('base', 10);
json
.put('jsonrpc', '2.0')
.put('method', 'generateIntegers')
.put('params', parameters)
.put('id', id);
request = HttpRequest.getData(
HttpRequest.RequestType.GET,
'https://api.random.org/json-rpc/1/invoke',
json.toString(),
header
);
if (request.success) {
var data = new JSONObject(request.content)
.getJSONObject('result')
.getJSONObject('random')
.getJSONArray('data');
if (data.length() > 0) {
return data.getInt(0);
}
} else {
if (request.httpCode == 0) {
$.log.error('Failed to use random.org: ' + request.exception);
} else {
$.log.error('Failed to use random.org: HTTP' + request.httpCode + ' ' + request.content);
}
}
} catch (error) {
$.log.error('Failed to use random.org: ' + error);
}
return randRange(min, max);
}
/**
* @function trueRandElement
* @exprtto $
* @param {Array} array
* @returns {*}
*/
function trueRandElement(array) {
if (array == null) {
return null;
}
return array[trueRand(array.length - 1)];
}
/**
* @function trueRand
* @export $
* @param {Number} max
* @returns {Number}
*/
function trueRand(max) {
return trueRandRange(0, max);
}
/**
* @function outOfRange
* @export $
* @param {Number} number
* @param {Number} min
* @param {Number} max
* @returns {boolean}
*/
function outOfRange(number, min, max) {
return (number < min || number > max);
}
/**
* @function getOrdinal
* @export $
* @param {Number} number
* @returns {string}
*/
function getOrdinal(number) {
var s = ["th", "st", "nd", "rd"],
v = number % 100;
return (number + (s[(v - 20) % 10] || s[v] || s[0]));
}
/**
* @function getPercentage
* @export $
* @param {Number} current
* @param {Number} total
* @returns {Number}
*/
function getPercentage(current, total) {
return Math.ceil((current / total) * 100);
}
/**
* @function getIniDbBoolean
* @export $
* @param {string} fileName
* @param {string|Number} key
* @param {boolean} [defaultValue]
* @returns {boolean}
*/
function getIniDbBoolean(fileName, key, defaultValue) {
if ($.inidb.exists(fileName, key) == true) {
return ($.inidb.get(fileName, key) == 'true');
} else {
return (defaultValue);
}
}
/**
* @function getSetIniDbBoolean
* @export $
* @param {string} fileName
* @param {string|Number} key
* @param {boolean} [defaultValue]
* @returns {boolean}
*/
function getSetIniDbBoolean(fileName, key, defaultValue) {
if ($.inidb.exists(fileName, key) == true) {
return ($.inidb.get(fileName, key) == 'true');
} else {
$.inidb.set(fileName, key, defaultValue.toString());
return (defaultValue);
}
}
/**
* @function setIniDbBoolean
* @export $
* @param {string} fileName
* @param {string|Number} key
* @param {boolean} state
*/
function setIniDbBoolean(fileName, key, state) {
$.inidb.set(fileName, key, state.toString());
}
/**
* @function getIniDbString
* @export $
* @param {string}
* @param {string}
* @param {string}
*/
function getIniDbString(fileName, key, defaultValue) {
if ($.inidb.exists(fileName, key) == true) {
return ($.inidb.get(fileName, key) + '');
} else {
return (defaultValue);
}
}
/**
* @function getSetIniDbString
* @export $
* @param {string}
* @param {string}
* @param {string}
*/
function getSetIniDbString(fileName, key, defaultValue) {
if ($.inidb.exists(fileName, key) == true) {
return ($.inidb.get(fileName, key) + '');
} else {
$.inidb.set(fileName, key, defaultValue);
return (defaultValue);
}
}
/**
* @function setIniDbString
* @export $
* @param {string}
* @param {string}
* @param {string}
*/
function setIniDbString(fileName, key, value) {
$.inidb.set(fileName, key, value);
}
/**
* @function getIniDbNumber
* @export $
* @param {string}
* @param {string}
* @param {number}
*/
function getIniDbNumber(fileName, key, defaultValue) {
if ($.inidb.exists(fileName, key) == true) {
return parseInt($.inidb.get(fileName, key));
} else {
return defaultValue;
}
}
/**
* @function getSetIniDbNumber
* @export $
* @param {string}
* @param {string}
* @param {number}
*/
function getSetIniDbNumber(fileName, key, defaultValue) {
if ($.inidb.exists(fileName, key) == true) {
return parseInt($.inidb.get(fileName, key));
} else {
$.inidb.set(fileName, key, defaultValue.toString());
return defaultValue;
}
}
/**
* @function setIniDbNumber
* @export $
* @param {string}
* @param {string}
* @param {number}
*/
function setIniDbNumber(fileName, key, value) {
$.inidb.set(fileName, key, value.toString());
}
/**
* @function getIniDbFloat
* @export $
* @param {string}
* @param {string}
* @param {number}
*/
function getIniDbFloat(fileName, key, defaultValue) {
if ($.inidb.exists(fileName, key) == true) {
return parseFloat($.inidb.get(fileName, key));
} else {
return defaultValue;
}
}
/**
* @function getSetIniDbFloat
* @export $
* @param {string}
* @param {string}
* @param {number}
*/
function getSetIniDbFloat(fileName, key, defaultValue) {
if ($.inidb.exists(fileName, key) == true) {
return parseFloat($.inidb.get(fileName, key));
} else {
$.inidb.set(fileName, key, defaultValue.toString());
return defaultValue;
}
}
/**
* @function setIniDbFloat
* @export $
* @param {string}
* @param {string}
* @param {number}
*/
function setIniDbFloat(fileName, key, value) {
$.inidb.set(fileName, key, value.toString());
}
/**
* @function paginateArray
* @export $
* @param {Array} Input array of data to paginate
* @param {String} Key in the $.lang system
* @param {String} Seperator to use between items
* @param {boolean} Use $.whisperPrefix(sender) ?
* @param {String} Value of sender for $.whisperPrefix
* @param {Number} Page to display, 0 for ALL
* @return {Number} Total number of pages.
*
*/
function paginateArray(array, langKey, sep, whisper, sender, display_page) {
var idx,
output = '',
maxlen,
hasNoLang = langKey.startsWith('NULL'),
pageCount = 0;
if (display_page === undefined) {
display_page = 0;
}
maxlen = 440 - (hasNoLang ? langKey.length : $.lang.get(langKey).length);
langKey = langKey.replace('NULL', '');
for (idx in array) {
output += array[idx];
if (output.length >= maxlen) {
pageCount++;
if (display_page === 0 || display_page === pageCount) {
if (output.length > 0) {
if (whisper) {
$.say($.whisperPrefix(sender) + (hasNoLang ? (langKey + output) : $.lang.get(langKey, output)));
} else {
$.say((hasNoLang ? (langKey + output) : $.lang.get(langKey, output)));
}
}
}
output = '';
} else {
if (idx < array.length - 1) {
output += sep;
}
}
}
pageCount++;
if (output.length > 0) {
if (display_page === 0 || display_page === pageCount) {
if (whisper) {
$.say($.whisperPrefix(sender) + (hasNoLang ? (langKey + output) : $.lang.get(langKey, output)));
} else {
$.say((hasNoLang ? (langKey + output) : $.lang.get(langKey, output)));
}
}
}
return pageCount;
}
/**
* @function paginateArrayDiscord
* @export $
* @param {Array} Input array of data to paginate
* @param {String} Key in the $.lang system
* @param {String} Seperator to use between items
* @param {String} Value of sender for $.whisperPrefix
* @param {Number} Page to display, 0 for ALL
* @return {Number} Total number of pages.
*
*/
function paginateArrayDiscord(array, langKey, sep, channel, sender, display_page) {
var idx,
output = '',
maxlen,
hasNoLang = langKey.startsWith('NULL'),
pageCount = 0;
if (display_page === undefined) {
display_page = 0;
}
maxlen = 1400 - (hasNoLang ? langKey.length : $.lang.get(langKey).length);
langKey = langKey.replace('NULL', '');
for (idx in array) {
output += array[idx];
if (output.length >= maxlen) {
pageCount++;
if (output.length > 0) {
if (display_page === 0 || display_page === pageCount) {
$.discord.say(channel, $.discord.userPrefix(sender) + ' ' + (hasNoLang ? (langKey + output) : $.lang.get(langKey, output)));
}
}
output = '';
} else {
if (idx < array.length - 1) {
output += sep;
}
}
}
pageCount++;
if (output.length > 0) {
if (display_page === 0 || display_page === pageCount) {
$.discord.say(channel, $.discord.userPrefix(sender) + ' ' + (hasNoLang ? (langKey + output) : $.lang.get(langKey, output)));
}
}
return pageCount;
}
/**
* Taken from: https://jsperf.com/replace-vs-split-join-vs-replaceall/95s
*
* Implementation of string.replaceAll
*
* @function replace
* @export $
* @param {string}
*/
function replace(str, from, to) {
var idx, parts = [], l = from.length, prev = 0;
for (; ~(idx = str.indexOf(from, prev)); ) {
parts.push(str.slice(prev, idx), to);
prev = idx + l;
}
parts.push(str.slice(prev));
return parts.join('');
}
/**
* Taken from: https://github.com/tc39/proposal-string-matchall
*
* Implementation of string.matchAll
*
* @function matchAll
* @export $
* @param {type} str
* @param {type} regex
* @returns {Array}
*/
function matchAll(str, regex) {
regex.lastIndex = 0;
var matches = [];
str.replace(regex, function () {
var match = Array.prototype.slice.call(arguments, 0, -2);
match.input = arguments[arguments.length - 1];
match.index = arguments[arguments.length - 2];
matches.push(match);
});
return matches;
}
function match(str, regex) {
regex.lastIndex = 0;
return str.match(regex);
}
function test(str, regex) {
regex.lastIndex = 0;
return regex.test(str);
}
function regexExec(str, regex) {
regex.lastIndex = 0;
return regex.exec(str);
}
/**
* @function userPrefix
* @export $
* @param {username}
*/
function userPrefix(username, comma) {
if (!comma) {
return '@' + $.username.resolve(username) + ' ';
}
return '@' + $.username.resolve(username) + ', ';
}
function javaString(str) {
return new Packages.java.lang.String(str);
}
function jsString(str) {
return String(str + '');
}
/** Export functions to API */
$.user = {
isKnown: isKnown,
isFollower: isFollower,
sanitize: sanitize
};
$.arrayShuffle = arrayShuffle;
$.getCurrentHostTarget = getCurrentHostTarget;
$.getIniDbBoolean = getIniDbBoolean;
$.getIniDbString = getIniDbString;
$.getIniDbNumber = getIniDbNumber;
$.getIniDbFloat = getIniDbFloat;
$.getSetIniDbBoolean = getSetIniDbBoolean;
$.getSetIniDbString = getSetIniDbString;
$.getSetIniDbNumber = getSetIniDbNumber;
$.getSetIniDbFloat = getSetIniDbFloat;
$.setIniDbBoolean = setIniDbBoolean;
$.setIniDbString = setIniDbString;
$.setIniDbNumber = setIniDbNumber;
$.setIniDbFloat = setIniDbFloat;
$.getOrdinal = getOrdinal;
$.getPercentage = getPercentage;
$.outOfRange = outOfRange;
$.rand = rand;
$.randElement = randElement;
$.randInterval = randInterval;
$.randRange = randRange;
$.say = say;
$.strlen = strlen;
$.systemTime = systemTime;
$.trueRand = trueRand;
$.trueRandElement = trueRandElement;
$.trueRandRange = trueRandRange;
$.paginateArray = paginateArray;
$.replace = replace;
$.matchAll = matchAll;
$.match = match;
$.test = test;
$.regexExec = regexExec;
$.userPrefix = userPrefix;
$.reloadMisc = reloadMisc;
$.hasKey = hasKey;
$.systemTimeNano = systemTimeNano;
$.getMessageWrites = getMessageWrites;
$.sayWithTimeout = sayWithTimeout;
$.paginateArrayDiscord = paginateArrayDiscord;
$.equalsIgnoreCase = equalsIgnoreCase;
$.javaString = javaString;
$.jsString = jsString;
})();

View File

@@ -0,0 +1,537 @@
/*
* Copyright (C) 2016-2020 phantombot.github.io/PhantomBot
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* This script is used to reload variables from scripts when you edit stuff on the panel. Only the bot can use these, and you can't disable them
*/
(function() {
$.bind('command', function(event) {
var sender = event.getSender(),
command = event.getCommand(),
args = event.getArgs(),
action = args[0];
/* reloads the betting vars */
if (command.equalsIgnoreCase('reloadbet')) {
if (!$.isBot(sender)) {
return;
}
$.reloadBet();
}
/** Adds or removes a user from the moderator cache */
if (command.equalsIgnoreCase('permissionsetuser')) {
if (!$.isBot(sender)) {
return;
}
if (parseInt(args[1]) <= 2) {
$.addModeratorToCache(action.toLowerCase());
} else {
$.removeModeratorFromCache(action.toLowerCase());
}
}
if (command.equalsIgnoreCase('reloadmisc')) {
if (!$.isBot(sender)) {
return;
}
$.reloadMisc();
$.reloadWhispers();
}
/*
* Reloads the tipeeestream vars.
*/
if (command.equalsIgnoreCase('tipeeestreamreload')) {
if (!$.isBot(sender)) {
return;
}
$.reloadTipeeeStream();
}
/*
* Reloads the streamelements vars.
*/
if (command.equalsIgnoreCase('streamelementsreload')) {
if (!$.isBot(sender)) {
return;
}
$.reloadStreamElements();
}
/*
* Sets permissions on a command.
*/
if (command.equalsIgnoreCase('permcomsilent')) {
if (!$.isBot(sender)) {
return;
}
if (args.length == 2) {
var group = args[1];
if (isNaN(parseInt(group))) {
group = $.getGroupIdByName(group);
}
var list = $.inidb.GetKeyList('aliases', ''),
i;
for (i in list) {
if (list[i].equalsIgnoreCase(action)) {
$.inidb.set('permcom', $.inidb.get('aliases', list[i]), group);
$.updateCommandGroup($.inidb.get('aliases', list[i]), group);
}
}
$.inidb.set('permcom', action, group);
$.updateCommandGroup(action, group);
return;
}
var subcommand = args[1],
group = args[2];
if (isNaN(parseInt(group))) {
group = $.getGroupIdByName(group);
}
$.inidb.set('permcom', action + ' ' + subcommand, group);
$.updateSubcommandGroup(action, subcommand, group);
return;
}
/*
* Reloads the command variables.
*/
if (command.equalsIgnoreCase('reloadcommand')) {
if (!$.isBot(sender)) {
return;
}
$.addComRegisterAliases();
$.addComRegisterCommands();
if (action) {
$.unregisterChatCommand(action);
}
return;
}
/*
* Registers a command
*/
if (command.equalsIgnoreCase('registerpanel')) {
if (!$.isBot(sender)) {
return;
}
$.registerChatCommand(($.inidb.exists('tempDisabledCommandScript', args[0].toLowerCase()) ? $.inidb.get('tempDisabledCommandScript', args[0].toLowerCase()) : './commands/customCommands.js'), args[0].toLowerCase());
$.inidb.del('tempDisabledCommandScript', args[0].toLowerCase());
return;
}
/*
* unregtisters a command
*/
if (command.equalsIgnoreCase('unregisterpanel')) {
if (!$.isBot(sender)) {
return;
}
$.tempUnRegisterChatCommand(args[0].toLowerCase());
return;
}
/*
* Reloads the moderation variables.
*/
if (command.equalsIgnoreCase('reloadmod')) {
if (!$.isBot(sender)) {
return;
}
$.reloadModeration();
}
if (command.equalsIgnoreCase('reloadkill')) {
if (!$.isBot(sender)) {
return;
}
$.reloadKill();
}
if (command.equalsIgnoreCase('reloadraid')) {
if (!$.isBot(sender)) {
return;
}
$.reloadRaid();
}
/* reloads the clip vars */
if (command.equalsIgnoreCase('reloadclip')) {
if (!$.isBot(sender)) {
return;
}
$.reloadClips();
}
/*
* Clears the highlight
*/
if (command.equalsIgnoreCase("clearhighlightspanel")) {
if (!$.isBot(sender)) {
return;
}
$.inidb.RemoveFile("highlights");
return;
}
/*
* makes a highlight
*/
if (command.equalsIgnoreCase('highlightpanel')) {
if (!$.isBot(sender)) {
return;
}
if (!$.isOnline($.channelName)) {
return;
}
var streamUptimeMinutes = parseInt($.getStreamUptimeSeconds($.channelName) / 60);
var hours = parseInt(streamUptimeMinutes / 60);
var minutes = parseInt(streamUptimeMinutes % 60);
if (minutes < 10) {
minutes = "0" + minutes;
}
timestamp = hours + ":" + minutes;
localDate = $.getCurLocalTimeString("'['dd-MM-yyyy']'");
$.inidb.set('highlights', timestamp, localDate + ' ' + args.splice(0).join(' '));
}
/*
* Sets the title on stream
*/
if (command.equalsIgnoreCase('settitlesilent')) {
if (!$.isBot(sender)) {
return;
}
var argsString = args.splice(0).join(' ');
$.updateStatus($.channelName, argsString, sender, true);
return;
}
/*
* Sets the game on stream
*/
if (command.equalsIgnoreCase('setgamesilent')) {
if (!$.isBot(sender)) {
return;
}
var argsString = args.splice(0).join(' ');
$.updateGame($.channelName, argsString, sender, true);
return;
}
/*
* Sets the community on stream
*/
if (command.equalsIgnoreCase('setcommunitysilent')) {
if (!$.isBot(sender)) {
return;
}
var argsString = args.join(' ').split(', ');
$.updateCommunity($.channelName, argsString, sender, true);
return;
}
/*
* Reloads the adventure variables.
*/
if (command.equalsIgnoreCase('reloadadventure')) {
if (!$.isBot(sender)) {
return;
}
$.reloadAdventure();
return;
}
/*
* Reloads the gambling variables.
*/
if (command.equalsIgnoreCase('reloadgamble')) {
if (!$.isBot(sender)) {
return;
}
$.reloadGamble();
return;
}
/*
* Reloads the roll variables.
*/
if (command.equalsIgnoreCase('loadprizesroll')) {
if (!$.isBot(sender)) {
return;
}
$.loadPrizes();
return;
}
/*
* Reloads the roulette variables.
*/
if (command.equalsIgnoreCase('reloadroulette')) {
if (!$.isBot(sender)) {
return;
}
$.reloadRoulette();
return;
}
/*
* Reloads the slot variables.
*/
if (command.equalsIgnoreCase('loadprizes')) {
if (!$.isBot(sender)) {
return;
}
$.loadPrizesSlot();
return;
}
/*
* Reloads the bits variables.
*/
if (command.equalsIgnoreCase('reloadbits')) {
if (!$.isBot(sender)) {
return;
}
$.reloadBits();
return;
}
/*
* Reloads the donation variables.
*/
if (command.equalsIgnoreCase('donationpanelupdate')) {
if (!$.isBot(sender)) {
return;
}
$.donationpanelupdate();
return;
}
/*
* Reloads the follow variables.
*/
if (command.equalsIgnoreCase('followerpanelupdate')) {
if (!$.isBot(sender)) {
return;
}
$.updateFollowConfig();
return;
}
/*
* Reloads the host variables.
*/
if (command.equalsIgnoreCase('reloadhost')) {
if (!$.isBot(sender)) {
return;
}
$.updateHost();
return;
}
/*
* Reloads the subscriber variables.
*/
if (command.equalsIgnoreCase('subscriberpanelupdate')) {
if (!$.isBot(sender)) {
return;
}
$.updateSubscribeConfig();
return;
}
/*
* Reloads the greeting variables.
*/
if (command.equalsIgnoreCase('greetingspanelupdate')) {
if (!$.isBot(sender)) {
return;
}
$.greetingspanelupdate();
return;
}
/*
* Reloads the notice variables.
*/
if (command.equalsIgnoreCase('reloadnotice')) {
if (!$.isBot(sender)) {
return;
}
$.reloadNoticeSettings();
}
/*
* Reloads the points variables.
*/
if (command.equalsIgnoreCase('reloadpoints')) {
if (!$.isBot(sender)) {
return;
}
$.updateSettings();
return;
}
/*
* Sets a points bonus
*/
if (command.equalsIgnoreCase('pointsbonuspanel')) {
if (!$.isBot(sender)) {
return;
}
$.setTempBonus(action, args[1]);
return;
}
/*
* Gives points to everyone in the channel
*/
if (command.equalsIgnoreCase('pointsallpanel')) {
if (!$.isBot(sender)) {
return;
}
for (var i in $.users) {
$.inidb.incr('points', $.users[i].toLowerCase(), parseInt(action));
}
return;
}
/*
* Takes points from everyone in the channel
*/
if (command.equalsIgnoreCase('pointstakeallpanel')) {
if (!$.isBot(sender)) {
return;
}
for (var i in $.users) {
if ($.getUserPoints($.users[i].toLowerCase()) > parseInt(action)) {
$.inidb.decr('points', $.users[i].toLowerCase(), parseInt(action));
}
}
return;
}
/*
* Reloads the raffle variables.
*/
if (command.equalsIgnoreCase('reloadraffle')) {
if (!$.isBot(sender)) {
return;
}
$.reloadRaffle();
return;
}
/*
* Reloads the rank variables.
*/
if (command.equalsIgnoreCase('rankreloadtable')) {
if (!$.isBot(sender)) {
return;
}
$.loadRanksTimeTable();
return;
}
/*
* Reloads the ticket raffle variables.
*/
if (command.equalsIgnoreCase('reloadtraffle')) {
if (!$.isBot(sender)) {
return;
}
$.reloadTRaffle();
return;
}
/*
* Reloads the time variables.
*/
if (command.equalsIgnoreCase('updatetimesettings')) {
if (!$.isBot(sender)) {
return;
}
$.updateTimeSettings();
return;
}
/*
* Reloads the log variables.
*/
if (command.equalsIgnoreCase('reloadlogs')) {
if (!$.isBot(sender)) {
return;
}
$.reloadLogs();
return;
}
});
$.bind('initReady', function() {
/* 10 second delay here because I don't want these commands to be registered first. */
setTimeout(function() {
$.registerChatCommand('./core/panelCommands.js', 'permissionsetuser', 30);
$.registerChatCommand('./core/panelCommands.js', 'reloadcommand', 30);
$.registerChatCommand('./core/panelCommands.js', 'permcomsilent', 30);
$.registerChatCommand('./core/panelCommands.js', 'registerpanel', 30);
$.registerChatCommand('./core/panelCommands.js', 'unregisterpanel', 30);
$.registerChatCommand('./core/panelCommands.js', 'reloadmod', 30);
$.registerChatCommand('./core/panelCommands.js', 'clearhighlightspanel', 30);
$.registerChatCommand('./core/panelCommands.js', 'highlightpanel', 30);
$.registerChatCommand('./core/panelCommands.js', 'settitlesilent', 30);
$.registerChatCommand('./core/panelCommands.js', 'setgamesilent', 30);
$.registerChatCommand('./core/panelCommands.js', 'reloadadventure', 30);
$.registerChatCommand('./core/panelCommands.js', 'reloadgamble', 30);
$.registerChatCommand('./core/panelCommands.js', 'loadprizesroll', 30);
$.registerChatCommand('./core/panelCommands.js', 'reloadroulette', 30);
$.registerChatCommand('./core/panelCommands.js', 'loadprizes', 30);
$.registerChatCommand('./core/panelCommands.js', 'reloadbits', 30);
$.registerChatCommand('./core/panelCommands.js', 'donationpanelupdate', 30);
$.registerChatCommand('./core/panelCommands.js', 'followerpanelupdate', 30);
$.registerChatCommand('./core/panelCommands.js', 'reloadhost', 30);
$.registerChatCommand('./core/panelCommands.js', 'subscriberpanelupdate', 30);
$.registerChatCommand('./core/panelCommands.js', 'greetingspanelupdate', 30);
$.registerChatCommand('./core/panelCommands.js', 'reloadnotice', 30);
$.registerChatCommand('./core/panelCommands.js', 'reloadpoints', 30);
$.registerChatCommand('./core/panelCommands.js', 'pointsallpanel', 30);
$.registerChatCommand('./core/panelCommands.js', 'pointsbonuspanel', 30);
$.registerChatCommand('./core/panelCommands.js', 'pointstakeallpanel', 30);
$.registerChatCommand('./core/panelCommands.js', 'reloadraffle', 30);
$.registerChatCommand('./core/panelCommands.js', 'rankreloadtable', 30);
$.registerChatCommand('./core/panelCommands.js', 'reloadtraffle', 30);
$.registerChatCommand('./core/panelCommands.js', 'updatetimesettings', 30);
$.registerChatCommand('./core/panelCommands.js', 'reloadlogs', 30);
$.registerChatCommand('./core/panelCommands.js', 'reloadbet', 30);
$.registerChatCommand('./core/panelCommands.js', 'tipeeestreamreload', 30);
$.registerChatCommand('./core/panelCommands.js', 'streamelementsreload', 30);
$.registerChatCommand('./core/panelCommands.js', 'setcommunitysilent', 30);
$.registerChatCommand('./core/panelCommands.js', 'reloadclip', 30);
$.registerChatCommand('./core/panelCommands.js', 'reloadkill', 30);
$.registerChatCommand('./core/panelCommands.js', 'reloadraid', 30);
$.registerChatCommand('./core/panelCommands.js', 'reloadmisc', 30);
}, 10000);
});
})();

View File

@@ -0,0 +1,231 @@
/*
* Copyright (C) 2016-2020 phantombot.github.io/PhantomBot
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
// Only tracks data for now.
(function() {
/*
* @function addObjectToArray
*
* @param {String} table
* @param {String} key
* @param {String} type
* @param {Object} object
*/
function addObjectToArray(table, key, type, object) {
var array = ($.inidb.exists(table, key) ? JSON.parse($.inidb.get(table, key)) : []);
// Make sure it is an array.
if (object.type === undefined) {
object.type = type;
}
// Add the object to the array.
array.push(object);
// Only keep 50 objects in the array.
if (array.length > 50) {
// Sort for newer events
array.sort(function(a, b) {
return b.date - a.date;
});
// Remove old events.
array = array.slice(0, 50);
}
// Save it.
saveObject(table, key, array);
}
/*
* @function saveObject
*
* @param {String} table
* @param {String} key
* @param {Object} object
*/
function saveObject(table, key, object) {
$.inidb.set(table, key, JSON.stringify(object, function(key, value) {
try {
if (value.getClass() !== null) {
switch (value) {
case value instanceof java.lang.Number:
return parseInt(value);
case value instanceof java.lang.Boolean:
return value.booleanValue();
default:
return (value + '');
}
}
} catch (e) {
// Ignore
}
return value;
}));
}
/*
* @function getFormatedUptime
*/
function getFormatedUptime() {
var streamUptimeMinutes = parseInt($.getStreamUptimeSeconds($.channelName) / 60),
hours = parseInt(streamUptimeMinutes / 60),
minutes = (parseInt(streamUptimeMinutes % 60) < 10 ? '0' + parseInt(streamUptimeMinutes % 60) : parseInt(streamUptimeMinutes % 60)),
timestamp = hours + ':' + minutes;
return timestamp;
}
/*
* @function updateStreamData
*/
function updateStreamData() {
saveObject('panelData', 'stream', {
'communities': $.twitchcache.getCommunities().join(','),
'views' : $.twitchcache.getViews() + '',
'followers' : $.getFollows($.channelName),
'viewers' : $.getViewers($.channelName),
'title' : $.getStatus($.channelName),
'isLive' : $.isOnline($.channelName),
'game' : $.getGame($.channelName),
'uptime' : getFormatedUptime(),
'chatters' : $.users.length,
});
}
/*
* @event twitchOnline
*/
$.bind('twitchOnline', function() {
updateStreamData();
});
/*
* @event twitchOffline
*/
$.bind('twitchOffline', function() {
updateStreamData();
});
/*
* @event twitchFollow
*/
$.bind('twitchFollow', function(event) {
addObjectToArray('panelData', 'data', 'Follower', {
'username': event.getFollower(),
'date' : $.systemTime()
});
});
/*
* @event bits
*/
$.bind('twitchBits', function(event) {
addObjectToArray('panelData', 'data', 'Bits', {
'username': event.getUsername(),
'amount' : event.getBits(),
'date' : $.systemTime()
});
});
/*
* @event twitchAutoHosted
*/
$.bind('twitchAutoHosted', function(event) {
addObjectToArray('panelData', 'data', 'Auto-Host', {
'username': event.getHoster(),
'viewers' : event.getUsers(),
'date' : $.systemTime(),
'isAuto' : true
});
});
/*
* @event twitchHosted
*/
$.bind('twitchHosted', function(event) {
addObjectToArray('panelData', 'data', 'Host', {
'username': event.getHoster(),
'viewers' : event.getUsers(),
'date' : $.systemTime(),
'isAuto' : false
});
});
/*
* @event twitchSubscriber
*/
$.bind('twitchSubscriber', function(event) {
addObjectToArray('panelData', 'data', 'Subscriber', {
'username': event.getSubscriber(),
'date' : $.systemTime(),
'isReSub' : false,
'months' : 0
});
});
/*
* @event twitchPrimeSubscriber
*/
$.bind('twitchPrimeSubscriber', function(event) {
addObjectToArray('panelData', 'data', 'Prime Subscriber', {
'username': event.getSubscriber(),
'date' : $.systemTime(),
'isReSub' : false,
'months' : 0
});
});
/*
* @event twitchReSubscriber
*/
$.bind('twitchReSubscriber', function(event) {
addObjectToArray('panelData', 'data', 'ReSubscriber', {
'username': event.getReSubscriber(),
'months' : event.getMonths(),
'date' : $.systemTime(),
'isReSub' : true
});
});
/*
* @event twitchSubscriptionGift
*/
$.bind('twitchSubscriptionGift', function(event) {
addObjectToArray('panelData', 'data', 'Gifted Subscription', {
'recipient': event.getRecipient(),
'username' : event.getUsername(),
'months' : event.getMonths(),
'date' : $.systemTime(),
'isReSub' : (parseInt(event.getMonths()) > 1)
});
});
/*
* @event twitchRaid
*/
$.bind('twitchRaid', function(event) {
addObjectToArray('panelData', 'data', 'Raid', {
'username' : event.getUsername(),
'viewers' : event.getViewers(),
'date' : $.systemTime()
});
});
// Interval that updates stream data.
setInterval(updateStreamData, 2e4);
})();

View File

@@ -0,0 +1,210 @@
/*
* Copyright (C) 2016-2020 phantombot.github.io/PhantomBot
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* patterDetector.js
*
* Export an API for checking chat messages for links, email addresses, excessive character sequenses etc.
* Use the $.patternDetector API
*/
(function() {
var patterns = {
link: new RegExp('((?:(http|https|rtsp):\\/\\/(?:(?:[a-z0-9\\$\\-\\_\\.\\+\\!\\*\\\'\\(\\)' + '\\,\\;\\?\\&\\=]|(?:\\%[a-fA-F0-9]{2})){1,64}(?:\\:(?:[a-z0-9\\$\\-\\_' + '\\.\\+\\!\\*\\\'\\(\\)\\,\\;\\?\\&\\=]|(?:\\%[a-fA-F0-9]{2})){1,25})?\\@)?)?' + '((?:(?:[a-z0-9][a-z0-9\\-]{0,64}\\.)+' + '(?:' + '(?:aero|a[cdefgilmnoqrstuwxz])' + '|(?:biz|bike|bot|b[abdefghijmnorstvwyz])' + '|(?:com|c[acdfghiklmnoruvxyz])' + '|d[ejkmoz]' + '|(?:edu|e[cegrstu])' + '|(?:fyi|f[ijkmor])' + '|(?:gov|g[abdefghilmnpqrstuwy])' + '|(?:how|h[kmnrtu])' + '|(?:info|i[delmnoqrst])' + '|(?:jobs|j[emop])' + '|k[eghimnrwyz]' + '|l[abcikrstuvy]' + '|(?:mil|mobi|moe|m[acdeghklmnopqrstuvwxyz])' + '|(?:name|net|n[acefgilopruz])' + '|(?:org|om)' + '|(?:pro|p[aefghklmnrstwy])' + '|qa' + '|(?:r[eouw])' + '|(?:s[abcdeghijklmnortuvyz])' + '|(?:t[cdfghjklmnoprtvwz])' + '|u[agkmsyz]' + '|(?:vote|v[ceginu])' + '|(?:xxx)' + '|(?:watch|w[fs])' + '|y[etu]' + '|z[amw]))' + '|(?:(?:25[0-5]|2[0-4]' + '[0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9])\\.(?:25[0-5]|2[0-4][0-9]' + '|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(?:25[0-5]|2[0-4][0-9]|[0-1]' + '[0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(?:25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}' + '|[1-9][0-9]|[0-9])))' + '(?:\\:\\d{1,5})?)' + '(\\/(?:(?:[a-z0-9\\;\\/\\?\\:\\@\\&\\=\\#\\~' + '\\-\\.\\+\\!\\*\\\'\\(\\)\\,\\_])|(?:\\%[a-fA-F0-9]{2}))*)?' + '(?:\\b|$)' + '|(\\.[a-z]+\\/|magnet:\/\/|mailto:\/\/|ed2k:\/\/|irc:\/\/|ircs:\/\/|skype:\/\/|ymsgr:\/\/|xfire:\/\/|steam:\/\/|aim:\/\/|spotify:\/\/)', 'ig'),
emotes: new RegExp('([0-9][0-9]-[0-9][0-9])|([0-9]-[0-9])', 'g'),
repeatedSeq: /(.)(\1+)/ig,
nonAlphaSeq: /([^a-z0-9 ])(\1+)/ig,
nonAlphaCount: /([^a-z0-9 ])/ig,
capsCount: /([A-Z])/g,
meCheck: /^\/me/,
fakePurge: new RegExp(/^<message \w+>|^<\w+ deleted>/i)
};
/**
* @function hasLinks
* @export $.patternDetector
* @param {Object} event
* @returns {boolean}
*/
function hasLinks(event) {
return $.test(event.getMessage(), patterns.link);
}
/**
* @function getLinks
* @export $.patternDetector
* @param {String} message
* @returns {string[]}
*/
function getLinks(message) {
// turn Java String into JavaScript string
// https://github.com/mozilla/rhino/issues/638
message = message + '';
return $.match(message, patterns.link);
}
/**
* @function logLastLink
* @export $.patternDetector
*/
function logLastLink(event) {
$.log.file('patternDetector', 'Matched link on message from ' + event.getSender() + ': ' + $.regexExec(event.getMessage(), patterns.link)[0]);
}
/**
* @function getLongestRepeatedSequence
* @export $.patternDetector
* @param {Object} event
* @returns {number}
*/
function getLongestRepeatedSequence(event) {
var sequences = $.match(event.getMessage(), patterns.repeatedSeq);
return (sequences === null ? 0 : sequences.sort(function(a, b) {
return b.length - a.length;
})[0].length);
}
/**
* @function getLongestNonLetterSequence
* @export $.patternDetector
* @param {Object} event
* @returns {number}
*/
function getLongestNonLetterSequence(event) {
var message = (event.getMessage() + ''),
sequences = $.match(message, patterns.nonAlphaSeq);
return (sequences === null ? 0 : sequences.sort(function(a, b) {
return b.length - a.length;
})[0].length);
}
/**
* @function getNumberOfNonLetters
* @export $.patternDetector
* @param {Object} event
* @returns {number}
*/
function getNumberOfNonLetters(event) {
var sequences = $.match(event.getMessage(), patterns.nonAlphaCount);
return (sequences === null ? 0 : sequences.length);
}
/**
* @function getEmotesCount
* @export $.patternDetector
* @param {Object} event
* @returns {number}
* @info this gets the emote count from the ircv3 tags and the emotes cache if enabled.
*/
function getEmotesCount(event) {
var emotes = event.getTags().get('emotes'),
matched = $.match(emotes, patterns.emotes),
extraEmotes = $.emotesHandler.getEmotesMatchCount(event.getMessage());
return (matched === null ? extraEmotes : (matched.length + extraEmotes));
}
/**
* @function getMessageWithoutEmotes
* @export $.patternDetector
* @param {Object} event
* @returns {string}
*/
function getMessageWithoutEmotes(event, message) {
var emotes = event.getTags().get('emotes'),
str = message,
i;
if (emotes.length() > 0) {
emotes = emotes.replaceAll('[0-9]+:', '').split('/');
for (i in emotes) {
str = str.replace(getWordAt(message, parseInt(emotes[i].split('-')[0])), '');
}
}
return str;
}
/**
* @function getWordAt
*
* @param {String} str
* @param {Number} pos
* @return {String}
*/
function getWordAt(str, pos) {
str = String(str);
pos = pos >>> 0;
var left = str.slice(0, pos + 2).search(/\S+$/),
right = str.slice(pos).search(/\s/);
if (right < 0) {
return str.slice(left);
}
return str.slice(left, right + pos);
}
/**
* @function getNumberOfCaps
* @export $.patternDetector
* @param {Object} event
* @returns {number}
*/
function getNumberOfCaps(event) {
var sequences = $.match(getMessageWithoutEmotes(event, event.getMessage()), patterns.capsCount);
return (sequences === null ? 0 : sequences.length);
}
/**
* @function getColoredMessage
* @export $.patternDetector
* @param {Object} event
* @returns {boolean}
*/
function getColoredMessage(event) {
return event.getMessage().indexOf('/me') === 0;
}
/**
* @function getFakePurge
* @export $.patternDetector
* @param {Object} event
* @returns {boolean}
*/
function getFakePurge(event) {
return $.test(String(event.getMessage()).replace(patterns.meCheck, ''), patterns.fakePurge);
}
/** Export functions to API */
$.patternDetector = {
hasLinks: hasLinks,
getLinks: getLinks,
getLongestRepeatedSequence: getLongestRepeatedSequence,
getLongestNonLetterSequence: getLongestNonLetterSequence,
getNumberOfNonLetters: getNumberOfNonLetters,
getEmotesCount: getEmotesCount,
getMessageWithoutEmotes: getMessageWithoutEmotes,
getNumberOfCaps: getNumberOfCaps,
logLastLink: logLastLink,
getColoredMessage: getColoredMessage,
getFakePurge: getFakePurge
};
})();

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,531 @@
/*
* Copyright (C) 2016-2020 phantombot.github.io/PhantomBot
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
(function() {
var currentGame = null;
var count = 1;
var gamesPlayed;
/**
* @event twitchOnline
*/
$.bind('twitchOnline', function(event) {
if (($.systemTime() - $.inidb.get('panelstats', 'playTimeReset')) >= (480 * 6e4)) {
var uptime = getStreamUptimeSeconds($.channelName);
$.inidb.set('panelstats', 'gameCount', 1);
count = $.inidb.get('panelstats', 'gameCount');
$.inidb.del('streamInfo', 'gamesPlayed');
$.inidb.set('panelstats', 'playTimeStart', $.systemTime());
$.inidb.set('panelstats', 'playTimeReset', $.systemTime());
$.inidb.set('streamInfo', 'gamesPlayed', (count + ': ' + $.twitchcache.getGameTitle() + ' - ' + (uptime / 3600 < 10 ? '0' : '') + Math.floor(uptime / 3600) + ':' + ((uptime % 3600) / 60 < 10 ? '0' : '') + Math.floor((uptime % 3600) / 60) + '='));
}
});
/**
* @event twitchOffline
*/
$.bind('twitchOffline', function(event) {
if (($.systemTime() - $.inidb.get('panelstats', 'playTimeReset')) >= (480 * 6e4)) {
$.inidb.set('panelstats', 'playTimeStart', 0);
$.inidb.set('panelstats', 'playTimeReset', 0);
$.inidb.set('panelstats', 'gameCount', 1);
$.inidb.del('streamInfo', 'gamesPlayed');
}
$.inidb.set('streamInfo', 'downtime', String($.systemTime()));
});
/**
* @event twitchGameChange
*/
$.bind('twitchGameChange', function(event) {
var uptime = getStreamUptimeSeconds($.channelName);
if ($.isOnline($.channelName)) {
$.inidb.set('panelstats', 'playTimeStart', $.systemTime());
if ($.inidb.exists('streamInfo', 'gamesPlayed')) {
$.inidb.incr('panelstats', 'gameCount', 1);
count = $.inidb.get('panelstats', 'gameCount');
gamesPlayed = $.inidb.get('streamInfo', 'gamesPlayed');
gamesPlayed += (count + ': ' + $.twitchcache.getGameTitle() + ' - ' + (uptime / 3600 < 10 ? '0' : '') + Math.floor(uptime / 3600) + ':' + ((uptime % 3600) / 60 < 10 ? '0' : '') + Math.floor((uptime % 3600) / 60) + '=');
$.inidb.set('streamInfo', 'gamesPlayed', gamesPlayed);
} else {
count = $.inidb.get('panelstats', 'gameCount');
$.inidb.set('streamInfo', 'gamesPlayed', (count + ': ' + $.twitchcache.getGameTitle() + ' - ' + (uptime / 3600 < 10 ? '0' : '') + Math.floor(uptime / 3600) + ':' + ((uptime % 3600) / 60 < 10 ? '0' : '') + Math.floor((uptime % 3600) / 60) + '='));
}
}
});
/**
* @function getGamesPlayed()
* @export $
* @return string
*/
function getGamesPlayed() {
if ($.inidb.exists('streamInfo', 'gamesPlayed')) {
var games = $.inidb.get('streamInfo', 'gamesPlayed'),
string = games.split('=').join(', ');
return string;
}
return '';
}
/**
* @function getPlayTime()
* @export $
*/
function getPlayTime() {
var playTime = parseInt($.inidb.get('panelstats', 'playTimeStart')),
time;
if (playTime) {
time = ($.systemTime() - playTime);
return $.getTimeStringMinutes(time / 1000);
} else {
return null;
}
}
/**
* @function isOnline
* @export $
* @param {string} channelName
* @returns {boolean}
*/
function isOnline(channelName) {
if ($.twitchCacheReady.equals('true') && channelName.equalsIgnoreCase($.channelName)) {
return $.twitchcache.isStreamOnlineString().equals('true');
} else {
return !$.twitch.GetStream(channelName).isNull('stream');
}
}
/**
* @function getStatus
* @export $
* @param {string} channelName
* @returns {string}
*/
function getStatus(channelName) {
if ($.twitchCacheReady.equals('true') && channelName.equalsIgnoreCase($.channelName)) {
return ($.twitchcache.getStreamStatus() + '');
} else {
var channelData = $.twitch.GetChannel(channelName);
if (!channelData.isNull('status') && channelData.getInt('_http') == 200) {
return channelData.getString('status');
} else if (channelData.isNull('status') && channelData.getInt('_http') == 200) {
return $.lang.get('common.twitch.no.status');
}
$.log.error('Failed to get the current status: ' + channelData.getString('message'));
return '';
}
}
/**
* @function getGame
* @export $
* @param channelName
* @returns {string}
*/
function getGame(channelName) {
if ($.twitchCacheReady.equals('true') && channelName.equalsIgnoreCase($.channelName)) {
return ($.twitchcache.getGameTitle() + '');
} else {
var channelData = $.twitch.GetChannel(channelName);
if (!channelData.isNull('game') && channelData.getInt('_http') == 200) {
return channelData.getString("game");
} else if (channelData.isNull('game') && channelData.getInt('_http') == 200) {
return $.lang.get('common.twitch.no.game');
}
if (!channelData.isNull('message')) {
$.log.error('Failed to get the current game: ' + channelData.getString('message'));
}
return '';
}
}
/**
* @function getLogo
* @export $
* @param channelName
* @returns {Url}
*/
function getLogo(channelName) {
var channel = $.twitch.GetChannel(channelName);
if (!channel.isNull('logo') && channel.getInt('_http') == 200) {
return channel.getString('logo');
} else {
return 0;
}
}
/**
* @function getStreamUptimeSeconds
* @export $
* @param channelName
* @returns {number}
*/
function getStreamUptimeSeconds(channelName) {
if ($.twitchCacheReady.equals('true') && channelName.equalsIgnoreCase($.channelName)) {
return $.twitchcache.getStreamUptimeSeconds();
} else {
var stream = $.twitch.GetStream(channelName),
now = new Date(),
createdAtDate,
time;
if (stream.isNull('stream')) {
return 0;
}
createdAtDate = new Date(stream.getJSONObject('stream').getString('created_at'));
if (createdAtDate) {
time = (now - createdAtDate);
return Math.floor(time / 1000);
} else {
return 0;
}
}
}
/**
* @function getStreamUptime
* @export $
* @param channelName
* @returns {string}
*/
function getStreamUptime(channelName) {
if ($.twitchCacheReady.equals('true') && channelName.equalsIgnoreCase($.channelName)) {
var uptime = $.twitchcache.getStreamUptimeSeconds();
if (uptime === 0) {
$.consoleLn("Fallback uptime");
var stream = $.twitch.GetStream(channelName),
now = new Date(),
createdAtDate,
time;
if (stream.isNull('stream')) {
return '';
}
createdAtDate = new Date(stream.getJSONObject('stream').getString('created_at'));
time = (now - createdAtDate);
return $.getTimeString(time / 1000);
}
return $.getTimeString(uptime);
} else {
var stream = $.twitch.GetStream(channelName),
now = new Date(),
createdAtDate,
time;
if (stream.isNull('stream')) {
return '';
}
createdAtDate = new Date(stream.getJSONObject('stream').getString('created_at'));
if (createdAtDate) {
time = now - createdAtDate;
return $.getTimeString(time / 1000);
} else {
return '';
}
}
}
/**
* @function getStreamDownTime
* @export $
* @returns {string}
*/
function getStreamDownTime() {
var now = $.systemTime(),
down = $.inidb.get('streamInfo', 'downtime'),
time;
if (down > 0) {
time = (now - down);
return $.getTimeString(time / 1000);
}
return 0;
}
/**
* @function getStreamStartedAt
* @export $
* @param channelName
* @returns {string}
*/
function getStreamStartedAt(channelName) {
if ($.twitchCacheReady.equals('true') && channelName.equalsIgnoreCase($.channelName)) {
if ($.twitchcache.getStreamOnlineString === 'false') {
return 'Stream is offline';
}
createdAtDate = new Date($.twitchcache.getStreamCreatedAt() + '');
return $.dateToString(createdAtDate);
} else {
var stream = $.twitch.GetStream(channelName),
createdAtDate;
if (stream.isNull('stream')) {
return 0;
}
createdAtDate = new Date(stream.getJSONObject('stream').getString('created_at'));
return $.dateToString(createdAtDate);
}
}
/**
* @function getViewers
* @export $
* @param channelName
* @returns {Number}
*/
function getViewers(channelName) {
if ($.twitchCacheReady.equals('true') && channelName.equalsIgnoreCase($.channelName)) {
return $.twitchcache.getViewerCount();
} else {
var stream = $.twitch.GetStream(channelName);
if (!stream.isNull('stream') && stream.getInt('_http') == 200) {
return stream.getJSONObject('stream').getInt('viewers');
} else {
return 0;
}
}
}
/**
* @function getFollows
* @export $
* @param channelName
* @returns {Number}
*/
function getFollows(channelName) {
var channel = $.twitch.GetChannel(channelName);
if (!channel.isNull('followers') && channel.getInt('_http') == 200) {
return channel.getInt('followers');
} else {
return 0;
}
}
/**
* @function getFollowDate
* @export $
* @param username
* @param channelName
*/
function getFollowDate(sender, username, channelName) {
username = $.user.sanitize(username);
channelName = $.user.sanitize(channelName);
var user = $.twitch.GetUserFollowsChannel(username, channelName);
if (user.getInt('_http') === 404) {
return $.lang.get('followhandler.follow.age.datefmt.404');
}
var date = new Date(user.getString('created_at')),
dateFormat = new java.text.SimpleDateFormat($.lang.get('followhandler.follow.age.datefmt')),
dateFinal = dateFormat.format(date);
return dateFinal;
}
/**
* @function getFollowAge
* @export $
* @param username
* @param channelName
*/
function getFollowAge(sender, username, channelName) {
username = $.user.sanitize(username);
channelName = $.user.sanitize(channelName);
var user = $.twitch.GetUserFollowsChannel(username, channelName);
if (user.getInt('_http') === 404) {
$.say($.lang.get('followhandler.follow.age.err.404', $.userPrefix(sender, true), username, channelName));
return;
}
var date = new Date(user.getString('created_at')),
dateFormat = new java.text.SimpleDateFormat("MMMM dd', 'yyyy"),
dateFinal = dateFormat.format(date),
days = Math.floor((($.systemTime() - date.getTime()) / 1000) / 86400);
if (days > 0) {
$.say($.lang.get('followhandler.follow.age.time.days', $.userPrefix(sender, true), username, channelName, dateFinal, days));
} else {
$.say($.lang.get('followhandler.follow.age.time', $.userPrefix(sender, true), username, channelName, dateFinal));
}
}
/**
* @function getChannelAge
* @export $
* @param event
*/
function getChannelAge(event) {
var channelData = $.twitch.GetChannel((!event.getArgs()[0] ? event.getSender() : $.user.sanitize(event.getArgs()[0])));
if (channelData.getInt('_http') === 404) {
$.say($.userPrefix(event.getSender(), true) + $.lang.get('channel.age.user.404'));
return;
}
var date = new Date(channelData.getString('created_at')),
dateFormat = new java.text.SimpleDateFormat("MMMM dd', 'yyyy"),
dateFinal = dateFormat.format(date),
days = Math.floor((Math.abs((date.getTime() - $.systemTime()) / 1000)) / 86400);
if (days > 0) {
$.say($.lang.get('common.get.age.days', $.userPrefix(event.getSender(), true), (!event.getArgs()[0] ? event.getSender() : $.user.sanitize(event.getArgs()[0])), dateFinal, days));
} else {
$.say($.lang.get('common.get.age', $.userPrefix(event.getSender(), true), (!event.getArgs()[0] ? event.getSender() : $.user.sanitize(event.getArgs()[0])), dateFinal));
}
}
/**
* @function getSubscriberCount
* @export $
* @return {number} count
*/
function getSubscriberCount() {
var jsonObject = $.twitch.GetChannelSubscriptions($.channelName.toLowerCase(), 100, 0, true);
if (jsonObject.getInt('_http') !== 200) {
return 0;
}
return jsonObject.getInt('_total') - 1;
}
/**
* @function updateGame
* @export $
* @param {string} channelName
* @param {string} game
* @param {string} sender
* @param {boolean} silent
*/
function updateGame(channelName, game, sender, silent) {
var http = $.twitch.UpdateChannel(channelName, '', game);
if (http.getBoolean('_success')) {
if (http.getInt('_http') == 200) {
if (!silent) {
$.say($.lang.get('common.game.change', http.getString('game')));
}
$.twitchcache.setGameTitle(http.getString('game'));
$.inidb.set('streamInfo', 'game', http.getString('game'));
$.log.event($.username.resolve(sender) + ' changed the current game to ' + http.getString('game'));
if ($.bot.isModuleEnabled('./commands/deathctrCommand.js')) {
$.deathUpdateFile(game);
}
} else {
$.log.error('Failed to change the game. The Twitch API might be having issues.');
$.log.error(http.getString('message'));
}
} else {
$.log.error('Failed to change the game. Make sure you have your api oauth code set. https://phantombot.github.io/PhantomBot/oauth/');
$.log.error(http.getString('_exception') + ' ' + http.getString('_exceptionMessage'));
}
}
/**
* @function updateStatus
* @export $
* @param {string} channelName
* @param {string} status
* @param {string} sender
* @param {boolean} silent
*/
function updateStatus(channelName, status, sender, silent) {
var http = $.twitch.UpdateChannel(channelName, status, '');
if (http.getBoolean('_success')) {
if (http.getInt('_http') == 200) {
if (!silent) {
$.say($.lang.get('common.title.change', http.getString('status')));
}
$.twitchcache.setStreamStatus(http.getString('status'));
$.inidb.set('streamInfo', 'title', http.getString('status'));
$.log.event(sender + ' changed the current status to ' + http.getString('status'));
} else {
$.log.error('Failed to change the status. The Twitch API might be having issues.');
$.log.error(http.getString('message'));
}
} else {
$.log.error('Failed to change the status. Make sure you have your api oauth code set. https://phantombot.github.io/PhantomBot/oauth/');
$.log.error(http.getString('_exception') + ' ' + http.getString('_exceptionMessage'));
}
}
/**
* @function updateStatus
* @export $
* @param {string} channelName
* @param {string} communities
* @param {string} sender
* @param {boolean} silent
*/
function updateCommunity(channelName, communities, sender, silent) {
var http = $.twitch.UpdateCommunities(channelName, communities);
if (http.getBoolean('_success') && http.getInt('_http') == 204) {
if (!silent) {
$.say($.lang.get('common.communities.change'));
}
$.twitchcache.setCommunities(communities);
$.inidb.set('streamInfo', 'communities', communities.join(', '));
} else {
$.log.error('Failed to change the status. Make sure you have your api oauth code set. https://phantombot.github.io/PhantomBot/oauth/');
$.log.error(http.getString('_exception') + ' ' + http.getString('_exceptionMessage'));
}
}
/** Export functions to API */
$.getPlayTime = getPlayTime;
$.getFollows = getFollows;
$.getGame = getGame;
$.getLogo = getLogo;
$.getStatus = getStatus;
$.getStreamStartedAt = getStreamStartedAt;
$.getStreamUptime = getStreamUptime;
$.getStreamUptimeSeconds = getStreamUptimeSeconds;
$.getViewers = getViewers;
$.isOnline = isOnline;
$.updateGame = updateGame;
$.updateStatus = updateStatus;
$.updateCommunity = updateCommunity;
$.getFollowAge = getFollowAge;
$.getFollowDate = getFollowDate;
$.getChannelAge = getChannelAge;
$.getStreamDownTime = getStreamDownTime;
$.getGamesPlayed = getGamesPlayed;
$.getSubscriberCount = getSubscriberCount;
})();

View File

@@ -0,0 +1,548 @@
/*
* Copyright (C) 2016-2020 phantombot.github.io/PhantomBot
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* timeSystem.js
*
* Keep track of users in the channel and log their time in the channel
* Exports various time formatting functions
* Use the $ API
*/
(function() {
var levelWithTime = $.getSetIniDbBoolean('timeSettings', 'timeLevel', false),
timeLevelWarning = $.getSetIniDbBoolean('timeSettings', 'timeLevelWarning', true),
keepTimeWhenOffline = $.getSetIniDbBoolean('timeSettings', 'keepTimeWhenOffline', true),
hoursForLevelUp = $.getSetIniDbNumber('timeSettings', 'timePromoteHours', 50),
regularsGroupId = 6,
interval,
inter;
/**
* @function updateTimeSettings
*/
function updateTimeSettings() {
levelWithTime = $.getIniDbBoolean('timeSettings', 'timeLevel');
keepTimeWhenOffline = $.getIniDbBoolean('timeSettings', 'keepTimeWhenOffline');
hoursForLevelUp = $.getIniDbNumber('timeSettings', 'timePromoteHours');
timeLevelWarning = $.getIniDbBoolean('timeSettings', 'timeLevelWarning');
}
/**
* @function getCurLocalTimeString
* @export $
* @param {String} timeformat
* @returns {String}
*
* timeformat = java.text.SimpleDateFormat allowed formats:
* Letter Date or Time Component Presentation Examples
* G Era designator Text AD
* y Year Year 1996; 96
* M Month in year Month July; Jul; 07
* w Week in year Number 27
* W Week in month Number 2
* D Day in year Number 189
* d Day in month Number 9
* F Day of week in month Number 2
* E Day in week Text Tuesday; Tue
* a AM/PM marker Text PM
* H Hour in day (0-23) Number 0
* k Hour in day (1-24) Number 24
* K Hour in am/pm (0-11) Number 0
* h Hour in am/pm (1-12) Number 12
* m Minute in hour Number 30
* s Second in minute Number 55
* S Millisecond Number 978
* z Time zone General time zone Pacific Standard Time; PST; GMT-08:00
* Z Time zone RFC 822 time zone -0800
*
* Note that fixed strings must be encapsulated with quotes. For example, the below inserts a comma
* and paranthesis into the returned time string:
*
* getCurLocalTimeString("MMMM dd', 'yyyy hh:mm:ss zzz '('Z')'");
*/
function getCurLocalTimeString(format) {
var dateFormat = new java.text.SimpleDateFormat(format);
dateFormat.setTimeZone(java.util.TimeZone.getTimeZone(($.inidb.exists('settings', 'timezone') ? $.inidb.get('settings', 'timezone') : "GMT")));
return dateFormat.format(new java.util.Date());
}
/**
* @function getLocalTimeString
* @export $
* @param {String} timeformat
* @param {Number} utc_seconds
* @return {String}
*/
function getLocalTimeString(format, utc_secs) {
var dateFormat = new java.text.SimpleDateFormat(format);
dateFormat.setTimeZone(java.util.TimeZone.getTimeZone(($.inidb.exists('settings', 'timezone') ? $.inidb.get('settings', 'timezone') : "GMT")));
return dateFormat.format(new java.util.Date(utc_secs));
}
/**
* @function getCurrentLocalTimeString
* @export $
* @param {String} timeformat
* @param {String} timeZone
* @return {String}
*/
function getCurrentLocalTimeString(format, timeZone) {
var dateFormat = new java.text.SimpleDateFormat(format);
dateFormat.setTimeZone(java.util.TimeZone.getTimeZone(timeZone));
return dateFormat.format(new java.util.Date());
}
/**
* @function getLocalTime
* @export $
* @param {String} timeformat
* @param {String} timeZone
* @return {String}
*/
function getLocalTime() {
var dateFormat = new java.text.SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
dateFormat.setTimeZone(java.util.TimeZone.getTimeZone(($.inidb.exists('settings', 'timezone') ? $.inidb.get('settings', 'timezone') : "GMT")));
return dateFormat.format(new java.util.Date());
}
/**
* @function dateToString
* @export $
* @param {Date} date
* @param {boolean} [timeOnly]
* @returns {string}
*/
function dateToString(date, timeOnly) {
var year = date.getFullYear(),
month = date.getMonth() + 1,
day = date.getDate(),
hours = date.getHours(),
minutes = date.getMinutes();
if (timeOnly) {
return hours + ':' + minutes;
} else {
return day + '-' + month + '-' + year + ' @ ' + hours + ':' + minutes;
}
}
/**
* @function getTimeString
* @export $
* @param {Number} time
* @param {boolean} [hoursOnly]
* @returns {string}
*/
function getTimeString(time, hoursOnly) {
var floor = Math.floor,
months = (time / 2628000);
days = ((months % 1) * 30.42),
hours = ((days % 1) * 24),
minutes = ((hours % 1) * 60),
seconds = ((minutes % 1) * 60);
if (hoursOnly) {
return floor(time / 3600) + $.lang.get('common.hours3');
} else {
var timeStringParts = [],
timeString = '';
// Append months if greater than one.
if (months >= 1) {
timeStringParts.push(floor(months) + ' ' + (months < 2 ? $.lang.get('common.time.month') : $.lang.get('common.time.months')));
}
// Append days if greater than one.
if (days >= 1) {
timeStringParts.push(floor(days) + ' ' + (days < 2 ? $.lang.get('common.time.day') : $.lang.get('common.time.days')));
}
// Append hours if greater than one.
if (hours >= 1) {
timeStringParts.push(floor(hours) + ' ' + (hours < 2 ? $.lang.get('common.time.hour') : $.lang.get('common.time.hours')));
}
// Append minutes if greater than one.
if (minutes >= 1) {
timeStringParts.push(floor(minutes) + ' ' + (minutes < 2 ? $.lang.get('common.time.minute') : $.lang.get('common.time.minutes')));
}
// Append seconds if greater than one.
if (seconds >= 1) {
timeStringParts.push(floor(seconds) + ' ' + (seconds < 2 ? $.lang.get('common.time.second') : $.lang.get('common.time.seconds')));
}
// If the array is empty, return 0 seconds.
if (timeStringParts.length === 0) {
return ('0 ' + $.lang.get('common.time.seconds'));
}
// Join the array to make a string.
timeString = timeStringParts.join(', ');
// Replace last comma with ", and".
if (timeString.indexOf(',') !== -1) {
timeString = (timeString.substr(0, timeString.lastIndexOf(',')) + $.lang.get('common.time.and') + timeString.substr(timeString.lastIndexOf(',') + 2));
}
return timeString;
}
}
/**
* @function getCountString
* @export $
* @param {Number} time
* @param {boolean} [countUp]
* @returns {string}
*/
function getCountString(time, countUp) {
var floor = Math.floor,
months = (time / 2628000);
days = ((months % 1) * 30.42),
hours = ((days % 1) * 24),
minutes = ((hours % 1) * 60),
seconds = ((minutes % 1) * 60);
var timeStringParts = [],
timeString = '';
// Append months if greater than one.
if (months >= 1) {
timeStringParts.push(floor(months) + ' ' + (months < 2 ? $.lang.get('common.time.month') : $.lang.get('common.time.months')));
}
// Append days if greater than one.
if (days >= 1) {
timeStringParts.push(floor(days) + ' ' + (days < 2 ? $.lang.get('common.time.day') : $.lang.get('common.time.days')));
}
// Append hours if greater than one.
if (hours >= 1) {
timeStringParts.push(floor(hours) + ' ' + (hours < 2 ? $.lang.get('common.time.hour') : $.lang.get('common.time.hours')));
}
// Append minutes if greater than one.
if (minutes >= 1) {
timeStringParts.push(floor(minutes) + ' ' + (minutes < 2 ? $.lang.get('common.time.minute') : $.lang.get('common.time.minutes')));
}
// Append seconds if greater than one.
if (seconds >= 1) {
timeStringParts.push(floor(seconds) + ' ' + (seconds < 2 ? $.lang.get('common.time.second') : $.lang.get('common.time.seconds')));
}
// If the array is empty, return 0 seconds.
if (timeStringParts.length === 0) {
if (countUp) {
return ($.lang.get('common.time.nostart'));
} else {
return ($.lang.get('common.time.expired'));
}
}
// Join the array to make a string.
timeString = timeStringParts.join(', ');
// Replace last comma with ", and".
if (timeString.indexOf(',') !== -1) {
timeString = (timeString.substr(0, timeString.lastIndexOf(',')) + $.lang.get('common.time.and') + timeString.substr(timeString.lastIndexOf(',') + 2));
}
return timeString;
}
/**
* @function getTimeStringMinutes
* @export $
* @param {Number} time
* @param {boolean} [hoursOnly]
* @returns {string}
*/
function getTimeStringMinutes(time) {
var floor = Math.floor,
cHours = time / 3600,
cMins = cHours % 1 * 60;
if (cHours == 0 || cHours < 1) {
return (floor(~~cMins) + $.lang.get('common.minutes2'));
} else {
return (floor(cHours) + $.lang.get('common.hours2') + floor(~~cMins) + $.lang.get('common.minutes2'));
}
}
/**
* @function getUserTime
* @export $
* @param {string} username
* @returns {number}
*/
function getUserTime(username) {
return ($.inidb.exists('time', username.toLowerCase()) ? $.inidb.get('time', username.toLowerCase()) : 0);
}
/**
* @function getUserTimeString
* @export $
* @param {string} username
* @returns {string}
*/
function getUserTimeString(username) {
var floor = Math.floor,
time = $.getUserTime(username.toLowerCase()),
cHours = time / 3600,
cMins = cHours % 1 * 60;
if (floor(cHours) > 0) {
return ($.lang.get('user.time.string.hours', floor(cHours), floor(~~cMins)));
} else {
return ($.lang.get('user.time.string.minutes', floor(~~cMins)));
}
}
/**
* @event command
*/
$.bind('command', function(event) {
var sender = event.getSender().toLowerCase(),
username = $.username.resolve(sender),
command = event.getCommand(),
args = event.getArgs(),
action = args[0],
subject,
timeArg;
/**
* @commandpath time - Announce amount of time spent in channel
*/
if (command.equalsIgnoreCase('time')) {
if (!action) {
$.say($.whisperPrefix(sender) + $.lang.get("timesystem.get.self", $.resolveRank(sender), getUserTimeString(sender)));
} else if (action && $.inidb.exists('time', action.toLowerCase())) {
$.say($.whisperPrefix(sender) + $.lang.get("timesystem.get.other", $.username.resolve(action), getUserTimeString(action)));
} else {
subject = args[1];
timeArg = parseInt(args[2]);
/**
* @commandpath time add [user] [seconds] - Add seconds to a user's logged time (for correction purposes)
*/
if (action.equalsIgnoreCase('add')) {
if (!subject || isNaN(timeArg)) {
$.say($.whisperPrefix(sender) + $.lang.get('timesystem.add.usage'));
return;
}
subject = $.user.sanitize(subject);
if (timeArg < 0) {
$.say($.whisperPrefix(sender) + $.lang.get('timesystem.add.error.negative'));
return;
}
if ($.user.isKnown(subject)) {
$.inidb.incr('time', subject, timeArg);
$.say($.whisperPrefix(sender) + $.lang.get('timesystem.add.success', getTimeString(timeArg), $.username.resolve(subject), getUserTimeString(subject)));
} else {
$.say($.whisperPrefix(sender) + $.lang.get('common.user.404', $.username.resolve(subject)));
}
}
/**
* @commandpath time take [user] [seconds] - Take seconds from a user's logged time
*/
if (action.equalsIgnoreCase('take')) {
if (!subject || isNaN(timeArg)) {
$.say($.whisperPrefix(sender) + $.lang.get('timesystem.take.usage'));
return;
}
subject = $.user.sanitize(subject);
if (!$.user.isKnown(subject)) {
$.say($.whisperPrefix(sender) + $.lang.get('common.user.404', subject));
}
if (timeArg > $.getUserTime(subject)) {
$.say($.whisperPrefix(sender) + $.lang.get('timesystem.take.error.toomuch', subject));
return;
}
$.inidb.decr('time', subject, timeArg);
$.say($.whisperPrefix(sender) + $.lang.get('timesystem.take.success', $.getTimeString(timeArg), $.username.resolve(subject), getUserTimeString(subject)))
}
if (action.equalsIgnoreCase('set')) {
if (!subject || isNaN(timeArg)) {
$.say($.whisperPrefix(sender) + $.lang.get('timesystem.settime.usage'));
return;
}
if (timeArg < 0) {
$.say($.whisperPrefix(sender) + $.lang.get('timesystem.settime.error.negative'));
return;
}
subject = $.user.sanitize(subject);
if ($.user.isKnown(subject)) {
$.inidb.set('time', subject, timeArg);
$.say($.whisperPrefix(sender) + $.lang.get('timesystem.settime.success', $.username.resolve(subject), $.getUserTimeString(subject)));
} else {
$.say($.whisperPrefix(sender) + $.lang.get('common.user.404', subject));
}
}
/**
* @commandpath time promotehours [hours] - Set the amount of hours a user has to be logged to automatically become a regular
*/
if (action.equalsIgnoreCase('promotehours')) {
if (isNaN(subject)) {
$.say($.whisperPrefix(sender) + $.lang.get('timesystem.set.promotehours.usage'));
return;
}
if (subject < 0) {
$.say($.whisperPrefix(sender) + $.lang.get('timesystem.set.promotehours.error.negative', $.getGroupNameById(regularsGroupId)));
return;
}
hoursForLevelUp = parseInt(subject);
$.inidb.set('timeSettings', 'timePromoteHours', hoursForLevelUp);
$.say($.whisperPrefix(sender) + $.lang.get('timesystem.set.promotehours.success', $.getGroupNameById(regularsGroupId), hoursForLevelUp));
}
/**
* @commandpath time autolevel - Auto levels a user to regular after hitting 50 hours.
*/
if (action.equalsIgnoreCase('autolevel')) {
levelWithTime = !levelWithTime;
$.setIniDbBoolean('timeSettings', 'timeLevel', levelWithTime);
$.say($.whisperPrefix(sender) + (levelWithTime ? $.lang.get('timesystem.autolevel.enabled', $.getGroupNameById(regularsGroupId), hoursForLevelUp) : $.lang.get('timesystem.autolevel.disabled', $.getGroupNameById(regularsGroupId), hoursForLevelUp)));
}
/**
* @commandpath time autolevelnotification - Toggles if a chat announcement is made when a user is promoted to a regular.
*/
if (action.equalsIgnoreCase('autolevelnotification')) {
timeLevelWarning = !timeLevelWarning;
$.setIniDbBoolean('timeSettings', 'timeLevelWarning', timeLevelWarning);
$.say($.whisperPrefix(sender) + (timeLevelWarning ? $.lang.get('timesystem.autolevel.chat.enabled') : $.lang.get('timesystem.autolevel.chat.disabled')));
}
/**
* @commandpath time offlinetime - Toggle logging a user's time when the channel is offline
*/
if (action.equalsIgnoreCase('offlinetime')) {
keepTimeWhenOffline = !keepTimeWhenOffline;
$.setIniDbBoolean('timeSettings', 'keepTimeWhenOffline', keepTimeWhenOffline);
$.say($.whisperPrefix(sender) + (keepTimeWhenOffline ? $.lang.get('timesystem.offlinetime.enabled') : $.lang.get('timesystem.offlinetime.disabled')));
}
}
}
/**
* @commandpath streamertime - Announce the caster's local time
*/
if (command.equalsIgnoreCase('streamertime')) {
$.say($.whisperPrefix(sender) + $.lang.get('timesystem.streamertime', getCurLocalTimeString("MMMM dd', 'yyyy hh:mm:ss a zzz '('Z')'"), $.username.resolve($.ownerName)));
}
/**
* @commandpath timezone [timezone name] - Show configured timezone or optionally set the timezone. See List: https://en.wikipedia.org/wiki/List_of_tz_database_time_zones
*/
if (command.equalsIgnoreCase('timezone')) {
var tzData;
if (!action) {
$.say($.whisperPrefix(sender) + $.lang.get('timesystem.set.timezone.usage', ($.inidb.exists('settings', 'timezone') ? $.inidb.get('settings', 'timezone') : "GMT")));
return;
}
tzData = java.util.TimeZone.getTimeZone(action);
if (tzData.getID().equals("GMT") && !action.equals("GMT")) {
$.say($.whisperPrefix(sender) + $.lang.get('timesystem.set.timezone.invalid', action));
return;
} else {
$.say($.whisperPrefix(sender) + $.lang.get('timesystem.set.timezone.success', tzData.getID(), tzData.observesDaylightTime()));
$.inidb.set('settings', 'timezone', tzData.getID());
}
}
});
// Set an interval for increasing all current users logged time
interval = setInterval(function() {
var username,
i;
if ($.isOnline($.channelName) || keepTimeWhenOffline) {
$.inidb.IncreaseBatchString('time', '', $.users, '60');
}
}, 6e4, 'scripts::systems::timeSystem.js#1');
// Interval for auto level to regular
inter = setInterval(function() {
var username,
i;
if (levelWithTime) {
for (i in $.users) {
username = $.users[i].toLowerCase();
if (!$.isMod(username) && !$.isAdmin(username) && !$.isSub(username) && !$.isVIP(username) && $.inidb.exists('time', username) && Math.floor(parseInt($.inidb.get('time', username)) / 3600) >= hoursForLevelUp && parseInt($.getUserGroupId(username)) > regularsGroupId) {
if (!$.hasModList(username)) { // Added a second check here to be 100% sure the user is not a mod.
$.setUserGroupById(username, regularsGroupId);
if (timeLevelWarning) {
$.say($.lang.get(
'timesystem.autolevel.promoted',
$.username.resolve(username),
$.getGroupNameById(regularsGroupId).toLowerCase(),
hoursForLevelUp
)); //No whisper mode needed here.
}
}
}
}
}
}, 9e5, 'scripts::systems::timeSystem.js#2');
/**
* @event initReady
*/
$.bind('initReady', function() {
$.registerChatCommand('./core/timeSystem.js', 'streamertime');
$.registerChatCommand('./core/timeSystem.js', 'timezone', 1);
$.registerChatCommand('./core/timeSystem.js', 'time');
$.registerChatSubcommand('time', 'add', 1);
$.registerChatSubcommand('time', 'take', 1);
$.registerChatSubcommand('time', 'set', 1);
$.registerChatSubcommand('time', 'autolevel', 1);
$.registerChatSubcommand('time', 'promotehours', 1);
$.registerChatSubcommand('time', 'autolevelnotification', 1);
});
/** Export functions to API */
$.dateToString = dateToString;
$.getTimeString = getTimeString;
$.getCountString = getCountString;
$.getUserTime = getUserTime;
$.getUserTimeString = getUserTimeString;
$.getCurLocalTimeString = getCurLocalTimeString;
$.getLocalTimeString = getLocalTimeString;
$.getTimeStringMinutes = getTimeStringMinutes;
$.updateTimeSettings = updateTimeSettings;
$.getCurrentLocalTimeString = getCurrentLocalTimeString;
$.getLocalTime = getLocalTime;
})();

View File

@@ -0,0 +1,980 @@
/*
* Copyright (C) 2016-2020 phantombot.github.io/PhantomBot
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* updater.js
*
* Update PhantomBot database
*
* This module will be executed before loading any of the other scripts even the core!
* Add a new wrapped function if you want to apply updates for a new version
*/
/**
* PhantomBot v2.0
*/
(function() {
var modules,
versions,
sounds,
i;
/** New setup */
if ($.changed == true && $.changed != null && $.changed != undefined && !$.inidb.exists('updates', 'installedNewBot') && $.inidb.get('updates', 'installedNewBot') != 'true') {
$.consoleLn('');
$.consoleLn('Initializing PhantomBot version ' + $.version + ' for the first time...');
modules = [
'./commands/topCommand.js',
'./commands/highlightCommand.js',
'./commands/deathctrCommand.js',
'./commands/dualstreamCommand.js',
'./games/8ball.js',
'./games/adventureSystem.js',
'./games/killCommand.js',
'./games/random.js',
'./games/roll.js',
'./games/roulette.js',
'./games/slotMachine.js',
'./games/gambling.js',
'./handlers/followHandler.js',
'./handlers/hostHandler.js',
'./handlers/subscribeHandler.js',
'./handlers/donationHandler.js',
'./handlers/wordCounter.js',
'./handlers/gameWispHandler.js',
'./handlers/keywordHandler.js',
'./handlers/twitterHandler.js',
'./handlers/tipeeeStreamHandler.js',
'./systems/cleanupSystem.js',
'./systems/greetingSystem.js',
'./systems/pointSystem.js',
'./systems/noticeSystem.js',
'./systems/pollSystem.js',
'./systems/quoteSystem.js',
'./systems/raffleSystem.js',
'./systems/ticketraffleSystem.js',
'./systems/raidSystem.js',
'./systems/youtubePlayer.js',
'./systems/ranksSystem.js',
'./systems/auctionSystem.js',
'./systems/audioPanelSystem.js',
'./systems/queueSystem.js',
'./systems/bettingSystem.js',
'./commands/nameConverter.js',
'./handlers/clipHandler.js',
'./handlers/dataServiceHandler.js',
'./handlers/gameScanHandler.js',
'./discord/handlers/bitsHandler.js',
'./discord/handlers/followHandler.js',
'./discord/handlers/subscribeHandler.js',
'./discord/handlers/tipeeeStreamHandler.js',
'./discord/handlers/streamlabsHandler.js',
'./discord/handlers/hostHandler.js',
'./discord/handlers/twitterHandler.js',
'./discord/handlers/keywordHandler.js',
'./discord/handlers/streamHandler.js',
'./discord/systems/greetingsSystem.js',
'./discord/commands/customCommands.js',
'./discord/games/8ball.js',
'./discord/games/kill.js',
'./discord/games/random.js',
'./discord/games/roulette.js',
'./discord/games/gambling.js',
'./discord/games/roll.js',
'./discord/games/slotMachine.js',
'./discord/systems/pointSystem.js'
];
$.consoleLn('Disabling default modules...');
for (i in modules) {
$.inidb.set('modules', modules[i], 'false');
}
$.consoleLn('Adding default custom commands...');
$.inidb.set('command', 'uptime', '(pointtouser) (channelname) has been online for (uptime)');
$.inidb.set('command', 'followage', '(followage)');
$.inidb.set('command', 'playtime', '(pointtouser) (channelname) has been playing (game) for (playtime)');
$.inidb.set('command', 'title', '(pointtouser) (titleinfo)');
$.inidb.set('command', 'game', '(pointtouser) (gameinfo)');
$.inidb.set('command', 'age', '(age)');
$.consoleLn('Installing old updates...');
versions = ['installedv2', 'installedv2.0.5', 'installedv2.0.6', 'installedv2.0.7', 'installedv2.0.7.2',
'installedv2.0.8', 'installedv2.0.9', 'installedv2.1.0', 'installedv2.1.1', 'installedv2.2.1', 'installedv2.3s',
'installedv2.3.3ss', 'installedv2.3.5ss', 'installedv2.3.5.1', 'installedv2.3.5.2', 'installedv2.3.5.3', 'installedv2.3.6',
'installedv2.3.6ss', 'installedv2.3.6b', 'installedv2.3.7', 'installedv2.3.7b', 'installedv2.3.9', 'installedv2.3.9.1', 'installedv2.3.9.1b',
'installedv2.4.0', 'installedv2.4.1'
];
for (i in versions) {
$.inidb.set('updates', versions[i], 'true');
}
sounds = "";
modules = "";
versions = "";
$.changed = false;
$.inidb.set('updates', 'installedNewBot', 'true');
$.consoleLn('Initializing complete!');
$.consoleLn('');
}
/** Version 2.0 updates */
if (!$.inidb.exists('updates', 'installedv2') || $.inidb.get('updates', 'installedv2') != 'true') {
$.consoleLn('Starting PhantomBot version 2.0 updates...');
var tableNamesList = $.inidb.GetFileList(),
commandsBackup,
timeBackup,
pointsBackup,
defaultDisabledModules = [
'./games/8ball.js',
'./games/adventureSystem.js',
'./games/killCommand.js',
'./commands/topCommand.js',
'./games/random.js',
'./games/roll.js',
'./games/roulette.js',
'./games/slotMachine.js',
'./handlers/followHandler.js',
'./handlers/hostHandler.js',
'./handlers/subscribeHandler.js',
'./handlers/donationHandler.js',
'./systems/cleanupSystem.js',
'./systems/greetingSystem.js',
'./systems/pointSystem.js',
'./systems/noticeSystem.js',
'./systems/pollSystem.js',
'./systems/quoteSystem.js',
'./systems/raffleSystem.js',
'./systems/ticketraffleSystem.js',
'./systems/raidSystem.js',
'./systems/youtubePlayer.js',
'./systems/audioPanelSystem.js'
];
if ($.inidb.FileExists('points') || $.inidb.FileExists('command') || $.inidb.FileExists('time')) {
$.consoleLn('Backing up commands...');
commandsBackup = getTableContents('command');
$.consoleLn('Backing up times...');
timeBackup = getTableContents('time');
$.consoleLn('Backing up points...');
pointsBackup = getTableContents('points');
$.consoleLn('Backup completed.');
$.consoleLn('Deleting old files...');
for (i in tableNamesList) {
$.inidb.RemoveFile(tableNamesList[i]);
}
$.consoleLn('Restoring commands...');
restoreTableContents('command', commandsBackup);
$.consoleLn('Restoring times...');
restoreTableContents('time', timeBackup);
$.consoleLn('Restoring points...');
restoreTableContents('points', pointsBackup);
}
$.consoleLn('Disabling default modules...');
for (i in defaultDisabledModules) {
$.inidb.set('modules', defaultDisabledModules[i], 'false');
}
$.consoleLn('PhantomBot v2.0 updates completed!');
$.inidb.set('updates', 'installedv2', 'true');
}
/** Version 2.0.5 updates */
if (!$.inidb.exists('updates', 'installedv2.0.5') || $.inidb.get('updates', 'installedv2.0.5') != 'true') {
var newDefaultDisabledModules = [
'./systems/betSystem.js',
'./handlers/wordCounter.js',
'./systems/ranksSystem.js',
'./systems/auctionSystem.js',
'./commands/highlightCommand.js'
]; //ADD NEW MODULES IN 2.0.5 TO BE DISABLED PLEASE.
$.consoleLn('Starting PhantomBot version 2.0.5 updates...');
$.consoleLn('Disabling new default modules...');
for (i in newDefaultDisabledModules) {
$.inidb.set('modules', newDefaultDisabledModules[i], 'false');
}
$.consoleLn('Removing commandCooldown table...');
$.inidb.RemoveFile('commandCooldown');
$.consoleLn('PhantomBot v2.0.5 updates completed!');
$.inidb.set('updates', 'installedv2.0.5', 'true');
}
if (!$.inidb.exists('updates', 'installedv2.0.6') || $.inidb.get('updates', 'installedv2.0.6') != 'true') {
$.consoleLn('Starting PhantomBot version 2.0.6 updates...');
if ($.inidb.exists('chatModerator', 'capsLimit')) {
$.inidb.del('chatModerator', 'capsLimit');
}
$.consoleLn('PhantomBot v2.0.6 updates completed!');
$.inidb.set('updates', 'installedv2.0.6', 'true');
}
/** Version 2.0.7 updates */
if (!$.inidb.exists('updates', 'installedv2.0.7') || $.inidb.get('updates', 'installedv2.0.7') != 'true') {
$.consoleLn('Starting PhantomBot version 2.0.7 updates...');
var newDefaultDisabledModules = [
'./handlers/gameWispHandler.js',
'./commands/deathctrCommand.js',
]; //ADD NEW MODULES IN 2.0.7 TO BE DISABLED PLEASE.
$.consoleLn('Disabling new default modules...');
for (i in newDefaultDisabledModules) {
$.inidb.set('modules', newDefaultDisabledModules[i], 'false');
}
if ($.inidb.exists('chatModerator', 'regularsToggle')) {
if ($.inidb.get('chatModerator', 'regularsToggle').equalsIgnoreCase('true')) {
$.inidb.set('chatModerator', 'regularsModerateLinks', false);
$.inidb.del('chatModerator', 'regularsToggle');
} else if ($.inidb.get('chatModerator', 'regularsToggle').equalsIgnoreCase('false')) {
$.inidb.set('chatModerator', 'regularsModerateLinks', true);
$.inidb.del('chatModerator', 'regularsToggle');
}
}
if ($.inidb.exists('chatModerator', 'subscribersToggle')) {
if ($.inidb.get('chatModerator', 'subscribersToggle').equalsIgnoreCase('true')) {
$.inidb.set('chatModerator', 'subscribersModerateLinks', false);
$.inidb.del('chatModerator', 'subscribersToggle');
} else if ($.inidb.get('chatModerator', 'subscribersToggle').equalsIgnoreCase('false')) {
$.inidb.set('chatModerator', 'subscribersModerateLinks', true);
$.inidb.del('chatModerator', 'subscribersToggle');
}
}
/**
* delete uptime command if it exits because I added this as a default command.
*/
if ($.inidb.exists('command', 'uptime')) {
$.inidb.del('command', 'uptime');
}
$.consoleLn('PhantomBot v2.0.7 updates completed!');
$.inidb.set('updates', 'installedv2.0.7', 'true');
}
/** Version 2.0.7.2 updates */
if (!$.inidb.exists('updates', 'installedv2.0.7.2') || $.inidb.get('updates', 'installedv2.0.7.2') != 'true') {
$.consoleLn('Starting PhantomBot version 2.0.7.2 updates...');
if ($.inidb.exists('chatModerator', 'longMessageMessage')) {
if ($.inidb.get('chatModerator', 'longMessageMessage').equalsIgnoreCase('false')) {
$.inidb.del('chatModerator', 'longMessageMessage');
}
}
$.consoleLn('PhantomBot v2.0.7.2 updates completed!');
$.inidb.set('updates', 'installedv2.0.7.2', 'true');
}
/** Version 2.0.8 updates */
if (!$.inidb.exists('updates', 'installedv2.0.8') || $.inidb.get('updates', 'installedv2.0.8') != 'true') {
$.consoleLn('Starting PhantomBot version 2.0.8 updates...');
var newDefaultDisabledModules = [
'./handlers/twitterHandler.js',
'./systems/audioPanelSystem.js',
'./systems/queueSystem.js'
]; //ADD NEW MODULES IN 2.0.8 TO BE DISABLED PLEASE.
$.consoleLn('Disabling new default modules...');
for (i in newDefaultDisabledModules) {
$.inidb.set('modules', newDefaultDisabledModules[i], 'false');
}
$.consoleLn('PhantomBot v2.0.8 updates completed!');
$.inidb.set('updates', 'installedv2.0.8', 'true');
}
/** Version 2.0.9 updates */
if (!$.inidb.exists('updates', 'installedv2.0.9') || $.inidb.get('updates', 'installedv2.0.9') != 'true') {
$.consoleLn('Starting PhantomBot version 2.0.9 updates...');
$.consoleLn('Deleting old emotes cache...');
$.inidb.del('emotescache', 'emotes');
$.consoleLn('PhantomBot v2.0.9 updates completed!');
$.inidb.set('updates', 'installedv2.0.9', 'true');
}
/** Version 2.1/2.0.10 updates */
if (!$.inidb.exists('updates', 'installedv2.1.0') || $.inidb.get('updates', 'installedv2.1.0') != 'true') {
$.consoleLn('Starting PhantomBot version 2.1 updates...');
$.consoleLn('Aliasing !permission to !group...');
$.inidb.set('aliases', 'group', 'permission');
$.consoleLn('Aliasing !permissionpoints to !grouppoints...');
$.inidb.set('aliases', 'grouppoints', 'permissionpoints');
$.consoleLn('Aliasing !permissions to !groups...');
$.inidb.set('aliases', 'groups', 'permissions');
$.consoleLn('Disabling new modules...');
$.inidb.set('modules', './games/gambling.js', 'false');
$.consoleLn('Setting up the new Twitter post delay...');
$.inidb.set('twitter', 'postdelay_update', 180);
$.consoleLn('PhantomBot v2.1 updates completed!');
$.inidb.set('updates', 'installedv2.1.0', 'true');
$.inidb.set('updates', 'installedNewBot', 'true'); //If bot login is deleted after updates were installed we don't want to reset the modules.
}
/** Version 2.2 updates */
if (!$.inidb.exists('updates', 'installedv2.1.1') || $.inidb.get('updates', 'installedv2.1.1') != 'true') {
$.consoleLn('Starting PhantomBot v2.2 updates...');
$.consoleLn('PhantomBot v2.2 updates completed!');
$.inidb.set('updates', 'installedv2.1.1', 'true');
}
/** Version 2.3 updates */
if (!$.inidb.exists('updates', 'installedv2.3s') || $.inidb.get('updates', 'installedv2.3s') != 'true') {
$.consoleLn('Starting PhantomBot v2.3 updates...');
$.consoleLn('Disabling new modules...');
$.inidb.set('modules', './handlers/bitsHandler.js', 'false');
$.consoleLn('Setting up new default custom commands...');
if (!$.inidb.exists('command', 'uptime')) {
$.inidb.set('command', 'uptime', '(pointtouser) (channelname) has been online for (uptime)');
}
if (!$.inidb.exists('command', 'followage')) {
$.inidb.set('command', 'followage', '(followage)');
}
if (!$.inidb.exists('command', 'playtime')) {
$.inidb.set('command', 'playtime', '(pointtouser) (channelname) has been playing (game) for (playtime)');
}
if (!$.inidb.exists('command', 'title')) {
$.inidb.set('command', 'title', '(pointtouser) (titleinfo)');
}
if (!$.inidb.exists('command', 'game')) {
$.inidb.set('command', 'game', '(pointtouser) (gameinfo)');
}
if (!$.inidb.exists('command', 'age')) {
$.inidb.set('command', 'age', '(age)');
}
if ($.inidb.exists('permcom', 'game set')) {
$.inidb.set('permcom', 'setgame', $.inidb.get('permcom', 'game set'));
}
if ($.inidb.exists('permcom', 'title set')) {
$.inidb.set('permcom', 'settitle', $.inidb.get('permcom', 'title set'));
}
$.inidb.del('permcom', 'game set');
$.inidb.del('permcom', 'title set');
$.consoleLn('Setting up new toggles...');
$.inidb.set('adventureSettings', 'warningMessage', true);
$.inidb.set('adventureSettings', 'enterMessage', true);
$.consoleLn('PhantomBot v2.3 updates completed!');
$.inidb.set('updates', 'installedv2.3s', 'true');
}
/* version 2.3.3s updates */
if (!$.inidb.exists('updates', 'installedv2.3.3ss') || $.inidb.get('updates', 'installedv2.3.3ss') != 'true') {
$.consoleLn('Starting PhantomBot update 2.3.3 updates...');
$.consoleLn('Deleting the old emotes cache.');
$.inidb.RemoveFile('emotecache');
$.consoleLn('Updating raffle settings...');
if ($.inidb.exists('settings', 'raffleMSGToggle')) {
$.inidb.set('raffleSettings', 'raffleMSGToggle', $.inidb.get('settings', 'raffleMSGToggle'));
$.inidb.del('settings', 'raffleMSGToggle');
}
if ($.inidb.exists('settings', 'noRepickSame')) {
$.inidb.set('raffleSettings', 'noRepickSame', $.inidb.get('settings', 'noRepickSame'));
$.inidb.del('settings', 'noRepickSame');
}
if ($.inidb.exists('settings', 'raffleMessage')) {
$.inidb.set('raffleSettings', 'raffleMessage', $.inidb.get('settings', 'raffleMessage'));
$.inidb.del('settings', 'raffleMessage');
}
if ($.inidb.exists('settings', 'raffleMessageInterval')) {
$.inidb.set('raffleSettings', 'raffleMessageInterval', $.inidb.get('settings', 'raffleMessageInterval'));
$.inidb.del('settings', 'raffleMessageInterval');
}
if ($.inidb.exists('command', 'uptime') && $.inidb.get('command', 'uptime').equalsIgnoreCase('(@sender) (channelname) has been online for (uptime)')) {
$.inidb.set('command', 'uptime', '(pointtouser) (channelname) has been online for (uptime)');
}
if ($.inidb.exists('command', 'playtime') && $.inidb.get('command', 'playtime').equalsIgnoreCase('(@sender) (channelname) has been playing (game) for (playtime)')) {
$.inidb.set('command', 'playtime', '(pointtouser) (channelname) has been playing (game) for (playtime)');
}
if ($.inidb.exists('command', 'title') && $.inidb.get('command', 'title').equalsIgnoreCase('(@sender) (titleinfo)')) {
$.inidb.set('command', 'title', '(pointtouser) (titleinfo)');
}
if ($.inidb.exists('command', 'game') && $.inidb.get('command', 'game').equalsIgnoreCase('(@sender) (gameinfo)')) {
$.inidb.set('command', 'game', '(pointtouser) (gameinfo)');
}
$.consoleLn('PhantomBot update 2.3.3 completed!');
$.inidb.set('updates', 'installedv2.3.3ss', 'true');
}
/* version 2.3.5 updates */
if (!$.inidb.exists('updates', 'installedv2.3.5ss') || $.inidb.get('updates', 'installedv2.3.5ss') != 'true') {
$.consoleLn('Starting PhantomBot update 2.3.5 updates...');
$.inidb.set('chatModerator', 'moderationLogs', 'false');
$.inidb.set('modules', './systems/bettingSystem.js', 'false');
$.inidb.del('modules', './systems/betSystem.js');
$.consoleLn('Removing old discord settings...');
$.inidb.RemoveFile('discordSettings');
$.inidb.RemoveFile('discordKeywords');
$.inidb.RemoveFile('discordCommands');
$.inidb.RemoveFile('discordCooldown');
$.inidb.del('modules', './handlers/discordHandler.js');
$.consoleLn('Disabling new modules.');
$.inidb.set('modules', './handlers/tipeeeStreamHandler.js', 'false');
$.consoleLn('Reloading blacklist and whitelist...');
var keys = $.inidb.GetKeyList('blackList', ''),
i;
for (i = 0; i < keys.length; i++) {
$.inidb.set('blackList', $.inidb.get('blackList', keys[i]), 'true');
$.inidb.del('blackList', keys[i]);
}
keys = $.inidb.GetKeyList('whiteList', '');
for (i = 0; i < keys.length; i++) {
$.inidb.set('whiteList', $.inidb.get('whiteList', keys[i]), 'true');
$.inidb.del('whiteList', keys[i]);
}
$.consoleLn('Updating host settings...');
$.inidb.set('settings', 'hostToggle', true);
$.consoleLn('Disabling default discord modules.');
modules = [
'./discord/handlers/bitsHandler.js',
'./discord/handlers/followHandler.js',
'./discord/handlers/subscribeHandler.js',
'./discord/handlers/streamlabsHandler.js',
'./discord/handlers/tipeeeStreamHandler.js',
'./discord/handlers/hostHandler.js',
'./discord/handlers/twitterHandler.js',
'./discord/handlers/keywordHandler.js',
'./discord/handlers/streamHandler.js',
'./discord/handlers/gamewispHandler.js',
'./discord/systems/greetingsSystem.js',
'./discord/commands/customCommands.js',
'./discord/games/8ball.js',
'./discord/games/kill.js',
'./discord/games/random.js',
'./discord/games/roulette.js'
];
for (i in modules) {
$.inidb.set('modules', modules[i], 'false');
}
$.inidb.set('permcom', 'permission', '1');
if ($.inidb.exists('permcom', 'group')) {
$.inidb.set('permcom', 'group', '1');
}
$.consoleLn('PhantomBot update 2.3.5 completed!');
$.inidb.set('updates', 'installedv2.3.5ss', 'true');
}
/* version 2.3.5.1 updates */
if (!$.inidb.exists('updates', 'installedv2.3.5.1') || $.inidb.get('updates', 'installedv2.3.5.1') != 'true') {
$.consoleLn('Starting PhantomBot update 2.3.5.1 updates...');
if ($.inidb.exists('aliases', 'points')) {
$.inidb.del('aliases', 'points');
}
if ($.inidb.exists('aliases', 'point')) {
$.inidb.del('aliases', 'point');
}
$.consoleLn('PhantomBot update 2.3.5.1 completed!');
$.inidb.set('updates', 'installedv2.3.5.1', 'true');
}
/* version 2.3.5.2 updates */
if (!$.inidb.exists('updates', 'installedv2.3.5.2') || $.inidb.get('updates', 'installedv2.3.5.2') != 'true') {
$.consoleLn('Starting PhantomBot update 2.3.5.2 updates...');
$.consoleLn('Reloading quotes... Please do not turn off your bot.');
var keys = $.inidb.GetKeyList('quotes', ''),
temp = [],
i;
for (i in keys) {
var quote = $.inidb.get('quotes', keys[i]);
if (quote != null) {
temp.push(quote);
}
}
$.inidb.RemoveFile('quotes');
for (i in temp) {
$.inidb.set('quotes', i, temp[i]);
}
$.inidb.SaveAll(true);
$.inidb.del('modules', './handlers/discordHandler.js');
$.consoleLn('PhantomBot update 2.3.5.2 completed!');
$.inidb.set('updates', 'installedv2.3.5.2', 'true');
}
/* version 2.3.5.3 updates */
if (!$.inidb.exists('updates', 'installedv2.3.5.3') || $.inidb.get('updates', 'installedv2.3.5.3') != 'true') {
$.consoleLn('Starting PhantomBot update 2.3.5.3 updates...');
if (!$.inidb.exists('settings', 'followDelay') || ($.inidb.exists('settings', 'followDelay') && parseInt($.inidb.get('settings', 'followDelay')) < 5)) {
$.inidb.set('settings', 'followDelay', 5);
}
$.consoleLn('PhantomBot update 2.3.5.3 completed!');
$.inidb.set('updates', 'installedv2.3.5.3', 'true');
}
/* version 2.3.6 updates */
if (!$.inidb.exists('updates', 'installedv2.3.6') || $.inidb.get('updates', 'installedv2.3.6') != 'true') {
$.consoleLn('Starting PhantomBot update 2.3.6 updates...');
$.consoleLn('Disabling default discord modules.');
$.inidb.set('modules', './discord/games/roll.js', 'false');
$.inidb.set('modules', './discord/games/slotMachine.js', 'false');
$.inidb.set('modules', './discord/games/gambling.js', 'false');
$.inidb.set('modules', './discord/systems/pointSystem.js', 'false');
$.inidb.set('permcom', $.botName.toLowerCase(), '2');
$.consoleLn('PhantomBot update 2.3.6 completed!');
$.inidb.set('updates', 'installedv2.3.6', 'true');
}
/* version 2.3.6s updates */
if (!$.inidb.exists('updates', 'installedv2.3.6ss') || $.inidb.get('updates', 'installedv2.3.6ss') != 'true') {
$.consoleLn('Starting PhantomBot update 2.3.6s updates...');
$.inidb.del('cooldown', 'globalCooldownTime');
$.inidb.del('cooldown', 'modCooldown');
$.inidb.del('cooldown', 'perUserCooldown');
$.inidb.del('cooldown', 'globalCooldown');
$.inidb.del('discordCooldown', 'globalCooldown');
$.inidb.del('discordCooldown', 'globalCooldownTime');
var keys = $.inidb.GetKeyList('cooldown', ''),
seconds,
i;
$.consoleLn('Updating cooldowns...');
for (i in keys) {
seconds = $.inidb.get('cooldown', keys[i]);
$.inidb.set('cooldown', keys[i], JSON.stringify({
command: String(keys[i]),
seconds: String(seconds),
isGlobal: 'true'
}));
}
$.consoleLn('Updating Discord cooldowns...');
for (i in keys) {
seconds = $.inidb.get('discordCooldown', keys[i]);
$.inidb.set('discordCooldown', keys[i], JSON.stringify({
command: String(keys[i]),
seconds: String(seconds),
isGlobal: 'true'
}));
}
$.consoleLn('PhantomBot update 2.3.6s completed!');
$.inidb.set('updates', 'installedv2.3.6ss', 'true');
}
/* version 2.3.6b updates */
if (!$.inidb.exists('updates', 'installedv2.3.6b') || $.inidb.get('updates', 'installedv2.3.6b') != 'true') {
$.consoleLn('Starting PhantomBot update 2.3.6b updates...');
$.consoleLn('Fixing uppercase usernames in tables.');
var keys = $.inidb.GetKeyList('points', ''),
i;
for (i in keys) {
if (keys[i].match(/[A-Z]/)) {
if ($.inidb.get('points', keys[i]) == null) {
$.inidb.del('points', null);
continue;
}
$.inidb.incr('points', keys[i].toLowerCase(), parseInt($.inidb.get('points', keys[i])));
$.inidb.del('points', keys[i]);
$.consoleLn('[points] ' + keys[i] + ' -> ' + keys[i].toLowerCase() + '::' + $.inidb.get('points', keys[i].toLowerCase()));
} else if (keys[i].match(/[^a-zA-Z0-9_]/)) {
$.inidb.del('points', keys[i]);
$.consoleLn('[points] [remove] ' + keys[i]);
}
}
keys = $.inidb.GetKeyList('group', '');
for (i in keys) {
if (keys[i].match(/[A-Z]/)) {
$.inidb.set('group', keys[i].toLowerCase(), $.inidb.get('group', keys[i]));
$.inidb.del('group', keys[i]);
$.consoleLn('[permission] ' + keys[i] + ' -> ' + keys[i].toLowerCase() + '::' + $.inidb.get('group', keys[i].toLowerCase()));
} else if (keys[i].match(/[^a-zA-Z0-9_]/)) {
$.inidb.del('group', keys[i]);
$.consoleLn('[permission] [remove] ' + keys[i]);
}
}
$.inidb.SaveAll(true);
$.consoleLn('PhantomBot update 2.3.6b completed!');
$.inidb.set('updates', 'installedv2.3.6b', 'true');
}
/* version 2.3.7 updates */
if (!$.inidb.exists('updates', 'installedv2.3.7b') || $.inidb.get('updates', 'installedv2.3.7b') != 'true') {
$.consoleLn('Starting PhantomBot update 2.3.7 updates...');
var keys = $.inidb.GetKeyList('blackList', ''),
timeout = $.getIniDbNumber('chatModerator', 'blacklistTimeoutTime', 600),
message = $.getIniDbString('chatModerator', 'blacklistMessage', 'you were timed out for using a blacklisted phrase.'),
messageB = $.getIniDbString('chatModerator', 'silentBlacklistMessage', 'Using a blacklisted word. (Automated by ' + $.botName + ')'),
obj = {},
i;
if ($.getIniDbNumber('chatModerator', 'msgCooldownSecs', 45) == 45) {
$.inidb.set('chatModerator', 'msgCooldownSecs', 30);
}
$.consoleLn('Updating blacklist...');
for (i in keys) {
obj = {
id: String(i),
timeout: String(timeout),
isRegex: keys[i].startsWith('regex:'),
phrase: String(keys[i]),
isSilent: false,
excludeRegulars: false,
excludeSubscribers: false,
message: String(message),
banReason: String(messageB)
};
$.inidb.set('blackList', keys[i], JSON.stringify(obj));
}
$.consoleLn('PhantomBot update 2.3.7 completed!');
$.inidb.set('updates', 'installedv2.3.7b', 'true');
}
/* version 2.3.9 updates */
if (!$.inidb.exists('updates', 'installedv2.3.9') || $.inidb.get('updates', 'installedv2.3.9') != 'true') {
$.consoleLn('Starting PhantomBot update 2.3.9 updates...');
$.consoleLn('Removing old discord handler...');
$.inidb.del('modules', './handlers/discordHandler.js');
$.consoleLn('Removing old emotes cache...');
$.inidb.RemoveFile('emotecache');
$.inidb.set('modules', './discord/handlers/streamElementsHandler.js', 'false');
$.inidb.set('modules', './handlers/streamElementsHandler.js', 'false');
$.consoleLn('PhantomBot update 2.3.9 completed!');
$.inidb.set('updates', 'installedv2.3.9', 'true');
}
/* version 2.3.9.1 updates */
if (!$.inidb.exists('updates', 'installedv2.3.9.1') || $.inidb.get('updates', 'installedv2.3.9.1') != 'true') {
$.consoleLn('Starting PhantomBot update 2.3.9.1 updates...');
$.consoleLn('Updating old variables...');
if ($.inidb.FileExists('discordSettings')) {
$.inidb.set('discordSettings', 'gameMessage', '(name) just changed game on Twitch!');
$.inidb.set('discordSettings', 'onlineMessage', '(name) just went online on Twitch!');
}
$.consoleLn('PhantomBot update 2.3.9.1 completed!');
$.inidb.set('updates', 'installedv2.3.9.1', 'true');
}
/* version 2.3.9.1b updates */
if (!$.inidb.exists('updates', 'installedv2.3.9.1b') || $.inidb.get('updates', 'installedv2.3.9.1b') != 'true') {
$.consoleLn('Starting PhantomBot update 2.3.9.1b updates...');
if ($.inidb.FileExists('discordStreamStats')) {
$.consoleLn('Removing old Discord stats...');
$.inidb.RemoveFile('discordStreamStats');
}
$.consoleLn('PhantomBot update 2.3.9.1b completed!');
$.inidb.set('updates', 'installedv2.3.9.1b', 'true');
}
/* version 2.4.0 updates */
if (!$.inidb.exists('updates', 'installedv2.4.0') || $.inidb.get('updates', 'installedv2.4.0') != 'true') {
$.consoleLn('Starting PhantomBot update 2.4.0 updates...');
if ($.getIniDbNumber('cooldownSettings', 'defaultCooldownTime', 5) < 5) {
$.inidb.set('cooldownSettings', 'defaultCooldownTime', 5);
}
$.consoleLn('Updating keywords...');
var keys = $.inidb.GetKeyList('keywords', ''),
keywords = [],
i;
for (i in keys) {
keywords.push({
key: keys[i],
res: $.inidb.get('keywords', keys[i])
});
}
$.inidb.RemoveFile('keywords');
for (i in keywords) {
try {
new RegExp('\\b' + keywords[i].key + '\\b');
$.inidb.set('keywords', 'regex:\\b' + keywords[i].key + '\\b', JSON.stringify({
keyword: 'regex:\\b' + keywords[i].key + '\\b',
response: keywords[i].res + '',
isRegex: true
}));
$.inidb.set('coolkey', 'regex:\\b' + keywords[i].key + '\\b', $.getIniDbNumber('coolkey', keywords[i].key, 5));
$.inidb.del('coolkey', keywords[i].key);
} catch (e) {
$.inidb.set('keywords', keywords[i].key, JSON.stringify({
keyword: keywords[i].key,
response: keywords[i].res + '',
isRegex: false
}));
}
}
$.consoleLn('PhantomBot update 2.4.0 completed!');
$.inidb.set('updates', 'installedv2.4.0', 'true');
}
/* version 2.4.1 updates */
if (!$.inidb.exists('updates', 'installedv2.4.1') || $.inidb.get('updates', 'installedv2.4.1') != 'true') {
$.consoleLn('Starting PhantomBot update 2.4.1 updates...');
$.inidb.del('modules', './systems/raidSystem.js');
// Remove old raids for the new format.
$.inidb.RemoveFile('outgoing_raids');
$.consoleLn('PhantomBot update 2.4.1 completed!');
$.inidb.set('updates', 'installedv2.4.1', 'true');
}
/* version 2.4.2.1 updates */
if (!$.inidb.exists('updates', 'installedv2.4.2.1') || $.inidb.get('updates', 'installedv2.4.2.1') != 'true') {
$.consoleLn('Starting PhantomBot update 2.4.2.1 updates...');
$.inidb.del('modules', './discord/handlers/gamewispHandler.js');
$.inidb.del('modules', './handlers/gameWispHandler.js');
$.consoleLn('PhantomBot update 2.4.2.1 completed!');
$.inidb.set('updates', 'installedv2.4.2.1', 'true');
}
/* version 3.0.1 updates */
if (!$.inidb.exists('updates', 'installedv3.0.1') || $.inidb.get('updates', 'installedv3.0.1') != 'true') {
$.consoleLn('Starting PhantomBot update 3.0.1 updates...');
if (!$.hasDiscordToken) {
while (!$.inidb.exists('discordPermsObj', 'obj')) {
try {
java.lang.Thread.sleep(1000);
} catch (ex) {
$.log.error('Failed to run update as Discord is not yet connected, please restart PhantomBot...');
return;
}
}
var discordCommandPermissions = $.inidb.GetKeyList('discordPermcom', '');
var everyoneRoleID = 0;
var discordRoles = $.discordAPI.getGuildRoles();
for (var i = 0; i < discordRoles.size(); i++) {
if (discordRoles.get(i).getName().equalsIgnoreCase('@everyone')) {
everyoneRoleID = discordRoles.get(i).getId().asString();
break;
}
}
for (var i = 0; i < discordCommandPermissions.length; i++) {
var permission = $.inidb.get('discordPermcom', discordCommandPermissions[i]);
var permissionsObj = {
'roles': [], // Array of string IDs.
'permissions': [] // Array of objects.
};
if ((permission + '').equals('0')) {
permissionsObj.roles.push(everyoneRoleID + '');
}
permissionsObj.permissions.push({
'name': 'Administrator',
'selected': ((permission + '').equals('1') + '')
});
$.inidb.set('discordPermcom', discordCommandPermissions[i], JSON.stringify(permissionsObj));
}
}
$.consoleLn('PhantomBot update 3.0.1 completed!');
$.inidb.set('updates', 'installedv3.0.1', 'true');
}
/* version 3.3.0 updates */
if (!$.inidb.exists('updates', 'installedv3.3.0') || $.inidb.get('updates', 'installedv3.3.0') != 'true') {
$.consoleLn('Starting PhantomBot update 3.3.0 updates...');
$.consoleLn('Updating keywords...');
var keys = $.inidb.GetKeyList('keywords', ''),
newKeywords = [],
key,
json,
i,
strippedKeys = {};
for (i = 0; i < keys.length; i++) {
key = keys[i];
json = JSON.parse($.inidb.get('keywords', key));
if (json.isRegex) {
json.isCaseSensitive = true;
key = key.replace('regex:', '');
json.keyword = json.keyword.replace('regex:', '');
} else {
json.isCaseSensitive = false;
}
if (strippedKeys.hasOwnProperty(key)) {
throw 'Could not update keywords list. The keyword "' + key +
'" exists both as regex and as plain keyword. ' +
"Please resolve the conflict and restart phantombot.";
}
strippedKeys[key] = true;
newKeywords.push({
key: key,
json: json
});
}
$.inidb.RemoveFile('keywords');
for (i = 0; i < newKeywords.length; i++) {
$.inidb.set('keywords', newKeywords[i].key, JSON.stringify(newKeywords[i].json));
}
$.consoleLn('PhantomBot update 3.3.0 completed!');
$.inidb.set('updates', 'installedv3.3.0', 'true');
}
/**
* @function getTableContents
* @param {string} tableName
* @returns {Array}
*/
function getTableContents(tableName) {
var contents = [],
keyList = $.inidb.GetKeyList(tableName, ''),
temp,
i;
for (i in keyList) {
// Handle Exceptions per table
switch (tableName) {
// Ignore rows with less than 600 seconds (10 minutes)
case 'time':
temp = parseInt($.inidb.get(tableName, keyList[i]));
if (temp >= 600) {
contents[keyList[i]] = $.inidb.get(tableName, keyList[i]);
}
break;
// Ignore rows with less than 10 points
case 'points':
temp = parseInt($.inidb.get(tableName, keyList[i]));
if (temp >= 10) {
contents[keyList[i]] = $.inidb.get(tableName, keyList[i]);
}
break;
// Put the rows in by default
default:
contents[keyList[i]] = $.inidb.get(tableName, keyList[i]);
break;
}
}
return contents;
}
/**
* @function setTableContents
* @param {string} tableName
* @param {Array} contents
*/
function restoreTableContents(tableName, contents) {
var i;
for (i in contents) {
$.inidb.set(tableName, i, contents[i]);
}
$.inidb.SaveAll(true);
}
})();

View File

@@ -0,0 +1,134 @@
/*
* Copyright (C) 2016-2020 phantombot.github.io/PhantomBot
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
(function() {
var whisperMode = $.getSetIniDbBoolean('settings', 'whisperMode', false),
ScriptEventManager = Packages.tv.phantombot.script.ScriptEventManager,
CommandEvent = Packages.tv.phantombot.event.command.CommandEvent;
/**
* @function reloadWhispers
*/
function reloadWhispers() {
whisperMode = $.getIniDbBoolean('settings', 'whisperMode');
}
/**
* @function hasKey
*
* @param {array} list
* @param {string} value
* @param {int} subIndex
* @returns {boolean}
*/
function hasKey(list, value, subIndex) {
var i;
for (i in list) {
if (list[i][subIndex].equalsIgnoreCase(value)) {
return true;
}
}
return false;
}
/**
* @function whisperPrefix
*
* @export $
* @param {string} username
* @param {boolean} force
* @returns {string}
*/
function whisperPrefix(username, force) {
if (username.toLowerCase() == $.botName.toLowerCase()) {
return '';
}
if (whisperMode || force) {
return '/w ' + username + ' ';
}
return '@' + $.username.resolve(username) + ', ';
}
/**
* @function getBotWhisperMode
*
* @export $
* @returns {boolean}
*/
function getBotWhisperMode() {
return whisperMode;
}
/**
* @event ircPrivateMessage
*/
$.bind('ircPrivateMessage', function(event) {
var sender = event.getSender(),
message = event.getMessage(),
arguments = '',
split,
command;
if (sender.equalsIgnoreCase('jtv') || sender.equalsIgnoreCase('twitchnotify')) {
return;
}
if (message.startsWith('!') && $.isMod(sender) && $.userExists(sender)) {
message = message.substring(1);
if (message.includes(' ')) {
split = message.indexOf(' ');
command = message.substring(0, split).toLowerCase();
arguments = message.substring(split + 1);
} else {
command = message;
}
ScriptEventManager.instance().onEvent(new CommandEvent(sender, command, arguments));
$.log.file('whispers', '' + sender + ': ' + message);
}
});
/**
* @event command
*/
$.bind('command', function(event) {
var sender = event.getSender(),
command = event.getCommand();
/**
* @commandpath togglewhispermode - Toggle whisper mode
*/
if (command.equalsIgnoreCase('togglewhispermode')) {
whisperMode = !whisperMode;
$.setIniDbBoolean('settings', 'whisperMode', whisperMode);
$.say(whisperPrefix(sender) + (whisperMode ? $.lang.get('whisper.whispers.enabled') : $.lang.get('whisper.whispers.disabled')));
}
});
/**
* @event initReady
*/
$.bind('initReady', function() {
$.registerChatCommand('./core/whisper.js', 'togglewhispermode', 1);
});
/** Export functions to API */
$.whisperPrefix = whisperPrefix;
$.getBotWhisperMode = getBotWhisperMode;
$.reloadWhispers = reloadWhispers;
})();