From eca2ddd57d95b9e4349bd72d09de3ba78fc00fe2 Mon Sep 17 00:00:00 2001 From: Carlos Date: Thu, 5 Sep 2019 02:55:43 -0400 Subject: [PATCH 01/63] First Commit for reddit top photo command --- .env.example | 15 --- package-lock.json | 154 ++++++++++++++++++++++++----- package.json | 2 + src/commands/admin/deployreddit.js | 51 ++++++++++ 4 files changed, 185 insertions(+), 37 deletions(-) delete mode 100644 .env.example create mode 100644 src/commands/admin/deployreddit.js diff --git a/.env.example b/.env.example deleted file mode 100644 index dace595..0000000 --- a/.env.example +++ /dev/null @@ -1,15 +0,0 @@ -# This is an example environment variable file. -# If you want to use this bot for your own server, you need to change the values in here. - -# A token from the Discord API to let the bot log in and send messages. -BOT_TOKEN='token' - -# Characters the bot should look for when a user sends a message. The bot should only respond to -# messages if they start with this prefix. -COMMAND_PREFIX='!!' - -# A list of people, separated by spaces who have full control over this bot. -BOT_OWNERS='' - -# The name of the database that this bot should use when storing settings for a Discord server. -DATABASE_NAME='serversettings.db' \ No newline at end of file diff --git a/package-lock.json b/package-lock.json index 298a36a..e96a66a 100644 --- a/package-lock.json +++ b/package-lock.json @@ -42,8 +42,7 @@ "@types/node": { "version": "10.12.1", "resolved": "https://registry.npmjs.org/@types/node/-/node-10.12.1.tgz", - "integrity": "sha512-i1sl+WCX2OCHeUi9oi7PiCNUtYFrpWhpcx878vpeq/tlZTKzcFdHePlyFHVbWqeuKN0SRPl/9ZFDSTsfv9h7VQ==", - "dev": true + "integrity": "sha512-i1sl+WCX2OCHeUi9oi7PiCNUtYFrpWhpcx878vpeq/tlZTKzcFdHePlyFHVbWqeuKN0SRPl/9ZFDSTsfv9h7VQ==" }, "abbrev": { "version": "1.1.1", @@ -185,6 +184,11 @@ "underscore": "~1.4.4" } }, + "boolbase": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/boolbase/-/boolbase-1.0.0.tgz", + "integrity": "sha1-aN/1++YMUes3cl6p4+0xDcwed24=" + }, "brace-expansion": { "version": "1.1.11", "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz", @@ -231,6 +235,19 @@ "integrity": "sha512-mT8iDcrh03qDGRRmoA2hmBJnxpllMR+0/0qlzjqZES6NdiWDcZkCNAk4rPFZ9Q85r27unkiNNg8ZOiwZXBHwcA==", "dev": true }, + "cheerio": { + "version": "1.0.0-rc.3", + "resolved": "https://registry.npmjs.org/cheerio/-/cheerio-1.0.0-rc.3.tgz", + "integrity": "sha512-0td5ijfUPuubwLUu0OBoe98gZj8C/AA+RW3v67GPlGOrvxWjZmBXiBCRU+I8VEiNyJzjth40POfHiz2RB3gImA==", + "requires": { + "css-select": "~1.2.0", + "dom-serializer": "~0.1.1", + "entities": "~1.1.1", + "htmlparser2": "^3.9.1", + "lodash": "^4.15.0", + "parse5": "^3.0.1" + } + }, "chownr": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/chownr/-/chownr-1.1.1.tgz", @@ -313,9 +330,9 @@ } }, "combined-stream": { - "version": "1.0.7", - "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.7.tgz", - "integrity": "sha512-brWl9y6vOB1xYPZcpZde3N9zDByXTosAeMDo4p1wzo6UMOX4vumB+TP1RZ76sfE6Md68Q0NJSrE/gbezd4Ul+w==", + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz", + "integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==", "requires": { "delayed-stream": "~1.0.0" } @@ -353,6 +370,22 @@ "which": "^1.2.9" } }, + "css-select": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/css-select/-/css-select-1.2.0.tgz", + "integrity": "sha1-KzoRBTnFNV8c2NMUYj6HCxIeyFg=", + "requires": { + "boolbase": "~1.0.0", + "css-what": "2.1", + "domutils": "1.5.1", + "nth-check": "~1.0.1" + } + }, + "css-what": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/css-what/-/css-what-2.1.3.tgz", + "integrity": "sha512-a+EPoD+uZiNfh+5fxw2nO9QwFa6nJe2Or35fGY6Ipw1R3R4AGz1d1TEZrCegvw2YTmZ0jXirGYlzxxpYSHwpEg==" + }, "dashdash": { "version": "1.14.1", "resolved": "https://registry.npmjs.org/dashdash/-/dashdash-1.14.1.tgz", @@ -443,6 +476,37 @@ "esutils": "^2.0.2" } }, + "dom-serializer": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/dom-serializer/-/dom-serializer-0.1.1.tgz", + "integrity": "sha512-l0IU0pPzLWSHBcieZbpOKgkIn3ts3vAh7ZuFyXNwJxJXk/c4Gwj9xaTJwIDVQCXawWD0qb3IzMGH5rglQaO0XA==", + "requires": { + "domelementtype": "^1.3.0", + "entities": "^1.1.1" + } + }, + "domelementtype": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/domelementtype/-/domelementtype-1.3.1.tgz", + "integrity": "sha512-BSKB+TSpMpFI/HOxCNr1O8aMOTZ8hT3pM3GQ0w/mWRmkhEDSFJkkyzz4XQsBV44BChwGkrDfMyjVD0eA2aFV3w==" + }, + "domhandler": { + "version": "2.4.2", + "resolved": "https://registry.npmjs.org/domhandler/-/domhandler-2.4.2.tgz", + "integrity": "sha512-JiK04h0Ht5u/80fdLMCEmV4zkNh2BcoMFBmZ/91WtYZ8qVXSKjiw7fXMgFPnHcSZgOo3XdinHvmnDUeMf5R4wA==", + "requires": { + "domelementtype": "1" + } + }, + "domutils": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/domutils/-/domutils-1.5.1.tgz", + "integrity": "sha1-3NhIiib1Y9YQeeSMn3t+Mjc2gs8=", + "requires": { + "dom-serializer": "0", + "domelementtype": "1" + } + }, "dotenv": { "version": "6.1.0", "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-6.1.0.tgz", @@ -465,6 +529,11 @@ "env-variable": "0.0.x" } }, + "entities": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/entities/-/entities-1.1.2.tgz", + "integrity": "sha512-f2LZMYl1Fzu7YSBKg+RoROelpOaNrcGmE9AZubeDfrCEia483oW4MI4VyFd5VNHIgQ/7qm1I0wUHK1eJnn2y2w==" + }, "env-variable": { "version": "0.0.5", "resolved": "https://registry.npmjs.org/env-variable/-/env-variable-0.0.5.tgz", @@ -807,6 +876,31 @@ "resolved": "https://registry.npmjs.org/has-unicode/-/has-unicode-2.0.1.tgz", "integrity": "sha1-4Ob+aijPUROIVeCG0Wkedx3iqLk=" }, + "htmlparser2": { + "version": "3.10.1", + "resolved": "https://registry.npmjs.org/htmlparser2/-/htmlparser2-3.10.1.tgz", + "integrity": "sha512-IgieNijUMbkDovyoKObU1DUhm1iwNYE/fuifEoEHfd1oZKZDaONBSkal7Y01shxsM49R4XaMdGez3WnF9UfiCQ==", + "requires": { + "domelementtype": "^1.3.1", + "domhandler": "^2.3.0", + "domutils": "^1.5.1", + "entities": "^1.1.1", + "inherits": "^2.0.1", + "readable-stream": "^3.1.1" + }, + "dependencies": { + "readable-stream": { + "version": "3.4.0", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.4.0.tgz", + "integrity": "sha512-jItXPLmrSR8jmTRmRWJXCnGJsfy85mB3Wd/uINMXA65yrnFo0cPClFIUWzo2najVNSl+mx7/4W8ttlLWJe99pQ==", + "requires": { + "inherits": "^2.0.3", + "string_decoder": "^1.1.1", + "util-deprecate": "^1.0.1" + } + } + } + }, "http-signature": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/http-signature/-/http-signature-1.2.0.tgz", @@ -1084,16 +1178,16 @@ "integrity": "sha512-XsP+KhQif4bjX1kbuSiySJFNAehNxgLb6hPRGJ9QsUr8ajHkuXGdrHmFUTUUXhDwVX2R5bY4JNZEwbUiMhV+MA==" }, "mime-db": { - "version": "1.37.0", - "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.37.0.tgz", - "integrity": "sha512-R3C4db6bgQhlIhPU48fUtdVmKnflq+hRdad7IyKhtFj06VPNVdk2RhiYL3UjQIlso8L+YxAtFkobT0VK+S/ybg==" + "version": "1.40.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.40.0.tgz", + "integrity": "sha512-jYdeOMPy9vnxEqFRRo6ZvTZ8d9oPb+k18PKoYNYUe2stVEBPPwsln/qWzdbmaIvnhZ9v2P+CuecK+fpUfsV2mA==" }, "mime-types": { - "version": "2.1.21", - "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.21.tgz", - "integrity": "sha512-3iL6DbwpyLzjR3xHSFNFeb9Nz/M8WDkX33t1GFQnFOllWk8pOrh/LSrB5OXlnlW5P9LH73X6loW/eogc+F5lJg==", + "version": "2.1.24", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.24.tgz", + "integrity": "sha512-WaFHS3MCl5fapm3oLxU4eYDw77IQM2ACcxQ9RIxfaC3ooc6PFuBMGZZsYpvoXS5D5QTWPieo1jjLdAm3TBP3cQ==", "requires": { - "mime-db": "~1.37.0" + "mime-db": "1.40.0" } }, "mimic-fn": { @@ -1253,6 +1347,14 @@ "set-blocking": "~2.0.0" } }, + "nth-check": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/nth-check/-/nth-check-1.0.2.tgz", + "integrity": "sha512-WeBOdju8SnzPN5vTUJYxYUxLeXpCaVP5i5e0LF8fg7WORF2Wd7wFX/pk0tYZk7s8T+J7VLy0Da6J1+wCT0AtHg==", + "requires": { + "boolbase": "~1.0.0" + } + }, "number-is-nan": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/number-is-nan/-/number-is-nan-1.0.1.tgz", @@ -1323,6 +1425,14 @@ "os-tmpdir": "^1.0.0" } }, + "parse5": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/parse5/-/parse5-3.0.3.tgz", + "integrity": "sha512-rgO9Zg5LLLkfJF9E6CCmXlSE4UVceloys8JrFqCcHloC3usd/kJCyPDwH2SOlzix2j3xaP9sUX3e8+kvkuleAA==", + "requires": { + "@types/node": "*" + } + }, "path-is-absolute": { "version": "1.0.1", "resolved": "http://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz", @@ -1374,9 +1484,9 @@ "dev": true }, "psl": { - "version": "1.1.29", - "resolved": "https://registry.npmjs.org/psl/-/psl-1.1.29.tgz", - "integrity": "sha512-AeUmQ0oLN02flVHXWh9sSJF7mcdFq0ppid/JkErufc3hGIV/AMa8Fo9VgDo/cT2jFdOWoFvHp90qqBH54W+gjQ==" + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/psl/-/psl-1.3.1.tgz", + "integrity": "sha512-2KLd5fKOdAfShtY2d/8XDWVRnmp3zp40Qt6ge2zBPFARLXOGUf2fHD5eg+TV/5oxBtQKVhjUaKFsAaE4HnwfSA==" }, "punycode": { "version": "2.1.1", @@ -1617,9 +1727,9 @@ } }, "sshpk": { - "version": "1.15.2", - "resolved": "https://registry.npmjs.org/sshpk/-/sshpk-1.15.2.tgz", - "integrity": "sha512-Ra/OXQtuh0/enyl4ETZAfTaeksa6BXks5ZcjpSUNrjBr0DvrJKX+1fsKDPpT9TBXgHAFsa4510aNVgI8g/+SzA==", + "version": "1.16.1", + "resolved": "https://registry.npmjs.org/sshpk/-/sshpk-1.16.1.tgz", + "integrity": "sha512-HXXqVUq7+pcKeLqqZj6mHFUMvXtOJt1uoUx09pFW6011inTMxqI8BA8PM95myrIyyKwdnzjdFjLiE6KBPVtJIg==", "requires": { "asn1": "~0.2.3", "assert-plus": "^1.0.0", @@ -1837,9 +1947,9 @@ "integrity": "sha1-RQ1Nyfpw3nMnYvvS1KKJgUGaDM8=" }, "uuid": { - "version": "3.3.2", - "resolved": "https://registry.npmjs.org/uuid/-/uuid-3.3.2.tgz", - "integrity": "sha512-yXJmeNaw3DnnKAOKJE51sL/ZaYfWJRl1pK9dr19YFCu0ObS231AB1/LbqTKRAQ5kw8A90rA6fr4riOUpTZvQZA==" + "version": "3.3.3", + "resolved": "https://registry.npmjs.org/uuid/-/uuid-3.3.3.tgz", + "integrity": "sha512-pW0No1RGHgzlpHJO1nsVrHKpOEIxkGg1xB+v0ZmdNH5OAeAwzAVrCnI2/6Mtx+Uys6iaylxa+D3g4j63IKKjSQ==" }, "verror": { "version": "1.10.0", @@ -1928,4 +2038,4 @@ "integrity": "sha512-S+Zk8DEWE6oKpV+vI3qWkaK+jSbIK86pCwe2IF/xwIpQ8jEuxpw9NyaGjmp9+BoJv5FV2piqCDcoCtStppiq2A==" } } -} +} \ No newline at end of file diff --git a/package.json b/package.json index d4a0abb..555b3ee 100644 --- a/package.json +++ b/package.json @@ -20,11 +20,13 @@ }, "homepage": "https://github.com/FGCUSoftwareEngineeringClub/FGCUSECRoleBot#readme", "dependencies": { + "cheerio": "^1.0.0-rc.3", "discord.js": "^11.4.2", "discord.js-commando": "^0.10.0", "dotenv": "^6.1.0", "moment": "^2.22.2", "nedb": "^1.8.0", + "request": "^2.88.0", "sqlite": "^3.0.0", "sqlite3": "^4.0.4", "winston": "^3.1.0", diff --git a/src/commands/admin/deployreddit.js b/src/commands/admin/deployreddit.js new file mode 100644 index 0000000..407b8ba --- /dev/null +++ b/src/commands/admin/deployreddit.js @@ -0,0 +1,51 @@ +const Discord = require('discord.js'); +const Commando = require('discord.js-commando'); +const Logger = require('../../logging/Logger'); +const cheerio = require('cheerio'); +const request = require('request'); + +class DeployNews extends Commando.Command { + /** @param {Commando.CommandoClient} client */ + constructor(client) { + super(client, { + name: 'deployreddit', + description: 'Deploys the top news story in any subreddit every 24hrs', + guildOnly: true, + group: 'admin', + memberName: 'deployreddit', + + args: [ + { + key: 'redditURL', + prompt: 'What subreddit URL would you like to follow?', + type: 'string', + + }, + ], + }); + } + + async run(message, { redditURL }) { + request(redditURL, (error, response, html) => { + if (!error && response.statusCode == 200) { + const $ = cheerio.load(html); + var picture_not_found = true; + var img_index = 0 + while (picture_not_found) { + //console.log($(html).find('img').eq(img_index).attr('src')) + if ($(html).find('img').eq(img_index).attr('src') == undefined) { + return + } + if ($(html).find('img').eq(img_index).attr('src').substring(8, 9) == 'i' || $(html).find('img').eq(img_index).attr('src').substring(8, 9) == 'p') { + picture_not_found = false; + return message.reply($(html).find('img').eq(img_index).attr('src')); + } else { + img_index++; + } + } + } + }); + } +} + +module.exports = DeployNews; From 853d0ee36126fc7660a92cac78465442fb33e3d6 Mon Sep 17 00:00:00 2001 From: Carlos Date: Fri, 6 Sep 2019 17:52:51 -0400 Subject: [PATCH 02/63] Modified parsing code --- src/commands/admin/deployreddit.js | 38 +++++++++++++++++------------- 1 file changed, 22 insertions(+), 16 deletions(-) diff --git a/src/commands/admin/deployreddit.js b/src/commands/admin/deployreddit.js index 407b8ba..41a4858 100644 --- a/src/commands/admin/deployreddit.js +++ b/src/commands/admin/deployreddit.js @@ -4,12 +4,12 @@ const Logger = require('../../logging/Logger'); const cheerio = require('cheerio'); const request = require('request'); -class DeployNews extends Commando.Command { +class DeployReddit extends Commando.Command { /** @param {Commando.CommandoClient} client */ constructor(client) { super(client, { name: 'deployreddit', - description: 'Deploys the top news story in any subreddit every 24hrs', + description: 'Deploys the top img in any subreddit every 24hrs', guildOnly: true, group: 'admin', memberName: 'deployreddit', @@ -28,19 +28,16 @@ class DeployNews extends Commando.Command { async run(message, { redditURL }) { request(redditURL, (error, response, html) => { if (!error && response.statusCode == 200) { - const $ = cheerio.load(html); - var picture_not_found = true; - var img_index = 0 - while (picture_not_found) { - //console.log($(html).find('img').eq(img_index).attr('src')) - if ($(html).find('img').eq(img_index).attr('src') == undefined) { - return - } - if ($(html).find('img').eq(img_index).attr('src').substring(8, 9) == 'i' || $(html).find('img').eq(img_index).attr('src').substring(8, 9) == 'p') { - picture_not_found = false; - return message.reply($(html).find('img').eq(img_index).attr('src')); - } else { - img_index++; + const json_data = JSON.parse(html); + for (var counter = 0; counter < json_data.data.dist; counter++) { + //console.log(json_data.data.children[counter].data.post_hint) + if (json_data.data.children[counter].data.post_hint == "image" || linksToImage(json_data.data.children[counter].data.url)) { + const message_to_embed = { + "image": { + "url": json_data.data.children[counter].data.url + } + }; + return message.embed(message_to_embed); } } } @@ -48,4 +45,13 @@ class DeployNews extends Commando.Command { } } -module.exports = DeployNews; +function linksToImage(link) { + img_extensions = ['jpg', 'png', 'gif'] + //console.log(link.substr(link.length - 3)); + if (img_extensions.includes(link.substr(link.length - 3))) { + return true; + } + return false; +} + +module.exports = DeployReddit; From 5fdbf65b10cf783b02f9383b05491f459f52c4d3 Mon Sep 17 00:00:00 2001 From: Carlos Date: Fri, 6 Sep 2019 18:43:19 -0400 Subject: [PATCH 03/63] Added thumbs up/down reactions --- src/commands/admin/deployreddit.js | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/src/commands/admin/deployreddit.js b/src/commands/admin/deployreddit.js index 41a4858..9862ea8 100644 --- a/src/commands/admin/deployreddit.js +++ b/src/commands/admin/deployreddit.js @@ -37,7 +37,14 @@ class DeployReddit extends Commando.Command { "url": json_data.data.children[counter].data.url } }; - return message.embed(message_to_embed); + message.embed(message_to_embed).then(function (reply) { + //console.log(reply.id) + reply.channel.fetchMessage(reply.id).then(function (message_retrieved) { + message_retrieved.react('👎'); + message_retrieved.react('👍'); + }); + }); + return; } } } From bc974424695118a9172af9efd570752898798a9e Mon Sep 17 00:00:00 2001 From: Carlos Date: Fri, 6 Sep 2019 21:28:19 -0400 Subject: [PATCH 04/63] Working on implementing deploy timing --- package-lock.json | 121 ++--------------------------- package.json | 2 +- src/commands/admin/deployreddit.js | 54 +++++++------ 3 files changed, 40 insertions(+), 137 deletions(-) diff --git a/package-lock.json b/package-lock.json index e96a66a..29d7e11 100644 --- a/package-lock.json +++ b/package-lock.json @@ -42,7 +42,8 @@ "@types/node": { "version": "10.12.1", "resolved": "https://registry.npmjs.org/@types/node/-/node-10.12.1.tgz", - "integrity": "sha512-i1sl+WCX2OCHeUi9oi7PiCNUtYFrpWhpcx878vpeq/tlZTKzcFdHePlyFHVbWqeuKN0SRPl/9ZFDSTsfv9h7VQ==" + "integrity": "sha512-i1sl+WCX2OCHeUi9oi7PiCNUtYFrpWhpcx878vpeq/tlZTKzcFdHePlyFHVbWqeuKN0SRPl/9ZFDSTsfv9h7VQ==", + "dev": true }, "abbrev": { "version": "1.1.1", @@ -184,11 +185,6 @@ "underscore": "~1.4.4" } }, - "boolbase": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/boolbase/-/boolbase-1.0.0.tgz", - "integrity": "sha1-aN/1++YMUes3cl6p4+0xDcwed24=" - }, "brace-expansion": { "version": "1.1.11", "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz", @@ -235,19 +231,6 @@ "integrity": "sha512-mT8iDcrh03qDGRRmoA2hmBJnxpllMR+0/0qlzjqZES6NdiWDcZkCNAk4rPFZ9Q85r27unkiNNg8ZOiwZXBHwcA==", "dev": true }, - "cheerio": { - "version": "1.0.0-rc.3", - "resolved": "https://registry.npmjs.org/cheerio/-/cheerio-1.0.0-rc.3.tgz", - "integrity": "sha512-0td5ijfUPuubwLUu0OBoe98gZj8C/AA+RW3v67GPlGOrvxWjZmBXiBCRU+I8VEiNyJzjth40POfHiz2RB3gImA==", - "requires": { - "css-select": "~1.2.0", - "dom-serializer": "~0.1.1", - "entities": "~1.1.1", - "htmlparser2": "^3.9.1", - "lodash": "^4.15.0", - "parse5": "^3.0.1" - } - }, "chownr": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/chownr/-/chownr-1.1.1.tgz", @@ -370,22 +353,6 @@ "which": "^1.2.9" } }, - "css-select": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/css-select/-/css-select-1.2.0.tgz", - "integrity": "sha1-KzoRBTnFNV8c2NMUYj6HCxIeyFg=", - "requires": { - "boolbase": "~1.0.0", - "css-what": "2.1", - "domutils": "1.5.1", - "nth-check": "~1.0.1" - } - }, - "css-what": { - "version": "2.1.3", - "resolved": "https://registry.npmjs.org/css-what/-/css-what-2.1.3.tgz", - "integrity": "sha512-a+EPoD+uZiNfh+5fxw2nO9QwFa6nJe2Or35fGY6Ipw1R3R4AGz1d1TEZrCegvw2YTmZ0jXirGYlzxxpYSHwpEg==" - }, "dashdash": { "version": "1.14.1", "resolved": "https://registry.npmjs.org/dashdash/-/dashdash-1.14.1.tgz", @@ -476,37 +443,6 @@ "esutils": "^2.0.2" } }, - "dom-serializer": { - "version": "0.1.1", - "resolved": "https://registry.npmjs.org/dom-serializer/-/dom-serializer-0.1.1.tgz", - "integrity": "sha512-l0IU0pPzLWSHBcieZbpOKgkIn3ts3vAh7ZuFyXNwJxJXk/c4Gwj9xaTJwIDVQCXawWD0qb3IzMGH5rglQaO0XA==", - "requires": { - "domelementtype": "^1.3.0", - "entities": "^1.1.1" - } - }, - "domelementtype": { - "version": "1.3.1", - "resolved": "https://registry.npmjs.org/domelementtype/-/domelementtype-1.3.1.tgz", - "integrity": "sha512-BSKB+TSpMpFI/HOxCNr1O8aMOTZ8hT3pM3GQ0w/mWRmkhEDSFJkkyzz4XQsBV44BChwGkrDfMyjVD0eA2aFV3w==" - }, - "domhandler": { - "version": "2.4.2", - "resolved": "https://registry.npmjs.org/domhandler/-/domhandler-2.4.2.tgz", - "integrity": "sha512-JiK04h0Ht5u/80fdLMCEmV4zkNh2BcoMFBmZ/91WtYZ8qVXSKjiw7fXMgFPnHcSZgOo3XdinHvmnDUeMf5R4wA==", - "requires": { - "domelementtype": "1" - } - }, - "domutils": { - "version": "1.5.1", - "resolved": "https://registry.npmjs.org/domutils/-/domutils-1.5.1.tgz", - "integrity": "sha1-3NhIiib1Y9YQeeSMn3t+Mjc2gs8=", - "requires": { - "dom-serializer": "0", - "domelementtype": "1" - } - }, "dotenv": { "version": "6.1.0", "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-6.1.0.tgz", @@ -529,11 +465,6 @@ "env-variable": "0.0.x" } }, - "entities": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/entities/-/entities-1.1.2.tgz", - "integrity": "sha512-f2LZMYl1Fzu7YSBKg+RoROelpOaNrcGmE9AZubeDfrCEia483oW4MI4VyFd5VNHIgQ/7qm1I0wUHK1eJnn2y2w==" - }, "env-variable": { "version": "0.0.5", "resolved": "https://registry.npmjs.org/env-variable/-/env-variable-0.0.5.tgz", @@ -876,31 +807,6 @@ "resolved": "https://registry.npmjs.org/has-unicode/-/has-unicode-2.0.1.tgz", "integrity": "sha1-4Ob+aijPUROIVeCG0Wkedx3iqLk=" }, - "htmlparser2": { - "version": "3.10.1", - "resolved": "https://registry.npmjs.org/htmlparser2/-/htmlparser2-3.10.1.tgz", - "integrity": "sha512-IgieNijUMbkDovyoKObU1DUhm1iwNYE/fuifEoEHfd1oZKZDaONBSkal7Y01shxsM49R4XaMdGez3WnF9UfiCQ==", - "requires": { - "domelementtype": "^1.3.1", - "domhandler": "^2.3.0", - "domutils": "^1.5.1", - "entities": "^1.1.1", - "inherits": "^2.0.1", - "readable-stream": "^3.1.1" - }, - "dependencies": { - "readable-stream": { - "version": "3.4.0", - "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.4.0.tgz", - "integrity": "sha512-jItXPLmrSR8jmTRmRWJXCnGJsfy85mB3Wd/uINMXA65yrnFo0cPClFIUWzo2najVNSl+mx7/4W8ttlLWJe99pQ==", - "requires": { - "inherits": "^2.0.3", - "string_decoder": "^1.1.1", - "util-deprecate": "^1.0.1" - } - } - } - }, "http-signature": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/http-signature/-/http-signature-1.2.0.tgz", @@ -1129,6 +1035,11 @@ "colornames": "^1.1.1" } }, + "later": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/later/-/later-1.2.0.tgz", + "integrity": "sha1-8s9sTdeVbdL1IK3wMpg26YdrrQ8=" + }, "levn": { "version": "0.3.0", "resolved": "https://registry.npmjs.org/levn/-/levn-0.3.0.tgz", @@ -1347,14 +1258,6 @@ "set-blocking": "~2.0.0" } }, - "nth-check": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/nth-check/-/nth-check-1.0.2.tgz", - "integrity": "sha512-WeBOdju8SnzPN5vTUJYxYUxLeXpCaVP5i5e0LF8fg7WORF2Wd7wFX/pk0tYZk7s8T+J7VLy0Da6J1+wCT0AtHg==", - "requires": { - "boolbase": "~1.0.0" - } - }, "number-is-nan": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/number-is-nan/-/number-is-nan-1.0.1.tgz", @@ -1425,14 +1328,6 @@ "os-tmpdir": "^1.0.0" } }, - "parse5": { - "version": "3.0.3", - "resolved": "https://registry.npmjs.org/parse5/-/parse5-3.0.3.tgz", - "integrity": "sha512-rgO9Zg5LLLkfJF9E6CCmXlSE4UVceloys8JrFqCcHloC3usd/kJCyPDwH2SOlzix2j3xaP9sUX3e8+kvkuleAA==", - "requires": { - "@types/node": "*" - } - }, "path-is-absolute": { "version": "1.0.1", "resolved": "http://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz", @@ -2038,4 +1933,4 @@ "integrity": "sha512-S+Zk8DEWE6oKpV+vI3qWkaK+jSbIK86pCwe2IF/xwIpQ8jEuxpw9NyaGjmp9+BoJv5FV2piqCDcoCtStppiq2A==" } } -} \ No newline at end of file +} diff --git a/package.json b/package.json index 555b3ee..e5ade48 100644 --- a/package.json +++ b/package.json @@ -20,10 +20,10 @@ }, "homepage": "https://github.com/FGCUSoftwareEngineeringClub/FGCUSECRoleBot#readme", "dependencies": { - "cheerio": "^1.0.0-rc.3", "discord.js": "^11.4.2", "discord.js-commando": "^0.10.0", "dotenv": "^6.1.0", + "later": "^1.2.0", "moment": "^2.22.2", "nedb": "^1.8.0", "request": "^2.88.0", diff --git a/src/commands/admin/deployreddit.js b/src/commands/admin/deployreddit.js index 9862ea8..b8295ea 100644 --- a/src/commands/admin/deployreddit.js +++ b/src/commands/admin/deployreddit.js @@ -1,8 +1,8 @@ const Discord = require('discord.js'); const Commando = require('discord.js-commando'); const Logger = require('../../logging/Logger'); -const cheerio = require('cheerio'); const request = require('request'); +var later = require('later'); class DeployReddit extends Commando.Command { /** @param {Commando.CommandoClient} client */ @@ -25,31 +25,39 @@ class DeployReddit extends Commando.Command { }); } - async run(message, { redditURL }) { - request(redditURL, (error, response, html) => { - if (!error && response.statusCode == 200) { - const json_data = JSON.parse(html); - for (var counter = 0; counter < json_data.data.dist; counter++) { - //console.log(json_data.data.children[counter].data.post_hint) - if (json_data.data.children[counter].data.post_hint == "image" || linksToImage(json_data.data.children[counter].data.url)) { - const message_to_embed = { - "image": { - "url": json_data.data.children[counter].data.url - } - }; - message.embed(message_to_embed).then(function (reply) { - //console.log(reply.id) - reply.channel.fetchMessage(reply.id).then(function (message_retrieved) { - message_retrieved.react('👎'); - message_retrieved.react('👍'); - }); + run(message, { redditURL }) { + // time default is UTC | 4 hours ahead of FL + var sched = later.parse.text('at 09:28pm every day'); + later.date.localTime(); + var t = later.setInterval(function () { query_reddit(message, redditURL) }, sched); // t.clear() clears timer + } +} + +async function query_reddit(message, redditURL) { + request(redditURL, (error, response, html) => { + if (!error && response.statusCode == 200) { + const json_data = JSON.parse(html); + for (var counter = 0; counter < json_data.data.dist; counter++) { + //console.log(json_data.data.children[counter].data.post_hint) + if (json_data.data.children[counter].data.post_hint == "image" || linksToImage(json_data.data.children[counter].data.url)) { + const message_to_embed = { + "image": { + "url": json_data.data.children[counter].data.url + } + }; + message.embed(message_to_embed).then(async function (reply) { + //console.log(reply.id) + reply.channel.fetchMessage(reply.id).then(async function (message_retrieved) { + await message_retrieved.react('👍'); + await message_retrieved.react('👎'); }); - return; - } + }); + return; } } - }); - } + } + }); + console.log(new Date()); } function linksToImage(link) { From 01204ccdd963a833f1b3e8ae3def0d6460d45978 Mon Sep 17 00:00:00 2001 From: Carlos Date: Fri, 6 Sep 2019 21:55:46 -0400 Subject: [PATCH 05/63] new reddit posts are now daily at 08:00 local time --- src/commands/admin/deployreddit.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/commands/admin/deployreddit.js b/src/commands/admin/deployreddit.js index b8295ea..9910951 100644 --- a/src/commands/admin/deployreddit.js +++ b/src/commands/admin/deployreddit.js @@ -27,7 +27,7 @@ class DeployReddit extends Commando.Command { run(message, { redditURL }) { // time default is UTC | 4 hours ahead of FL - var sched = later.parse.text('at 09:28pm every day'); + var sched = later.parse.text('at 08:00am'); later.date.localTime(); var t = later.setInterval(function () { query_reddit(message, redditURL) }, sched); // t.clear() clears timer } From b7775e6afff775365aadb01f02d28868e2d81516 Mon Sep 17 00:00:00 2001 From: Carlos Date: Fri, 6 Sep 2019 22:02:53 -0400 Subject: [PATCH 06/63] Added testing argument --- src/commands/admin/deployreddit.js | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/commands/admin/deployreddit.js b/src/commands/admin/deployreddit.js index 9910951..9d8a370 100644 --- a/src/commands/admin/deployreddit.js +++ b/src/commands/admin/deployreddit.js @@ -27,13 +27,16 @@ class DeployReddit extends Commando.Command { run(message, { redditURL }) { // time default is UTC | 4 hours ahead of FL - var sched = later.parse.text('at 08:00am'); + const daily_time = 'at 08:00am'; + //const testing_time = 'every 10 seconds'; + var sched = later.parse.text(daily_time); later.date.localTime(); var t = later.setInterval(function () { query_reddit(message, redditURL) }, sched); // t.clear() clears timer } } async function query_reddit(message, redditURL) { + redditURL += ".json" request(redditURL, (error, response, html) => { if (!error && response.statusCode == 200) { const json_data = JSON.parse(html); From e0531fa9ca5d94c9ec0f60f83334c56c5bc3479e Mon Sep 17 00:00:00 2001 From: Carlos Date: Sat, 7 Sep 2019 22:23:57 -0400 Subject: [PATCH 07/63] Added some error checking and comments --- src/commands/admin/deployreddit.js | 53 ++++++++++++++++++++++++++---- 1 file changed, 47 insertions(+), 6 deletions(-) diff --git a/src/commands/admin/deployreddit.js b/src/commands/admin/deployreddit.js index 9d8a370..c52b8fe 100644 --- a/src/commands/admin/deployreddit.js +++ b/src/commands/admin/deployreddit.js @@ -25,18 +25,59 @@ class DeployReddit extends Commando.Command { }); } - run(message, { redditURL }) { + /** + * TO-DO + * Example Args + * !!deployreddit --stop + * stops execution + * !!deployreddit --edit + * here's how you can edit: + * !!deployreddit --edit https:newlink + * Link updated + * !!deployreddit --status + * gives current link, and iteration time + * + * if (!!deployreddit http:link) when an instance is already deployed + * send message to try using --stop or --edit + * + * upon bot reset, if instance was active when shutdown, relauch this instance + */ + + async run(message, args) { + // catching broken link errors + var error_given = false; + + await request(args.redditURL, (error, response, html) => { + if (error) { + message.say("Sorry, this link did not work."); + error_given = true; + } + }); + + if (error_given) return; + // time default is UTC | 4 hours ahead of FL const daily_time = 'at 08:00am'; - //const testing_time = 'every 10 seconds'; - var sched = later.parse.text(daily_time); + const testing_time = 'every 10 seconds'; + var sched = later.parse.text(testing_time); + //console.log(message.channel.id) gets the ID of current text channel + console.log(args.redditURL.charAt(args.redditURL.length - 1)) later.date.localTime(); - var t = later.setInterval(function () { query_reddit(message, redditURL) }, sched); // t.clear() clears timer + var interval_instance = later.setInterval(function () { query_reddit(message, args.redditURL, interval_instance) }, sched); // interval_instance.clear() clears timer } } -async function query_reddit(message, redditURL) { - redditURL += ".json" +async function query_reddit(message, redditURL, interval_instance) { + const last_char_of_URL = redditURL.charAt(redditURL.length - 1); + switch (last_char_of_URL) { + case '/': + redditURL += ".json" + break; + default: + redditURL += "/.json" + break; + } + //console.log(redditURL) request(redditURL, (error, response, html) => { if (!error && response.statusCode == 200) { const json_data = JSON.parse(html); From fdbaf19bb667b2e10a5bb1828cea2472a9535428 Mon Sep 17 00:00:00 2001 From: Carlos Date: Sun, 8 Sep 2019 18:29:17 -0400 Subject: [PATCH 08/63] Improved URL verification --- src/commands/admin/deployreddit.js | 60 ++++++++++++++++++------------ 1 file changed, 36 insertions(+), 24 deletions(-) diff --git a/src/commands/admin/deployreddit.js b/src/commands/admin/deployreddit.js index c52b8fe..5cccc8c 100644 --- a/src/commands/admin/deployreddit.js +++ b/src/commands/admin/deployreddit.js @@ -44,41 +44,53 @@ class DeployReddit extends Commando.Command { */ async run(message, args) { + args.redditURL = "https://www.reddit.com/" + args.redditURL; + const last_char_of_URL = args.redditURL.charAt(args.redditURL.length - 1); + switch (last_char_of_URL) { + case '/': + args.redditURL += ".json" + break; + default: + args.redditURL += "/.json" + break; + } + console.log(args.redditURL) + + // catching broken link errors - var error_given = false; + var error_given; + await request(args.redditURL, async (error, response, html) => { + var json_data; + try { + json_data = await JSON.parse(html) + } catch (e) { + message.say("Sorry, this link did not work."); + return; + } + error_given = json_data.error == '404' ? true : false; - await request(args.redditURL, (error, response, html) => { if (error) { message.say("Sorry, this link did not work."); - error_given = true; + return; + } else if (error_given == true) { + message.say("Sorry, this link did not work."); + return; } - }); - - if (error_given) return; - // time default is UTC | 4 hours ahead of FL - const daily_time = 'at 08:00am'; - const testing_time = 'every 10 seconds'; - var sched = later.parse.text(testing_time); - //console.log(message.channel.id) gets the ID of current text channel - console.log(args.redditURL.charAt(args.redditURL.length - 1)) - later.date.localTime(); - var interval_instance = later.setInterval(function () { query_reddit(message, args.redditURL, interval_instance) }, sched); // interval_instance.clear() clears timer + // time default is UTC | 4 hours ahead of FL + const daily_time = 'at 08:00am'; + const testing_time = 'every 10 seconds'; + var sched = later.parse.text(testing_time); + //console.log(message.channel.id) gets the ID of current text channel + later.date.localTime(); + var interval_instance = later.setInterval(function () { query_reddit(message, args.redditURL, interval_instance) }, sched); // interval_instance.clear() clears timer + }); } } async function query_reddit(message, redditURL, interval_instance) { - const last_char_of_URL = redditURL.charAt(redditURL.length - 1); - switch (last_char_of_URL) { - case '/': - redditURL += ".json" - break; - default: - redditURL += "/.json" - break; - } //console.log(redditURL) - request(redditURL, (error, response, html) => { + await request(redditURL, (error, response, html) => { if (!error && response.statusCode == 200) { const json_data = JSON.parse(html); for (var counter = 0; counter < json_data.data.dist; counter++) { From e7621129b67b3edee165174e7ff89a2e8d5c9046 Mon Sep 17 00:00:00 2001 From: Carlos Date: Sun, 8 Sep 2019 18:51:32 -0400 Subject: [PATCH 09/63] Improved URL validation --- src/commands/admin/deployreddit.js | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/src/commands/admin/deployreddit.js b/src/commands/admin/deployreddit.js index 5cccc8c..f6b9aee 100644 --- a/src/commands/admin/deployreddit.js +++ b/src/commands/admin/deployreddit.js @@ -44,7 +44,10 @@ class DeployReddit extends Commando.Command { */ async run(message, args) { - args.redditURL = "https://www.reddit.com/" + args.redditURL; + // appending the argument of "r/...." to make a URL + if (args.redditURL.search("reddit.com/") == -1) { + args.redditURL = "https://www.reddit.com/" + args.redditURL; + } const last_char_of_URL = args.redditURL.charAt(args.redditURL.length - 1); switch (last_char_of_URL) { case '/': @@ -77,11 +80,11 @@ class DeployReddit extends Commando.Command { return; } - // time default is UTC | 4 hours ahead of FL + //console.log(message.channel.id) gets the ID of current text channel const daily_time = 'at 08:00am'; const testing_time = 'every 10 seconds'; var sched = later.parse.text(testing_time); - //console.log(message.channel.id) gets the ID of current text channel + // time default is UTC | 4 hours ahead of FL later.date.localTime(); var interval_instance = later.setInterval(function () { query_reddit(message, args.redditURL, interval_instance) }, sched); // interval_instance.clear() clears timer }); From 02b8e003cc417f8268ea993082d0adad93f3194a Mon Sep 17 00:00:00 2001 From: Carlos Date: Sat, 14 Sep 2019 00:18:44 -0400 Subject: [PATCH 10/63] Added support for complex arguments --- src/commands/admin/deployreddit.js | 43 ++++++++++++++++++------------ 1 file changed, 26 insertions(+), 17 deletions(-) diff --git a/src/commands/admin/deployreddit.js b/src/commands/admin/deployreddit.js index f6b9aee..47afcbe 100644 --- a/src/commands/admin/deployreddit.js +++ b/src/commands/admin/deployreddit.js @@ -13,15 +13,6 @@ class DeployReddit extends Commando.Command { guildOnly: true, group: 'admin', memberName: 'deployreddit', - - args: [ - { - key: 'redditURL', - prompt: 'What subreddit URL would you like to follow?', - type: 'string', - - }, - ], }); } @@ -44,25 +35,43 @@ class DeployReddit extends Commando.Command { */ async run(message, args) { + const messageArguments = args.split(' '); + + switch (messageArguments[0]) { + case '--stop': + return; + case '--edit': + if (messageArguments[1].length > 0) { + //test the url and replace + } else { + //send message about how to edit + } + return; + case '--status': + return; + default: + break; + } + // appending the argument of "r/...." to make a URL - if (args.redditURL.search("reddit.com/") == -1) { - args.redditURL = "https://www.reddit.com/" + args.redditURL; + if (messageArguments[0].search("reddit.com/") == -1) { + messageArguments[0] = "https://www.reddit.com/" + messageArguments[0]; } - const last_char_of_URL = args.redditURL.charAt(args.redditURL.length - 1); + const last_char_of_URL = messageArguments[0].charAt(messageArguments[0].length - 1); switch (last_char_of_URL) { case '/': - args.redditURL += ".json" + messageArguments[0] += ".json" break; default: - args.redditURL += "/.json" + messageArguments[0] += "/.json" break; } - console.log(args.redditURL) + console.log(messageArguments[0]) // catching broken link errors var error_given; - await request(args.redditURL, async (error, response, html) => { + await request(messageArguments[0], async (error, response, html) => { var json_data; try { json_data = await JSON.parse(html) @@ -86,7 +95,7 @@ class DeployReddit extends Commando.Command { var sched = later.parse.text(testing_time); // time default is UTC | 4 hours ahead of FL later.date.localTime(); - var interval_instance = later.setInterval(function () { query_reddit(message, args.redditURL, interval_instance) }, sched); // interval_instance.clear() clears timer + var interval_instance = later.setInterval(function () { query_reddit(message, messageArguments[0], interval_instance) }, sched); // interval_instance.clear() clears timer }); } } From 2ab4bf1067d187835bcdcabf3a509fc381bc0a02 Mon Sep 17 00:00:00 2001 From: careyes17 Date: Sat, 14 Sep 2019 15:05:34 -0400 Subject: [PATCH 11/63] Succesfully added test setting to db --- src/commands/admin/deployreddit.js | 24 ++++++++++++++++++++++++ src/settings/SettingsProvider.js | 1 + 2 files changed, 25 insertions(+) diff --git a/src/commands/admin/deployreddit.js b/src/commands/admin/deployreddit.js index 47afcbe..b990513 100644 --- a/src/commands/admin/deployreddit.js +++ b/src/commands/admin/deployreddit.js @@ -1,6 +1,7 @@ const Discord = require('discord.js'); const Commando = require('discord.js-commando'); const Logger = require('../../logging/Logger'); +const {settingsKeys, settingNames} = require('../../settings/SettingsProvider'); const request = require('request'); var later = require('later'); @@ -39,6 +40,7 @@ class DeployReddit extends Commando.Command { switch (messageArguments[0]) { case '--stop': + setSettingFromKey(message,messageArguments); return; case '--edit': if (messageArguments[1].length > 0) { @@ -100,6 +102,28 @@ class DeployReddit extends Commando.Command { } } +/** + * + * ANY NEW SETTINGS NEED TO BE ADDED TO "SettingsProvider" + * + */ + +function setSettingFromKey(message, messageArguments) { + const [settingKey, newSetting] = messageArguments; + console.log(settingKey + " " + newSetting); + if (settingNames.includes(settingKey)) { + Logger.info({ + server: message.guild, + message: `${message.author.tag} updated ${settingKey} to ${newSetting}`, + }); + message.guild.settings.set(settingKey, newSetting); + return message.reply(`${settingKey} was assigned '${newSetting}'`); + } else { + return message.reply('Only preset settings can be set or modified. ' + + 'Use --listkeys to see a list of possible options.'); + } + } + async function query_reddit(message, redditURL, interval_instance) { //console.log(redditURL) await request(redditURL, (error, response, html) => { diff --git a/src/settings/SettingsProvider.js b/src/settings/SettingsProvider.js index b2bd427..29e5bc8 100644 --- a/src/settings/SettingsProvider.js +++ b/src/settings/SettingsProvider.js @@ -26,6 +26,7 @@ const settingKeys = { DEFAULT_LOGGING_CHANNEL: 'guild.loggingChannel', DEFAULT_ROLE_ASSIGNMENT_CHANNEL: 'guild.roles.roleAssignmentChannel', ROLE_ASSIGNMENT_MESSAGES: 'guild.roles.roleAssignmentMessages', + TEST_MESSAGE: '--stop' }; /** @type {string[]} */ From b0ba0e10a4c1b4aeb1b2edaa1cc1623381121ee1 Mon Sep 17 00:00:00 2001 From: careyes17 Date: Sat, 14 Sep 2019 16:05:08 -0400 Subject: [PATCH 12/63] Added reddit settings to settings files --- src/commands/admin/deployreddit.js | 28 +++++++++++++++++++--------- src/commands/admin/managesettings.js | 11 ++++++++++- src/settings/SettingsProvider.js | 9 +++++++-- 3 files changed, 36 insertions(+), 12 deletions(-) diff --git a/src/commands/admin/deployreddit.js b/src/commands/admin/deployreddit.js index b990513..5515a0a 100644 --- a/src/commands/admin/deployreddit.js +++ b/src/commands/admin/deployreddit.js @@ -1,7 +1,7 @@ const Discord = require('discord.js'); const Commando = require('discord.js-commando'); const Logger = require('../../logging/Logger'); -const {settingsKeys, settingNames} = require('../../settings/SettingsProvider'); +const {redditKeys, redditNames} = require('../../settings/SettingsProvider'); const request = require('request'); var later = require('later'); @@ -40,7 +40,8 @@ class DeployReddit extends Commando.Command { switch (messageArguments[0]) { case '--stop': - setSettingFromKey(message,messageArguments); + getValueOfReddit(message,messageArguments) + //setRedditFromKey(message,messageArguments); return; case '--edit': if (messageArguments[1].length > 0) { @@ -108,22 +109,31 @@ class DeployReddit extends Commando.Command { * */ -function setSettingFromKey(message, messageArguments) { - const [settingKey, newSetting] = messageArguments; - console.log(settingKey + " " + newSetting); - if (settingNames.includes(settingKey)) { +function setRedditFromKey(message, messageArguments) { + const [redditKey, newSetting] = messageArguments; + console.log(redditKey + " " + newSetting); + if (redditNames.includes(redditKey)) { Logger.info({ server: message.guild, - message: `${message.author.tag} updated ${settingKey} to ${newSetting}`, + message: `${message.author.tag} updated ${redditKey} to ${newSetting}`, }); - message.guild.settings.set(settingKey, newSetting); - return message.reply(`${settingKey} was assigned '${newSetting}'`); + message.guild.settings.set(redditKey, newSetting); + return message.reply(`${redditKey} was assigned '${newSetting}'`); } else { return message.reply('Only preset settings can be set or modified. ' + 'Use --listkeys to see a list of possible options.'); } } + function getValueOfReddit(message, messageArguments) { + const redditValue = message.guild.settings.get(messageArguments[0], null); + if (redditValue) { + return message.reply(`Value for ${messageArguments[0]} is ${redditValue}`); + } else { + return message.reply(`There is no value for key ${messageArguments[0]}`); + } + } + async function query_reddit(message, redditURL, interval_instance) { //console.log(redditURL) await request(redditURL, (error, response, html) => { diff --git a/src/commands/admin/managesettings.js b/src/commands/admin/managesettings.js index a45a2b4..d52dac4 100644 --- a/src/commands/admin/managesettings.js +++ b/src/commands/admin/managesettings.js @@ -1,6 +1,6 @@ // @ts-check const Commando = require('discord.js-commando'); -const {settingsKeys, settingNames} = require('../../settings/SettingsProvider'); +const {settingsKeys, settingNames, redditNames, redditKeys} = require('../../settings/SettingsProvider'); const Discord = require('discord.js'); const Logger = require('../../logging/Logger'); @@ -50,6 +50,8 @@ class SettingsCommand extends Commando.Command { return listServerSettings(message, messageArguments); case '--listkeys': return listSettingKeys(message, messageArguments); + case '--listreddit': + return listRedditKeys(message, messageArguments); case '--remove': return removeServerSetting(message, messageArguments); } @@ -127,6 +129,9 @@ function setSettingFromKey(message, messageArguments) { * @return {Promise} */ function getValueOfSetting(message, messageArguments) { + if (!settingNames.includes(messageArguments[0])) { + return message.reply(`The key ${messageArguments[0]} does not exist.`); + } const settingValue = message.guild.settings.get(messageArguments[0], null); if (settingValue) { return message.reply(`Value for ${messageArguments[0]} is ${settingValue}`); @@ -147,4 +152,8 @@ function listSettingKeys(message, messageArguments) { return message.reply(settingNames.join('\n'), {code: true}); } +function listRedditKeys(message, messageArguments) { + return message.reply(redditNames.join('\n'), {code: true}); +} + module.exports = SettingsCommand; diff --git a/src/settings/SettingsProvider.js b/src/settings/SettingsProvider.js index 29e5bc8..0967348 100644 --- a/src/settings/SettingsProvider.js +++ b/src/settings/SettingsProvider.js @@ -26,15 +26,20 @@ const settingKeys = { DEFAULT_LOGGING_CHANNEL: 'guild.loggingChannel', DEFAULT_ROLE_ASSIGNMENT_CHANNEL: 'guild.roles.roleAssignmentChannel', ROLE_ASSIGNMENT_MESSAGES: 'guild.roles.roleAssignmentMessages', - TEST_MESSAGE: '--stop' +}; + +const redditKeys = { + TEST_MESSAGE: '--stop', }; /** @type {string[]} */ const settingNames = Object.getOwnPropertyNames(settingKeys).map((key) => settingKeys[key]); - +const redditNames = Object.getOwnPropertyNames(redditKeys).map((key) => redditKeys[key]); module.exports = { setupSettingsProvider, settingsKeys: settingKeys, settingNames: settingNames, + redditKeys: redditKeys, + redditNames: redditNames, }; From b8d136a64d8aff26b4864f6a07b23e3119367dc6 Mon Sep 17 00:00:00 2001 From: Carlos Date: Sun, 15 Sep 2019 13:44:23 -0400 Subject: [PATCH 13/63] Added more reddit URL input tolerance --- src/commands/admin/deployreddit.js | 43 ++++++++++++++++++------------ src/settings/SettingsProvider.js | 2 +- 2 files changed, 27 insertions(+), 18 deletions(-) diff --git a/src/commands/admin/deployreddit.js b/src/commands/admin/deployreddit.js index 5515a0a..5b54fbd 100644 --- a/src/commands/admin/deployreddit.js +++ b/src/commands/admin/deployreddit.js @@ -1,7 +1,7 @@ const Discord = require('discord.js'); const Commando = require('discord.js-commando'); const Logger = require('../../logging/Logger'); -const {redditKeys, redditNames} = require('../../settings/SettingsProvider'); +const { redditKeys, redditNames } = require('../../settings/SettingsProvider'); const request = require('request'); var later = require('later'); @@ -40,8 +40,13 @@ class DeployReddit extends Commando.Command { switch (messageArguments[0]) { case '--stop': - getValueOfReddit(message,messageArguments) - //setRedditFromKey(message,messageArguments); + if (messageArguments.length > 1) { + messageArguments[0] = "guild.reddit.stop" + setRedditFromKey(message, messageArguments); + } else { + messageArguments[0] = "guild.reddit.stop" + getValueOfReddit(message, messageArguments) + } return; case '--edit': if (messageArguments[1].length > 0) { @@ -58,7 +63,11 @@ class DeployReddit extends Commando.Command { // appending the argument of "r/...." to make a URL if (messageArguments[0].search("reddit.com/") == -1) { - messageArguments[0] = "https://www.reddit.com/" + messageArguments[0]; + if (messageArguments[0].search("/") == 0) { + messageArguments[0] = "https://www.reddit.com" + messageArguments[0]; + } else { + messageArguments[0] = "https://www.reddit.com/" + messageArguments[0]; + } } const last_char_of_URL = messageArguments[0].charAt(messageArguments[0].length - 1); switch (last_char_of_URL) { @@ -113,26 +122,26 @@ function setRedditFromKey(message, messageArguments) { const [redditKey, newSetting] = messageArguments; console.log(redditKey + " " + newSetting); if (redditNames.includes(redditKey)) { - Logger.info({ - server: message.guild, - message: `${message.author.tag} updated ${redditKey} to ${newSetting}`, - }); - message.guild.settings.set(redditKey, newSetting); - return message.reply(`${redditKey} was assigned '${newSetting}'`); + Logger.info({ + server: message.guild, + message: `${message.author.tag} updated ${redditKey} to ${newSetting}`, + }); + message.guild.settings.set(redditKey, newSetting); + return message.reply(`${redditKey} was assigned '${newSetting}'`); } else { - return message.reply('Only preset settings can be set or modified. ' + - 'Use --listkeys to see a list of possible options.'); + return message.reply('Only preset settings can be set or modified. ' + + 'Use --listkeys to see a list of possible options.'); } - } +} - function getValueOfReddit(message, messageArguments) { +function getValueOfReddit(message, messageArguments) { const redditValue = message.guild.settings.get(messageArguments[0], null); if (redditValue) { - return message.reply(`Value for ${messageArguments[0]} is ${redditValue}`); + return message.reply(`Value for ${messageArguments[0]} is ${redditValue}`); } else { - return message.reply(`There is no value for key ${messageArguments[0]}`); + return message.reply(`There is no value for key ${messageArguments[0]}`); } - } +} async function query_reddit(message, redditURL, interval_instance) { //console.log(redditURL) diff --git a/src/settings/SettingsProvider.js b/src/settings/SettingsProvider.js index 0967348..bae3d99 100644 --- a/src/settings/SettingsProvider.js +++ b/src/settings/SettingsProvider.js @@ -29,7 +29,7 @@ const settingKeys = { }; const redditKeys = { - TEST_MESSAGE: '--stop', + TEST_MESSAGE: 'guild.reddit.stop', }; /** @type {string[]} */ From bea5f5ff184db4d26e1766a0bb6872404ecea69e Mon Sep 17 00:00:00 2001 From: Carlos Date: Sun, 15 Sep 2019 14:50:11 -0400 Subject: [PATCH 14/63] Planned methodology for storing db information --- src/commands/admin/deployreddit.js | 16 ++++++++++++++-- src/settings/SettingsProvider.js | 2 +- 2 files changed, 15 insertions(+), 3 deletions(-) diff --git a/src/commands/admin/deployreddit.js b/src/commands/admin/deployreddit.js index 5b54fbd..e426081 100644 --- a/src/commands/admin/deployreddit.js +++ b/src/commands/admin/deployreddit.js @@ -41,10 +41,10 @@ class DeployReddit extends Commando.Command { switch (messageArguments[0]) { case '--stop': if (messageArguments.length > 1) { - messageArguments[0] = "guild.reddit.stop" + messageArguments[0] = "guild.reddit.instances" setRedditFromKey(message, messageArguments); } else { - messageArguments[0] = "guild.reddit.stop" + messageArguments[0] = "guild.reddit.instances" getValueOfReddit(message, messageArguments) } return; @@ -116,6 +116,18 @@ class DeployReddit extends Commando.Command { * * ANY NEW SETTINGS NEED TO BE ADDED TO "SettingsProvider" * + * + * Method to alter guild.reddit.instance + array = [["a","b","c"],["d","e","f"],["g","h","i"]] + console.log(array) + for (element in array) { + if(array[element][0] == "d") { + array.splice(element,1) + } + } + console.log(array) + * + * */ function setRedditFromKey(message, messageArguments) { diff --git a/src/settings/SettingsProvider.js b/src/settings/SettingsProvider.js index bae3d99..0a48881 100644 --- a/src/settings/SettingsProvider.js +++ b/src/settings/SettingsProvider.js @@ -29,7 +29,7 @@ const settingKeys = { }; const redditKeys = { - TEST_MESSAGE: 'guild.reddit.stop', + REDDIT_INSTANCES: 'guild.reddit.instances', }; /** @type {string[]} */ From 724547caec19e5f1d75fa19b8274ad7cfd9a163c Mon Sep 17 00:00:00 2001 From: Carlos Date: Sun, 15 Sep 2019 18:34:48 -0400 Subject: [PATCH 15/63] In the process of making setRedditFromKey function --- src/commands/admin/deployreddit.js | 91 ++++++++++++++++++++++++++++-- 1 file changed, 85 insertions(+), 6 deletions(-) diff --git a/src/commands/admin/deployreddit.js b/src/commands/admin/deployreddit.js index e426081..4e903c5 100644 --- a/src/commands/admin/deployreddit.js +++ b/src/commands/admin/deployreddit.js @@ -42,10 +42,10 @@ class DeployReddit extends Commando.Command { case '--stop': if (messageArguments.length > 1) { messageArguments[0] = "guild.reddit.instances" - setRedditFromKey(message, messageArguments); + aaasetRedditFromKey(message, messageArguments); } else { messageArguments[0] = "guild.reddit.instances" - getValueOfReddit(message, messageArguments) + console.log(aaagetValueOfReddit(message, messageArguments, "12313")) } return; case '--edit': @@ -56,6 +56,7 @@ class DeployReddit extends Commando.Command { } return; case '--status': + TESTING(message); return; default: break; @@ -132,13 +133,24 @@ class DeployReddit extends Commando.Command { function setRedditFromKey(message, messageArguments) { const [redditKey, newSetting] = messageArguments; - console.log(redditKey + " " + newSetting); + //console.log(redditKey + " " + newSetting); + //var collection = [["a", "b", "c"], ["d", "e", "f"], ["g", "h", "i"]] + //var collection = { type: "Fiat", model: "500", color: "white" }; + var collection = { + "instances": { + id12313: "something1", + id1234: "something2", + } + }; + + + if (redditNames.includes(redditKey)) { Logger.info({ server: message.guild, message: `${message.author.tag} updated ${redditKey} to ${newSetting}`, }); - message.guild.settings.set(redditKey, newSetting); + message.guild.settings.set(redditKey, JSON.stringify(collection)); return message.reply(`${redditKey} was assigned '${newSetting}'`); } else { return message.reply('Only preset settings can be set or modified. ' + @@ -146,8 +158,43 @@ function setRedditFromKey(message, messageArguments) { } } -function getValueOfReddit(message, messageArguments) { - const redditValue = message.guild.settings.get(messageArguments[0], null); +function aaasetRedditFromKey(message, messageArguments) { + const [redditKey, newSetting] = messageArguments; + if (aaagetValueOfReddit(message, messageArguments, "12313", true) === undefined) { + var default_instance_object = { + "instances": { + } + }; + default_instance_object = JSON.stringify(default_instance_object); + message.guild.settings.set(redditKey, default_instance_object); + default_instance_object = JSON.parse(default_instance_object); + console.log(default_instance_object.instances) + default_instance_object.instances.push({ id12313: "something1" }); + console.log(default_instance_object) + default_instance_object = JSON.stringify(default_instance_object); + message.guild.settings.set(redditKey, default_instance_object); + console.log("Default created!") + } +} + +function TESTING(message) { + console.log(message.guild.settings.remove('guild.reddit.instances', null)) +} + +function getValueOfReddit(message, messageArguments, channelID) { + var redditValue = message.guild.settings.get(messageArguments, null); + console.log(messageArguments) + redditValue = JSON.parse(redditValue) + console.log(redditValue) + //console.log(redditValue.instances.id12313) + //console.log(redditValue.instances.id1234) + for (x in redditValue.instances) { + if (channelID === x) console.log(redditValue.instances[x]); + redditValue.instances[x] = "changedval" + console.log(redditValue.instances[x]) + var toChange = JSON.stringify(redditValue); + message.guild.settings.set("guild.reddit.instances", toChange); + } if (redditValue) { return message.reply(`Value for ${messageArguments[0]} is ${redditValue}`); } else { @@ -155,6 +202,38 @@ function getValueOfReddit(message, messageArguments) { } } +function aaagetValueOfReddit(message, messageArguments, channelID, setting_default) { + channelID = "id" + channelID; + var redditValue = message.guild.settings.get(messageArguments[0], null); + console.log(redditValue) + if (redditValue == null) { + if (!setting_default) { + message.reply(`${messageArguments[0]} was not found`); + return undefined; + } else { + return undefined; + } + } + redditValue = JSON.parse(redditValue) + for (key in redditValue.instances) { + //console.log(key) + if (channelID === key) { + //console.log(redditValue.instances[key]); + redditValue = redditValue.instances[key]; + break; + } + } + //console.log(redditValue) + + if (typeof redditValue !== 'string') { + message.reply(`The given ID for ${messageArguments[0]} was not found`); + return null; + } else { + message.reply(`Value for ${messageArguments[0]} is ${redditValue}`); + return redditValue; + } +} + async function query_reddit(message, redditURL, interval_instance) { //console.log(redditURL) await request(redditURL, (error, response, html) => { From e8f0570183d8982909472b1cdb8feda086f0eaf8 Mon Sep 17 00:00:00 2001 From: Carlos Date: Sun, 15 Sep 2019 18:56:04 -0400 Subject: [PATCH 16/63] In the process of parsing JSON --- src/commands/admin/deployreddit.js | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/src/commands/admin/deployreddit.js b/src/commands/admin/deployreddit.js index 4e903c5..5a144be 100644 --- a/src/commands/admin/deployreddit.js +++ b/src/commands/admin/deployreddit.js @@ -162,16 +162,12 @@ function aaasetRedditFromKey(message, messageArguments) { const [redditKey, newSetting] = messageArguments; if (aaagetValueOfReddit(message, messageArguments, "12313", true) === undefined) { var default_instance_object = { - "instances": { - } + "instances": [ + ] }; - default_instance_object = JSON.stringify(default_instance_object); - message.guild.settings.set(redditKey, default_instance_object); - default_instance_object = JSON.parse(default_instance_object); - console.log(default_instance_object.instances) default_instance_object.instances.push({ id12313: "something1" }); - console.log(default_instance_object) default_instance_object = JSON.stringify(default_instance_object); + console.log(default_instance_object) message.guild.settings.set(redditKey, default_instance_object); console.log("Default created!") } @@ -215,9 +211,13 @@ function aaagetValueOfReddit(message, messageArguments, channelID, setting_defau } } redditValue = JSON.parse(redditValue) + console.log(redditValue) + console.log(redditValue.instances) + console.log(redditValue.instances[0].id12313) + console.log("test-text") for (key in redditValue.instances) { - //console.log(key) - if (channelID === key) { + console.log(redditValue + "test-text 2") + if (channelID === redditValue.instances.channelID) { //console.log(redditValue.instances[key]); redditValue = redditValue.instances[key]; break; From 62f8e7020d931b87f7d709232c0d7865f97c4302 Mon Sep 17 00:00:00 2001 From: Carlos Date: Sun, 15 Sep 2019 19:29:29 -0400 Subject: [PATCH 17/63] Modified get function --- src/commands/admin/deployreddit.js | 18 ++++++++---------- 1 file changed, 8 insertions(+), 10 deletions(-) diff --git a/src/commands/admin/deployreddit.js b/src/commands/admin/deployreddit.js index 5a144be..a4fadc3 100644 --- a/src/commands/admin/deployreddit.js +++ b/src/commands/admin/deployreddit.js @@ -45,7 +45,7 @@ class DeployReddit extends Commando.Command { aaasetRedditFromKey(message, messageArguments); } else { messageArguments[0] = "guild.reddit.instances" - console.log(aaagetValueOfReddit(message, messageArguments, "12313")) + console.log(aaagetValueOfReddit(message, messageArguments, "1234")) } return; case '--edit': @@ -166,6 +166,7 @@ function aaasetRedditFromKey(message, messageArguments) { ] }; default_instance_object.instances.push({ id12313: "something1" }); + default_instance_object.instances.push({ id1234: "something2" }); default_instance_object = JSON.stringify(default_instance_object); console.log(default_instance_object) message.guild.settings.set(redditKey, default_instance_object); @@ -201,7 +202,7 @@ function getValueOfReddit(message, messageArguments, channelID) { function aaagetValueOfReddit(message, messageArguments, channelID, setting_default) { channelID = "id" + channelID; var redditValue = message.guild.settings.get(messageArguments[0], null); - console.log(redditValue) + //console.log(redditValue) if (redditValue == null) { if (!setting_default) { message.reply(`${messageArguments[0]} was not found`); @@ -211,15 +212,12 @@ function aaagetValueOfReddit(message, messageArguments, channelID, setting_defau } } redditValue = JSON.parse(redditValue) - console.log(redditValue) - console.log(redditValue.instances) - console.log(redditValue.instances[0].id12313) - console.log("test-text") for (key in redditValue.instances) { - console.log(redditValue + "test-text 2") - if (channelID === redditValue.instances.channelID) { - //console.log(redditValue.instances[key]); - redditValue = redditValue.instances[key]; + //console.log(key) + //console.log(redditValue.instances[key][channelID]) + if (redditValue.instances[key][channelID] !== undefined) { + //console.log("Matched!"); + redditValue = redditValue.instances[key][channelID]; break; } } From 76e8286fb3ec93f510afb3ecda00634cd797e1b4 Mon Sep 17 00:00:00 2001 From: Carlos Date: Sun, 15 Sep 2019 20:19:21 -0400 Subject: [PATCH 18/63] Working on function to change URL --- src/commands/admin/deployreddit.js | 26 +++++++++++++++++++++++--- 1 file changed, 23 insertions(+), 3 deletions(-) diff --git a/src/commands/admin/deployreddit.js b/src/commands/admin/deployreddit.js index a4fadc3..5f351a9 100644 --- a/src/commands/admin/deployreddit.js +++ b/src/commands/admin/deployreddit.js @@ -158,8 +158,9 @@ function setRedditFromKey(message, messageArguments) { } } -function aaasetRedditFromKey(message, messageArguments) { +function aaasetRedditFromKey(message, messageArguments, channelID) { const [redditKey, newSetting] = messageArguments; + //console.log(aaagetValueOfReddit(message, messageArguments, "12313")) if (aaagetValueOfReddit(message, messageArguments, "12313", true) === undefined) { var default_instance_object = { "instances": [ @@ -168,9 +169,29 @@ function aaasetRedditFromKey(message, messageArguments) { default_instance_object.instances.push({ id12313: "something1" }); default_instance_object.instances.push({ id1234: "something2" }); default_instance_object = JSON.stringify(default_instance_object); - console.log(default_instance_object) + //console.log(default_instance_object) message.guild.settings.set(redditKey, default_instance_object); console.log("Default created!") + return; + } + var redditValue = message.guild.settings.get(redditKey, null); + redditValue = JSON.parse(redditValue) + for (key in redditValue.instances) { + //console.log(key) + console.log(redditValue.instances[0]["id12313"]) + if (redditValue.instances[key]["id12313"] !== undefined) { + //console.log("Matched!"); + redditValue = redditValue.instances[key]["id12313"]; + break; + } + } + //console.log(redditValue) + if (typeof redditValue !== 'string') { + message.reply(`The given ID for ${messageArguments[0]} was not found`); + return null; + } else { + message.reply(`Value for ${messageArguments[0]} is ${redditValue}`); + return redditValue; } } @@ -202,7 +223,6 @@ function getValueOfReddit(message, messageArguments, channelID) { function aaagetValueOfReddit(message, messageArguments, channelID, setting_default) { channelID = "id" + channelID; var redditValue = message.guild.settings.get(messageArguments[0], null); - //console.log(redditValue) if (redditValue == null) { if (!setting_default) { message.reply(`${messageArguments[0]} was not found`); From 73b82ee25a939b80dc0782f21e7274041f61b575 Mon Sep 17 00:00:00 2001 From: Carlos Date: Sun, 15 Sep 2019 21:22:28 -0400 Subject: [PATCH 19/63] Set and Get reddit db queries are functional --- src/commands/admin/deployreddit.js | 26 +++++++++++++++++--------- 1 file changed, 17 insertions(+), 9 deletions(-) diff --git a/src/commands/admin/deployreddit.js b/src/commands/admin/deployreddit.js index 5f351a9..7f48f38 100644 --- a/src/commands/admin/deployreddit.js +++ b/src/commands/admin/deployreddit.js @@ -45,7 +45,7 @@ class DeployReddit extends Commando.Command { aaasetRedditFromKey(message, messageArguments); } else { messageArguments[0] = "guild.reddit.instances" - console.log(aaagetValueOfReddit(message, messageArguments, "1234")) + console.log(aaagetValueOfReddit(message, messageArguments, "12313")) } return; case '--edit': @@ -160,7 +160,6 @@ function setRedditFromKey(message, messageArguments) { function aaasetRedditFromKey(message, messageArguments, channelID) { const [redditKey, newSetting] = messageArguments; - //console.log(aaagetValueOfReddit(message, messageArguments, "12313")) if (aaagetValueOfReddit(message, messageArguments, "12313", true) === undefined) { var default_instance_object = { "instances": [ @@ -178,20 +177,25 @@ function aaasetRedditFromKey(message, messageArguments, channelID) { redditValue = JSON.parse(redditValue) for (key in redditValue.instances) { //console.log(key) - console.log(redditValue.instances[0]["id12313"]) + //console.log(redditValue.instances[0]["id12313"]) if (redditValue.instances[key]["id12313"] !== undefined) { //console.log("Matched!"); - redditValue = redditValue.instances[key]["id12313"]; + redditValue.instances[key]["id12313"] = "message argument 6"; + redditValue = JSON.stringify(redditValue); + if (typeof redditValue === 'string') { + message.guild.settings.set(redditKey, redditValue); + message.reply(`${redditKey} was assigned ${JSON.parse(redditValue).instances[key]["id12313"]}`); + return redditValue; + } break; } } //console.log(redditValue) + //console.log(redditKey) + //message.guild.settings.set(redditKey, JSON.stringify(collection)); if (typeof redditValue !== 'string') { message.reply(`The given ID for ${messageArguments[0]} was not found`); return null; - } else { - message.reply(`Value for ${messageArguments[0]} is ${redditValue}`); - return redditValue; } } @@ -247,8 +251,12 @@ function aaagetValueOfReddit(message, messageArguments, channelID, setting_defau message.reply(`The given ID for ${messageArguments[0]} was not found`); return null; } else { - message.reply(`Value for ${messageArguments[0]} is ${redditValue}`); - return redditValue; + if (setting_default != true) { + message.reply(`Value for ${messageArguments[0]} is ${redditValue}`); + return redditValue; + } else { + return redditValue; + } } } From e2a969456da5a27e1d9a6d6194a4cddf590dd071 Mon Sep 17 00:00:00 2001 From: Carlos Date: Sun, 15 Sep 2019 21:40:46 -0400 Subject: [PATCH 20/63] Cleaned up some get and set code --- src/commands/admin/deployreddit.js | 63 ++++-------------------------- 1 file changed, 8 insertions(+), 55 deletions(-) diff --git a/src/commands/admin/deployreddit.js b/src/commands/admin/deployreddit.js index 7f48f38..1a8114f 100644 --- a/src/commands/admin/deployreddit.js +++ b/src/commands/admin/deployreddit.js @@ -42,10 +42,10 @@ class DeployReddit extends Commando.Command { case '--stop': if (messageArguments.length > 1) { messageArguments[0] = "guild.reddit.instances" - aaasetRedditFromKey(message, messageArguments); + setRedditFromKey(message, messageArguments); } else { messageArguments[0] = "guild.reddit.instances" - console.log(aaagetValueOfReddit(message, messageArguments, "12313")) + console.log(getValueOfReddit(message, messageArguments, "12313")) } return; case '--edit': @@ -56,7 +56,7 @@ class DeployReddit extends Commando.Command { } return; case '--status': - TESTING(message); + delete_instances(message); return; default: break; @@ -131,36 +131,9 @@ class DeployReddit extends Commando.Command { * */ -function setRedditFromKey(message, messageArguments) { +function setRedditFromKey(message, messageArguments, channelID) { const [redditKey, newSetting] = messageArguments; - //console.log(redditKey + " " + newSetting); - //var collection = [["a", "b", "c"], ["d", "e", "f"], ["g", "h", "i"]] - //var collection = { type: "Fiat", model: "500", color: "white" }; - var collection = { - "instances": { - id12313: "something1", - id1234: "something2", - } - }; - - - - if (redditNames.includes(redditKey)) { - Logger.info({ - server: message.guild, - message: `${message.author.tag} updated ${redditKey} to ${newSetting}`, - }); - message.guild.settings.set(redditKey, JSON.stringify(collection)); - return message.reply(`${redditKey} was assigned '${newSetting}'`); - } else { - return message.reply('Only preset settings can be set or modified. ' + - 'Use --listkeys to see a list of possible options.'); - } -} - -function aaasetRedditFromKey(message, messageArguments, channelID) { - const [redditKey, newSetting] = messageArguments; - if (aaagetValueOfReddit(message, messageArguments, "12313", true) === undefined) { + if (getValueOfReddit(message, messageArguments, "12313", true) === undefined) { var default_instance_object = { "instances": [ ] @@ -171,6 +144,7 @@ function aaasetRedditFromKey(message, messageArguments, channelID) { //console.log(default_instance_object) message.guild.settings.set(redditKey, default_instance_object); console.log("Default created!") + message.reply(`Reddit instances can now be made!`); return; } var redditValue = message.guild.settings.get(redditKey, null); @@ -199,32 +173,11 @@ function aaasetRedditFromKey(message, messageArguments, channelID) { } } -function TESTING(message) { +function delete_instances(message) { console.log(message.guild.settings.remove('guild.reddit.instances', null)) } -function getValueOfReddit(message, messageArguments, channelID) { - var redditValue = message.guild.settings.get(messageArguments, null); - console.log(messageArguments) - redditValue = JSON.parse(redditValue) - console.log(redditValue) - //console.log(redditValue.instances.id12313) - //console.log(redditValue.instances.id1234) - for (x in redditValue.instances) { - if (channelID === x) console.log(redditValue.instances[x]); - redditValue.instances[x] = "changedval" - console.log(redditValue.instances[x]) - var toChange = JSON.stringify(redditValue); - message.guild.settings.set("guild.reddit.instances", toChange); - } - if (redditValue) { - return message.reply(`Value for ${messageArguments[0]} is ${redditValue}`); - } else { - return message.reply(`There is no value for key ${messageArguments[0]}`); - } -} - -function aaagetValueOfReddit(message, messageArguments, channelID, setting_default) { +function getValueOfReddit(message, messageArguments, channelID, setting_default) { channelID = "id" + channelID; var redditValue = message.guild.settings.get(messageArguments[0], null); if (redditValue == null) { From 42018c5357d42c005d7e00819234309c06e93ff5 Mon Sep 17 00:00:00 2001 From: Carlos Date: Fri, 20 Sep 2019 11:35:06 -0400 Subject: [PATCH 21/63] Added default channel ID for set and get --- src/commands/admin/deployreddit.js | 33 +++++++++++++++++++++--------- 1 file changed, 23 insertions(+), 10 deletions(-) diff --git a/src/commands/admin/deployreddit.js b/src/commands/admin/deployreddit.js index 1a8114f..ce117f0 100644 --- a/src/commands/admin/deployreddit.js +++ b/src/commands/admin/deployreddit.js @@ -42,7 +42,7 @@ class DeployReddit extends Commando.Command { case '--stop': if (messageArguments.length > 1) { messageArguments[0] = "guild.reddit.instances" - setRedditFromKey(message, messageArguments); + setRedditFromKey(message, messageArguments, "12313"); } else { messageArguments[0] = "guild.reddit.instances" console.log(getValueOfReddit(message, messageArguments, "12313")) @@ -133,7 +133,7 @@ class DeployReddit extends Commando.Command { function setRedditFromKey(message, messageArguments, channelID) { const [redditKey, newSetting] = messageArguments; - if (getValueOfReddit(message, messageArguments, "12313", true) === undefined) { + if (getValueOfReddit(message, messageArguments, channelID, true) === undefined) { var default_instance_object = { "instances": [ ] @@ -147,18 +147,25 @@ function setRedditFromKey(message, messageArguments, channelID) { message.reply(`Reddit instances can now be made!`); return; } + if (channelID === undefined) { + channelID = "id" + message.channel.id; + console.log(channelID) + } else { + channelID = "id" + channelID; + console.log(channelID) + } var redditValue = message.guild.settings.get(redditKey, null); redditValue = JSON.parse(redditValue) for (key in redditValue.instances) { //console.log(key) //console.log(redditValue.instances[0]["id12313"]) - if (redditValue.instances[key]["id12313"] !== undefined) { + if (redditValue.instances[key][channelID] !== undefined) { //console.log("Matched!"); - redditValue.instances[key]["id12313"] = "message argument 6"; + redditValue.instances[key][channelID] = "message argument 6"; redditValue = JSON.stringify(redditValue); if (typeof redditValue === 'string') { message.guild.settings.set(redditKey, redditValue); - message.reply(`${redditKey} was assigned ${JSON.parse(redditValue).instances[key]["id12313"]}`); + message.reply(`${redditKey} was assigned ${JSON.parse(redditValue).instances[key][channelID]}`); return redditValue; } break; @@ -173,12 +180,14 @@ function setRedditFromKey(message, messageArguments, channelID) { } } -function delete_instances(message) { - console.log(message.guild.settings.remove('guild.reddit.instances', null)) -} - function getValueOfReddit(message, messageArguments, channelID, setting_default) { - channelID = "id" + channelID; + if (channelID === undefined) { + channelID = "id" + message.channel.id; + console.log(channelID) + } else { + channelID = "id" + channelID; + console.log(channelID) + } var redditValue = message.guild.settings.get(messageArguments[0], null); if (redditValue == null) { if (!setting_default) { @@ -213,6 +222,10 @@ function getValueOfReddit(message, messageArguments, channelID, setting_default) } } +function delete_instances(message) { + console.log(message.guild.settings.remove('guild.reddit.instances', null)) +} + async function query_reddit(message, redditURL, interval_instance) { //console.log(redditURL) await request(redditURL, (error, response, html) => { From e486e816f9734e492cd5c07c5cbefda2b885b4fd Mon Sep 17 00:00:00 2001 From: Carlos Date: Fri, 20 Sep 2019 13:21:46 -0400 Subject: [PATCH 22/63] Added remove method --- src/commands/admin/deployreddit.js | 53 ++++++++++++++++++++++++++++-- 1 file changed, 50 insertions(+), 3 deletions(-) diff --git a/src/commands/admin/deployreddit.js b/src/commands/admin/deployreddit.js index ce117f0..a6cd9f4 100644 --- a/src/commands/admin/deployreddit.js +++ b/src/commands/admin/deployreddit.js @@ -45,14 +45,20 @@ class DeployReddit extends Commando.Command { setRedditFromKey(message, messageArguments, "12313"); } else { messageArguments[0] = "guild.reddit.instances" - console.log(getValueOfReddit(message, messageArguments, "12313")) + console.log(getValueOfReddit(message, messageArguments, "12313")); } return; case '--edit': - if (messageArguments[1].length > 0) { - //test the url and replace + if (messageArguments[1] !== undefined) { + if (messageArguments[1].length > 0) { + //test the url and replace + messageArguments[0] = "guild.reddit.instances" + removeRedditFromKey(message, messageArguments, "12313"); + } } else { //send message about how to edit + messageArguments[0] = "guild.reddit.instances" + removeRedditFromKey(message, messageArguments, "12313"); } return; case '--status': @@ -131,6 +137,47 @@ class DeployReddit extends Commando.Command { * */ +function removeRedditFromKey(message, messageArguments, channelID) { + console.log(messageArguments[0]) + var redditValue = message.guild.settings.get(messageArguments[0], null); + console.log(redditValue) + if (redditValue == null) { + message.reply(`${messageArguments[0]} was not found`); + return undefined; + } + if (channelID === undefined) { + channelID = "id" + message.channel.id; + //console.log(channelID) + } else { + channelID = "id" + channelID; + //console.log(channelID) + } + redditValue = JSON.parse(redditValue) + console.log(redditValue.instances) + for (key in redditValue.instances) { + //console.log(key) + //console.log(redditValue.instances[0]["id12313"]) + if (redditValue.instances[key][channelID] !== undefined) { + //console.log("Matched!"); + //redditValue.instances[key][channelID] = "message argument 6"; + console.log(JSON.stringify(redditValue.instances) + " start"); + console.log(redditValue.instances[key]); + redditValue.instances.splice(key, 1); + console.log(JSON.stringify(redditValue.instances) + " end"); + redditValue = JSON.stringify(redditValue); + if (typeof redditValue === 'string') { + message.guild.settings.set(messageArguments[0], redditValue); + message.reply(`${channelID} was removed from this guild`); + return; + } + break; + } + } + + message.reply(`${channelID} was not found`); + return undefined; +} + function setRedditFromKey(message, messageArguments, channelID) { const [redditKey, newSetting] = messageArguments; if (getValueOfReddit(message, messageArguments, channelID, true) === undefined) { From 9a36bbe3621b7bdfa4aa6e03df1ae1b435b10833 Mon Sep 17 00:00:00 2001 From: Carlos Date: Fri, 20 Sep 2019 14:14:03 -0400 Subject: [PATCH 23/63] Cleaning code in progress --- src/commands/admin/deployreddit.js | 50 ++++++++++++++---------------- 1 file changed, 23 insertions(+), 27 deletions(-) diff --git a/src/commands/admin/deployreddit.js b/src/commands/admin/deployreddit.js index a6cd9f4..523c8f0 100644 --- a/src/commands/admin/deployreddit.js +++ b/src/commands/admin/deployreddit.js @@ -138,32 +138,21 @@ class DeployReddit extends Commando.Command { */ function removeRedditFromKey(message, messageArguments, channelID) { - console.log(messageArguments[0]) var redditValue = message.guild.settings.get(messageArguments[0], null); - console.log(redditValue) if (redditValue == null) { message.reply(`${messageArguments[0]} was not found`); return undefined; } if (channelID === undefined) { channelID = "id" + message.channel.id; - //console.log(channelID) } else { channelID = "id" + channelID; - //console.log(channelID) } redditValue = JSON.parse(redditValue) console.log(redditValue.instances) for (key in redditValue.instances) { - //console.log(key) - //console.log(redditValue.instances[0]["id12313"]) if (redditValue.instances[key][channelID] !== undefined) { - //console.log("Matched!"); - //redditValue.instances[key][channelID] = "message argument 6"; - console.log(JSON.stringify(redditValue.instances) + " start"); - console.log(redditValue.instances[key]); redditValue.instances.splice(key, 1); - console.log(JSON.stringify(redditValue.instances) + " end"); redditValue = JSON.stringify(redditValue); if (typeof redditValue === 'string') { message.guild.settings.set(messageArguments[0], redditValue); @@ -181,14 +170,17 @@ function removeRedditFromKey(message, messageArguments, channelID) { function setRedditFromKey(message, messageArguments, channelID) { const [redditKey, newSetting] = messageArguments; if (getValueOfReddit(message, messageArguments, channelID, true) === undefined) { + if (channelID === undefined) { + channelID = "id" + message.channel.id; + } else { + channelID = "id" + channelID; + } var default_instance_object = { "instances": [ ] }; - default_instance_object.instances.push({ id12313: "something1" }); - default_instance_object.instances.push({ id1234: "something2" }); + default_instance_object.instances.push({ [channelID]: newSetting }); default_instance_object = JSON.stringify(default_instance_object); - //console.log(default_instance_object) message.guild.settings.set(redditKey, default_instance_object); console.log("Default created!") message.reply(`Reddit instances can now be made!`); @@ -196,19 +188,18 @@ function setRedditFromKey(message, messageArguments, channelID) { } if (channelID === undefined) { channelID = "id" + message.channel.id; - console.log(channelID) } else { channelID = "id" + channelID; - console.log(channelID) } + + channelID = "19" + var redditValue = message.guild.settings.get(redditKey, null); redditValue = JSON.parse(redditValue) for (key in redditValue.instances) { - //console.log(key) - //console.log(redditValue.instances[0]["id12313"]) if (redditValue.instances[key][channelID] !== undefined) { //console.log("Matched!"); - redditValue.instances[key][channelID] = "message argument 6"; + redditValue.instances[key][channelID] = newSetting; redditValue = JSON.stringify(redditValue); if (typeof redditValue === 'string') { message.guild.settings.set(redditKey, redditValue); @@ -218,22 +209,30 @@ function setRedditFromKey(message, messageArguments, channelID) { break; } } - //console.log(redditValue) - //console.log(redditKey) - //message.guild.settings.set(redditKey, JSON.stringify(collection)); + + // Adding a new ID and value + var redditValue = message.guild.settings.get(redditKey, null); + redditValue = JSON.parse(redditValue) + console.log("testing testing") + redditValue.instances.push({ [channelID]: newSetting }); + console.log(JSON.stringify(redditValue)) + redditValue = JSON.stringify(redditValue); + message.guild.settings.set(redditKey, redditValue); + if (typeof redditValue !== 'string') { message.reply(`The given ID for ${messageArguments[0]} was not found`); return null; + } else { + message.reply(`${redditKey} was assigned ${JSON.parse(redditValue).instances[channelID]}`); + return; } } function getValueOfReddit(message, messageArguments, channelID, setting_default) { if (channelID === undefined) { channelID = "id" + message.channel.id; - console.log(channelID) } else { channelID = "id" + channelID; - console.log(channelID) } var redditValue = message.guild.settings.get(messageArguments[0], null); if (redditValue == null) { @@ -246,15 +245,12 @@ function getValueOfReddit(message, messageArguments, channelID, setting_default) } redditValue = JSON.parse(redditValue) for (key in redditValue.instances) { - //console.log(key) - //console.log(redditValue.instances[key][channelID]) if (redditValue.instances[key][channelID] !== undefined) { //console.log("Matched!"); redditValue = redditValue.instances[key][channelID]; break; } } - //console.log(redditValue) if (typeof redditValue !== 'string') { message.reply(`The given ID for ${messageArguments[0]} was not found`); From a40804411083624850112c13e2208f548a9d35c5 Mon Sep 17 00:00:00 2001 From: Carlos Date: Fri, 20 Sep 2019 14:19:01 -0400 Subject: [PATCH 24/63] Adding new arbitrary channels implemented --- src/commands/admin/deployreddit.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/commands/admin/deployreddit.js b/src/commands/admin/deployreddit.js index 523c8f0..9df508b 100644 --- a/src/commands/admin/deployreddit.js +++ b/src/commands/admin/deployreddit.js @@ -192,7 +192,7 @@ function setRedditFromKey(message, messageArguments, channelID) { channelID = "id" + channelID; } - channelID = "19" + channelID = "23" var redditValue = message.guild.settings.get(redditKey, null); redditValue = JSON.parse(redditValue) @@ -223,7 +223,7 @@ function setRedditFromKey(message, messageArguments, channelID) { message.reply(`The given ID for ${messageArguments[0]} was not found`); return null; } else { - message.reply(`${redditKey} was assigned ${JSON.parse(redditValue).instances[channelID]}`); + message.reply(`${channelID} was assigned ${JSON.parse(redditValue).instances[JSON.parse(redditValue).instances.length - 1][channelID]}`); return; } } From 3dad9db5093e4f12e2d35141da2346b46a191326 Mon Sep 17 00:00:00 2001 From: Carlos Date: Fri, 20 Sep 2019 14:33:42 -0400 Subject: [PATCH 25/63] get, set, add new, and remove working --- src/commands/admin/deployreddit.js | 11 ++--------- 1 file changed, 2 insertions(+), 9 deletions(-) diff --git a/src/commands/admin/deployreddit.js b/src/commands/admin/deployreddit.js index 9df508b..d44b3e3 100644 --- a/src/commands/admin/deployreddit.js +++ b/src/commands/admin/deployreddit.js @@ -192,8 +192,6 @@ function setRedditFromKey(message, messageArguments, channelID) { channelID = "id" + channelID; } - channelID = "23" - var redditValue = message.guild.settings.get(redditKey, null); redditValue = JSON.parse(redditValue) for (key in redditValue.instances) { @@ -219,13 +217,8 @@ function setRedditFromKey(message, messageArguments, channelID) { redditValue = JSON.stringify(redditValue); message.guild.settings.set(redditKey, redditValue); - if (typeof redditValue !== 'string') { - message.reply(`The given ID for ${messageArguments[0]} was not found`); - return null; - } else { - message.reply(`${channelID} was assigned ${JSON.parse(redditValue).instances[JSON.parse(redditValue).instances.length - 1][channelID]}`); - return; - } + message.reply(`${channelID} was assigned ${newSetting}`); + return; } function getValueOfReddit(message, messageArguments, channelID, setting_default) { From 800de7ecdda1e44ee91b17acc762b323a54b2250 Mon Sep 17 00:00:00 2001 From: Carlos Date: Fri, 20 Sep 2019 15:49:04 -0400 Subject: [PATCH 26/63] Developed "--stop" function --- src/commands/admin/deployreddit.js | 17 +++++++---------- 1 file changed, 7 insertions(+), 10 deletions(-) diff --git a/src/commands/admin/deployreddit.js b/src/commands/admin/deployreddit.js index d44b3e3..8f81fbf 100644 --- a/src/commands/admin/deployreddit.js +++ b/src/commands/admin/deployreddit.js @@ -40,29 +40,26 @@ class DeployReddit extends Commando.Command { switch (messageArguments[0]) { case '--stop': - if (messageArguments.length > 1) { - messageArguments[0] = "guild.reddit.instances" - setRedditFromKey(message, messageArguments, "12313"); + messageArguments[0] = "guild.reddit.instances" + if (messageArguments.length == 2) { + // removes channel key and reddit URL from db + removeRedditFromKey(message, messageArguments, messageArguments[1]); } else { - messageArguments[0] = "guild.reddit.instances" - console.log(getValueOfReddit(message, messageArguments, "12313")); + message.reply(`!!deployreddit --stop \nStops the execution of the reddit deployment in the specified channel.`); } return; case '--edit': + messageArguments[0] = "guild.reddit.instances" if (messageArguments[1] !== undefined) { if (messageArguments[1].length > 0) { //test the url and replace - messageArguments[0] = "guild.reddit.instances" - removeRedditFromKey(message, messageArguments, "12313"); } } else { //send message about how to edit - messageArguments[0] = "guild.reddit.instances" - removeRedditFromKey(message, messageArguments, "12313"); } return; case '--status': - delete_instances(message); + messageArguments[0] = "guild.reddit.instances" return; default: break; From 2abbcba5519c619d50a5572831b768cad6144bc4 Mon Sep 17 00:00:00 2001 From: Carlos Date: Fri, 20 Sep 2019 16:26:52 -0400 Subject: [PATCH 27/63] Developed "--edit" function --- src/commands/admin/deployreddit.js | 151 +++++++++++++++++++---------- 1 file changed, 98 insertions(+), 53 deletions(-) diff --git a/src/commands/admin/deployreddit.js b/src/commands/admin/deployreddit.js index 8f81fbf..c0b48ad 100644 --- a/src/commands/admin/deployreddit.js +++ b/src/commands/admin/deployreddit.js @@ -50,69 +50,109 @@ class DeployReddit extends Commando.Command { return; case '--edit': messageArguments[0] = "guild.reddit.instances" - if (messageArguments[1] !== undefined) { - if (messageArguments[1].length > 0) { - //test the url and replace + if (messageArguments.length == 3) { + // appending the argument of "r/...." to make a URL + if (messageArguments[2].search("reddit.com/") == -1) { + if (messageArguments[2].search("/") == 0) { + messageArguments[2] = "https://www.reddit.com" + messageArguments[2]; + } else { + messageArguments[2] = "https://www.reddit.com/" + messageArguments[2]; + } + } + const last_char_of_URL = messageArguments[2].charAt(messageArguments[2].length - 1); + switch (last_char_of_URL) { + case '/': + messageArguments[2] += ".json" + break; + default: + messageArguments[2] += "/.json" + break; } + console.log(messageArguments[2]) + + + // catching broken link errors + var error_given; + await request(messageArguments[2], async (error, response, html) => { + var json_data; + try { + json_data = await JSON.parse(html) + } catch (e) { + message.say("Sorry, this link did not work."); + return; + } + error_given = json_data.error == '404' ? true : false; + + if (error) { + message.say("Sorry, this link did not work."); + return; + } else if (error_given == true) { + message.say("Sorry, this link did not work."); + return; + } + + console.log(messageArguments) + setRedditFromKey(message, messageArguments, messageArguments[1]); + + }); } else { - //send message about how to edit + message.reply(`!!deployreddit --edit \nStops the execution of the reddit deployment in the specified channel.`); } return; case '--status': messageArguments[0] = "guild.reddit.instances" return; default: - break; - } - - // appending the argument of "r/...." to make a URL - if (messageArguments[0].search("reddit.com/") == -1) { - if (messageArguments[0].search("/") == 0) { - messageArguments[0] = "https://www.reddit.com" + messageArguments[0]; - } else { - messageArguments[0] = "https://www.reddit.com/" + messageArguments[0]; - } - } - const last_char_of_URL = messageArguments[0].charAt(messageArguments[0].length - 1); - switch (last_char_of_URL) { - case '/': - messageArguments[0] += ".json" - break; - default: - messageArguments[0] += "/.json" - break; - } - console.log(messageArguments[0]) + // appending the argument of "r/...." to make a URL + if (messageArguments[0].search("reddit.com/") == -1) { + if (messageArguments[0].search("/") == 0) { + messageArguments[0] = "https://www.reddit.com" + messageArguments[0]; + } else { + messageArguments[0] = "https://www.reddit.com/" + messageArguments[0]; + } + } + const last_char_of_URL = messageArguments[0].charAt(messageArguments[0].length - 1); + switch (last_char_of_URL) { + case '/': + messageArguments[0] += ".json" + break; + default: + messageArguments[0] += "/.json" + break; + } + console.log(messageArguments[0]) - // catching broken link errors - var error_given; - await request(messageArguments[0], async (error, response, html) => { - var json_data; - try { - json_data = await JSON.parse(html) - } catch (e) { - message.say("Sorry, this link did not work."); - return; - } - error_given = json_data.error == '404' ? true : false; + // catching broken link errors + var error_given; + await request(messageArguments[0], async (error, response, html) => { + var json_data; + try { + json_data = await JSON.parse(html) + } catch (e) { + message.say("Sorry, this link did not work."); + return; + } + error_given = json_data.error == '404' ? true : false; - if (error) { - message.say("Sorry, this link did not work."); - return; - } else if (error_given == true) { - message.say("Sorry, this link did not work."); - return; - } + if (error) { + message.say("Sorry, this link did not work."); + return; + } else if (error_given == true) { + message.say("Sorry, this link did not work."); + return; + } - //console.log(message.channel.id) gets the ID of current text channel - const daily_time = 'at 08:00am'; - const testing_time = 'every 10 seconds'; - var sched = later.parse.text(testing_time); - // time default is UTC | 4 hours ahead of FL - later.date.localTime(); - var interval_instance = later.setInterval(function () { query_reddit(message, messageArguments[0], interval_instance) }, sched); // interval_instance.clear() clears timer - }); + //console.log(message.channel.id) gets the ID of current text channel + const daily_time = 'at 08:00am'; + const testing_time = 'every 10 seconds'; + var sched = later.parse.text(testing_time); + // time default is UTC | 4 hours ahead of FL + later.date.localTime(); + var interval_instance = later.setInterval(function () { query_reddit(message, messageArguments[0], interval_instance) }, sched); // interval_instance.clear() clears timer + }); + break; + } } } @@ -165,8 +205,10 @@ function removeRedditFromKey(message, messageArguments, channelID) { } function setRedditFromKey(message, messageArguments, channelID) { - const [redditKey, newSetting] = messageArguments; - if (getValueOfReddit(message, messageArguments, channelID, true) === undefined) { + const [redditKey, tempChannelID, newSetting] = messageArguments; + channelID = tempChannelID; + status_of_value = getValueOfReddit(message, messageArguments, channelID, true); + if (status_of_value === undefined) { if (channelID === undefined) { channelID = "id" + message.channel.id; } else { @@ -182,6 +224,9 @@ function setRedditFromKey(message, messageArguments, channelID) { console.log("Default created!") message.reply(`Reddit instances can now be made!`); return; + } else if (status_of_value === null) { + console.log("ID not found") + return; } if (channelID === undefined) { channelID = "id" + message.channel.id; From 1e45428b888e0cf416b40df1105273ce2cc6c822 Mon Sep 17 00:00:00 2001 From: Carlos Date: Fri, 20 Sep 2019 17:03:09 -0400 Subject: [PATCH 28/63] developing several flag commands --- src/commands/admin/deployreddit.js | 113 ++++++++++++++++------------- 1 file changed, 64 insertions(+), 49 deletions(-) diff --git a/src/commands/admin/deployreddit.js b/src/commands/admin/deployreddit.js index c0b48ad..e09dae0 100644 --- a/src/commands/admin/deployreddit.js +++ b/src/commands/admin/deployreddit.js @@ -36,7 +36,7 @@ class DeployReddit extends Commando.Command { */ async run(message, args) { - const messageArguments = args.split(' '); + var messageArguments = args.split(' '); switch (messageArguments[0]) { case '--stop': @@ -92,65 +92,80 @@ class DeployReddit extends Commando.Command { } console.log(messageArguments) - setRedditFromKey(message, messageArguments, messageArguments[1]); + setRedditFromKey(message, messageArguments, messageArguments[1], true); }); } else { - message.reply(`!!deployreddit --edit \nStops the execution of the reddit deployment in the specified channel.`); + message.reply(`!!deployreddit --edit \nChanges the given URL of a channel.`); } return; case '--status': messageArguments[0] = "guild.reddit.instances" + if (messageArguments.length == 2) { + getValueOfReddit(message, messageArguments, messageArguments[1]) + } else { + message.reply(`!!deployreddit --status \nGives information about the given channel with respect to reddit deployment.`); + } + return; + case '--removeall': + delete_instances(message); return; default: - // appending the argument of "r/...." to make a URL - if (messageArguments[0].search("reddit.com/") == -1) { - if (messageArguments[0].search("/") == 0) { - messageArguments[0] = "https://www.reddit.com" + messageArguments[0]; - } else { - messageArguments[0] = "https://www.reddit.com/" + messageArguments[0]; + if (messageArguments.length == 2) { + // appending the argument of "r/...." to make a URL + if (messageArguments[1].search("reddit.com/") == -1) { + if (messageArguments[1].search("/") == 0) { + messageArguments[1] = "https://www.reddit.com" + messageArguments[1]; + } else { + messageArguments[1] = "https://www.reddit.com/" + messageArguments[1]; + } } - } - const last_char_of_URL = messageArguments[0].charAt(messageArguments[0].length - 1); - switch (last_char_of_URL) { - case '/': - messageArguments[0] += ".json" - break; - default: - messageArguments[0] += "/.json" - break; - } - console.log(messageArguments[0]) + const last_char_of_URL = messageArguments[1].charAt(messageArguments[1].length - 1); + switch (last_char_of_URL) { + case '/': + messageArguments[1] += ".json" + break; + default: + messageArguments[1] += "/.json" + break; + } + console.log(messageArguments[1]) - // catching broken link errors - var error_given; - await request(messageArguments[0], async (error, response, html) => { - var json_data; - try { - json_data = await JSON.parse(html) - } catch (e) { - message.say("Sorry, this link did not work."); - return; - } - error_given = json_data.error == '404' ? true : false; + // catching broken link errors + var error_given; + await request(messageArguments[1], async (error, response, html) => { + var json_data; + try { + json_data = await JSON.parse(html) + } catch (e) { + message.say("Sorry, this link did not work."); + return; + } + error_given = json_data.error == '404' ? true : false; - if (error) { - message.say("Sorry, this link did not work."); - return; - } else if (error_given == true) { - message.say("Sorry, this link did not work."); - return; - } + if (error) { + message.say("Sorry, this link did not work."); + return; + } else if (error_given == true) { + message.say("Sorry, this link did not work."); + return; + } - //console.log(message.channel.id) gets the ID of current text channel - const daily_time = 'at 08:00am'; - const testing_time = 'every 10 seconds'; - var sched = later.parse.text(testing_time); - // time default is UTC | 4 hours ahead of FL - later.date.localTime(); - var interval_instance = later.setInterval(function () { query_reddit(message, messageArguments[0], interval_instance) }, sched); // interval_instance.clear() clears timer - }); + messageArguments = ["guild.reddit.instances", messageArguments[0], messageArguments[1]]; + setRedditFromKey(message, messageArguments, messageArguments[1], false); + + //console.log(message.channel.id) gets the ID of current text channel + const daily_time = 'at 08:00am'; + const testing_time = 'every 10 seconds'; + var sched = later.parse.text(testing_time); + // time default is UTC | 4 hours ahead of FL + later.date.localTime(); + var interval_instance = later.setInterval(function () { query_reddit(message, messageArguments[1], interval_instance) }, sched); // interval_instance.clear() clears timer + }); + } else { + message.reply(`!!deployreddit \nAdds a reddit instance to a given channel.`); + } break; } } @@ -204,11 +219,11 @@ function removeRedditFromKey(message, messageArguments, channelID) { return undefined; } -function setRedditFromKey(message, messageArguments, channelID) { +function setRedditFromKey(message, messageArguments, channelID, edit) { const [redditKey, tempChannelID, newSetting] = messageArguments; channelID = tempChannelID; status_of_value = getValueOfReddit(message, messageArguments, channelID, true); - if (status_of_value === undefined) { + if (status_of_value === undefined && edit == true) { if (channelID === undefined) { channelID = "id" + message.channel.id; } else { @@ -292,7 +307,7 @@ function getValueOfReddit(message, messageArguments, channelID, setting_default) return null; } else { if (setting_default != true) { - message.reply(`Value for ${messageArguments[0]} is ${redditValue}`); + message.reply(`Value for ${channelID} is ${redditValue}`); return redditValue; } else { return redditValue; From 1b474bd6f2f1819e7612ddc3071845c7d640e870 Mon Sep 17 00:00:00 2001 From: Carlos Date: Fri, 20 Sep 2019 19:13:50 -0400 Subject: [PATCH 29/63] Tested add, edit, and status --- src/commands/admin/deployreddit.js | 59 +++++++++++++++++++++++++----- 1 file changed, 49 insertions(+), 10 deletions(-) diff --git a/src/commands/admin/deployreddit.js b/src/commands/admin/deployreddit.js index e09dae0..d760b97 100644 --- a/src/commands/admin/deployreddit.js +++ b/src/commands/admin/deployreddit.js @@ -92,6 +92,7 @@ class DeployReddit extends Commando.Command { } console.log(messageArguments) + console.log("aa333aa") setRedditFromKey(message, messageArguments, messageArguments[1], true); }); @@ -105,10 +106,14 @@ class DeployReddit extends Commando.Command { getValueOfReddit(message, messageArguments, messageArguments[1]) } else { message.reply(`!!deployreddit --status \nGives information about the given channel with respect to reddit deployment.`); + let redditValue = message.guild.settings.get("guild.reddit.instances", null); + console.log(redditValue); } return; case '--removeall': delete_instances(message); + let redditValue = message.guild.settings.get("guild.reddit.instances", null); + console.log(redditValue); return; default: if (messageArguments.length == 2) { @@ -153,7 +158,32 @@ class DeployReddit extends Commando.Command { } messageArguments = ["guild.reddit.instances", messageArguments[0], messageArguments[1]]; - setRedditFromKey(message, messageArguments, messageArguments[1], false); + + //if instances doesnt exist, make it exist + // set reddti key + + if (messageArguments[1] === undefined) { + messageArguments[1] = "id" + message.channel.id; + } else { + messageArguments[1] = "id" + messageArguments[1]; + } + + if (getValueOfReddit(message, messageArguments, messageArguments[1], true) === undefined) { + var default_instance_object = { + "instances": [ + ] + }; + default_instance_object.instances.push({ [messageArguments[1]]: messageArguments[2] }); + default_instance_object = JSON.stringify(default_instance_object); + message.guild.settings.set("guild.reddit.instances", default_instance_object); + console.log("Default created!") + message.reply(`First Reddit instance made!`); + return; + } else { + setRedditFromKey(message, messageArguments, messageArguments[1], false); + console.log("new instance added") + return; + } //console.log(message.channel.id) gets the ID of current text channel const daily_time = 'at 08:00am'; @@ -223,6 +253,7 @@ function setRedditFromKey(message, messageArguments, channelID, edit) { const [redditKey, tempChannelID, newSetting] = messageArguments; channelID = tempChannelID; status_of_value = getValueOfReddit(message, messageArguments, channelID, true); + console.log(status_of_value) if (status_of_value === undefined && edit == true) { if (channelID === undefined) { channelID = "id" + message.channel.id; @@ -241,12 +272,15 @@ function setRedditFromKey(message, messageArguments, channelID, edit) { return; } else if (status_of_value === null) { console.log("ID not found") - return; + //return; } - if (channelID === undefined) { - channelID = "id" + message.channel.id; - } else { - channelID = "id" + channelID; + + if (channelID.search("id") == -1) { + if (channelID === undefined) { + channelID = "id" + message.channel.id; + } else { + channelID = "id" + channelID; + } } var redditValue = message.guild.settings.get(redditKey, null); @@ -279,12 +313,15 @@ function setRedditFromKey(message, messageArguments, channelID, edit) { } function getValueOfReddit(message, messageArguments, channelID, setting_default) { - if (channelID === undefined) { - channelID = "id" + message.channel.id; - } else { - channelID = "id" + channelID; + if (channelID.search("id") == -1) { + if (channelID === undefined) { + channelID = "id" + message.channel.id; + } else { + channelID = "id" + channelID; + } } var redditValue = message.guild.settings.get(messageArguments[0], null); + console.log(redditValue + "AAAAAAAAAAAAA") if (redditValue == null) { if (!setting_default) { message.reply(`${messageArguments[0]} was not found`); @@ -294,6 +331,8 @@ function getValueOfReddit(message, messageArguments, channelID, setting_default) } } redditValue = JSON.parse(redditValue) + console.log(redditValue) + console.log(channelID) for (key in redditValue.instances) { if (redditValue.instances[key][channelID] !== undefined) { //console.log("Matched!"); From 75833027d207c3ebaefe962b1c8b4491291295cb Mon Sep 17 00:00:00 2001 From: Carlos Date: Fri, 20 Sep 2019 19:31:13 -0400 Subject: [PATCH 30/63] Placing code for bot startup execution --- src/commands/admin/deployreddit.js | 25 ++++++++++++++++--------- 1 file changed, 16 insertions(+), 9 deletions(-) diff --git a/src/commands/admin/deployreddit.js b/src/commands/admin/deployreddit.js index d760b97..d285eae 100644 --- a/src/commands/admin/deployreddit.js +++ b/src/commands/admin/deployreddit.js @@ -176,22 +176,18 @@ class DeployReddit extends Commando.Command { default_instance_object.instances.push({ [messageArguments[1]]: messageArguments[2] }); default_instance_object = JSON.stringify(default_instance_object); message.guild.settings.set("guild.reddit.instances", default_instance_object); + initializeInstance(message, messageArguments); console.log("Default created!") message.reply(`First Reddit instance made!`); return; } else { setRedditFromKey(message, messageArguments, messageArguments[1], false); console.log("new instance added") - return; + initializeInstance(message, messageArguments); } - - //console.log(message.channel.id) gets the ID of current text channel - const daily_time = 'at 08:00am'; - const testing_time = 'every 10 seconds'; - var sched = later.parse.text(testing_time); - // time default is UTC | 4 hours ahead of FL - later.date.localTime(); - var interval_instance = later.setInterval(function () { query_reddit(message, messageArguments[1], interval_instance) }, sched); // interval_instance.clear() clears timer + //if flag set for startup, put variables in here. + initializeInstance(message, messageArguments); + return; }); } else { message.reply(`!!deployreddit \nAdds a reddit instance to a given channel.`); @@ -219,6 +215,17 @@ class DeployReddit extends Commando.Command { * */ +function initializeInstance(message, messageArguments) { + //console.log(message.channel.id) gets the ID of current text channel + const daily_time = 'at 08:00am'; + const testing_time = 'every 10 seconds'; + var sched = later.parse.text(testing_time); + // time default is UTC | 4 hours ahead of FL + later.date.localTime(); + query_reddit(message, messageArguments[2]); + //var interval_instance = later.setInterval(function () { query_reddit(message, messageArguments[2], interval_instance) }, sched); // interval_instance.clear() clears timer +} + function removeRedditFromKey(message, messageArguments, channelID) { var redditValue = message.guild.settings.get(messageArguments[0], null); if (redditValue == null) { From 1376ebdaa13caef46195de42aabc4a9741d1d77a Mon Sep 17 00:00:00 2001 From: Carlos Date: Sat, 21 Sep 2019 01:22:06 -0400 Subject: [PATCH 31/63] Working on start up function --- src/commands/admin/deployreddit.js | 20 ++++++++++++++++++-- src/main.js | 7 ++++--- 2 files changed, 22 insertions(+), 5 deletions(-) diff --git a/src/commands/admin/deployreddit.js b/src/commands/admin/deployreddit.js index d285eae..7ac31c0 100644 --- a/src/commands/admin/deployreddit.js +++ b/src/commands/admin/deployreddit.js @@ -186,7 +186,7 @@ class DeployReddit extends Commando.Command { initializeInstance(message, messageArguments); } //if flag set for startup, put variables in here. - initializeInstance(message, messageArguments); + //initializeInstance(message, messageArguments); return; }); } else { @@ -224,6 +224,22 @@ function initializeInstance(message, messageArguments) { later.date.localTime(); query_reddit(message, messageArguments[2]); //var interval_instance = later.setInterval(function () { query_reddit(message, messageArguments[2], interval_instance) }, sched); // interval_instance.clear() clears timer + + var redditValue = message.guild.settings.get(messageArguments[0], null); + redditValue = JSON.parse(redditValue) + for (var counter = 0; counter < redditValue.instances.length; counter++) { + for (x in redditValue.instances[counter]) { + /** + * + * Loop through all of the instances and instatiate them using the startup + * + * work normally otherwise + * + */ + console.log(x) + redditValue.instances[counter][x] // URL + } + } } function removeRedditFromKey(message, messageArguments, channelID) { @@ -365,7 +381,7 @@ function delete_instances(message) { console.log(message.guild.settings.remove('guild.reddit.instances', null)) } -async function query_reddit(message, redditURL, interval_instance) { +async function query_reddit(message, redditURL) { //console.log(redditURL) await request(redditURL, (error, response, html) => { if (!error && response.statusCode == 200) { diff --git a/src/main.js b/src/main.js index 9fef6fb..78adfad 100644 --- a/src/main.js +++ b/src/main.js @@ -6,8 +6,8 @@ const Commando = require('discord.js-commando'); const Logger = require('./logging/Logger'); // Import logger for tracking bot progress. const addDiscordChannelLogger = require('./logging/addDiscordChannelLogger'); -const {setupSettingsProvider} = require('./settings/SettingsProvider'); -const {listenForRoleAssignmentMessages} = require('./events/setUserRoleOnReaction'); +const { setupSettingsProvider } = require('./settings/SettingsProvider'); +const { listenForRoleAssignmentMessages } = require('./events/setUserRoleOnReaction'); const loadEvents = require('./util/eventLoader'); // Import methods responsible for creating roles in servers as necessary. @@ -30,7 +30,7 @@ const discordClient = new Commando.CommandoClient({ * When you want to wait for something that takes time to finish before moving on, you place the * 'await' keyword in front of it to have the function wait for that to finish before continuing. */ -discordClient.on('ready', async function() { +discordClient.on('ready', async function () { addDiscordChannelLogger(discordClient); Logger.debug('FSEC Role Bot logged in as ' + discordClient.user.tag + '!'); @@ -63,6 +63,7 @@ discordClient.on('ready', async function() { * will be created. */ createServerRoles(discordClient); + discordClient.channels.get("619024772898095115").send("HAHAHA!") }); discordClient.registry.registerGroups([ From afcc2b7019863c83e447c547c746adaa85530ed5 Mon Sep 17 00:00:00 2001 From: Carlos Date: Sat, 21 Sep 2019 15:00:58 -0400 Subject: [PATCH 32/63] Made separate file for start up --- src/commands/admin/deployreddit.js | 26 ++------- src/commands/admin/postreddit.js | 91 ++++++++++++++++++++++++++++++ src/main.js | 17 ++++++ 3 files changed, 113 insertions(+), 21 deletions(-) create mode 100644 src/commands/admin/postreddit.js diff --git a/src/commands/admin/deployreddit.js b/src/commands/admin/deployreddit.js index 7ac31c0..41551c4 100644 --- a/src/commands/admin/deployreddit.js +++ b/src/commands/admin/deployreddit.js @@ -215,31 +215,15 @@ class DeployReddit extends Commando.Command { * */ -function initializeInstance(message, messageArguments) { +function initializeInstance(message, messageArguments, discordClient) { //console.log(message.channel.id) gets the ID of current text channel const daily_time = 'at 08:00am'; const testing_time = 'every 10 seconds'; var sched = later.parse.text(testing_time); // time default is UTC | 4 hours ahead of FL later.date.localTime(); - query_reddit(message, messageArguments[2]); - //var interval_instance = later.setInterval(function () { query_reddit(message, messageArguments[2], interval_instance) }, sched); // interval_instance.clear() clears timer - - var redditValue = message.guild.settings.get(messageArguments[0], null); - redditValue = JSON.parse(redditValue) - for (var counter = 0; counter < redditValue.instances.length; counter++) { - for (x in redditValue.instances[counter]) { - /** - * - * Loop through all of the instances and instatiate them using the startup - * - * work normally otherwise - * - */ - console.log(x) - redditValue.instances[counter][x] // URL - } - } + query_reddit(message, messageArguments[2], null); + //var interval_instance = later.setInterval(function () { query_reddit(message, messageArguments[2], null) }, sched); // interval_instance.clear() clears timer } function removeRedditFromKey(message, messageArguments, channelID) { @@ -344,7 +328,7 @@ function getValueOfReddit(message, messageArguments, channelID, setting_default) } } var redditValue = message.guild.settings.get(messageArguments[0], null); - console.log(redditValue + "AAAAAAAAAAAAA") + console.log(redditValue) if (redditValue == null) { if (!setting_default) { message.reply(`${messageArguments[0]} was not found`); @@ -418,4 +402,4 @@ function linksToImage(link) { return false; } -module.exports = DeployReddit; +module.exports = DeployReddit; \ No newline at end of file diff --git a/src/commands/admin/postreddit.js b/src/commands/admin/postreddit.js new file mode 100644 index 0000000..851d530 --- /dev/null +++ b/src/commands/admin/postreddit.js @@ -0,0 +1,91 @@ +const Discord = require('discord.js'); +const Commando = require('discord.js-commando'); +const Logger = require('../../logging/Logger'); +const { redditKeys, redditNames } = require('../../settings/SettingsProvider'); +const request = require('request'); +var later = require('later'); + +class DeployReddit extends Commando.Command { + /** @param {Commando.CommandoClient} client */ + constructor(client) { + super(client, { + description: 'Deploys the top img in any subreddit every 24hrs', + guildOnly: true, + group: 'admin', + memberName: 'deployreddit', + }); + } +} + +function initializeInstance(message, messageArguments, discordClient) { + if (discordClient !== undefined) { + var redditValue = discordClient.guilds.get("619024772415881240").settings.get("guild.reddit.instances") + redditValue = JSON.parse(redditValue) + for (var counter = 0; counter < redditValue.instances.length; counter++) { + for (x in redditValue.instances[counter]) { + /** + * + * Loop through all of the instances and instatiate them using the startup + * + * work normally otherwise + * + */ + console.log(x) + redditValue.instances[counter][x] // URL + query_reddit(message, redditValue.instances[counter][x], discordClient, x); + } + } + } +} + +async function query_reddit(message, redditURL, discordClient, channelID) { + //console.log(redditURL) + await request(redditURL, (error, response, html) => { + if (!error && response.statusCode == 200) { + const json_data = JSON.parse(html); + for (var counter = 0; counter < json_data.data.dist; counter++) { + //console.log(json_data.data.children[counter].data.post_hint) + if (json_data.data.children[counter].data.post_hint == "image" || linksToImage(json_data.data.children[counter].data.url)) { + if (discordClient !== null) { + const message_to_embed = new Discord.RichEmbed().setImage('https://preview.redd.it/d3b8tswrbxn31.jpg?width=640&crop=smart&auto=webp&s=8133c0e5fae51db9bd9eaa583c1989a4d79e0ee7') + discordClient.channels.get("619024772898095115").send(message_to_embed).then(async function (reply) { + //console.log(reply.id) + reply.channel.fetchMessage(reply.id).then(async function (message_retrieved) { + await message_retrieved.react('👍'); + await message_retrieved.react('👎'); + }); + }); + return; + } else { + const message_to_embed = { + "image": { + "url": json_data.data.children[counter].data.url + } + }; + message.embed(message_to_embed).then(async function (reply) { + //console.log(reply.id) + reply.channel.fetchMessage(reply.id).then(async function (message_retrieved) { + await message_retrieved.react('👍'); + await message_retrieved.react('👎'); + }); + }); + return; + return; + } + } + } + } + }); + console.log(new Date()); +} + +function linksToImage(link) { + img_extensions = ['jpg', 'png', 'gif'] + //console.log(link.substr(link.length - 3)); + if (img_extensions.includes(link.substr(link.length - 3))) { + return true; + } + return false; +} + +module.exports = { initializeInstance: initializeInstance }; \ No newline at end of file diff --git a/src/main.js b/src/main.js index 78adfad..766594b 100644 --- a/src/main.js +++ b/src/main.js @@ -12,6 +12,7 @@ const loadEvents = require('./util/eventLoader'); // Import methods responsible for creating roles in servers as necessary. const createServerRoles = require('./events/createServerRoles').run; +const initializeInstance = require('./commands/admin/postreddit').initializeInstance; const discordClient = new Commando.CommandoClient({ owner: Settings.botOwners, @@ -63,7 +64,23 @@ discordClient.on('ready', async function () { * will be created. */ createServerRoles(discordClient); + //const message_to_embed = new Discord.RichEmbed().setImage('https://preview.redd.it/d3b8tswrbxn31.jpg?width=640&crop=smart&auto=webp&s=8133c0e5fae51db9bd9eaa583c1989a4d79e0ee7') + //message.embed(message_to_embed) + //discordClient.channels.get("619024772898095115") discordClient.channels.get("619024772898095115").send("HAHAHA!") + //DeployReddit.initializeInstance(null, null, discordClient) + //.get("guild.reddit.instances", null); + var redditValue = discordClient + //var redditValue = message.guild.settings.get(messageArguments[0], null); + //console.log(discordClient.guilds.get("619024772415881240").settings.get("guild.reddit.instances")) + initializeInstance(null, null, discordClient) + // discordClient.channels.get("619024772898095115").send(message_to_embed).then(async function (reply) { + // //console.log(reply.id) + // reply.channel.fetchMessage(reply.id).then(async function (message_retrieved) { + // await message_retrieved.react('👍'); + // await message_retrieved.react('👎'); + // }); + // }); }); discordClient.registry.registerGroups([ From cfe979305f6baf4cdf1bb264f79044669b1b3fba Mon Sep 17 00:00:00 2001 From: Carlos Date: Sat, 21 Sep 2019 16:53:30 -0400 Subject: [PATCH 33/63] Functional Start Up instantiation --- src/commands/admin/postreddit.js | 49 +++++++++++--------------------- 1 file changed, 16 insertions(+), 33 deletions(-) diff --git a/src/commands/admin/postreddit.js b/src/commands/admin/postreddit.js index 851d530..69b70ba 100644 --- a/src/commands/admin/postreddit.js +++ b/src/commands/admin/postreddit.js @@ -1,44 +1,42 @@ const Discord = require('discord.js'); const Commando = require('discord.js-commando'); const Logger = require('../../logging/Logger'); -const { redditKeys, redditNames } = require('../../settings/SettingsProvider'); const request = require('request'); var later = require('later'); -class DeployReddit extends Commando.Command { +class PostReddit extends Commando.Command { /** @param {Commando.CommandoClient} client */ constructor(client) { super(client, { - description: 'Deploys the top img in any subreddit every 24hrs', + description: 'Deploys the top img in any subreddit on startup', guildOnly: true, group: 'admin', - memberName: 'deployreddit', }); } } -function initializeInstance(message, messageArguments, discordClient) { +async function initializeInstance(message, messageArguments, discordClient) { if (discordClient !== undefined) { - var redditValue = discordClient.guilds.get("619024772415881240").settings.get("guild.reddit.instances") - redditValue = JSON.parse(redditValue) + const daily_time = 'at 08:00am'; + const testing_time = 'every 20 seconds'; + var sched = later.parse.text(daily_time); + // time default is UTC | 4 hours ahead of FL + later.date.localTime(); + var redditValue = await discordClient.guilds.get("619024772415881240").settings.get("guild.reddit.instances") + redditValue = await JSON.parse(redditValue) for (var counter = 0; counter < redditValue.instances.length; counter++) { for (x in redditValue.instances[counter]) { - /** - * - * Loop through all of the instances and instatiate them using the startup - * - * work normally otherwise - * - */ - console.log(x) - redditValue.instances[counter][x] // URL - query_reddit(message, redditValue.instances[counter][x], discordClient, x); + channelID = x; + redditURL = redditValue.instances[counter][x]; + await query_reddit(redditValue.instances[counter][x], discordClient, x); + await later.setInterval(function () { query_reddit(redditURL, discordClient, channelID) }, sched); + console.log(1) } } } } -async function query_reddit(message, redditURL, discordClient, channelID) { +async function query_reddit(redditURL, discordClient, channelID) { //console.log(redditURL) await request(redditURL, (error, response, html) => { if (!error && response.statusCode == 200) { @@ -56,21 +54,6 @@ async function query_reddit(message, redditURL, discordClient, channelID) { }); }); return; - } else { - const message_to_embed = { - "image": { - "url": json_data.data.children[counter].data.url - } - }; - message.embed(message_to_embed).then(async function (reply) { - //console.log(reply.id) - reply.channel.fetchMessage(reply.id).then(async function (message_retrieved) { - await message_retrieved.react('👍'); - await message_retrieved.react('👎'); - }); - }); - return; - return; } } } From 402b32adf39b200a7c7bac33fb8374a5bb7c4b24 Mon Sep 17 00:00:00 2001 From: Carlos Date: Sat, 21 Sep 2019 17:28:38 -0400 Subject: [PATCH 34/63] Startup now takes saved images --- src/commands/admin/postreddit.js | 18 ++++++++---------- src/main.js | 3 ++- 2 files changed, 10 insertions(+), 11 deletions(-) diff --git a/src/commands/admin/postreddit.js b/src/commands/admin/postreddit.js index 69b70ba..8929cda 100644 --- a/src/commands/admin/postreddit.js +++ b/src/commands/admin/postreddit.js @@ -15,37 +15,35 @@ class PostReddit extends Commando.Command { } } -async function initializeInstance(message, messageArguments, discordClient) { +async function initializeInstance(discordClient) { if (discordClient !== undefined) { const daily_time = 'at 08:00am'; const testing_time = 'every 20 seconds'; - var sched = later.parse.text(daily_time); - // time default is UTC | 4 hours ahead of FL - later.date.localTime(); - var redditValue = await discordClient.guilds.get("619024772415881240").settings.get("guild.reddit.instances") + var sched = later.parse.text(testing_time); + later.date.localTime(); // time default is UTC | 4 hours ahead of FL + var guild = discordClient.guilds.keyArray()[0]; + var redditValue = await discordClient.guilds.get(guild).settings.get("guild.reddit.instances") redditValue = await JSON.parse(redditValue) for (var counter = 0; counter < redditValue.instances.length; counter++) { for (x in redditValue.instances[counter]) { channelID = x; redditURL = redditValue.instances[counter][x]; await query_reddit(redditValue.instances[counter][x], discordClient, x); - await later.setInterval(function () { query_reddit(redditURL, discordClient, channelID) }, sched); - console.log(1) + //await later.setInterval(function () { query_reddit(redditURL, discordClient, channelID) }, sched); } } } } async function query_reddit(redditURL, discordClient, channelID) { - //console.log(redditURL) await request(redditURL, (error, response, html) => { if (!error && response.statusCode == 200) { const json_data = JSON.parse(html); for (var counter = 0; counter < json_data.data.dist; counter++) { - //console.log(json_data.data.children[counter].data.post_hint) if (json_data.data.children[counter].data.post_hint == "image" || linksToImage(json_data.data.children[counter].data.url)) { if (discordClient !== null) { - const message_to_embed = new Discord.RichEmbed().setImage('https://preview.redd.it/d3b8tswrbxn31.jpg?width=640&crop=smart&auto=webp&s=8133c0e5fae51db9bd9eaa583c1989a4d79e0ee7') + console.log(redditURL) + const message_to_embed = new Discord.RichEmbed().setImage(json_data.data.children[counter].data.url) discordClient.channels.get("619024772898095115").send(message_to_embed).then(async function (reply) { //console.log(reply.id) reply.channel.fetchMessage(reply.id).then(async function (message_retrieved) { diff --git a/src/main.js b/src/main.js index 766594b..0b780b9 100644 --- a/src/main.js +++ b/src/main.js @@ -73,7 +73,8 @@ discordClient.on('ready', async function () { var redditValue = discordClient //var redditValue = message.guild.settings.get(messageArguments[0], null); //console.log(discordClient.guilds.get("619024772415881240").settings.get("guild.reddit.instances")) - initializeInstance(null, null, discordClient) + //discordClient.guilds.keyArray + initializeInstance(discordClient) // discordClient.channels.get("619024772898095115").send(message_to_embed).then(async function (reply) { // //console.log(reply.id) // reply.channel.fetchMessage(reply.id).then(async function (message_retrieved) { From fa96becaf62c17741bc83bcabd8b58619c2650fa Mon Sep 17 00:00:00 2001 From: Carlos Date: Sat, 21 Sep 2019 18:22:57 -0400 Subject: [PATCH 35/63] Can no longer edit reddit link without "--edit" --- src/commands/admin/deployreddit.js | 38 +++++++++++++++++------------- 1 file changed, 21 insertions(+), 17 deletions(-) diff --git a/src/commands/admin/deployreddit.js b/src/commands/admin/deployreddit.js index 41551c4..58bc9ac 100644 --- a/src/commands/admin/deployreddit.js +++ b/src/commands/admin/deployreddit.js @@ -159,8 +159,6 @@ class DeployReddit extends Commando.Command { messageArguments = ["guild.reddit.instances", messageArguments[0], messageArguments[1]]; - //if instances doesnt exist, make it exist - // set reddti key if (messageArguments[1] === undefined) { messageArguments[1] = "id" + message.channel.id; @@ -168,6 +166,13 @@ class DeployReddit extends Commando.Command { messageArguments[1] = "id" + messageArguments[1]; } + let key_value_exits = getValueOfReddit(message, messageArguments, messageArguments[1], true) === null ? false : true; + console.log(key_value_exits) + if (key_value_exits) { + message.reply(`${messageArguments[1]} was already found\nTry using "--edit"`); + return; + } + if (getValueOfReddit(message, messageArguments, messageArguments[1], true) === undefined) { var default_instance_object = { "instances": [ @@ -215,15 +220,15 @@ class DeployReddit extends Commando.Command { * */ -function initializeInstance(message, messageArguments, discordClient) { +function initializeInstance(message, messageArguments) { //console.log(message.channel.id) gets the ID of current text channel const daily_time = 'at 08:00am'; - const testing_time = 'every 10 seconds'; + const testing_time = 'every 20 seconds'; + const redditURL = messageArguments[2]; var sched = later.parse.text(testing_time); - // time default is UTC | 4 hours ahead of FL - later.date.localTime(); - query_reddit(message, messageArguments[2], null); - //var interval_instance = later.setInterval(function () { query_reddit(message, messageArguments[2], null) }, sched); // interval_instance.clear() clears timer + later.date.localTime(); // time default is UTC | 4 hours ahead of FL + //query_reddit(message, redditURL); + //later.setInterval(function () { query_reddit(message, redditURL); }, sched); / / interval_instance.clear() clears timer } function removeRedditFromKey(message, messageArguments, channelID) { @@ -309,9 +314,9 @@ function setRedditFromKey(message, messageArguments, channelID, edit) { // Adding a new ID and value var redditValue = message.guild.settings.get(redditKey, null); redditValue = JSON.parse(redditValue) - console.log("testing testing") + //console.log("testing testing") redditValue.instances.push({ [channelID]: newSetting }); - console.log(JSON.stringify(redditValue)) + //console.log(JSON.stringify(redditValue)) redditValue = JSON.stringify(redditValue); message.guild.settings.set(redditKey, redditValue); @@ -328,7 +333,7 @@ function getValueOfReddit(message, messageArguments, channelID, setting_default) } } var redditValue = message.guild.settings.get(messageArguments[0], null); - console.log(redditValue) + //console.log(redditValue) if (redditValue == null) { if (!setting_default) { message.reply(`${messageArguments[0]} was not found`); @@ -338,8 +343,8 @@ function getValueOfReddit(message, messageArguments, channelID, setting_default) } } redditValue = JSON.parse(redditValue) - console.log(redditValue) - console.log(channelID) + //console.log(redditValue) + //console.log(channelID) for (key in redditValue.instances) { if (redditValue.instances[key][channelID] !== undefined) { //console.log("Matched!"); @@ -348,7 +353,9 @@ function getValueOfReddit(message, messageArguments, channelID, setting_default) } } - if (typeof redditValue !== 'string') { + if (typeof redditValue !== 'string' && setting_default == true) { + return null; + } else if (typeof redditValue !== 'string') { message.reply(`The given ID for ${messageArguments[0]} was not found`); return null; } else { @@ -366,12 +373,10 @@ function delete_instances(message) { } async function query_reddit(message, redditURL) { - //console.log(redditURL) await request(redditURL, (error, response, html) => { if (!error && response.statusCode == 200) { const json_data = JSON.parse(html); for (var counter = 0; counter < json_data.data.dist; counter++) { - //console.log(json_data.data.children[counter].data.post_hint) if (json_data.data.children[counter].data.post_hint == "image" || linksToImage(json_data.data.children[counter].data.url)) { const message_to_embed = { "image": { @@ -379,7 +384,6 @@ async function query_reddit(message, redditURL) { } }; message.embed(message_to_embed).then(async function (reply) { - //console.log(reply.id) reply.channel.fetchMessage(reply.id).then(async function (message_retrieved) { await message_retrieved.react('👍'); await message_retrieved.react('👎'); From 1dbb3eeca6f590bba0758a28bdb0f091076956ec Mon Sep 17 00:00:00 2001 From: Carlos Date: Sat, 21 Sep 2019 19:08:57 -0400 Subject: [PATCH 36/63] Testing --- src/commands/admin/deployreddit.js | 19 ++++++++++++------- 1 file changed, 12 insertions(+), 7 deletions(-) diff --git a/src/commands/admin/deployreddit.js b/src/commands/admin/deployreddit.js index 58bc9ac..710a789 100644 --- a/src/commands/admin/deployreddit.js +++ b/src/commands/admin/deployreddit.js @@ -166,11 +166,15 @@ class DeployReddit extends Commando.Command { messageArguments[1] = "id" + messageArguments[1]; } - let key_value_exits = getValueOfReddit(message, messageArguments, messageArguments[1], true) === null ? false : true; - console.log(key_value_exits) - if (key_value_exits) { - message.reply(`${messageArguments[1]} was already found\nTry using "--edit"`); - return; + //checks whether the given channelID already exists + var key_value_exits = message.guild.settings.get(messageArguments[0], null); + key_value_exits = JSON.parse(key_value_exits) + for (var z in key_value_exits.instances) { + console.log(z) + if (key_value_exits.instances[z][messageArguments[1]] !== undefined) { + message.reply(`${messageArguments[1]} was already found\nTry using "--edit"`); + return; + } } if (getValueOfReddit(message, messageArguments, messageArguments[1], true) === undefined) { @@ -353,12 +357,13 @@ function getValueOfReddit(message, messageArguments, channelID, setting_default) } } - if (typeof redditValue !== 'string' && setting_default == true) { + if (typeof redditValue !== 'string' && setting_default) { return null; } else if (typeof redditValue !== 'string') { message.reply(`The given ID for ${messageArguments[0]} was not found`); return null; - } else { + } + else { if (setting_default != true) { message.reply(`Value for ${channelID} is ${redditValue}`); return redditValue; From 202e182b69890e5b8b914b0cfa3495cae15e7896 Mon Sep 17 00:00:00 2001 From: Carlos Date: Sat, 21 Sep 2019 19:14:33 -0400 Subject: [PATCH 37/63] Passed test cases, need to clean --- src/commands/admin/deployreddit.js | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/src/commands/admin/deployreddit.js b/src/commands/admin/deployreddit.js index 710a789..55f296c 100644 --- a/src/commands/admin/deployreddit.js +++ b/src/commands/admin/deployreddit.js @@ -169,11 +169,13 @@ class DeployReddit extends Commando.Command { //checks whether the given channelID already exists var key_value_exits = message.guild.settings.get(messageArguments[0], null); key_value_exits = JSON.parse(key_value_exits) - for (var z in key_value_exits.instances) { - console.log(z) - if (key_value_exits.instances[z][messageArguments[1]] !== undefined) { - message.reply(`${messageArguments[1]} was already found\nTry using "--edit"`); - return; + if (key_value_exits !== null) { + for (var z in key_value_exits.instances) { + console.log(z) + if (key_value_exits.instances[z][messageArguments[1]] !== undefined) { + message.reply(`${messageArguments[1]} was already found\nTry using "--edit"`); + return; + } } } From bf61dcc3f1c0f2efddcca02aabb6c584a868bfa2 Mon Sep 17 00:00:00 2001 From: Carlos Date: Sun, 22 Sep 2019 14:02:14 -0400 Subject: [PATCH 38/63] Cleaning up delete_reddit_instance --- src/commands/admin/deployreddit.js | 109 ++++++++--------------------- 1 file changed, 29 insertions(+), 80 deletions(-) diff --git a/src/commands/admin/deployreddit.js b/src/commands/admin/deployreddit.js index 55f296c..e67226b 100644 --- a/src/commands/admin/deployreddit.js +++ b/src/commands/admin/deployreddit.js @@ -6,7 +6,6 @@ const request = require('request'); var later = require('later'); class DeployReddit extends Commando.Command { - /** @param {Commando.CommandoClient} client */ constructor(client) { super(client, { name: 'deployreddit', @@ -17,24 +16,6 @@ class DeployReddit extends Commando.Command { }); } - /** - * TO-DO - * Example Args - * !!deployreddit --stop - * stops execution - * !!deployreddit --edit - * here's how you can edit: - * !!deployreddit --edit https:newlink - * Link updated - * !!deployreddit --status - * gives current link, and iteration time - * - * if (!!deployreddit http:link) when an instance is already deployed - * send message to try using --stop or --edit - * - * upon bot reset, if instance was active when shutdown, relauch this instance - */ - async run(message, args) { var messageArguments = args.split(' '); @@ -42,8 +23,7 @@ class DeployReddit extends Commando.Command { case '--stop': messageArguments[0] = "guild.reddit.instances" if (messageArguments.length == 2) { - // removes channel key and reddit URL from db - removeRedditFromKey(message, messageArguments, messageArguments[1]); + delete_reddit_instance(message, messageArguments, messageArguments[1]); } else { message.reply(`!!deployreddit --stop \nStops the execution of the reddit deployment in the specified channel.`); } @@ -68,8 +48,6 @@ class DeployReddit extends Commando.Command { messageArguments[2] += "/.json" break; } - console.log(messageArguments[2]) - // catching broken link errors var error_given; @@ -91,8 +69,6 @@ class DeployReddit extends Commando.Command { return; } - console.log(messageArguments) - console.log("aa333aa") setRedditFromKey(message, messageArguments, messageArguments[1], true); }); @@ -134,7 +110,6 @@ class DeployReddit extends Commando.Command { messageArguments[1] += "/.json" break; } - console.log(messageArguments[1]) // catching broken link errors @@ -171,9 +146,8 @@ class DeployReddit extends Commando.Command { key_value_exits = JSON.parse(key_value_exits) if (key_value_exits !== null) { for (var z in key_value_exits.instances) { - console.log(z) if (key_value_exits.instances[z][messageArguments[1]] !== undefined) { - message.reply(`${messageArguments[1]} was already found\nTry using "--edit"`); + message.reply(`${messageArguments[1]} was already found\nTry using "--edit" or "--stop`); return; } } @@ -188,16 +162,13 @@ class DeployReddit extends Commando.Command { default_instance_object = JSON.stringify(default_instance_object); message.guild.settings.set("guild.reddit.instances", default_instance_object); initializeInstance(message, messageArguments); - console.log("Default created!") message.reply(`First Reddit instance made!`); return; } else { setRedditFromKey(message, messageArguments, messageArguments[1], false); - console.log("new instance added") initializeInstance(message, messageArguments); + console.log(`${messageArguments[1]} : ${messageArguments[2]} has been added to Reddit instances.`) } - //if flag set for startup, put variables in here. - //initializeInstance(message, messageArguments); return; }); } else { @@ -208,26 +179,7 @@ class DeployReddit extends Commando.Command { } } -/** - * - * ANY NEW SETTINGS NEED TO BE ADDED TO "SettingsProvider" - * - * - * Method to alter guild.reddit.instance - array = [["a","b","c"],["d","e","f"],["g","h","i"]] - console.log(array) - for (element in array) { - if(array[element][0] == "d") { - array.splice(element,1) - } - } - console.log(array) - * - * - */ - function initializeInstance(message, messageArguments) { - //console.log(message.channel.id) gets the ID of current text channel const daily_time = 'at 08:00am'; const testing_time = 'every 20 seconds'; const redditURL = messageArguments[2]; @@ -237,41 +189,47 @@ function initializeInstance(message, messageArguments) { //later.setInterval(function () { query_reddit(message, redditURL); }, sched); / / interval_instance.clear() clears timer } -function removeRedditFromKey(message, messageArguments, channelID) { - var redditValue = message.guild.settings.get(messageArguments[0], null); - if (redditValue == null) { - message.reply(`${messageArguments[0]} was not found`); +function delete_reddit_instance(message, messageArguments) { + const INSTANCE_KEY = messageArguments[0]; + const CHANNEL_ID = refactor_id(message, messageArguments[1]); + + var instances = message.guild.settings.get(INSTANCE_KEY, null); + if (instances == null) { + message.reply(`${INSTANCE_KEY} was not found`); return undefined; } - if (channelID === undefined) { - channelID = "id" + message.channel.id; - } else { - channelID = "id" + channelID; - } - redditValue = JSON.parse(redditValue) - console.log(redditValue.instances) - for (key in redditValue.instances) { - if (redditValue.instances[key][channelID] !== undefined) { - redditValue.instances.splice(key, 1); - redditValue = JSON.stringify(redditValue); - if (typeof redditValue === 'string') { - message.guild.settings.set(messageArguments[0], redditValue); - message.reply(`${channelID} was removed from this guild`); + + instances = JSON.parse(instances) + for (key in instances.instances) { + if (instances.instances[key][CHANNEL_ID] !== undefined) { + instances.instances.splice(key, 1); + const new_instances = JSON.stringify(instances); + if (typeof new_instances === 'string') { + message.guild.settings.set(INSTANCE_KEY, new_instances); + message.reply(`${CHANNEL_ID} was removed from this guild`); return; } break; } } - message.reply(`${channelID} was not found`); + message.reply(`${channel_id} was not found`); return undefined; } +const refactor_id = (message, channel_id) => { + if (channel_id === undefined) { + channel_id = "id" + message.channel.id; + } else { + channel_id = "id" + channel_id; + } + return channel_id; +} + function setRedditFromKey(message, messageArguments, channelID, edit) { const [redditKey, tempChannelID, newSetting] = messageArguments; channelID = tempChannelID; status_of_value = getValueOfReddit(message, messageArguments, channelID, true); - console.log(status_of_value) if (status_of_value === undefined && edit == true) { if (channelID === undefined) { channelID = "id" + message.channel.id; @@ -290,7 +248,6 @@ function setRedditFromKey(message, messageArguments, channelID, edit) { return; } else if (status_of_value === null) { console.log("ID not found") - //return; } if (channelID.search("id") == -1) { @@ -305,7 +262,6 @@ function setRedditFromKey(message, messageArguments, channelID, edit) { redditValue = JSON.parse(redditValue) for (key in redditValue.instances) { if (redditValue.instances[key][channelID] !== undefined) { - //console.log("Matched!"); redditValue.instances[key][channelID] = newSetting; redditValue = JSON.stringify(redditValue); if (typeof redditValue === 'string') { @@ -320,9 +276,7 @@ function setRedditFromKey(message, messageArguments, channelID, edit) { // Adding a new ID and value var redditValue = message.guild.settings.get(redditKey, null); redditValue = JSON.parse(redditValue) - //console.log("testing testing") redditValue.instances.push({ [channelID]: newSetting }); - //console.log(JSON.stringify(redditValue)) redditValue = JSON.stringify(redditValue); message.guild.settings.set(redditKey, redditValue); @@ -339,7 +293,6 @@ function getValueOfReddit(message, messageArguments, channelID, setting_default) } } var redditValue = message.guild.settings.get(messageArguments[0], null); - //console.log(redditValue) if (redditValue == null) { if (!setting_default) { message.reply(`${messageArguments[0]} was not found`); @@ -349,11 +302,8 @@ function getValueOfReddit(message, messageArguments, channelID, setting_default) } } redditValue = JSON.parse(redditValue) - //console.log(redditValue) - //console.log(channelID) for (key in redditValue.instances) { if (redditValue.instances[key][channelID] !== undefined) { - //console.log("Matched!"); redditValue = redditValue.instances[key][channelID]; break; } @@ -406,7 +356,6 @@ async function query_reddit(message, redditURL) { function linksToImage(link) { img_extensions = ['jpg', 'png', 'gif'] - //console.log(link.substr(link.length - 3)); if (img_extensions.includes(link.substr(link.length - 3))) { return true; } From ff35bc2071ad6b08f9119a2e2b4d43aa68fa9ab2 Mon Sep 17 00:00:00 2001 From: Carlos Date: Sun, 22 Sep 2019 14:26:40 -0400 Subject: [PATCH 39/63] delete_reddit_instance cleaned up --- src/commands/admin/deployreddit.js | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/src/commands/admin/deployreddit.js b/src/commands/admin/deployreddit.js index e67226b..dca8f3b 100644 --- a/src/commands/admin/deployreddit.js +++ b/src/commands/admin/deployreddit.js @@ -194,26 +194,27 @@ function delete_reddit_instance(message, messageArguments) { const CHANNEL_ID = refactor_id(message, messageArguments[1]); var instances = message.guild.settings.get(INSTANCE_KEY, null); + if (instances == null) { - message.reply(`${INSTANCE_KEY} was not found`); + message.reply(`${INSTANCE_KEY} was not found.\nTry creating a new instance using "!!deployreddit "`); return undefined; } instances = JSON.parse(instances) - for (key in instances.instances) { - if (instances.instances[key][CHANNEL_ID] !== undefined) { - instances.instances.splice(key, 1); + for (index in instances.instances) { + if (instances.instances[index][CHANNEL_ID] !== undefined) { + instances.instances.splice(index, 1); const new_instances = JSON.stringify(instances); if (typeof new_instances === 'string') { message.guild.settings.set(INSTANCE_KEY, new_instances); - message.reply(`${CHANNEL_ID} was removed from this guild`); + message.reply(`${CHANNEL_ID} was removed from this guild.`); return; } break; } } - message.reply(`${channel_id} was not found`); + message.reply(`${CHANNEL_ID} was not in instances.`); return undefined; } From 0f15e5374a2f5838ea223b98e1704cb0beea0ef7 Mon Sep 17 00:00:00 2001 From: Carlos Date: Sun, 22 Sep 2019 14:49:38 -0400 Subject: [PATCH 40/63] cleaning up query_reddit --- src/commands/admin/deployreddit.js | 48 +++++++++++++++++------------- src/commands/admin/postreddit.js | 44 ++++++++++++++------------- 2 files changed, 51 insertions(+), 41 deletions(-) diff --git a/src/commands/admin/deployreddit.js b/src/commands/admin/deployreddit.js index dca8f3b..dddce9c 100644 --- a/src/commands/admin/deployreddit.js +++ b/src/commands/admin/deployreddit.js @@ -87,7 +87,7 @@ class DeployReddit extends Commando.Command { } return; case '--removeall': - delete_instances(message); + delete_all_instances(message); let redditValue = message.guild.settings.get("guild.reddit.instances", null); console.log(redditValue); return; @@ -218,15 +218,6 @@ function delete_reddit_instance(message, messageArguments) { return undefined; } -const refactor_id = (message, channel_id) => { - if (channel_id === undefined) { - channel_id = "id" + message.channel.id; - } else { - channel_id = "id" + channel_id; - } - return channel_id; -} - function setRedditFromKey(message, messageArguments, channelID, edit) { const [redditKey, tempChannelID, newSetting] = messageArguments; channelID = tempChannelID; @@ -326,22 +317,25 @@ function getValueOfReddit(message, messageArguments, channelID, setting_default) } } -function delete_instances(message) { - console.log(message.guild.settings.remove('guild.reddit.instances', null)) +function delete_all_instances(message) { + message.guild.settings.remove('guild.reddit.instances', null); + console.log("All instances deleted.") } async function query_reddit(message, redditURL) { await request(redditURL, (error, response, html) => { if (!error && response.statusCode == 200) { + const json_data = JSON.parse(html); - for (var counter = 0; counter < json_data.data.dist; counter++) { - if (json_data.data.children[counter].data.post_hint == "image" || linksToImage(json_data.data.children[counter].data.url)) { - const message_to_embed = { + for (var index = 0; index < json_data.data.dist; index++) { + + if (json_data.data.children[index].data.post_hint == "image" || links_to_image(json_data.data.children[index].data.url)) { + const image_to_embed = { "image": { - "url": json_data.data.children[counter].data.url + "url": json_data.data.children[index].data.url } }; - message.embed(message_to_embed).then(async function (reply) { + message.embed(image_to_embed).then(async function (reply) { reply.channel.fetchMessage(reply.id).then(async function (message_retrieved) { await message_retrieved.react('👍'); await message_retrieved.react('👎'); @@ -349,18 +343,30 @@ async function query_reddit(message, redditURL) { }); return; } + } + } }); - console.log(new Date()); + console.log("Reddit post made:", new Date()); } -function linksToImage(link) { - img_extensions = ['jpg', 'png', 'gif'] - if (img_extensions.includes(link.substr(link.length - 3))) { +const links_to_image = (link) => { + const IMG_EXTENSIONS = ['jpg', 'png', 'gif'] + const link_extension = link.substr(link.length - 3); + if (IMG_EXTENSIONS.includes(link_extension)) { return true; } return false; } +const refactor_id = (message, channel_id) => { + if (channel_id === undefined) { + channel_id = "id" + message.channel.id; + } else { + channel_id = "id" + channel_id; + } + return channel_id; +} + module.exports = DeployReddit; \ No newline at end of file diff --git a/src/commands/admin/postreddit.js b/src/commands/admin/postreddit.js index 8929cda..737fbfc 100644 --- a/src/commands/admin/postreddit.js +++ b/src/commands/admin/postreddit.js @@ -17,35 +17,37 @@ class PostReddit extends Commando.Command { async function initializeInstance(discordClient) { if (discordClient !== undefined) { - const daily_time = 'at 08:00am'; - const testing_time = 'every 20 seconds'; - var sched = later.parse.text(testing_time); + const DAILY_POST_TIME = 'at 08:00am'; + const TESTING_POST_TIME = 'every 20 seconds'; + var sched = later.parse.text(TESTING_POST_TIME); + later.date.localTime(); // time default is UTC | 4 hours ahead of FL + var guild = discordClient.guilds.keyArray()[0]; var redditValue = await discordClient.guilds.get(guild).settings.get("guild.reddit.instances") redditValue = await JSON.parse(redditValue) - for (var counter = 0; counter < redditValue.instances.length; counter++) { - for (x in redditValue.instances[counter]) { - channelID = x; - redditURL = redditValue.instances[counter][x]; - await query_reddit(redditValue.instances[counter][x], discordClient, x); - //await later.setInterval(function () { query_reddit(redditURL, discordClient, channelID) }, sched); + for (var index = 0; index < redditValue.instances.length; index++) { + for (x in redditValue.instances[index]) { + var channel_id = x; + var redditURL = redditValue.instances[index][x]; + await query_reddit(redditURL, discordClient, x); + //await later.setInterval(function () { query_reddit(redditURL, discordClient, channel_id) }, sched); } } } } -async function query_reddit(redditURL, discordClient, channelID) { +async function query_reddit(redditURL, discordClient, channel_id) { await request(redditURL, (error, response, html) => { if (!error && response.statusCode == 200) { + const json_data = JSON.parse(html); - for (var counter = 0; counter < json_data.data.dist; counter++) { - if (json_data.data.children[counter].data.post_hint == "image" || linksToImage(json_data.data.children[counter].data.url)) { + for (var index = 0; index < json_data.data.dist; index++) { + + if (json_data.data.children[index].data.post_hint == "image" || links_to_image(json_data.data.children[index].data.url)) { if (discordClient !== null) { - console.log(redditURL) - const message_to_embed = new Discord.RichEmbed().setImage(json_data.data.children[counter].data.url) + const message_to_embed = new Discord.RichEmbed().setImage(json_data.data.children[index].data.url) discordClient.channels.get("619024772898095115").send(message_to_embed).then(async function (reply) { - //console.log(reply.id) reply.channel.fetchMessage(reply.id).then(async function (message_retrieved) { await message_retrieved.react('👍'); await message_retrieved.react('👎'); @@ -54,16 +56,18 @@ async function query_reddit(redditURL, discordClient, channelID) { return; } } + } } + }); - console.log(new Date()); + console.log("Reddit post made:", new Date()); } -function linksToImage(link) { - img_extensions = ['jpg', 'png', 'gif'] - //console.log(link.substr(link.length - 3)); - if (img_extensions.includes(link.substr(link.length - 3))) { +const links_to_image = (link) => { + const IMG_EXTENSIONS = ['jpg', 'png', 'gif'] + const link_extension = link.substr(link.length - 3); + if (IMG_EXTENSIONS.includes(link_extension)) { return true; } return false; From 7e2275d0f3c4f9447c32179d8f2cf305c6b33c54 Mon Sep 17 00:00:00 2001 From: Carlos Date: Sun, 22 Sep 2019 15:26:28 -0400 Subject: [PATCH 41/63] Making functions to clean code --- src/commands/admin/deployreddit.js | 86 ++++++++++++++++-------------- src/commands/admin/postreddit.js | 2 +- 2 files changed, 48 insertions(+), 40 deletions(-) diff --git a/src/commands/admin/deployreddit.js b/src/commands/admin/deployreddit.js index dddce9c..aad8405 100644 --- a/src/commands/admin/deployreddit.js +++ b/src/commands/admin/deployreddit.js @@ -31,47 +31,11 @@ class DeployReddit extends Commando.Command { case '--edit': messageArguments[0] = "guild.reddit.instances" if (messageArguments.length == 3) { - // appending the argument of "r/...." to make a URL - if (messageArguments[2].search("reddit.com/") == -1) { - if (messageArguments[2].search("/") == 0) { - messageArguments[2] = "https://www.reddit.com" + messageArguments[2]; - } else { - messageArguments[2] = "https://www.reddit.com/" + messageArguments[2]; - } - } - const last_char_of_URL = messageArguments[2].charAt(messageArguments[2].length - 1); - switch (last_char_of_URL) { - case '/': - messageArguments[2] += ".json" - break; - default: - messageArguments[2] += "/.json" - break; - } - // catching broken link errors - var error_given; - await request(messageArguments[2], async (error, response, html) => { - var json_data; - try { - json_data = await JSON.parse(html) - } catch (e) { - message.say("Sorry, this link did not work."); - return; - } - error_given = json_data.error == '404' ? true : false; + let link = refactor_link(messageArguments[2]); + messageArguments[2] = link; + if (validated_link(link)) setRedditFromKey(message, messageArguments, messageArguments[1], true); - if (error) { - message.say("Sorry, this link did not work."); - return; - } else if (error_given == true) { - message.say("Sorry, this link did not work."); - return; - } - - setRedditFromKey(message, messageArguments, messageArguments[1], true); - - }); } else { message.reply(`!!deployreddit --edit \nChanges the given URL of a channel.`); } @@ -179,6 +143,50 @@ class DeployReddit extends Commando.Command { } } +const refactor_link = (link) => { + // appending the argument of "r/...." to make a URL + if (link.search("reddit.com/") == -1) { + if (link.search("/") == 0) { + link = "https://www.reddit.com" + link; + } else { + link = "https://www.reddit.com/" + link; + } + } + const last_char_of_URL = link.charAt(link.length - 1); + switch (last_char_of_URL) { + case '/': + link += ".json" + break; + default: + link += "/.json" + break; + } + return link; +} + +const validated_link = async (link) => { + var error_given; + await request(link, async (error, response, html) => { + var json_data; + try { + json_data = await JSON.parse(html) + } catch (e) { + message.say("Sorry, this link did not work."); + return false; + } + error_given = json_data.error == '404' ? true : false; + + if (error) { + message.say("Sorry, this link did not work."); + return false; + } else if (error_given == true) { + message.say("Sorry, this link did not work."); + return false; + } + }); + return true; +} + function initializeInstance(message, messageArguments) { const daily_time = 'at 08:00am'; const testing_time = 'every 20 seconds'; diff --git a/src/commands/admin/postreddit.js b/src/commands/admin/postreddit.js index 737fbfc..b5eb849 100644 --- a/src/commands/admin/postreddit.js +++ b/src/commands/admin/postreddit.js @@ -8,7 +8,7 @@ class PostReddit extends Commando.Command { /** @param {Commando.CommandoClient} client */ constructor(client) { super(client, { - description: 'Deploys the top img in any subreddit on startup', + description: 'Deploys the top img in any subreddit on bot startup', guildOnly: true, group: 'admin', }); From fb6cf874fd92cc1152df8f6b5eb793f60999e5dc Mon Sep 17 00:00:00 2001 From: Carlos Date: Sun, 22 Sep 2019 18:32:27 -0400 Subject: [PATCH 42/63] Cleaning up default switch case --- src/commands/admin/deployreddit.js | 128 +++++++++++------------------ 1 file changed, 49 insertions(+), 79 deletions(-) diff --git a/src/commands/admin/deployreddit.js b/src/commands/admin/deployreddit.js index aad8405..8165cce 100644 --- a/src/commands/admin/deployreddit.js +++ b/src/commands/admin/deployreddit.js @@ -43,7 +43,7 @@ class DeployReddit extends Commando.Command { case '--status': messageArguments[0] = "guild.reddit.instances" if (messageArguments.length == 2) { - getValueOfReddit(message, messageArguments, messageArguments[1]) + getValueOfReddit(message, messageArguments[0], messageArguments[1]) } else { message.reply(`!!deployreddit --status \nGives information about the given channel with respect to reddit deployment.`); let redditValue = message.guild.settings.get("guild.reddit.instances", null); @@ -57,94 +57,64 @@ class DeployReddit extends Commando.Command { return; default: if (messageArguments.length == 2) { - // appending the argument of "r/...." to make a URL - if (messageArguments[1].search("reddit.com/") == -1) { - if (messageArguments[1].search("/") == 0) { - messageArguments[1] = "https://www.reddit.com" + messageArguments[1]; - } else { - messageArguments[1] = "https://www.reddit.com/" + messageArguments[1]; - } - } - const last_char_of_URL = messageArguments[1].charAt(messageArguments[1].length - 1); - switch (last_char_of_URL) { - case '/': - messageArguments[1] += ".json" - break; - default: - messageArguments[1] += "/.json" - break; - } + let link = refactor_link(messageArguments[1]); + messageArguments[1] = link; + if (!validated_link(link)) return; - // catching broken link errors - var error_given; - await request(messageArguments[1], async (error, response, html) => { - var json_data; - try { - json_data = await JSON.parse(html) - } catch (e) { - message.say("Sorry, this link did not work."); - return; - } - error_given = json_data.error == '404' ? true : false; - - if (error) { - message.say("Sorry, this link did not work."); - return; - } else if (error_given == true) { - message.say("Sorry, this link did not work."); - return; - } + messageArguments = ["guild.reddit.instances", messageArguments[0], messageArguments[1]]; - messageArguments = ["guild.reddit.instances", messageArguments[0], messageArguments[1]]; + const channel_id = refactor_id(message, messageArguments[1]) + if (does_channel_exist(message, messageArguments[0], channel_id)) return; - if (messageArguments[1] === undefined) { - messageArguments[1] = "id" + message.channel.id; - } else { - messageArguments[1] = "id" + messageArguments[1]; - } - //checks whether the given channelID already exists - var key_value_exits = message.guild.settings.get(messageArguments[0], null); - key_value_exits = JSON.parse(key_value_exits) - if (key_value_exits !== null) { - for (var z in key_value_exits.instances) { - if (key_value_exits.instances[z][messageArguments[1]] !== undefined) { - message.reply(`${messageArguments[1]} was already found\nTry using "--edit" or "--stop`); - return; - } - } - } + if (!is_first_instance(message, messageArguments[0], channel_id, messageArguments[2])) { + setRedditFromKey(message, messageArguments, channel_id, false); + initializeInstance(message, messageArguments); + console.log(`${channel_id} : ${messageArguments[2]} has been added to Reddit instances.`) + } + return; - if (getValueOfReddit(message, messageArguments, messageArguments[1], true) === undefined) { - var default_instance_object = { - "instances": [ - ] - }; - default_instance_object.instances.push({ [messageArguments[1]]: messageArguments[2] }); - default_instance_object = JSON.stringify(default_instance_object); - message.guild.settings.set("guild.reddit.instances", default_instance_object); - initializeInstance(message, messageArguments); - message.reply(`First Reddit instance made!`); - return; - } else { - setRedditFromKey(message, messageArguments, messageArguments[1], false); - initializeInstance(message, messageArguments); - console.log(`${messageArguments[1]} : ${messageArguments[2]} has been added to Reddit instances.`) - } - return; - }); } else { message.reply(`!!deployreddit \nAdds a reddit instance to a given channel.`); } - break; + return; + } + } +} + +const is_first_instance = (message, instance_key, channel_id, reddit_URL) => { + if (getValueOfReddit(message, instance_key, channel_id, true) === undefined) { + var default_instance_object = { + "instances": [ + ] + }; + default_instance_object.instances.push({ [channel_id]: reddit_URL }); + default_instance_object = JSON.stringify(default_instance_object); + message.guild.settings.set(instance_key, default_instance_object); + initializeInstance(message, messageArguments); + message.reply(`First Reddit instance made!`); + return true; + } + return false; +} + +const does_channel_exist = (message, instance_key, channel_id) => { + var key_value_exits = message.guild.settings.get(instance_key, null); + key_value_exits = JSON.parse(key_value_exits) + if (key_value_exits !== null) { + for (var z in key_value_exits.instances) { + if (key_value_exits.instances[z][channel_id] !== undefined) { + message.reply(`${channel_id} was already found\nTry using "--edit" or "--stop`); + return true; + } } } + return false; } const refactor_link = (link) => { - // appending the argument of "r/...." to make a URL if (link.search("reddit.com/") == -1) { if (link.search("/") == 0) { link = "https://www.reddit.com" + link; @@ -229,7 +199,7 @@ function delete_reddit_instance(message, messageArguments) { function setRedditFromKey(message, messageArguments, channelID, edit) { const [redditKey, tempChannelID, newSetting] = messageArguments; channelID = tempChannelID; - status_of_value = getValueOfReddit(message, messageArguments, channelID, true); + status_of_value = getValueOfReddit(message, redditKey, channelID, true); if (status_of_value === undefined && edit == true) { if (channelID === undefined) { channelID = "id" + message.channel.id; @@ -284,7 +254,7 @@ function setRedditFromKey(message, messageArguments, channelID, edit) { return; } -function getValueOfReddit(message, messageArguments, channelID, setting_default) { +function getValueOfReddit(message, instance_key, channelID, setting_default) { if (channelID.search("id") == -1) { if (channelID === undefined) { channelID = "id" + message.channel.id; @@ -292,10 +262,10 @@ function getValueOfReddit(message, messageArguments, channelID, setting_default) channelID = "id" + channelID; } } - var redditValue = message.guild.settings.get(messageArguments[0], null); + var redditValue = message.guild.settings.get(instance_key, null); if (redditValue == null) { if (!setting_default) { - message.reply(`${messageArguments[0]} was not found`); + message.reply(`${instance_key} was not found`); return undefined; } else { return undefined; @@ -312,7 +282,7 @@ function getValueOfReddit(message, messageArguments, channelID, setting_default) if (typeof redditValue !== 'string' && setting_default) { return null; } else if (typeof redditValue !== 'string') { - message.reply(`The given ID for ${messageArguments[0]} was not found`); + message.reply(`The given ID for ${instance_key} was not found`); return null; } else { From fd73e2244ef5304db7eeb6bf4a40b648ad2c769b Mon Sep 17 00:00:00 2001 From: Carlos Date: Sun, 22 Sep 2019 20:11:30 -0400 Subject: [PATCH 43/63] Cleaning code --- src/commands/admin/deployreddit.js | 75 +++++++++++++----------------- 1 file changed, 33 insertions(+), 42 deletions(-) diff --git a/src/commands/admin/deployreddit.js b/src/commands/admin/deployreddit.js index 8165cce..653786b 100644 --- a/src/commands/admin/deployreddit.js +++ b/src/commands/admin/deployreddit.js @@ -34,7 +34,7 @@ class DeployReddit extends Commando.Command { let link = refactor_link(messageArguments[2]); messageArguments[2] = link; - if (validated_link(link)) setRedditFromKey(message, messageArguments, messageArguments[1], true); + if (validated_link(link)) updateRedditFromKey(message, messageArguments, messageArguments[1], true); } else { message.reply(`!!deployreddit --edit \nChanges the given URL of a channel.`); @@ -52,8 +52,7 @@ class DeployReddit extends Commando.Command { return; case '--removeall': delete_all_instances(message); - let redditValue = message.guild.settings.get("guild.reddit.instances", null); - console.log(redditValue); + message.guild.settings.get("guild.reddit.instances", null); return; default: if (messageArguments.length == 2) { @@ -71,7 +70,7 @@ class DeployReddit extends Commando.Command { if (!is_first_instance(message, messageArguments[0], channel_id, messageArguments[2])) { setRedditFromKey(message, messageArguments, channel_id, false); - initializeInstance(message, messageArguments); + initializeInstance(message, messageArguments[2]); console.log(`${channel_id} : ${messageArguments[2]} has been added to Reddit instances.`) } return; @@ -93,7 +92,7 @@ const is_first_instance = (message, instance_key, channel_id, reddit_URL) => { default_instance_object.instances.push({ [channel_id]: reddit_URL }); default_instance_object = JSON.stringify(default_instance_object); message.guild.settings.set(instance_key, default_instance_object); - initializeInstance(message, messageArguments); + initializeInstance(message, reddit_URL); message.reply(`First Reddit instance made!`); return true; } @@ -157,14 +156,13 @@ const validated_link = async (link) => { return true; } -function initializeInstance(message, messageArguments) { +function initializeInstance(message, reddit_URL) { const daily_time = 'at 08:00am'; const testing_time = 'every 20 seconds'; - const redditURL = messageArguments[2]; var sched = later.parse.text(testing_time); later.date.localTime(); // time default is UTC | 4 hours ahead of FL - //query_reddit(message, redditURL); - //later.setInterval(function () { query_reddit(message, redditURL); }, sched); / / interval_instance.clear() clears timer + //query_reddit(message, reddit_URL); + //later.setInterval(function () { query_reddit(message, reddit_URL); }, sched); / / interval_instance.clear() clears timer } function delete_reddit_instance(message, messageArguments) { @@ -196,54 +194,47 @@ function delete_reddit_instance(message, messageArguments) { return undefined; } -function setRedditFromKey(message, messageArguments, channelID, edit) { +function updateRedditFromKey(message, messageArguments, channelID, edit) { const [redditKey, tempChannelID, newSetting] = messageArguments; channelID = tempChannelID; - status_of_value = getValueOfReddit(message, redditKey, channelID, true); - if (status_of_value === undefined && edit == true) { - if (channelID === undefined) { - channelID = "id" + message.channel.id; - } else { - channelID = "id" + channelID; - } - var default_instance_object = { - "instances": [ - ] - }; - default_instance_object.instances.push({ [channelID]: newSetting }); - default_instance_object = JSON.stringify(default_instance_object); - message.guild.settings.set(redditKey, default_instance_object); - console.log("Default created!") - message.reply(`Reddit instances can now be made!`); - return; - } else if (status_of_value === null) { - console.log("ID not found") - } - if (channelID.search("id") == -1) { - if (channelID === undefined) { - channelID = "id" + message.channel.id; - } else { - channelID = "id" + channelID; - } - } + // else if (status_of_value === null) { + // console.log("ID not found") + // } + channelID = refactor_id(message, channelID) + //validate link + + // Altering old value var redditValue = message.guild.settings.get(redditKey, null); redditValue = JSON.parse(redditValue) - for (key in redditValue.instances) { - if (redditValue.instances[key][channelID] !== undefined) { - redditValue.instances[key][channelID] = newSetting; + for (index in redditValue.instances) { + if (redditValue.instances[index][channelID] !== undefined) { + redditValue.instances[index][channelID] = newSetting; redditValue = JSON.stringify(redditValue); if (typeof redditValue === 'string') { + console.log("altering old val") message.guild.settings.set(redditKey, redditValue); - message.reply(`${redditKey} was assigned ${JSON.parse(redditValue).instances[key][channelID]}`); + message.reply(`${redditKey} was assigned ${newSetting}`); return redditValue; } break; } } + return; +} + +function setRedditFromKey(message, messageArguments, channelID, edit) { + const [redditKey, tempChannelID, newSetting] = messageArguments; + channelID = tempChannelID; + + // else if (status_of_value === null) { + // console.log("ID not found") + // } + + channelID = refactor_id(message, channelID) + //validate link - // Adding a new ID and value var redditValue = message.guild.settings.get(redditKey, null); redditValue = JSON.parse(redditValue) redditValue.instances.push({ [channelID]: newSetting }); From ae348a37f0c1e78d83468944f98b86d5cd759133 Mon Sep 17 00:00:00 2001 From: Carlos Date: Mon, 23 Sep 2019 12:16:01 -0400 Subject: [PATCH 44/63] Cleaned "--edit" and "--stop" --- src/commands/admin/deployreddit.js | 57 +++++++++++++----------------- 1 file changed, 24 insertions(+), 33 deletions(-) diff --git a/src/commands/admin/deployreddit.js b/src/commands/admin/deployreddit.js index 653786b..8624de5 100644 --- a/src/commands/admin/deployreddit.js +++ b/src/commands/admin/deployreddit.js @@ -21,21 +21,20 @@ class DeployReddit extends Commando.Command { switch (messageArguments[0]) { case '--stop': - messageArguments[0] = "guild.reddit.instances" if (messageArguments.length == 2) { - delete_reddit_instance(message, messageArguments, messageArguments[1]); + let instance_key = "guild.reddit.instances"; + let channel_id = messageArguments[1]; + delete_reddit_instance(message, instance_key, channel_id); } else { message.reply(`!!deployreddit --stop \nStops the execution of the reddit deployment in the specified channel.`); } return; case '--edit': - messageArguments[0] = "guild.reddit.instances" if (messageArguments.length == 3) { - + let instance_key = "guild.reddit.instances" + let channel_id = messageArguments[1]; let link = refactor_link(messageArguments[2]); - messageArguments[2] = link; - if (validated_link(link)) updateRedditFromKey(message, messageArguments, messageArguments[1], true); - + if (validated_link(link)) updateRedditFromKey(message, instance_key, link, channel_id); } else { message.reply(`!!deployreddit --edit \nChanges the given URL of a channel.`); } @@ -46,8 +45,9 @@ class DeployReddit extends Commando.Command { getValueOfReddit(message, messageArguments[0], messageArguments[1]) } else { message.reply(`!!deployreddit --status \nGives information about the given channel with respect to reddit deployment.`); - let redditValue = message.guild.settings.get("guild.reddit.instances", null); - console.log(redditValue); + //debugging + let instances = message.guild.settings.get("guild.reddit.instances", null); + console.log(instances); } return; case '--removeall': @@ -165,57 +165,48 @@ function initializeInstance(message, reddit_URL) { //later.setInterval(function () { query_reddit(message, reddit_URL); }, sched); / / interval_instance.clear() clears timer } -function delete_reddit_instance(message, messageArguments) { - const INSTANCE_KEY = messageArguments[0]; - const CHANNEL_ID = refactor_id(message, messageArguments[1]); +function delete_reddit_instance(message, instance_key, channel_id) { + channel_id = refactor_id(message, channel_id); - var instances = message.guild.settings.get(INSTANCE_KEY, null); + var instances = message.guild.settings.get(instance_key, null); if (instances == null) { - message.reply(`${INSTANCE_KEY} was not found.\nTry creating a new instance using "!!deployreddit "`); + message.reply(`${instance_key} was not found.\nTry creating a new instance using "!!deployreddit "`); return undefined; } instances = JSON.parse(instances) for (index in instances.instances) { - if (instances.instances[index][CHANNEL_ID] !== undefined) { + if (instances.instances[index][channel_id] !== undefined) { instances.instances.splice(index, 1); const new_instances = JSON.stringify(instances); if (typeof new_instances === 'string') { - message.guild.settings.set(INSTANCE_KEY, new_instances); - message.reply(`${CHANNEL_ID} was removed from this guild.`); + message.guild.settings.set(instance_key, new_instances); + message.reply(`${channel_id} was removed from this guild.`); return; } break; } } - message.reply(`${CHANNEL_ID} was not in instances.`); + message.reply(`${channel_id} was not in instances.`); return undefined; } -function updateRedditFromKey(message, messageArguments, channelID, edit) { - const [redditKey, tempChannelID, newSetting] = messageArguments; - channelID = tempChannelID; - - // else if (status_of_value === null) { - // console.log("ID not found") - // } - - channelID = refactor_id(message, channelID) - //validate link +function updateRedditFromKey(message, instance_key, reddit_URL, channel_id) { + channel_id = refactor_id(message, channel_id) // Altering old value - var redditValue = message.guild.settings.get(redditKey, null); + var redditValue = message.guild.settings.get(instance_key, null); redditValue = JSON.parse(redditValue) for (index in redditValue.instances) { - if (redditValue.instances[index][channelID] !== undefined) { - redditValue.instances[index][channelID] = newSetting; + if (redditValue.instances[index][channel_id] !== undefined) { + redditValue.instances[index][channel_id] = reddit_URL; redditValue = JSON.stringify(redditValue); if (typeof redditValue === 'string') { console.log("altering old val") - message.guild.settings.set(redditKey, redditValue); - message.reply(`${redditKey} was assigned ${newSetting}`); + message.guild.settings.set(instance_key, redditValue); + message.reply(`${instance_key} was assigned ${reddit_URL}`); return redditValue; } break; From 0cc5749b20367b29946515da3a1dcaded31413e5 Mon Sep 17 00:00:00 2001 From: Carlos Date: Mon, 23 Sep 2019 12:28:12 -0400 Subject: [PATCH 45/63] Cleaning "--status" & "--removeall" & default --- src/commands/admin/deployreddit.js | 38 +++++++++++++++++------------- 1 file changed, 22 insertions(+), 16 deletions(-) diff --git a/src/commands/admin/deployreddit.js b/src/commands/admin/deployreddit.js index 8624de5..8ef0c7f 100644 --- a/src/commands/admin/deployreddit.js +++ b/src/commands/admin/deployreddit.js @@ -40,38 +40,43 @@ class DeployReddit extends Commando.Command { } return; case '--status': - messageArguments[0] = "guild.reddit.instances" if (messageArguments.length == 2) { - getValueOfReddit(message, messageArguments[0], messageArguments[1]) + let instance_key = "guild.reddit.instances"; + let channel_id = messageArguments[1]; + getValueOfReddit(message, instance_key, channel_id); } else { - message.reply(`!!deployreddit --status \nGives information about the given channel with respect to reddit deployment.`); //debugging - let instances = message.guild.settings.get("guild.reddit.instances", null); + let instance_key = "guild.reddit.instances"; + let instances = message.guild.settings.get(instance_key, null); console.log(instances); + + message.reply(`!!deployreddit --status \nGives information about the given channel with respect to reddit deployment.`); } return; case '--removeall': + //debugging + let instance_key = "guild.reddit.instances"; + let instances = message.guild.settings.get(instance_key, null); + console.log(instances); + delete_all_instances(message); - message.guild.settings.get("guild.reddit.instances", null); return; default: if (messageArguments.length == 2) { - + let instance_key = "guild.reddit.instances" + let channel_id = messageArguments[0]; let link = refactor_link(messageArguments[1]); - messageArguments[1] = link; - if (!validated_link(link)) return; - - messageArguments = ["guild.reddit.instances", messageArguments[0], messageArguments[1]]; - const channel_id = refactor_id(message, messageArguments[1]) + if (!validated_link(link)) return; - if (does_channel_exist(message, messageArguments[0], channel_id)) return; + const channel_id = refactor_id(message, channel_id) + if (does_channel_exist(message, instance_key, channel_id)) return; - if (!is_first_instance(message, messageArguments[0], channel_id, messageArguments[2])) { + if (!is_first_instance(message, instance_key, channel_id, link)) { setRedditFromKey(message, messageArguments, channel_id, false); - initializeInstance(message, messageArguments[2]); - console.log(`${channel_id} : ${messageArguments[2]} has been added to Reddit instances.`) + initializeInstance(message, link); + console.log(`${channel_id} : ${link} has been added to Reddit instances.`) } return; @@ -278,7 +283,8 @@ function getValueOfReddit(message, instance_key, channelID, setting_default) { } function delete_all_instances(message) { - message.guild.settings.remove('guild.reddit.instances', null); + let instance_key = "guild.reddit.instances"; + message.guild.settings.remove(instance_key, null); console.log("All instances deleted.") } From 9112bdad8f30c753c0d980c9d15e282470fabde1 Mon Sep 17 00:00:00 2001 From: Carlos Date: Mon, 23 Sep 2019 14:14:59 -0400 Subject: [PATCH 46/63] default fixed --- src/commands/admin/deployreddit.js | 44 ++++++++++++------------------ 1 file changed, 17 insertions(+), 27 deletions(-) diff --git a/src/commands/admin/deployreddit.js b/src/commands/admin/deployreddit.js index 8ef0c7f..a58b841 100644 --- a/src/commands/admin/deployreddit.js +++ b/src/commands/admin/deployreddit.js @@ -34,7 +34,7 @@ class DeployReddit extends Commando.Command { let instance_key = "guild.reddit.instances" let channel_id = messageArguments[1]; let link = refactor_link(messageArguments[2]); - if (validated_link(link)) updateRedditFromKey(message, instance_key, link, channel_id); + if (validated_link(message, link)) updateRedditFromKey(message, instance_key, channel_id, link); } else { message.reply(`!!deployreddit --edit \nChanges the given URL of a channel.`); } @@ -46,18 +46,18 @@ class DeployReddit extends Commando.Command { getValueOfReddit(message, instance_key, channel_id); } else { //debugging - let instance_key = "guild.reddit.instances"; - let instances = message.guild.settings.get(instance_key, null); - console.log(instances); + //let instance_key = "guild.reddit.instances"; + //let instances = message.guild.settings.get(instance_key, null); + //console.log(instances); message.reply(`!!deployreddit --status \nGives information about the given channel with respect to reddit deployment.`); } return; case '--removeall': //debugging - let instance_key = "guild.reddit.instances"; - let instances = message.guild.settings.get(instance_key, null); - console.log(instances); + //let instance_key = "guild.reddit.instances"; + //let instances = message.guild.settings.get(instance_key, null); + //console.log(instances); delete_all_instances(message); return; @@ -67,14 +67,14 @@ class DeployReddit extends Commando.Command { let channel_id = messageArguments[0]; let link = refactor_link(messageArguments[1]); - if (!validated_link(link)) return; + if (!validated_link(message, link)) return; - const channel_id = refactor_id(message, channel_id) + channel_id = refactor_id(message, channel_id) if (does_channel_exist(message, instance_key, channel_id)) return; if (!is_first_instance(message, instance_key, channel_id, link)) { - setRedditFromKey(message, messageArguments, channel_id, false); + setRedditFromKey(message, instance_key, channel_id, link); initializeInstance(message, link); console.log(`${channel_id} : ${link} has been added to Reddit instances.`) } @@ -138,7 +138,7 @@ const refactor_link = (link) => { return link; } -const validated_link = async (link) => { +const validated_link = async (message, link) => { var error_given; await request(link, async (error, response, html) => { var json_data; @@ -198,7 +198,7 @@ function delete_reddit_instance(message, instance_key, channel_id) { return undefined; } -function updateRedditFromKey(message, instance_key, reddit_URL, channel_id) { +function updateRedditFromKey(message, instance_key, channel_id, reddit_URL) { channel_id = refactor_id(message, channel_id) // Altering old value @@ -220,24 +220,14 @@ function updateRedditFromKey(message, instance_key, reddit_URL, channel_id) { return; } -function setRedditFromKey(message, messageArguments, channelID, edit) { - const [redditKey, tempChannelID, newSetting] = messageArguments; - channelID = tempChannelID; - - // else if (status_of_value === null) { - // console.log("ID not found") - // } - - channelID = refactor_id(message, channelID) - //validate link - - var redditValue = message.guild.settings.get(redditKey, null); +function setRedditFromKey(message, instance_key, channel_id, reddit_URL) { + var redditValue = message.guild.settings.get(instance_key, null); redditValue = JSON.parse(redditValue) - redditValue.instances.push({ [channelID]: newSetting }); + redditValue.instances.push({ [channel_id]: reddit_URL }); redditValue = JSON.stringify(redditValue); - message.guild.settings.set(redditKey, redditValue); + message.guild.settings.set(instance_key, redditValue); - message.reply(`${channelID} was assigned ${newSetting}`); + message.reply(`${channel_id} was assigned ${reddit_URL}`); return; } From 8d62f32e4b1bc7aa98167086a902f99e3f26eb4d Mon Sep 17 00:00:00 2001 From: Carlos Date: Mon, 23 Sep 2019 15:08:16 -0400 Subject: [PATCH 47/63] Separated getValueOfReddit more logically --- src/commands/admin/deployreddit.js | 211 ++++++++++++++--------------- 1 file changed, 99 insertions(+), 112 deletions(-) diff --git a/src/commands/admin/deployreddit.js b/src/commands/admin/deployreddit.js index a58b841..4afe88e 100644 --- a/src/commands/admin/deployreddit.js +++ b/src/commands/admin/deployreddit.js @@ -42,22 +42,22 @@ class DeployReddit extends Commando.Command { case '--status': if (messageArguments.length == 2) { let instance_key = "guild.reddit.instances"; - let channel_id = messageArguments[1]; + let channel_id = refactor_id(message, messageArguments[1]); getValueOfReddit(message, instance_key, channel_id); } else { //debugging - //let instance_key = "guild.reddit.instances"; - //let instances = message.guild.settings.get(instance_key, null); - //console.log(instances); + let instance_key = "guild.reddit.instances"; + let instances = message.guild.settings.get(instance_key, null); + console.log(instances); message.reply(`!!deployreddit --status \nGives information about the given channel with respect to reddit deployment.`); } return; case '--removeall': //debugging - //let instance_key = "guild.reddit.instances"; - //let instances = message.guild.settings.get(instance_key, null); - //console.log(instances); + let instance_key = "guild.reddit.instances"; + let instances = message.guild.settings.get(instance_key, null); + console.log(instances); delete_all_instances(message); return; @@ -88,79 +88,6 @@ class DeployReddit extends Commando.Command { } } -const is_first_instance = (message, instance_key, channel_id, reddit_URL) => { - if (getValueOfReddit(message, instance_key, channel_id, true) === undefined) { - var default_instance_object = { - "instances": [ - ] - }; - default_instance_object.instances.push({ [channel_id]: reddit_URL }); - default_instance_object = JSON.stringify(default_instance_object); - message.guild.settings.set(instance_key, default_instance_object); - initializeInstance(message, reddit_URL); - message.reply(`First Reddit instance made!`); - return true; - } - return false; -} - -const does_channel_exist = (message, instance_key, channel_id) => { - var key_value_exits = message.guild.settings.get(instance_key, null); - key_value_exits = JSON.parse(key_value_exits) - if (key_value_exits !== null) { - for (var z in key_value_exits.instances) { - if (key_value_exits.instances[z][channel_id] !== undefined) { - message.reply(`${channel_id} was already found\nTry using "--edit" or "--stop`); - return true; - } - } - } - return false; -} - -const refactor_link = (link) => { - if (link.search("reddit.com/") == -1) { - if (link.search("/") == 0) { - link = "https://www.reddit.com" + link; - } else { - link = "https://www.reddit.com/" + link; - } - } - const last_char_of_URL = link.charAt(link.length - 1); - switch (last_char_of_URL) { - case '/': - link += ".json" - break; - default: - link += "/.json" - break; - } - return link; -} - -const validated_link = async (message, link) => { - var error_given; - await request(link, async (error, response, html) => { - var json_data; - try { - json_data = await JSON.parse(html) - } catch (e) { - message.say("Sorry, this link did not work."); - return false; - } - error_given = json_data.error == '404' ? true : false; - - if (error) { - message.say("Sorry, this link did not work."); - return false; - } else if (error_given == true) { - message.say("Sorry, this link did not work."); - return false; - } - }); - return true; -} - function initializeInstance(message, reddit_URL) { const daily_time = 'at 08:00am'; const testing_time = 'every 20 seconds'; @@ -221,57 +148,44 @@ function updateRedditFromKey(message, instance_key, channel_id, reddit_URL) { } function setRedditFromKey(message, instance_key, channel_id, reddit_URL) { - var redditValue = message.guild.settings.get(instance_key, null); - redditValue = JSON.parse(redditValue) - redditValue.instances.push({ [channel_id]: reddit_URL }); - redditValue = JSON.stringify(redditValue); - message.guild.settings.set(instance_key, redditValue); + var instances = message.guild.settings.get(instance_key, null); + instances = JSON.parse(instances) + instances.instances.push({ [channel_id]: reddit_URL }); + instances = JSON.stringify(instances); + message.guild.settings.set(instance_key, instances); message.reply(`${channel_id} was assigned ${reddit_URL}`); return; } -function getValueOfReddit(message, instance_key, channelID, setting_default) { - if (channelID.search("id") == -1) { - if (channelID === undefined) { - channelID = "id" + message.channel.id; - } else { - channelID = "id" + channelID; - } - } +function getValueOfReddit(message, instance_key, channel_id) { var redditValue = message.guild.settings.get(instance_key, null); if (redditValue == null) { - if (!setting_default) { - message.reply(`${instance_key} was not found`); - return undefined; - } else { - return undefined; - } + message.reply(`${instance_key} was not found`); + return undefined; } redditValue = JSON.parse(redditValue) for (key in redditValue.instances) { - if (redditValue.instances[key][channelID] !== undefined) { - redditValue = redditValue.instances[key][channelID]; + if (redditValue.instances[key][channel_id] !== undefined) { + redditValue = redditValue.instances[key][channel_id]; break; } } - if (typeof redditValue !== 'string' && setting_default) { - return null; - } else if (typeof redditValue !== 'string') { + if (typeof redditValue !== 'string') { message.reply(`The given ID for ${instance_key} was not found`); return null; - } - else { - if (setting_default != true) { - message.reply(`Value for ${channelID} is ${redditValue}`); - return redditValue; - } else { - return redditValue; - } + } else { + message.reply(`Value for ${channel_id} is ${redditValue}`); + return redditValue; } } +function does_default_instance_exist(message, instance_key, channel_id) { + var redditValue = message.guild.settings.get(instance_key, null); + return (redditValue == null) ? false : true; +} + function delete_all_instances(message) { let instance_key = "guild.reddit.instances"; message.guild.settings.remove(instance_key, null); @@ -325,4 +239,77 @@ const refactor_id = (message, channel_id) => { return channel_id; } +const is_first_instance = (message, instance_key, channel_id, reddit_URL) => { + if (does_default_instance_exist(message, instance_key, channel_id) === false) { + var default_instance_object = { + "instances": [ + ] + }; + default_instance_object.instances.push({ [channel_id]: reddit_URL }); + default_instance_object = JSON.stringify(default_instance_object); + message.guild.settings.set(instance_key, default_instance_object); + initializeInstance(message, reddit_URL); + message.reply(`First Reddit instance made!`); + return true; + } + return false; +} + +const does_channel_exist = (message, instance_key, channel_id) => { + var key_value_exits = message.guild.settings.get(instance_key, null); + key_value_exits = JSON.parse(key_value_exits) + if (key_value_exits !== null) { + for (var z in key_value_exits.instances) { + if (key_value_exits.instances[z][channel_id] !== undefined) { + message.reply(`${channel_id} was already found\nTry using "--edit" or "--stop`); + return true; + } + } + } + return false; +} + +const refactor_link = (link) => { + if (link.search("reddit.com/") == -1) { + if (link.search("/") == 0) { + link = "https://www.reddit.com" + link; + } else { + link = "https://www.reddit.com/" + link; + } + } + const last_char_of_URL = link.charAt(link.length - 1); + switch (last_char_of_URL) { + case '/': + link += ".json" + break; + default: + link += "/.json" + break; + } + return link; +} + +const validated_link = async (message, link) => { + var error_given; + await request(link, async (error, response, html) => { + var json_data; + try { + json_data = await JSON.parse(html) + } catch (e) { + message.say("Sorry, this link did not work."); + return false; + } + error_given = json_data.error == '404' ? true : false; + + if (error) { + message.say("Sorry, this link did not work."); + return false; + } else if (error_given == true) { + message.say("Sorry, this link did not work."); + return false; + } + }); + return true; +} + module.exports = DeployReddit; \ No newline at end of file From 31fdc5125acfab19345aeec09d3125fe525798d1 Mon Sep 17 00:00:00 2001 From: Carlos Date: Mon, 23 Sep 2019 15:18:09 -0400 Subject: [PATCH 48/63] Cleaned startup --- src/commands/admin/deployreddit.js | 6 +++--- src/commands/admin/postreddit.js | 18 +++++++++--------- 2 files changed, 12 insertions(+), 12 deletions(-) diff --git a/src/commands/admin/deployreddit.js b/src/commands/admin/deployreddit.js index 4afe88e..87983e3 100644 --- a/src/commands/admin/deployreddit.js +++ b/src/commands/admin/deployreddit.js @@ -89,9 +89,9 @@ class DeployReddit extends Commando.Command { } function initializeInstance(message, reddit_URL) { - const daily_time = 'at 08:00am'; - const testing_time = 'every 20 seconds'; - var sched = later.parse.text(testing_time); + const DAILY_POST_TIME = 'at 08:00am'; + const TESTING_POST_TIME = 'every 20 seconds'; + var sched = later.parse.text(TESTING_POST_TIME); later.date.localTime(); // time default is UTC | 4 hours ahead of FL //query_reddit(message, reddit_URL); //later.setInterval(function () { query_reddit(message, reddit_URL); }, sched); / / interval_instance.clear() clears timer diff --git a/src/commands/admin/postreddit.js b/src/commands/admin/postreddit.js index b5eb849..eff9de2 100644 --- a/src/commands/admin/postreddit.js +++ b/src/commands/admin/postreddit.js @@ -24,21 +24,21 @@ async function initializeInstance(discordClient) { later.date.localTime(); // time default is UTC | 4 hours ahead of FL var guild = discordClient.guilds.keyArray()[0]; - var redditValue = await discordClient.guilds.get(guild).settings.get("guild.reddit.instances") - redditValue = await JSON.parse(redditValue) - for (var index = 0; index < redditValue.instances.length; index++) { - for (x in redditValue.instances[index]) { + var instances = await discordClient.guilds.get(guild).settings.get("guild.reddit.instances") + instances = await JSON.parse(instances) + for (var index = 0; index < instances.instances.length; index++) { + for (x in instances.instances[index]) { var channel_id = x; - var redditURL = redditValue.instances[index][x]; - await query_reddit(redditURL, discordClient, x); - //await later.setInterval(function () { query_reddit(redditURL, discordClient, channel_id) }, sched); + var reddit_URL = instances.instances[index][x]; + await query_reddit(discordClient, reddit_URL, x); + //await later.setInterval(function () { query_reddit(reddit_URL, discordClient, channel_id) }, sched); } } } } -async function query_reddit(redditURL, discordClient, channel_id) { - await request(redditURL, (error, response, html) => { +async function query_reddit(discordClient, reddit_URL, channel_id) { + await request(reddit_URL, (error, response, html) => { if (!error && response.statusCode == 200) { const json_data = JSON.parse(html); From d16400f3e83fba8fd13f0fc3a7fccfb0e6f4fac2 Mon Sep 17 00:00:00 2001 From: Carlos Date: Thu, 26 Sep 2019 00:56:44 -0400 Subject: [PATCH 49/63] Linted "deployreddit" --- src/commands/admin/deployreddit.js | 544 ++++++++++++++--------------- 1 file changed, 270 insertions(+), 274 deletions(-) diff --git a/src/commands/admin/deployreddit.js b/src/commands/admin/deployreddit.js index 87983e3..cfc1b04 100644 --- a/src/commands/admin/deployreddit.js +++ b/src/commands/admin/deployreddit.js @@ -1,315 +1,311 @@ -const Discord = require('discord.js'); const Commando = require('discord.js-commando'); const Logger = require('../../logging/Logger'); -const { redditKeys, redditNames } = require('../../settings/SettingsProvider'); const request = require('request'); -var later = require('later'); +const later = require('later'); class DeployReddit extends Commando.Command { - constructor(client) { - super(client, { - name: 'deployreddit', - description: 'Deploys the top img in any subreddit every 24hrs', - guildOnly: true, - group: 'admin', - memberName: 'deployreddit', - }); - } + constructor(client) { + super(client, { + name: 'deployreddit', + description: 'Deploys the top img in any subreddit every 24hrs', + guildOnly: true, + group: 'admin', + memberName: 'deployreddit', + }); + } - async run(message, args) { - var messageArguments = args.split(' '); - - switch (messageArguments[0]) { - case '--stop': - if (messageArguments.length == 2) { - let instance_key = "guild.reddit.instances"; - let channel_id = messageArguments[1]; - delete_reddit_instance(message, instance_key, channel_id); - } else { - message.reply(`!!deployreddit --stop \nStops the execution of the reddit deployment in the specified channel.`); - } - return; - case '--edit': - if (messageArguments.length == 3) { - let instance_key = "guild.reddit.instances" - let channel_id = messageArguments[1]; - let link = refactor_link(messageArguments[2]); - if (validated_link(message, link)) updateRedditFromKey(message, instance_key, channel_id, link); - } else { - message.reply(`!!deployreddit --edit \nChanges the given URL of a channel.`); - } - return; - case '--status': - if (messageArguments.length == 2) { - let instance_key = "guild.reddit.instances"; - let channel_id = refactor_id(message, messageArguments[1]); - getValueOfReddit(message, instance_key, channel_id); - } else { - //debugging - let instance_key = "guild.reddit.instances"; - let instances = message.guild.settings.get(instance_key, null); - console.log(instances); - - message.reply(`!!deployreddit --status \nGives information about the given channel with respect to reddit deployment.`); - } - return; - case '--removeall': - //debugging - let instance_key = "guild.reddit.instances"; - let instances = message.guild.settings.get(instance_key, null); - console.log(instances); - - delete_all_instances(message); - return; - default: - if (messageArguments.length == 2) { - let instance_key = "guild.reddit.instances" - let channel_id = messageArguments[0]; - let link = refactor_link(messageArguments[1]); - - if (!validated_link(message, link)) return; - - channel_id = refactor_id(message, channel_id) - - if (does_channel_exist(message, instance_key, channel_id)) return; - - if (!is_first_instance(message, instance_key, channel_id, link)) { - setRedditFromKey(message, instance_key, channel_id, link); - initializeInstance(message, link); - console.log(`${channel_id} : ${link} has been added to Reddit instances.`) - } - return; - - } else { - message.reply(`!!deployreddit \nAdds a reddit instance to a given channel.`); - } - return; + async run(message, args) { + const messageArguments = args.split(' '); + + switch (messageArguments[0]) { + case '--stop': + if (messageArguments.length == 2) { + const instanceKey = 'guild.reddit.instances'; + const channelID = messageArguments[1]; + deleteRedditInstance(message, instanceKey, channelID); + } else { + message.reply(`!!deployreddit --stop \nStops the execution of the reddit deployment in the specified channel.`); } + return; + case '--edit': + if (messageArguments.length == 3) { + const instanceKey = 'guild.reddit.instances'; + const channelID = messageArguments[1]; + const link = refactorLink(messageArguments[2]); + if (validatedLink(message, link)) { + updateRedditFromKey(message, instanceKey, channelID, link); + } + } else { + message.reply(`!!deployreddit --edit \nChanges the given URL of a channel.`); + } + return; + case '--status': + if (messageArguments.length == 2) { + const instanceKey = 'guild.reddit.instances'; + const channelID = refactorID(message, messageArguments[1]); + getValueOfReddit(message, instanceKey, channelID); + } else { + // debugging + const instanceKey = 'guild.reddit.instances'; + const instances = message.guild.settings.get(instanceKey, null); + console.log(instances); + + message.reply(`!!deployreddit --status \nGives information about the given channel with respect to reddit deployment.`); + } + return; + case '--removeall': + // debugging + const instanceKey = 'guild.reddit.instances'; + const instances = message.guild.settings.get(instanceKey, null); + console.log(instances); + + deleteAllInstances(message); + return; + default: + if (messageArguments.length == 2) { + const instanceKey = 'guild.reddit.instances'; + let channelID = messageArguments[0]; + const link = refactorLink(messageArguments[1]); + + if (!validatedLink(message, link)) return; + + channelID = refactorID(message, channelID); + + if (doesChannelExist(message, instanceKey, channelID)) return; + + if (!isFirstInstance(message, instanceKey, channelID, link)) { + setRedditFromKey(message, instanceKey, channelID, link); + initializeInstance(message, link); + console.log(`${channelID} : ${link} has been added to Reddit instances.`); + } + return; + } else { + message.reply(`!!deployreddit \nAdds a reddit instance to a given channel.`); + } + return; } + } } -function initializeInstance(message, reddit_URL) { - const DAILY_POST_TIME = 'at 08:00am'; - const TESTING_POST_TIME = 'every 20 seconds'; - var sched = later.parse.text(TESTING_POST_TIME); - later.date.localTime(); // time default is UTC | 4 hours ahead of FL - //query_reddit(message, reddit_URL); - //later.setInterval(function () { query_reddit(message, reddit_URL); }, sched); / / interval_instance.clear() clears timer +function initializeInstance(message, redditURL) { + const DAILY_POST_TIME = 'at 08:00am'; + const TESTING_POST_TIME = 'every 20 seconds'; + const sched = later.parse.text(TESTING_POST_TIME); + later.date.localTime(); // time default is UTC | 4 hours ahead of FL + // query_reddit(message, redditURL); + // later.setInterval(function () { query_reddit(message, redditURL); }, sched); } -function delete_reddit_instance(message, instance_key, channel_id) { - channel_id = refactor_id(message, channel_id); - - var instances = message.guild.settings.get(instance_key, null); +function deleteRedditInstance(message, instanceKey, channelID) { + channelID = refactorID(message, channelID); - if (instances == null) { - message.reply(`${instance_key} was not found.\nTry creating a new instance using "!!deployreddit "`); - return undefined; - } + let instances = message.guild.settings.get(instanceKey, null); - instances = JSON.parse(instances) - for (index in instances.instances) { - if (instances.instances[index][channel_id] !== undefined) { - instances.instances.splice(index, 1); - const new_instances = JSON.stringify(instances); - if (typeof new_instances === 'string') { - message.guild.settings.set(instance_key, new_instances); - message.reply(`${channel_id} was removed from this guild.`); - return; - } - break; - } + if (instances == null) { + message.reply(`${instanceKey} was not found.\nTry creating a new instance using "!!deployreddit "`); + return undefined; + } + + instances = JSON.parse(instances); + for (index in instances.instances) { + if (instances.instances[index][channelID] !== undefined) { + instances.instances.splice(index, 1); + const newInstances = JSON.stringify(instances); + if (typeof newInstances === 'string') { + message.guild.settings.set(instanceKey, newInstances); + message.reply(`${channelID} was removed from this guild.`); + return; + } + break; } + } - message.reply(`${channel_id} was not in instances.`); - return undefined; + message.reply(`${channelID} was not in instances.`); + return undefined; } -function updateRedditFromKey(message, instance_key, channel_id, reddit_URL) { - channel_id = refactor_id(message, channel_id) - - // Altering old value - var redditValue = message.guild.settings.get(instance_key, null); - redditValue = JSON.parse(redditValue) - for (index in redditValue.instances) { - if (redditValue.instances[index][channel_id] !== undefined) { - redditValue.instances[index][channel_id] = reddit_URL; - redditValue = JSON.stringify(redditValue); - if (typeof redditValue === 'string') { - console.log("altering old val") - message.guild.settings.set(instance_key, redditValue); - message.reply(`${instance_key} was assigned ${reddit_URL}`); - return redditValue; - } - break; - } +function updateRedditFromKey(message, instanceKey, channelID, redditURL) { + channelID = refactorID(message, channelID); + + // Altering old value + let redditValue = message.guild.settings.get(instanceKey, null); + redditValue = JSON.parse(redditValue); + for (index in redditValue.instances) { + if (redditValue.instances[index][channelID] !== undefined) { + redditValue.instances[index][channelID] = redditURL; + redditValue = JSON.stringify(redditValue); + if (typeof redditValue === 'string') { + console.log('altering old val'); + message.guild.settings.set(instanceKey, redditValue); + message.reply(`${instanceKey} was assigned ${redditURL}`); + return redditValue; + } + break; } - return; + } + return; } -function setRedditFromKey(message, instance_key, channel_id, reddit_URL) { - var instances = message.guild.settings.get(instance_key, null); - instances = JSON.parse(instances) - instances.instances.push({ [channel_id]: reddit_URL }); - instances = JSON.stringify(instances); - message.guild.settings.set(instance_key, instances); +function setRedditFromKey(message, instanceKey, channelID, redditURL) { + let instances = message.guild.settings.get(instanceKey, null); + instances = JSON.parse(instances); + instances.instances.push({[channelID]: redditURL}); + instances = JSON.stringify(instances); + message.guild.settings.set(instanceKey, instances); - message.reply(`${channel_id} was assigned ${reddit_URL}`); - return; + message.reply(`${channelID} was assigned ${redditURL}`); + return; } -function getValueOfReddit(message, instance_key, channel_id) { - var redditValue = message.guild.settings.get(instance_key, null); - if (redditValue == null) { - message.reply(`${instance_key} was not found`); - return undefined; - } - redditValue = JSON.parse(redditValue) - for (key in redditValue.instances) { - if (redditValue.instances[key][channel_id] !== undefined) { - redditValue = redditValue.instances[key][channel_id]; - break; - } - } - - if (typeof redditValue !== 'string') { - message.reply(`The given ID for ${instance_key} was not found`); - return null; - } else { - message.reply(`Value for ${channel_id} is ${redditValue}`); - return redditValue; +function getValueOfReddit(message, instanceKey, channelID) { + let redditValue = message.guild.settings.get(instanceKey, null); + if (redditValue == null) { + message.reply(`${instanceKey} was not found`); + return undefined; + } + redditValue = JSON.parse(redditValue); + for (key in redditValue.instances) { + if (redditValue.instances[key][channelID] !== undefined) { + redditValue = redditValue.instances[key][channelID]; + break; } + } + + if (typeof redditValue !== 'string') { + message.reply(`The given ID for ${instanceKey} was not found`); + return null; + } else { + message.reply(`Value for ${channelID} is ${redditValue}`); + return redditValue; + } } -function does_default_instance_exist(message, instance_key, channel_id) { - var redditValue = message.guild.settings.get(instance_key, null); - return (redditValue == null) ? false : true; +function doesDefaultInstanceExist(message, instanceKey, channelID) { + const redditValue = message.guild.settings.get(instanceKey, null); + return (redditValue == null) ? false : true; } -function delete_all_instances(message) { - let instance_key = "guild.reddit.instances"; - message.guild.settings.remove(instance_key, null); - console.log("All instances deleted.") +function deleteAllInstances(message) { + const instanceKey = 'guild.reddit.instances'; + message.guild.settings.remove(instanceKey, null); + console.log('All instances deleted.'); } -async function query_reddit(message, redditURL) { - await request(redditURL, (error, response, html) => { - if (!error && response.statusCode == 200) { - - const json_data = JSON.parse(html); - for (var index = 0; index < json_data.data.dist; index++) { - - if (json_data.data.children[index].data.post_hint == "image" || links_to_image(json_data.data.children[index].data.url)) { - const image_to_embed = { - "image": { - "url": json_data.data.children[index].data.url - } - }; - message.embed(image_to_embed).then(async function (reply) { - reply.channel.fetchMessage(reply.id).then(async function (message_retrieved) { - await message_retrieved.react('👍'); - await message_retrieved.react('👎'); - }); - }); - return; - } - - } - +async function queryReddit(message, redditURL) { + await request(redditURL, (error, response, html) => { + if (!error && response.statusCode == 200) { + const jsonData = JSON.parse(html); + for (let index = 0; index < jsonData.data.dist; index++) { + if (jsonData.data.children[index].data.post_hint == 'image' + || linksToImage(jsonData.data.children[index].data.url)) { + const imageToEmbed = { + 'image': { + 'url': jsonData.data.children[index].data.url, + }, + }; + message.embed(imageToEmbed).then(async function(reply) { + reply.channel.fetchMessage(reply.id).then(async function(messageRetrieved) { + await messageRetrieved.react('👍'); + await messageRetrieved.react('👎'); + }); + }); + return; } - }); - console.log("Reddit post made:", new Date()); -} - -const links_to_image = (link) => { - const IMG_EXTENSIONS = ['jpg', 'png', 'gif'] - const link_extension = link.substr(link.length - 3); - if (IMG_EXTENSIONS.includes(link_extension)) { - return true; + } } - return false; + }); + console.log('Reddit post made:', new Date()); } -const refactor_id = (message, channel_id) => { - if (channel_id === undefined) { - channel_id = "id" + message.channel.id; - } else { - channel_id = "id" + channel_id; - } - return channel_id; -} - -const is_first_instance = (message, instance_key, channel_id, reddit_URL) => { - if (does_default_instance_exist(message, instance_key, channel_id) === false) { - var default_instance_object = { - "instances": [ - ] - }; - default_instance_object.instances.push({ [channel_id]: reddit_URL }); - default_instance_object = JSON.stringify(default_instance_object); - message.guild.settings.set(instance_key, default_instance_object); - initializeInstance(message, reddit_URL); - message.reply(`First Reddit instance made!`); +const linksToImage = (link) => { + const IMG_EXTENSIONS = ['jpg', 'png', 'gif']; + const linkExtension = link.substr(link.length - 3); + if (IMG_EXTENSIONS.includes(linkExtension)) { + return true; + } + return false; +}; + +const refactorID = (message, channelID) => { + if (channelID === undefined) { + channelID = 'id' + message.channel.id; + } else { + channelID = 'id' + channelID; + } + return channelID; +}; + +const isFirstInstance = (message, instanceKey, channelID, redditURL) => { + if (doesDefaultInstanceExist(message, instanceKey, channelID) === false) { + let defaultInstanceObject = { + 'instances': [ + ], + }; + defaultInstanceObject.instances.push({[channelID]: redditURL}); + defaultInstanceObject = JSON.stringify(defaultInstanceObject); + message.guild.settings.set(instanceKey, defaultInstanceObject); + initializeInstance(message, redditURL); + message.reply(`First Reddit instance made!`); + return true; + } + return false; +}; + +const doesChannelExist = (message, instanceKey, channelID) => { + let keyValueExits = message.guild.settings.get(instanceKey, null); + keyValueExits = JSON.parse(keyValueExits); + if (keyValueExits !== null) { + for (const z in keyValueExits.instances) { + if (keyValueExits.instances[z][channelID] !== undefined) { + message.reply(`${channelID} was already found\nTry using "--edit" or "--stop`); return true; + } } - return false; -} - -const does_channel_exist = (message, instance_key, channel_id) => { - var key_value_exits = message.guild.settings.get(instance_key, null); - key_value_exits = JSON.parse(key_value_exits) - if (key_value_exits !== null) { - for (var z in key_value_exits.instances) { - if (key_value_exits.instances[z][channel_id] !== undefined) { - message.reply(`${channel_id} was already found\nTry using "--edit" or "--stop`); - return true; - } - } + } + return false; +}; + +const refactorLink = (link) => { + if (link.search('reddit.com/') == -1) { + if (link.search('/') == 0) { + link = 'https://www.reddit.com' + link; + } else { + link = 'https://www.reddit.com/' + link; } - return false; -} - -const refactor_link = (link) => { - if (link.search("reddit.com/") == -1) { - if (link.search("/") == 0) { - link = "https://www.reddit.com" + link; - } else { - link = "https://www.reddit.com/" + link; - } + } + const lastCharOfURL = link.charAt(link.length - 1); + switch (lastCharOfURL) { + case '/': + link += '.json'; + break; + default: + link += '/.json'; + break; + } + return link; +}; + +const validatedLink = async (message, link) => { + let errorGiven; + await request(link, async (error, response, html) => { + let jsonData; + try { + jsonData = await JSON.parse(html); + } catch (e) { + message.say('Sorry, this link did not work.'); + return false; } - const last_char_of_URL = link.charAt(link.length - 1); - switch (last_char_of_URL) { - case '/': - link += ".json" - break; - default: - link += "/.json" - break; + errorGiven = jsonData.error == '404' ? true : false; + + if (error) { + message.say('Sorry, this link did not work.'); + return false; + } else if (errorGiven == true) { + message.say('Sorry, this link did not work.'); + return false; } - return link; -} - -const validated_link = async (message, link) => { - var error_given; - await request(link, async (error, response, html) => { - var json_data; - try { - json_data = await JSON.parse(html) - } catch (e) { - message.say("Sorry, this link did not work."); - return false; - } - error_given = json_data.error == '404' ? true : false; - - if (error) { - message.say("Sorry, this link did not work."); - return false; - } else if (error_given == true) { - message.say("Sorry, this link did not work."); - return false; - } - }); - return true; -} + }); + return true; +}; -module.exports = DeployReddit; \ No newline at end of file +module.exports = DeployReddit; From 71f66f9bf14e4f24b5facd21e215f31822357c27 Mon Sep 17 00:00:00 2001 From: Carlos Date: Fri, 27 Sep 2019 11:37:19 -0400 Subject: [PATCH 50/63] Linted postreddit --- src/commands/admin/postreddit.js | 113 ++++++++++++++----------------- src/main.js | 28 ++++---- 2 files changed, 65 insertions(+), 76 deletions(-) diff --git a/src/commands/admin/postreddit.js b/src/commands/admin/postreddit.js index eff9de2..58056c9 100644 --- a/src/commands/admin/postreddit.js +++ b/src/commands/admin/postreddit.js @@ -1,76 +1,65 @@ const Discord = require('discord.js'); -const Commando = require('discord.js-commando'); const Logger = require('../../logging/Logger'); const request = require('request'); -var later = require('later'); - -class PostReddit extends Commando.Command { - /** @param {Commando.CommandoClient} client */ - constructor(client) { - super(client, { - description: 'Deploys the top img in any subreddit on bot startup', - guildOnly: true, - group: 'admin', - }); - } -} +const later = require('later'); async function initializeInstance(discordClient) { - if (discordClient !== undefined) { - const DAILY_POST_TIME = 'at 08:00am'; - const TESTING_POST_TIME = 'every 20 seconds'; - var sched = later.parse.text(TESTING_POST_TIME); + if (discordClient !== undefined) { + const DAILY_POST_TIME = 'at 08:00am'; + const TESTING_POST_TIME = 'every 20 seconds'; + const sched = later.parse.text(TESTING_POST_TIME); - later.date.localTime(); // time default is UTC | 4 hours ahead of FL + later.date.localTime(); // time default is UTC | 4 hours ahead of FL - var guild = discordClient.guilds.keyArray()[0]; - var instances = await discordClient.guilds.get(guild).settings.get("guild.reddit.instances") - instances = await JSON.parse(instances) - for (var index = 0; index < instances.instances.length; index++) { - for (x in instances.instances[index]) { - var channel_id = x; - var reddit_URL = instances.instances[index][x]; - await query_reddit(discordClient, reddit_URL, x); - //await later.setInterval(function () { query_reddit(reddit_URL, discordClient, channel_id) }, sched); - } - } + const guild = discordClient.guilds.keyArray()[0]; + let instances = await discordClient.guilds.get(guild).settings.get('guild.reddit.instances'); + instances = await JSON.parse(instances); + for (let index = 0; index < instances.instances.length; index++) { + for (x in instances.instances[index]) { + const channelID = x; + const redditURL = instances.instances[index][x]; + await queryReddit(discordClient, redditURL, x); + // await later.setInterval(function() { + // query_reddit(redditURL, discordClient, channelID); + // }, sched); + } } + } } -async function query_reddit(discordClient, reddit_URL, channel_id) { - await request(reddit_URL, (error, response, html) => { - if (!error && response.statusCode == 200) { - - const json_data = JSON.parse(html); - for (var index = 0; index < json_data.data.dist; index++) { - - if (json_data.data.children[index].data.post_hint == "image" || links_to_image(json_data.data.children[index].data.url)) { - if (discordClient !== null) { - const message_to_embed = new Discord.RichEmbed().setImage(json_data.data.children[index].data.url) - discordClient.channels.get("619024772898095115").send(message_to_embed).then(async function (reply) { - reply.channel.fetchMessage(reply.id).then(async function (message_retrieved) { - await message_retrieved.react('👍'); - await message_retrieved.react('👎'); - }); - }); - return; - } - } - - } +async function queryReddit(discordClient, redditURL, channelID) { + await request(redditURL, (error, response, html) => { + if (!error && response.statusCode == 200) { + const jsonData = JSON.parse(html); + for (let index = 0; index < jsonData.data.dist; index++) { + if (jsonData.data.children[index].data.post_hint == 'image' + || linksToImage(jsonData.data.children[index].data.url)) { + if (discordClient !== null) { + const messageToEmbed = new Discord.RichEmbed(); + messageToEmbed.setImage(jsonData.data.children[index].data.url); + const channel = discordClient.channels.get('619024772898095115'); + channel.send(messageToEmbed).then(async function(reply) { + reply.channel.fetchMessage(reply.id).then(async function(messageRetrieved) { + await messageRetrieved.react('👍'); + await messageRetrieved.react('👎'); + }); + }); + return; + } } - - }); - console.log("Reddit post made:", new Date()); -} - -const links_to_image = (link) => { - const IMG_EXTENSIONS = ['jpg', 'png', 'gif'] - const link_extension = link.substr(link.length - 3); - if (IMG_EXTENSIONS.includes(link_extension)) { - return true; + } } - return false; + }); + console.log('Reddit post made:', new Date()); } -module.exports = { initializeInstance: initializeInstance }; \ No newline at end of file +const linksToImage = (link) => { + const IMG_EXTENSIONS = ['jpg', 'png', 'gif']; + const linkExtension = link.substr(link.length - 3); + if (IMG_EXTENSIONS.includes(linkExtension)) { + return true; + } + return false; +}; + +module.exports = {initializeInstance: initializeInstance}; diff --git a/src/main.js b/src/main.js index 0b780b9..7bab18f 100644 --- a/src/main.js +++ b/src/main.js @@ -6,8 +6,8 @@ const Commando = require('discord.js-commando'); const Logger = require('./logging/Logger'); // Import logger for tracking bot progress. const addDiscordChannelLogger = require('./logging/addDiscordChannelLogger'); -const { setupSettingsProvider } = require('./settings/SettingsProvider'); -const { listenForRoleAssignmentMessages } = require('./events/setUserRoleOnReaction'); +const {setupSettingsProvider} = require('./settings/SettingsProvider'); +const {listenForRoleAssignmentMessages} = require('./events/setUserRoleOnReaction'); const loadEvents = require('./util/eventLoader'); // Import methods responsible for creating roles in servers as necessary. @@ -31,7 +31,7 @@ const discordClient = new Commando.CommandoClient({ * When you want to wait for something that takes time to finish before moving on, you place the * 'await' keyword in front of it to have the function wait for that to finish before continuing. */ -discordClient.on('ready', async function () { +discordClient.on('ready', async function() { addDiscordChannelLogger(discordClient); Logger.debug('FSEC Role Bot logged in as ' + discordClient.user.tag + '!'); @@ -64,17 +64,17 @@ discordClient.on('ready', async function () { * will be created. */ createServerRoles(discordClient); - //const message_to_embed = new Discord.RichEmbed().setImage('https://preview.redd.it/d3b8tswrbxn31.jpg?width=640&crop=smart&auto=webp&s=8133c0e5fae51db9bd9eaa583c1989a4d79e0ee7') - //message.embed(message_to_embed) - //discordClient.channels.get("619024772898095115") - discordClient.channels.get("619024772898095115").send("HAHAHA!") - //DeployReddit.initializeInstance(null, null, discordClient) - //.get("guild.reddit.instances", null); - var redditValue = discordClient - //var redditValue = message.guild.settings.get(messageArguments[0], null); - //console.log(discordClient.guilds.get("619024772415881240").settings.get("guild.reddit.instances")) - //discordClient.guilds.keyArray - initializeInstance(discordClient) + // const message_to_embed = new Discord.RichEmbed().setImage('https://preview.redd.it/d3b8tswrbxn31.jpg?width=640&crop=smart&auto=webp&s=8133c0e5fae51db9bd9eaa583c1989a4d79e0ee7') + // message.embed(message_to_embed) + // discordClient.channels.get("619024772898095115") + discordClient.channels.get('619024772898095115').send('HAHAHA!'); + // DeployReddit.initializeInstance(null, null, discordClient) + // .get("guild.reddit.instances", null); + // var redditValue = discordClient + // var redditValue = message.guild.settings.get(messageArguments[0], null); + // console.log(discordClient.guilds.get("619024772415881240").settings.get("guild.reddit.instances")) + // discordClient.guilds.keyArray + initializeInstance(discordClient); // discordClient.channels.get("619024772898095115").send(message_to_embed).then(async function (reply) { // //console.log(reply.id) // reply.channel.fetchMessage(reply.id).then(async function (message_retrieved) { From 5c9874fbe8d68ed08ddec08c9427bc01a8018a66 Mon Sep 17 00:00:00 2001 From: Carlos Date: Fri, 27 Sep 2019 14:44:37 -0400 Subject: [PATCH 51/63] link validation logic fixed --- src/commands/admin/deployreddit.js | 21 +++++++++++++++------ 1 file changed, 15 insertions(+), 6 deletions(-) diff --git a/src/commands/admin/deployreddit.js b/src/commands/admin/deployreddit.js index cfc1b04..0b63a23 100644 --- a/src/commands/admin/deployreddit.js +++ b/src/commands/admin/deployreddit.js @@ -67,6 +67,9 @@ class DeployReddit extends Commando.Command { let channelID = messageArguments[0]; const link = refactorLink(messageArguments[1]); + let temp = await validatedLink(message, link) + console.log(temp); + return; if (!validatedLink(message, link)) return; channelID = refactorID(message, channelID); @@ -286,26 +289,32 @@ const refactorLink = (link) => { }; const validatedLink = async (message, link) => { - let errorGiven; await request(link, async (error, response, html) => { + let errorGiven; let jsonData; try { jsonData = await JSON.parse(html); } catch (e) { - message.say('Sorry, this link did not work.'); + message.reply('Sorry, this link did not work.\nTry using a link like "r/programmerhumor" or "r/memes"'); + return false; + } + + try { + errorGiven = (jsonData.data.after == null) ? true : false; + } catch (e) { + message.reply('Sorry, this link did not work.\nTry using a link like "r/programmerhumor" or "r/memes"'); return false; } - errorGiven = jsonData.error == '404' ? true : false; if (error) { - message.say('Sorry, this link did not work.'); + message.reply('Sorry, this link did not work.\nTry using a link like "r/programmerhumor" or "r/memes"'); return false; } else if (errorGiven == true) { - message.say('Sorry, this link did not work.'); + message.reply('Sorry, this link did not work.\nTry using a link like "r/programmerhumor" or "r/memes"'); return false; } }); - return true; + return; }; module.exports = DeployReddit; From e5c01e84779b3b59a2573b0c1113116061520d3c Mon Sep 17 00:00:00 2001 From: Carlos Date: Fri, 27 Sep 2019 17:01:06 -0400 Subject: [PATCH 52/63] Added promised-based http requests --- package-lock.json | 29 +++++++++++++++++++++++++++++ package.json | 1 + src/commands/admin/deployreddit.js | 18 ++++++++---------- 3 files changed, 38 insertions(+), 10 deletions(-) diff --git a/package-lock.json b/package-lock.json index 29d7e11..92b01e3 100644 --- a/package-lock.json +++ b/package-lock.json @@ -185,6 +185,11 @@ "underscore": "~1.4.4" } }, + "bluebird": { + "version": "3.5.5", + "resolved": "https://registry.npmjs.org/bluebird/-/bluebird-3.5.5.tgz", + "integrity": "sha512-5am6HnnfN+urzt4yfg7IgTbotDjIT/u8AJpEt0sIU9FtXfVeezXAPKswrG+xKUCOYAINpSdgZVDU6QFh+cuH3w==" + }, "brace-expansion": { "version": "1.1.11", "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz", @@ -1458,6 +1463,25 @@ "uuid": "^3.3.2" } }, + "request-promise": { + "version": "4.2.4", + "resolved": "https://registry.npmjs.org/request-promise/-/request-promise-4.2.4.tgz", + "integrity": "sha512-8wgMrvE546PzbR5WbYxUQogUnUDfM0S7QIFZMID+J73vdFARkFy+HElj4T+MWYhpXwlLp0EQ8Zoj8xUA0he4Vg==", + "requires": { + "bluebird": "^3.5.0", + "request-promise-core": "1.1.2", + "stealthy-require": "^1.1.1", + "tough-cookie": "^2.3.3" + } + }, + "request-promise-core": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/request-promise-core/-/request-promise-core-1.1.2.tgz", + "integrity": "sha512-UHYyq1MO8GsefGEt7EprS8UrXsm1TxEvFUX1IMTuSLU2Rh7fTIdFtl8xD7JiEYiWU2dl+NYAjCTksTehQUxPag==", + "requires": { + "lodash": "^4.17.11" + } + }, "require-all": { "version": "2.2.0", "resolved": "https://registry.npmjs.org/require-all/-/require-all-2.2.0.tgz", @@ -1649,6 +1673,11 @@ "resolved": "https://registry.npmjs.org/stack-trace/-/stack-trace-0.0.10.tgz", "integrity": "sha1-VHxws0fo0ytOEI6hoqFZ5f3eGcA=" }, + "stealthy-require": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/stealthy-require/-/stealthy-require-1.1.1.tgz", + "integrity": "sha1-NbCYdbT/SfJqd35QmzCQoyJr8ks=" + }, "string-width": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/string-width/-/string-width-1.0.2.tgz", diff --git a/package.json b/package.json index e5ade48..6fbcdf3 100644 --- a/package.json +++ b/package.json @@ -27,6 +27,7 @@ "moment": "^2.22.2", "nedb": "^1.8.0", "request": "^2.88.0", + "request-promise": "^4.2.4", "sqlite": "^3.0.0", "sqlite3": "^4.0.4", "winston": "^3.1.0", diff --git a/src/commands/admin/deployreddit.js b/src/commands/admin/deployreddit.js index 0b63a23..ec9e997 100644 --- a/src/commands/admin/deployreddit.js +++ b/src/commands/admin/deployreddit.js @@ -1,6 +1,6 @@ const Commando = require('discord.js-commando'); const Logger = require('../../logging/Logger'); -const request = require('request'); +const request = require('request-promise'); const later = require('later'); class DeployReddit extends Commando.Command { @@ -32,7 +32,7 @@ class DeployReddit extends Commando.Command { const instanceKey = 'guild.reddit.instances'; const channelID = messageArguments[1]; const link = refactorLink(messageArguments[2]); - if (validatedLink(message, link)) { + if (await validatedLink(message, link)) { updateRedditFromKey(message, instanceKey, channelID, link); } } else { @@ -67,10 +67,7 @@ class DeployReddit extends Commando.Command { let channelID = messageArguments[0]; const link = refactorLink(messageArguments[1]); - let temp = await validatedLink(message, link) - console.log(temp); - return; - if (!validatedLink(message, link)) return; + if (validatedLink(message, link) != true) return; channelID = refactorID(message, channelID); @@ -289,11 +286,11 @@ const refactorLink = (link) => { }; const validatedLink = async (message, link) => { - await request(link, async (error, response, html) => { + await request(link, (error, response, html) => { let errorGiven; let jsonData; try { - jsonData = await JSON.parse(html); + jsonData = JSON.parse(html); } catch (e) { message.reply('Sorry, this link did not work.\nTry using a link like "r/programmerhumor" or "r/memes"'); return false; @@ -313,8 +310,9 @@ const validatedLink = async (message, link) => { message.reply('Sorry, this link did not work.\nTry using a link like "r/programmerhumor" or "r/memes"'); return false; } - }); - return; + return; + }) + return true; }; module.exports = DeployReddit; From e4da47dd709ae3c591550cf1683da59e9da40708 Mon Sep 17 00:00:00 2001 From: Carlos Date: Sun, 29 Sep 2019 13:37:06 -0400 Subject: [PATCH 53/63] Added comments and renamed file --- src/commands/admin/deployreddit.js | 75 +++++++++++++++++++----------- src/commands/admin/postreddit.js | 65 -------------------------- 2 files changed, 47 insertions(+), 93 deletions(-) delete mode 100644 src/commands/admin/postreddit.js diff --git a/src/commands/admin/deployreddit.js b/src/commands/admin/deployreddit.js index ec9e997..e984adb 100644 --- a/src/commands/admin/deployreddit.js +++ b/src/commands/admin/deployreddit.js @@ -3,6 +3,11 @@ const Logger = require('../../logging/Logger'); const request = require('request-promise'); const later = require('later'); +/** + * Sends an embedded message containing the most popular image on a given subreddit at + * a given time for a selected guild channel, daily. Offers C.R.U.D functionality for + * users to be able to manipulate their deployed instances. + */ class DeployReddit extends Commando.Command { constructor(client) { super(client, { @@ -45,7 +50,7 @@ class DeployReddit extends Commando.Command { const channelID = refactorID(message, messageArguments[1]); getValueOfReddit(message, instanceKey, channelID); } else { - // debugging + // debugging - remove following comments to enable debugging const instanceKey = 'guild.reddit.instances'; const instances = message.guild.settings.get(instanceKey, null); console.log(instances); @@ -54,7 +59,7 @@ class DeployReddit extends Commando.Command { } return; case '--removeall': - // debugging + // debugging - remove following comments to enable debugging const instanceKey = 'guild.reddit.instances'; const instances = message.guild.settings.get(instanceKey, null); console.log(instances); @@ -76,7 +81,7 @@ class DeployReddit extends Commando.Command { if (!isFirstInstance(message, instanceKey, channelID, link)) { setRedditFromKey(message, instanceKey, channelID, link); initializeInstance(message, link); - console.log(`${channelID} : ${link} has been added to Reddit instances.`); + console.log(`${channelID} : ${link} has been added to Reddit active instances.`); } return; } else { @@ -87,15 +92,22 @@ class DeployReddit extends Commando.Command { } } +/** + * Launches a Reddit instance upon first creation into + * specified channel + */ function initializeInstance(message, redditURL) { const DAILY_POST_TIME = 'at 08:00am'; const TESTING_POST_TIME = 'every 20 seconds'; const sched = later.parse.text(TESTING_POST_TIME); - later.date.localTime(); // time default is UTC | 4 hours ahead of FL + later.date.localTime(); // relative time default is UTC // query_reddit(message, redditURL); // later.setInterval(function () { query_reddit(message, redditURL); }, sched); } +/** + * @return undefined if channelID not found or DB not instantiated + */ function deleteRedditInstance(message, instanceKey, channelID) { channelID = refactorID(message, channelID); @@ -120,25 +132,26 @@ function deleteRedditInstance(message, instanceKey, channelID) { } } - message.reply(`${channelID} was not in instances.`); + message.reply(`${channelID} was not in active instances.`); return undefined; } +/** + * @return stringified JSON of instances if update successful + */ function updateRedditFromKey(message, instanceKey, channelID, redditURL) { channelID = refactorID(message, channelID); - - // Altering old value - let redditValue = message.guild.settings.get(instanceKey, null); - redditValue = JSON.parse(redditValue); - for (index in redditValue.instances) { - if (redditValue.instances[index][channelID] !== undefined) { - redditValue.instances[index][channelID] = redditURL; - redditValue = JSON.stringify(redditValue); - if (typeof redditValue === 'string') { + let instances = message.guild.settings.get(instanceKey, null); + instances = JSON.parse(instances); + for (index in instances.instances) { + if (instances.instances[index][channelID] !== undefined) { + instances.instances[index][channelID] = redditURL; + instances = JSON.stringify(instances); + if (typeof instances === 'string') { console.log('altering old val'); - message.guild.settings.set(instanceKey, redditValue); + message.guild.settings.set(instanceKey, instances); message.reply(`${instanceKey} was assigned ${redditURL}`); - return redditValue; + return instances; } break; } @@ -157,26 +170,29 @@ function setRedditFromKey(message, instanceKey, channelID, redditURL) { return; } +/** + * @return undefined if DB not found, null if ID not found, instances string + */ function getValueOfReddit(message, instanceKey, channelID) { - let redditValue = message.guild.settings.get(instanceKey, null); - if (redditValue == null) { + let instances = message.guild.settings.get(instanceKey, null); + if (instances == null) { message.reply(`${instanceKey} was not found`); return undefined; } - redditValue = JSON.parse(redditValue); - for (key in redditValue.instances) { - if (redditValue.instances[key][channelID] !== undefined) { - redditValue = redditValue.instances[key][channelID]; + instances = JSON.parse(instances); + for (key in instances.instances) { + if (instances.instances[key][channelID] !== undefined) { + instances = instances.instances[key][channelID]; break; } } - if (typeof redditValue !== 'string') { + if (typeof instances !== 'string') { message.reply(`The given ID for ${instanceKey} was not found`); return null; } else { - message.reply(`Value for ${channelID} is ${redditValue}`); - return redditValue; + message.reply(`Value for ${channelID} is ${instances}`); + return instances; } } @@ -191,6 +207,9 @@ function deleteAllInstances(message) { console.log('All instances deleted.'); } +/** + * Queries Reddit and sends embedded image + */ async function queryReddit(message, redditURL) { await request(redditURL, (error, response, html) => { if (!error && response.statusCode == 200) { @@ -214,7 +233,7 @@ async function queryReddit(message, redditURL) { } } }); - console.log('Reddit post made:', new Date()); + console.log('Reddit post deployed:', new Date()); } const linksToImage = (link) => { @@ -245,7 +264,7 @@ const isFirstInstance = (message, instanceKey, channelID, redditURL) => { defaultInstanceObject = JSON.stringify(defaultInstanceObject); message.guild.settings.set(instanceKey, defaultInstanceObject); initializeInstance(message, redditURL); - message.reply(`First Reddit instance made!`); + message.reply(`First Reddit instance has been deployed!`); return true; } return false; @@ -257,7 +276,7 @@ const doesChannelExist = (message, instanceKey, channelID) => { if (keyValueExits !== null) { for (const z in keyValueExits.instances) { if (keyValueExits.instances[z][channelID] !== undefined) { - message.reply(`${channelID} was already found\nTry using "--edit" or "--stop`); + message.reply(`${channelID} was already found in active instances\nTry using "--edit" or "--stop`); return true; } } diff --git a/src/commands/admin/postreddit.js b/src/commands/admin/postreddit.js deleted file mode 100644 index 58056c9..0000000 --- a/src/commands/admin/postreddit.js +++ /dev/null @@ -1,65 +0,0 @@ -const Discord = require('discord.js'); -const Logger = require('../../logging/Logger'); -const request = require('request'); -const later = require('later'); - -async function initializeInstance(discordClient) { - if (discordClient !== undefined) { - const DAILY_POST_TIME = 'at 08:00am'; - const TESTING_POST_TIME = 'every 20 seconds'; - const sched = later.parse.text(TESTING_POST_TIME); - - later.date.localTime(); // time default is UTC | 4 hours ahead of FL - - const guild = discordClient.guilds.keyArray()[0]; - let instances = await discordClient.guilds.get(guild).settings.get('guild.reddit.instances'); - instances = await JSON.parse(instances); - for (let index = 0; index < instances.instances.length; index++) { - for (x in instances.instances[index]) { - const channelID = x; - const redditURL = instances.instances[index][x]; - await queryReddit(discordClient, redditURL, x); - // await later.setInterval(function() { - // query_reddit(redditURL, discordClient, channelID); - // }, sched); - } - } - } -} - -async function queryReddit(discordClient, redditURL, channelID) { - await request(redditURL, (error, response, html) => { - if (!error && response.statusCode == 200) { - const jsonData = JSON.parse(html); - for (let index = 0; index < jsonData.data.dist; index++) { - if (jsonData.data.children[index].data.post_hint == 'image' - || linksToImage(jsonData.data.children[index].data.url)) { - if (discordClient !== null) { - const messageToEmbed = new Discord.RichEmbed(); - messageToEmbed.setImage(jsonData.data.children[index].data.url); - const channel = discordClient.channels.get('619024772898095115'); - channel.send(messageToEmbed).then(async function(reply) { - reply.channel.fetchMessage(reply.id).then(async function(messageRetrieved) { - await messageRetrieved.react('👍'); - await messageRetrieved.react('👎'); - }); - }); - return; - } - } - } - } - }); - console.log('Reddit post made:', new Date()); -} - -const linksToImage = (link) => { - const IMG_EXTENSIONS = ['jpg', 'png', 'gif']; - const linkExtension = link.substr(link.length - 3); - if (IMG_EXTENSIONS.includes(linkExtension)) { - return true; - } - return false; -}; - -module.exports = {initializeInstance: initializeInstance}; From 1e83a77cfffb6c640fecd77825713167bb63e715 Mon Sep 17 00:00:00 2001 From: Carlos Date: Sun, 29 Sep 2019 13:42:10 -0400 Subject: [PATCH 54/63] Renamed some variable names --- src/commands/admin/deployreddit.js | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/commands/admin/deployreddit.js b/src/commands/admin/deployreddit.js index e984adb..95399e8 100644 --- a/src/commands/admin/deployreddit.js +++ b/src/commands/admin/deployreddit.js @@ -99,10 +99,10 @@ class DeployReddit extends Commando.Command { function initializeInstance(message, redditURL) { const DAILY_POST_TIME = 'at 08:00am'; const TESTING_POST_TIME = 'every 20 seconds'; - const sched = later.parse.text(TESTING_POST_TIME); + const schedule = later.parse.text(TESTING_POST_TIME); later.date.localTime(); // relative time default is UTC // query_reddit(message, redditURL); - // later.setInterval(function () { query_reddit(message, redditURL); }, sched); + //later.setInterval(function () { query_reddit(message, redditURL); }, schedule); } /** @@ -197,8 +197,8 @@ function getValueOfReddit(message, instanceKey, channelID) { } function doesDefaultInstanceExist(message, instanceKey, channelID) { - const redditValue = message.guild.settings.get(instanceKey, null); - return (redditValue == null) ? false : true; + const instances = message.guild.settings.get(instanceKey, null); + return (instances == null) ? false : true; } function deleteAllInstances(message) { From 2a559b0ebfd06cc10cfd98a9e6cec5414d3b4fc6 Mon Sep 17 00:00:00 2001 From: Carlos Date: Sun, 29 Sep 2019 14:49:48 -0400 Subject: [PATCH 55/63] debugging channel acquisition --- src/commands/admin/deployreddit.js | 25 ++++++++++++++----------- src/main.js | 2 +- 2 files changed, 15 insertions(+), 12 deletions(-) diff --git a/src/commands/admin/deployreddit.js b/src/commands/admin/deployreddit.js index 95399e8..36b1239 100644 --- a/src/commands/admin/deployreddit.js +++ b/src/commands/admin/deployreddit.js @@ -11,7 +11,7 @@ const later = require('later'); class DeployReddit extends Commando.Command { constructor(client) { super(client, { - name: 'deployreddit', + name: 'dreddit', description: 'Deploys the top img in any subreddit every 24hrs', guildOnly: true, group: 'admin', @@ -51,18 +51,18 @@ class DeployReddit extends Commando.Command { getValueOfReddit(message, instanceKey, channelID); } else { // debugging - remove following comments to enable debugging - const instanceKey = 'guild.reddit.instances'; - const instances = message.guild.settings.get(instanceKey, null); - console.log(instances); + // const instanceKey = 'guild.reddit.instances'; + // const instances = message.guild.settings.get(instanceKey, null); + // console.log(instances); message.reply(`!!deployreddit --status \nGives information about the given channel with respect to reddit deployment.`); } return; case '--removeall': // debugging - remove following comments to enable debugging - const instanceKey = 'guild.reddit.instances'; - const instances = message.guild.settings.get(instanceKey, null); - console.log(instances); + // const instanceKey = 'guild.reddit.instances'; + // const instances = message.guild.settings.get(instanceKey, null); + // console.log(instances); deleteAllInstances(message); return; @@ -72,7 +72,7 @@ class DeployReddit extends Commando.Command { let channelID = messageArguments[0]; const link = refactorLink(messageArguments[1]); - if (validatedLink(message, link) != true) return; + if (await validatedLink(message, link) != true) return; channelID = refactorID(message, channelID); @@ -101,8 +101,8 @@ function initializeInstance(message, redditURL) { const TESTING_POST_TIME = 'every 20 seconds'; const schedule = later.parse.text(TESTING_POST_TIME); later.date.localTime(); // relative time default is UTC - // query_reddit(message, redditURL); - //later.setInterval(function () { query_reddit(message, redditURL); }, schedule); + queryReddit(message, redditURL); // one instant deployment + later.setInterval(function () { queryReddit(message, redditURL); }, schedule); } /** @@ -156,6 +156,8 @@ function updateRedditFromKey(message, instanceKey, channelID, redditURL) { break; } } + + message.reply(`${channelID} was not in active instances.`); return; } @@ -222,7 +224,8 @@ async function queryReddit(message, redditURL) { 'url': jsonData.data.children[index].data.url, }, }; - message.embed(imageToEmbed).then(async function(reply) { + const channel = message.guild.channels.get("619024772898095115"); + channel.embed(imageToEmbed).then(async function(reply) { reply.channel.fetchMessage(reply.id).then(async function(messageRetrieved) { await messageRetrieved.react('👍'); await messageRetrieved.react('👎'); diff --git a/src/main.js b/src/main.js index 7bab18f..c3ac86c 100644 --- a/src/main.js +++ b/src/main.js @@ -12,7 +12,7 @@ const loadEvents = require('./util/eventLoader'); // Import methods responsible for creating roles in servers as necessary. const createServerRoles = require('./events/createServerRoles').run; -const initializeInstance = require('./commands/admin/postreddit').initializeInstance; +const initializeInstance = require('./commands/admin/startupdeployreddit').initializeInstance; const discordClient = new Commando.CommandoClient({ owner: Settings.botOwners, From 950d65cd28098df4a71e43a7b71fd15d4c6e53e5 Mon Sep 17 00:00:00 2001 From: Carlos Date: Sun, 29 Sep 2019 15:53:38 -0400 Subject: [PATCH 56/63] Can now embed images from channel --- src/commands/admin/deployreddit.js | 25 +++++++++++++++---------- 1 file changed, 15 insertions(+), 10 deletions(-) diff --git a/src/commands/admin/deployreddit.js b/src/commands/admin/deployreddit.js index 36b1239..55ada73 100644 --- a/src/commands/admin/deployreddit.js +++ b/src/commands/admin/deployreddit.js @@ -80,7 +80,7 @@ class DeployReddit extends Commando.Command { if (!isFirstInstance(message, instanceKey, channelID, link)) { setRedditFromKey(message, instanceKey, channelID, link); - initializeInstance(message, link); + initializeInstance(message, link, channelID); console.log(`${channelID} : ${link} has been added to Reddit active instances.`); } return; @@ -96,13 +96,13 @@ class DeployReddit extends Commando.Command { * Launches a Reddit instance upon first creation into * specified channel */ -function initializeInstance(message, redditURL) { +function initializeInstance(message, redditURL, channelID) { const DAILY_POST_TIME = 'at 08:00am'; const TESTING_POST_TIME = 'every 20 seconds'; const schedule = later.parse.text(TESTING_POST_TIME); later.date.localTime(); // relative time default is UTC - queryReddit(message, redditURL); // one instant deployment - later.setInterval(function () { queryReddit(message, redditURL); }, schedule); + queryReddit(message, redditURL, channelID); // one instant deployment + later.setInterval(function () { queryReddit(message, redditURL, channelID); }, schedule); } /** @@ -212,8 +212,8 @@ function deleteAllInstances(message) { /** * Queries Reddit and sends embedded image */ -async function queryReddit(message, redditURL) { - await request(redditURL, (error, response, html) => { +async function queryReddit(message, redditURL, channelID) { + await request(redditURL, async (error, response, html) => { if (!error && response.statusCode == 200) { const jsonData = JSON.parse(html); for (let index = 0; index < jsonData.data.dist; index++) { @@ -224,8 +224,9 @@ async function queryReddit(message, redditURL) { 'url': jsonData.data.children[index].data.url, }, }; - const channel = message.guild.channels.get("619024772898095115"); - channel.embed(imageToEmbed).then(async function(reply) { + channelID = parseID(channelID); + const channel = await message.guild.channels.get(channelID); + channel.send({embed: imageToEmbed}).then(async function(reply) { reply.channel.fetchMessage(reply.id).then(async function(messageRetrieved) { await messageRetrieved.react('👍'); await messageRetrieved.react('👎'); @@ -236,7 +237,11 @@ async function queryReddit(message, redditURL) { } } }); - console.log('Reddit post deployed:', new Date()); + console.log('Reddit post deployed :', new Date()); +} + +const parseID = (channelID) => { + return channelID.substring(2); } const linksToImage = (link) => { @@ -266,7 +271,7 @@ const isFirstInstance = (message, instanceKey, channelID, redditURL) => { defaultInstanceObject.instances.push({[channelID]: redditURL}); defaultInstanceObject = JSON.stringify(defaultInstanceObject); message.guild.settings.set(instanceKey, defaultInstanceObject); - initializeInstance(message, redditURL); + initializeInstance(message, redditURL, channelID); message.reply(`First Reddit instance has been deployed!`); return true; } From ffa1fe10b008f5e7c67c89c8e9daf8c8ce85ff30 Mon Sep 17 00:00:00 2001 From: Carlos Date: Sun, 29 Sep 2019 16:43:18 -0400 Subject: [PATCH 57/63] Added renamed file --- src/commands/admin/startupdeployreddit.js | 79 +++++++++++++++++++++++ 1 file changed, 79 insertions(+) create mode 100644 src/commands/admin/startupdeployreddit.js diff --git a/src/commands/admin/startupdeployreddit.js b/src/commands/admin/startupdeployreddit.js new file mode 100644 index 0000000..e874a6c --- /dev/null +++ b/src/commands/admin/startupdeployreddit.js @@ -0,0 +1,79 @@ +const Discord = require('discord.js'); +const Logger = require('../../logging/Logger'); +const request = require('request-promise'); +const later = require('later'); + +/** + * Launches Reddit instances into every channel listed under a guild's + * active instances in the settings DB upon bot start up. + */ +async function initializeInstance(discordClient) { + if (discordClient !== undefined) { + const DAILY_POST_TIME = 'at 08:00am'; + const TESTING_POST_TIME = 'every 20 seconds'; + const schedule = later.parse.text(TESTING_POST_TIME); + + later.date.localTime(); // time default is UTC + + const guild = discordClient.guilds.keyArray()[0]; + let instances = await discordClient.guilds.get(guild).settings.get('guild.reddit.instances'); + instances = await JSON.parse(instances); + for (let index = 0; index < instances.instances.length; index++) { + for (x in instances.instances[index]) { + const channelID = x; + const redditURL = instances.instances[index][x]; + //await queryReddit(discordClient, redditURL, x); // debugging - instant reply + await later.setInterval(function() { + queryReddit(discordClient, redditURL, channelID); + }, schedule); + } + } + } +} + +/** + * Queries Reddit and sends embedded image + */ +async function queryReddit(discordClient, redditURL, channelID) { + await request(redditURL, (error, response, html) => { + if (!error && response.statusCode == 200) { + const jsonData = JSON.parse(html); + for (let index = 0; index < jsonData.data.dist; index++) { + if (jsonData.data.children[index].data.post_hint == 'image' + || linksToImage(jsonData.data.children[index].data.url)) { + if (discordClient !== null) { + const messageToEmbed = new Discord.RichEmbed(); + messageToEmbed.setImage(jsonData.data.children[index].data.url); + channelID = parseID(channelID); + //const channel = discordClient.channels.get('619024772898095115'); // debugging - all posted on specified channel + const channel = discordClient.channels.get(channelID); + channel.send(messageToEmbed).then(async function(reply) { + reply.channel.fetchMessage(reply.id).then(async function(messageRetrieved) { + await messageRetrieved.react('👍'); + await messageRetrieved.react('👎'); + }); + }); + return; + } + } + } + } + console.log(error) + }); + console.log(`Reddit post made from ${channelID} :`, new Date()); +} + +const parseID = (channelID) => { + return channelID.substring(2); +} + +const linksToImage = (link) => { + const IMG_EXTENSIONS = ['jpg', 'png', 'gif']; + const linkExtension = link.substr(link.length - 3); + if (IMG_EXTENSIONS.includes(linkExtension)) { + return true; + } + return false; +}; + +module.exports = {initializeInstance: initializeInstance}; From c626866d337a216c23edc3ab35b2f543a0811f54 Mon Sep 17 00:00:00 2001 From: Carlos Date: Sun, 29 Sep 2019 17:04:25 -0400 Subject: [PATCH 58/63] Edit now works with channel --- src/commands/admin/deployreddit.js | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/src/commands/admin/deployreddit.js b/src/commands/admin/deployreddit.js index 55ada73..31ad4a3 100644 --- a/src/commands/admin/deployreddit.js +++ b/src/commands/admin/deployreddit.js @@ -101,8 +101,8 @@ function initializeInstance(message, redditURL, channelID) { const TESTING_POST_TIME = 'every 20 seconds'; const schedule = later.parse.text(TESTING_POST_TIME); later.date.localTime(); // relative time default is UTC - queryReddit(message, redditURL, channelID); // one instant deployment - later.setInterval(function () { queryReddit(message, redditURL, channelID); }, schedule); + queryReddit(message, channelID); // one instant deployment + later.setInterval(function () { queryReddit(message, channelID); }, schedule); } /** @@ -212,7 +212,11 @@ function deleteAllInstances(message) { /** * Queries Reddit and sends embedded image */ -async function queryReddit(message, redditURL, channelID) { +async function queryReddit(message, channelID) { + const instanceKey = 'guild.reddit.instances'; + let instances = await message.guild.settings.get(instanceKey, null); + instances = await JSON.parse(instances); + const redditURL = instances.instances[0][channelID]; await request(redditURL, async (error, response, html) => { if (!error && response.statusCode == 200) { const jsonData = JSON.parse(html); From f2cdef321bcfe20dff5e42a5c6eb3ebfd6dc366e Mon Sep 17 00:00:00 2001 From: Carlos Date: Sun, 29 Sep 2019 17:42:12 -0400 Subject: [PATCH 59/63] startup and dreddit both query before deployment --- src/commands/admin/deployreddit.js | 13 ++++++++++--- src/commands/admin/startupdeployreddit.js | 16 +++++++++++++--- 2 files changed, 23 insertions(+), 6 deletions(-) diff --git a/src/commands/admin/deployreddit.js b/src/commands/admin/deployreddit.js index 31ad4a3..0ce6b5f 100644 --- a/src/commands/admin/deployreddit.js +++ b/src/commands/admin/deployreddit.js @@ -213,10 +213,17 @@ function deleteAllInstances(message) { * Queries Reddit and sends embedded image */ async function queryReddit(message, channelID) { + + let redditURL; const instanceKey = 'guild.reddit.instances'; - let instances = await message.guild.settings.get(instanceKey, null); - instances = await JSON.parse(instances); - const redditURL = instances.instances[0][channelID]; + let instances = message.guild.settings.get(instanceKey, null); + instances = JSON.parse(instances); + for (index in instances.instances) { + if (instances.instances[index][channelID] !== undefined) { + redditURL = instances.instances[index][channelID]; + } + } + await request(redditURL, async (error, response, html) => { if (!error && response.statusCode == 200) { const jsonData = JSON.parse(html); diff --git a/src/commands/admin/startupdeployreddit.js b/src/commands/admin/startupdeployreddit.js index e874a6c..f309c9b 100644 --- a/src/commands/admin/startupdeployreddit.js +++ b/src/commands/admin/startupdeployreddit.js @@ -21,10 +21,9 @@ async function initializeInstance(discordClient) { for (let index = 0; index < instances.instances.length; index++) { for (x in instances.instances[index]) { const channelID = x; - const redditURL = instances.instances[index][x]; //await queryReddit(discordClient, redditURL, x); // debugging - instant reply await later.setInterval(function() { - queryReddit(discordClient, redditURL, channelID); + queryReddit(discordClient, channelID); }, schedule); } } @@ -34,7 +33,18 @@ async function initializeInstance(discordClient) { /** * Queries Reddit and sends embedded image */ -async function queryReddit(discordClient, redditURL, channelID) { +async function queryReddit(discordClient, channelID) { + + let redditURL; + const guild = discordClient.guilds.keyArray()[0]; + let instances = await discordClient.guilds.get(guild).settings.get('guild.reddit.instances'); + instances = await JSON.parse(instances); + for (index in instances.instances) { + if (instances.instances[index][channelID] !== undefined) { + redditURL = instances.instances[index][channelID]; + } + } + await request(redditURL, (error, response, html) => { if (!error && response.statusCode == 200) { const jsonData = JSON.parse(html); From 3712599929d980ff8ec63c5eec0080886472b7fa Mon Sep 17 00:00:00 2001 From: Carlos Date: Sun, 29 Sep 2019 18:19:10 -0400 Subject: [PATCH 60/63] Cleaned console output --- src/commands/admin/deployreddit.js | 5 ++++- src/commands/admin/startupdeployreddit.js | 6 ++++-- 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/src/commands/admin/deployreddit.js b/src/commands/admin/deployreddit.js index 0ce6b5f..9d07a45 100644 --- a/src/commands/admin/deployreddit.js +++ b/src/commands/admin/deployreddit.js @@ -213,7 +213,7 @@ function deleteAllInstances(message) { * Queries Reddit and sends embedded image */ async function queryReddit(message, channelID) { - +try { let redditURL; const instanceKey = 'guild.reddit.instances'; let instances = message.guild.settings.get(instanceKey, null); @@ -249,6 +249,9 @@ async function queryReddit(message, channelID) { } }); console.log('Reddit post deployed :', new Date()); +} catch(e) { + return; +} } const parseID = (channelID) => { diff --git a/src/commands/admin/startupdeployreddit.js b/src/commands/admin/startupdeployreddit.js index f309c9b..c650d86 100644 --- a/src/commands/admin/startupdeployreddit.js +++ b/src/commands/admin/startupdeployreddit.js @@ -34,7 +34,7 @@ async function initializeInstance(discordClient) { * Queries Reddit and sends embedded image */ async function queryReddit(discordClient, channelID) { - + try { let redditURL; const guild = discordClient.guilds.keyArray()[0]; let instances = await discordClient.guilds.get(guild).settings.get('guild.reddit.instances'); @@ -68,9 +68,11 @@ async function queryReddit(discordClient, channelID) { } } } - console.log(error) }); console.log(`Reddit post made from ${channelID} :`, new Date()); +} catch(e) { + return; +} } const parseID = (channelID) => { From adad59b2758d253c427ccb936d4e0282015c8b38 Mon Sep 17 00:00:00 2001 From: Carlos Date: Sun, 29 Sep 2019 18:32:09 -0400 Subject: [PATCH 61/63] Linted --- src/commands/admin/deployreddit.js | 83 ++++++++++++----------- src/commands/admin/startupdeployreddit.js | 74 ++++++++++---------- src/main.js | 24 ++----- 3 files changed, 85 insertions(+), 96 deletions(-) diff --git a/src/commands/admin/deployreddit.js b/src/commands/admin/deployreddit.js index 9d07a45..1dafb17 100644 --- a/src/commands/admin/deployreddit.js +++ b/src/commands/admin/deployreddit.js @@ -1,11 +1,10 @@ const Commando = require('discord.js-commando'); -const Logger = require('../../logging/Logger'); const request = require('request-promise'); const later = require('later'); /** * Sends an embedded message containing the most popular image on a given subreddit at - * a given time for a selected guild channel, daily. Offers C.R.U.D functionality for + * a given time for a selected guild channel, daily. Offers C.R.U.D functionality for * users to be able to manipulate their deployed instances. */ class DeployReddit extends Commando.Command { @@ -98,11 +97,13 @@ class DeployReddit extends Commando.Command { */ function initializeInstance(message, redditURL, channelID) { const DAILY_POST_TIME = 'at 08:00am'; - const TESTING_POST_TIME = 'every 20 seconds'; - const schedule = later.parse.text(TESTING_POST_TIME); + // const TESTING_POST_TIME = 'every 20 seconds'; + const schedule = later.parse.text(DAILY_POST_TIME); later.date.localTime(); // relative time default is UTC queryReddit(message, channelID); // one instant deployment - later.setInterval(function () { queryReddit(message, channelID); }, schedule); + later.setInterval(function() { + queryReddit(message, channelID); + }, schedule); } /** @@ -213,50 +214,50 @@ function deleteAllInstances(message) { * Queries Reddit and sends embedded image */ async function queryReddit(message, channelID) { -try { - let redditURL; - const instanceKey = 'guild.reddit.instances'; - let instances = message.guild.settings.get(instanceKey, null); - instances = JSON.parse(instances); - for (index in instances.instances) { - if (instances.instances[index][channelID] !== undefined) { - redditURL = instances.instances[index][channelID]; + try { + let redditURL; + const instanceKey = 'guild.reddit.instances'; + let instances = message.guild.settings.get(instanceKey, null); + instances = JSON.parse(instances); + for (index in instances.instances) { + if (instances.instances[index][channelID] !== undefined) { + redditURL = instances.instances[index][channelID]; + } } - } - await request(redditURL, async (error, response, html) => { - if (!error && response.statusCode == 200) { - const jsonData = JSON.parse(html); - for (let index = 0; index < jsonData.data.dist; index++) { - if (jsonData.data.children[index].data.post_hint == 'image' + await request(redditURL, async (error, response, html) => { + if (!error && response.statusCode == 200) { + const jsonData = JSON.parse(html); + for (let index = 0; index < jsonData.data.dist; index++) { + if (jsonData.data.children[index].data.post_hint == 'image' || linksToImage(jsonData.data.children[index].data.url)) { - const imageToEmbed = { - 'image': { - 'url': jsonData.data.children[index].data.url, - }, - }; - channelID = parseID(channelID); - const channel = await message.guild.channels.get(channelID); - channel.send({embed: imageToEmbed}).then(async function(reply) { - reply.channel.fetchMessage(reply.id).then(async function(messageRetrieved) { - await messageRetrieved.react('👍'); - await messageRetrieved.react('👎'); + const imageToEmbed = { + 'image': { + 'url': jsonData.data.children[index].data.url, + }, + }; + channelID = parseID(channelID); + const channel = await message.guild.channels.get(channelID); + channel.send({embed: imageToEmbed}).then(async function(reply) { + reply.channel.fetchMessage(reply.id).then(async function(messageRetrieved) { + await messageRetrieved.react('👍'); + await messageRetrieved.react('👎'); + }); }); - }); - return; + return; + } } } - } - }); - console.log('Reddit post deployed :', new Date()); -} catch(e) { - return; -} + }); + console.log('Reddit post deployed :', new Date()); + } catch (e) { + return; + } } const parseID = (channelID) => { return channelID.substring(2); -} +}; const linksToImage = (link) => { const IMG_EXTENSIONS = ['jpg', 'png', 'gif']; @@ -338,7 +339,7 @@ const validatedLink = async (message, link) => { } try { - errorGiven = (jsonData.data.after == null) ? true : false; + errorGiven = (jsonData.data.after == null) ? true : false; } catch (e) { message.reply('Sorry, this link did not work.\nTry using a link like "r/programmerhumor" or "r/memes"'); return false; @@ -352,7 +353,7 @@ const validatedLink = async (message, link) => { return false; } return; - }) + }); return true; }; diff --git a/src/commands/admin/startupdeployreddit.js b/src/commands/admin/startupdeployreddit.js index c650d86..81d6bde 100644 --- a/src/commands/admin/startupdeployreddit.js +++ b/src/commands/admin/startupdeployreddit.js @@ -1,5 +1,4 @@ const Discord = require('discord.js'); -const Logger = require('../../logging/Logger'); const request = require('request-promise'); const later = require('later'); @@ -10,8 +9,8 @@ const later = require('later'); async function initializeInstance(discordClient) { if (discordClient !== undefined) { const DAILY_POST_TIME = 'at 08:00am'; - const TESTING_POST_TIME = 'every 20 seconds'; - const schedule = later.parse.text(TESTING_POST_TIME); + // const TESTING_POST_TIME = 'every 20 seconds'; + const schedule = later.parse.text(DAILY_POST_TIME); later.date.localTime(); // time default is UTC @@ -21,9 +20,9 @@ async function initializeInstance(discordClient) { for (let index = 0; index < instances.instances.length; index++) { for (x in instances.instances[index]) { const channelID = x; - //await queryReddit(discordClient, redditURL, x); // debugging - instant reply + // await queryReddit(discordClient, redditURL, x); // debugging - instant reply await later.setInterval(function() { - queryReddit(discordClient, channelID); + queryReddit(discordClient, channelID); }, schedule); } } @@ -35,49 +34,50 @@ async function initializeInstance(discordClient) { */ async function queryReddit(discordClient, channelID) { try { - let redditURL; - const guild = discordClient.guilds.keyArray()[0]; - let instances = await discordClient.guilds.get(guild).settings.get('guild.reddit.instances'); - instances = await JSON.parse(instances); - for (index in instances.instances) { - if (instances.instances[index][channelID] !== undefined) { - redditURL = instances.instances[index][channelID]; + let redditURL; + const guild = discordClient.guilds.keyArray()[0]; + let instances = await discordClient.guilds.get(guild).settings.get('guild.reddit.instances'); + instances = await JSON.parse(instances); + for (index in instances.instances) { + if (instances.instances[index][channelID] !== undefined) { + redditURL = instances.instances[index][channelID]; + } } - } - await request(redditURL, (error, response, html) => { - if (!error && response.statusCode == 200) { - const jsonData = JSON.parse(html); - for (let index = 0; index < jsonData.data.dist; index++) { - if (jsonData.data.children[index].data.post_hint == 'image' + await request(redditURL, (error, response, html) => { + if (!error && response.statusCode == 200) { + const jsonData = JSON.parse(html); + for (let index = 0; index < jsonData.data.dist; index++) { + if (jsonData.data.children[index].data.post_hint == 'image' || linksToImage(jsonData.data.children[index].data.url)) { - if (discordClient !== null) { - const messageToEmbed = new Discord.RichEmbed(); - messageToEmbed.setImage(jsonData.data.children[index].data.url); - channelID = parseID(channelID); - //const channel = discordClient.channels.get('619024772898095115'); // debugging - all posted on specified channel - const channel = discordClient.channels.get(channelID); - channel.send(messageToEmbed).then(async function(reply) { - reply.channel.fetchMessage(reply.id).then(async function(messageRetrieved) { - await messageRetrieved.react('👍'); - await messageRetrieved.react('👎'); + if (discordClient !== null) { + const messageToEmbed = new Discord.RichEmbed(); + messageToEmbed.setImage(jsonData.data.children[index].data.url); + channelID = parseID(channelID); + // debugging - line below results in all posts on one channel + // const channel = discordClient.channels.get('619024772898095115'); + const channel = discordClient.channels.get(channelID); + channel.send(messageToEmbed).then(async function(reply) { + reply.channel.fetchMessage(reply.id).then(async function(messageRetrieved) { + await messageRetrieved.react('👍'); + await messageRetrieved.react('👎'); + }); }); - }); - return; + return; + } } } } - } - }); - console.log(`Reddit post made from ${channelID} :`, new Date()); -} catch(e) { - return; -} + }); + console.log(`Reddit post made from ${channelID} :`, new Date()); + } catch (e) { + return; + } } const parseID = (channelID) => { return channelID.substring(2); -} +}; const linksToImage = (link) => { const IMG_EXTENSIONS = ['jpg', 'png', 'gif']; diff --git a/src/main.js b/src/main.js index c3ac86c..4a47422 100644 --- a/src/main.js +++ b/src/main.js @@ -60,28 +60,16 @@ discordClient.on('ready', async function() { }); /** - * Create server roles if necessary. Any roles that aren't in the server that are in settings + * Creates server roles if necessary. Any roles that aren't in the server that are in settings * will be created. */ createServerRoles(discordClient); - // const message_to_embed = new Discord.RichEmbed().setImage('https://preview.redd.it/d3b8tswrbxn31.jpg?width=640&crop=smart&auto=webp&s=8133c0e5fae51db9bd9eaa583c1989a4d79e0ee7') - // message.embed(message_to_embed) - // discordClient.channels.get("619024772898095115") - discordClient.channels.get('619024772898095115').send('HAHAHA!'); - // DeployReddit.initializeInstance(null, null, discordClient) - // .get("guild.reddit.instances", null); - // var redditValue = discordClient - // var redditValue = message.guild.settings.get(messageArguments[0], null); - // console.log(discordClient.guilds.get("619024772415881240").settings.get("guild.reddit.instances")) - // discordClient.guilds.keyArray + + /** + * Creates instances of all of the channel and URL pairsin reddit instances + * within the settings db + */ initializeInstance(discordClient); - // discordClient.channels.get("619024772898095115").send(message_to_embed).then(async function (reply) { - // //console.log(reply.id) - // reply.channel.fetchMessage(reply.id).then(async function (message_retrieved) { - // await message_retrieved.react('👍'); - // await message_retrieved.react('👎'); - // }); - // }); }); discordClient.registry.registerGroups([ From 2fd41b774ef3857701c8a164b5df3ac9d0d9b0ab Mon Sep 17 00:00:00 2001 From: Carlos Date: Tue, 1 Oct 2019 20:33:18 -0400 Subject: [PATCH 62/63] Added permissions, changed helper messages --- src/commands/admin/deployreddit.js | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/src/commands/admin/deployreddit.js b/src/commands/admin/deployreddit.js index 1dafb17..5776234 100644 --- a/src/commands/admin/deployreddit.js +++ b/src/commands/admin/deployreddit.js @@ -18,6 +18,12 @@ class DeployReddit extends Commando.Command { }); } + hasPermission(message) { + // Use officer role. + const isUserAnOfficer = message.member.roles.find((role) => role.name === 'Club Officers'); + return !!isUserAnOfficer || message.member.permissions.has('ADMINISTRATOR'); + } + async run(message, args) { const messageArguments = args.split(' '); @@ -28,7 +34,7 @@ class DeployReddit extends Commando.Command { const channelID = messageArguments[1]; deleteRedditInstance(message, instanceKey, channelID); } else { - message.reply(`!!deployreddit --stop \nStops the execution of the reddit deployment in the specified channel.`); + message.reply(`!!dreddit --stop \nStops the execution of the reddit deployment in the specified channel.`); } return; case '--edit': @@ -40,7 +46,7 @@ class DeployReddit extends Commando.Command { updateRedditFromKey(message, instanceKey, channelID, link); } } else { - message.reply(`!!deployreddit --edit \nChanges the given URL of a channel.`); + message.reply(`!!dreddit --edit \nChanges the given URL of a channel.`); } return; case '--status': @@ -54,7 +60,7 @@ class DeployReddit extends Commando.Command { // const instances = message.guild.settings.get(instanceKey, null); // console.log(instances); - message.reply(`!!deployreddit --status \nGives information about the given channel with respect to reddit deployment.`); + message.reply(`!!dreddit --status \nGives information about the given channel with respect to reddit deployment.`); } return; case '--removeall': @@ -84,7 +90,7 @@ class DeployReddit extends Commando.Command { } return; } else { - message.reply(`!!deployreddit \nAdds a reddit instance to a given channel.`); + message.reply(`!!dreddit \nAdds a reddit instance to a given channel.`); } return; } @@ -115,7 +121,7 @@ function deleteRedditInstance(message, instanceKey, channelID) { let instances = message.guild.settings.get(instanceKey, null); if (instances == null) { - message.reply(`${instanceKey} was not found.\nTry creating a new instance using "!!deployreddit "`); + message.reply(`${instanceKey} was not found.\nTry creating a new instance using "!!dreddit "`); return undefined; } From ec570634a567a5c080c359c199a7b34df601dd1f Mon Sep 17 00:00:00 2001 From: Carlos Date: Mon, 21 Oct 2019 10:40:23 -0400 Subject: [PATCH 63/63] Starts up all bot guild instances upon reset --- src/commands/admin/startupdeployreddit.js | 30 ++++++++++++----------- 1 file changed, 16 insertions(+), 14 deletions(-) diff --git a/src/commands/admin/startupdeployreddit.js b/src/commands/admin/startupdeployreddit.js index 81d6bde..d9987c8 100644 --- a/src/commands/admin/startupdeployreddit.js +++ b/src/commands/admin/startupdeployreddit.js @@ -14,16 +14,18 @@ async function initializeInstance(discordClient) { later.date.localTime(); // time default is UTC - const guild = discordClient.guilds.keyArray()[0]; - let instances = await discordClient.guilds.get(guild).settings.get('guild.reddit.instances'); - instances = await JSON.parse(instances); - for (let index = 0; index < instances.instances.length; index++) { - for (x in instances.instances[index]) { - const channelID = x; - // await queryReddit(discordClient, redditURL, x); // debugging - instant reply - await later.setInterval(function() { - queryReddit(discordClient, channelID); - }, schedule); + for (const guildIndex in discordClient.guilds.keyArray()) { + guild = discordClient.guilds.keyArray()[guildIndex]; + let instances = discordClient.guilds.get(guild).settings.get('guild.reddit.instances'); + instances = JSON.parse(instances); + for (let index = 0; index < instances.instances.length; index++) { + for (x in instances.instances[index]) { + const channelID = x; + // await queryReddit(discordClient, redditURL, x); // debugging - instant reply + await later.setInterval(function () { + queryReddit(discordClient, channelID); + }, schedule); + } } } } @@ -49,7 +51,7 @@ async function queryReddit(discordClient, channelID) { const jsonData = JSON.parse(html); for (let index = 0; index < jsonData.data.dist; index++) { if (jsonData.data.children[index].data.post_hint == 'image' - || linksToImage(jsonData.data.children[index].data.url)) { + || linksToImage(jsonData.data.children[index].data.url)) { if (discordClient !== null) { const messageToEmbed = new Discord.RichEmbed(); messageToEmbed.setImage(jsonData.data.children[index].data.url); @@ -57,8 +59,8 @@ async function queryReddit(discordClient, channelID) { // debugging - line below results in all posts on one channel // const channel = discordClient.channels.get('619024772898095115'); const channel = discordClient.channels.get(channelID); - channel.send(messageToEmbed).then(async function(reply) { - reply.channel.fetchMessage(reply.id).then(async function(messageRetrieved) { + channel.send(messageToEmbed).then(async function (reply) { + reply.channel.fetchMessage(reply.id).then(async function (messageRetrieved) { await messageRetrieved.react('👍'); await messageRetrieved.react('👎'); }); @@ -88,4 +90,4 @@ const linksToImage = (link) => { return false; }; -module.exports = {initializeInstance: initializeInstance}; +module.exports = { initializeInstance: initializeInstance };