[Reddit] Modmail++

Additional tools and information to Reddit's Modmail

目前为 2021-11-23 提交的版本。查看 最新版本

  1. // ==UserScript==
  2. // @name [Reddit] Modmail++
  3. // @namespace HKR
  4. // @match https://mod.reddit.com/mail/*
  5. // @grant none
  6. // @version 2.1
  7. // @author HKR
  8. // @description Additional tools and information to Reddit's Modmail
  9. // @icon https://www.redditstatic.com/modmail/favicon/favicon-32x32.png
  10. // @supportURL https://github.com/Hakorr/Userscripts/issues
  11. // ==/UserScript==
  12.  
  13. console.log("[Modmail++] %cScript started!", "color: green");
  14.  
  15. /* Do not touch */
  16. const $ = document.querySelector.bind(document);
  17. const $$ = document.querySelectorAll.bind(document);
  18. var first = false;
  19. /* Do not touch */
  20.  
  21. function main() {
  22. console.log("[Modmail++] %cMain function ran!", "color: grey");
  23.  
  24. /* SETTINGS */
  25.  
  26. //Variables for the responses
  27. const subTag = $(".ThreadTitle__community").href.slice(23); //Format r/subreddit
  28. const userTag = "u/" + $(".InfoBar__username").innerText; //Format u/username
  29. const modmail = `[modmail](https://www.reddit.com/message/compose?to=/${subTag})`;
  30. const rules = `https://www.reddit.com/${subTag}/about/rules`;
  31. const randItem = itemArr => itemArr[Math.floor(Math.random() * itemArr.length)];
  32.  
  33. //Text color settings
  34. var textColor = null, lightModeTextColor = "#6e6e6e", darkModeTextColor = "#757575";
  35.  
  36. //Title color settings
  37. var titleColor = null, lightModeTitleColor = "#2c2c2c", darkModeTitleColor = "#a7a7a7";
  38.  
  39. //Listbox color settings
  40. var listBoxColor = null, lightModeListColor = "#fff", darkModeListColor = "#242424";
  41.  
  42. //Data (Such as numbers) color settings
  43. const dataColor = "#0079d3";
  44.  
  45. //No response list is created if false
  46. const enableCustomResponses = true;
  47.  
  48. //No chat profile icons are added if false
  49. const chatProfileIcons = true;
  50.  
  51. const placeholderMessage = randItem([
  52. "Message...",
  53. "Look, a bird! Message...",
  54. "What have you been up to today? Message...",
  55. "Beautiful day, isn't it? Message...",
  56. "Was the weather nice? Message...",
  57. "You look good today! Message...",
  58. "What dreams did you see last night? Message...",
  59. "What did you do today? Message...",
  60. "ヽ(o`皿′o)ノ AAAAAAAaaahh, spooked you! Message...",
  61. "What did you eat today? Message...",
  62. "Have you drank enough water? Message...",
  63. "Remember to stretch! Message...",
  64. "≖‿≖ I live inside of your walls. Message...",
  65. "(✿◠‿◠) Message...",
  66. "ಠ╭╮ಠ This modmail isn't going to get a reply just by itself, get back to work! Message..."
  67. ]);
  68.  
  69. //Feel free to edit and add more responses suitable for you! Replace means if to replace all text or just to add the text.
  70. const responses = [
  71. {
  72. "name":"Select a template",
  73. "replace":true,
  74. "content":``
  75. },
  76. {
  77. "name":"Default Approved",
  78. "replace":true,
  79. "content":`Hey, approved the post!`
  80. },
  81. {
  82. "name":"Default Rule Broken",
  83. "replace":true,
  84. "content":`Your post broke our [rules](${rules}).\n\nThe action will not be reverted.`
  85. },
  86. {
  87. "name":"Add Greetings",
  88. "replace":false,
  89. "content":`${randItem(["Greetings","Hello","Hi"])} ${userTag},\n\n`
  90. },
  91. {
  92. "name":"Add Thanks",
  93. "replace":false,
  94. "content":`\n\nThank you!`
  95. },
  96. {
  97. "name":"Add Subreddit Mention",
  98. "replace":false,
  99. "content":`${subTag}`
  100. },
  101. {
  102. "name":"Add User Mention",
  103. "replace":false,
  104. "content":`${userTag}`
  105. },
  106. {
  107. "name":"Add Modmail Link",
  108. "replace":false,
  109. "content":`${modmail}`
  110. },
  111. {
  112. "name":"Add Karma Link",
  113. "replace":false,
  114. "content":`[karma](https://reddit.zendesk.com/hc/en-us/articles/204511829-What-is-karma-)`
  115. },
  116. {
  117. "name":"Add Content Policy",
  118. "replace":false,
  119. "content":`[Content Policy](https://www.redditinc.com/policies/content-policy)`
  120. },
  121. {
  122. "name":"Add User Agreement",
  123. "replace":false,
  124. "content":`[User Agreement](https://www.redditinc.com/policies/user-agreement)`
  125. },
  126. {
  127. "name":"Add Rickroll",
  128. "replace":false,
  129. "content":`[link](https://www.youtube.com/watch?v=dQw4w9WgXcQ)`
  130. }
  131. ];
  132.  
  133. /* ---------- JS & HTML ---------- */
  134. function time(UNIX_timestamp){
  135. //Get UNIX time
  136. var d = new Date(UNIX_timestamp * 1000);
  137. const months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
  138.  
  139. //Get year, month, date, hour, min & sec variables
  140. var year = d.getFullYear(),
  141. monthNum = d.getMonth() + 1,
  142. month = months[d.getMonth()],
  143. date = d.getDate(),
  144. hour = fixnumber(d.getHours()),
  145. min = fixnumber(d.getMinutes()),
  146. sec = fixnumber(d.getSeconds());
  147.  
  148. //Construct the time (DD/MM/YY HH/MM/SS) and return it
  149. var time = `${date}.${monthNum}.${year} ${hour}:${min}:${sec}`;
  150. return time;
  151. }
  152. //Adds a zero suffix if x < 10
  153. const fixnumber = number => number < 10 ? "0" + number : number;
  154.  
  155. //Removes the u/ prefix
  156. const removePrefix = username => username.includes("u/") ? username.slice(2) : username;
  157.  
  158. //Adds the u/ prefix if nonexistant
  159. const keepPrefix = username => username.includes("u/") ? username : "u/" + username;
  160.  
  161. //Function to avoid XSS
  162. function sanitize(evilstring) {
  163. const decoder = document.createElement('div')
  164. decoder.innerHTML = evilstring;
  165. return decoder.textContent;
  166. }
  167.  
  168. //Appends the info (main, karma, links) to the page
  169. function addInfo(){
  170. //Load and parse username
  171. var username = removePrefix($(".InfoBar__username").innerText);
  172. var about = `https://www.reddit.com/user/${username}/about.json`;
  173. const xhr = new XMLHttpRequest();
  174. //Once the user info JSON has been fetched
  175. xhr.onload = () => {
  176. var user = JSON.parse(xhr.responseText);
  177. //Separator HTML element
  178. var seperator = document.createElement('div');
  179. seperator.innerHTML = '<div class="InfoBar__modActions"></div>';
  180. //HTML element that contains all the data
  181. var userDetails = document.createElement('div');
  182. userDetails.classList.add("InfoBar__age");
  183. userDetails.innerHTML = `<img class="profileIcon" src="${user.data.icon_img}" width="25">
  184. <a class="InfoBar__username" href="https://www.reddit.com/user/${user.data.name}">${user.data.subreddit.display_name_prefixed}</a>
  185. <h1 style="color: ${textColor} ; font-size: 11px; margin-top: 17px; margin-bottom: 10px;">${sanitize(user.data.subreddit.public_description)}</h1>
  186. <h1 class="dataTitle">Main</h1>
  187. <div class="dataText">
  188. <p>Created: <span class="value">${time(user.data.created)}</span></p>
  189. <p>UserID: <span class="value">${user.data.id}</span></p>
  190. <p>Verified: <span class="value">${user.data.verified}</span></p>
  191. <p>Employee: <span class="value">${user.data.is_employee}</span></p>
  192. <p>NSFW Profile: <span class="value">${user.data.subreddit.over_18}</span></p>
  193. </div>
  194. <h1 class="dataTitle">Karma</h1>
  195. <div class="dataText">
  196. <p>Post: <span class="value">${user.data.link_karma}</span></p>
  197. <p>Comment: <span class="value">${user.data.comment_karma}</span></p>
  198. <p>Total: <span class="value">${user.data.total_karma}</span></p>
  199. <p>Awardee: <span class="value">${user.data.awardee_karma}</span></p>
  200. <p>Awarder: <span class="value">${user.data.awarder_karma}</span></p>
  201. </div>
  202. <h1 class="dataTitle">Links</h1>
  203. <div style="padding-left: 10px;">
  204. <a class="InfoBar__recent" href="https://redditmetis.com/user/${user.data.name}" target="_blank">Redditmetis</a>
  205. <a class="InfoBar__recent" href="https://www.reddit.com/search?q=${user.data.name}" target="_blank">Reddit Search</a>
  206. <a class="InfoBar__recent" href="https://www.google.com/search?q=%22${user.data.name}%22" target="_blank">Google Search</a>
  207. </div>`;
  208.  
  209. //Add profile pictures
  210. if(chatProfileIcons) {
  211. //Icon element
  212. var chatProfileIcon = document.createElement('div');
  213. chatProfileIcon.innerHTML = `<img class="chatProfileIcon" src="${user.data.icon_img}" width="25">`;
  214.  
  215. //Loop trough every username on chat
  216. for(var i = 0; i < $$(".ThreadPreview__author").length; i++) {
  217. //Get username (u/xxxxxx)
  218. let name = $$(".Author__text")[i].innerText;
  219. //Check if there is an icon appended already
  220. let exists = $$(".ThreadPreview__author")[i].childNodes.length == 1 ? false : true;
  221. //If the username is the user (non-mod)
  222. if(removePrefix(name) == username && !exists) {
  223. //Append the icon next to the username -> [icon] u/username
  224. $$(".ThreadPreview__author")[i].insertBefore(chatProfileIcon.cloneNode(true), $$(".ThreadPreview__author")[i].firstChild);
  225. }
  226. }
  227. }
  228.  
  229. //Append the elements
  230. $(".ThreadViewer__infobar").appendChild(seperator);
  231. $(".ThreadViewer__infobar").appendChild(seperator);
  232. $(".ThreadViewer__infobar").appendChild(userDetails);
  233. $(".ThreadViewer__infobar").appendChild($(".ThreadViewer__infobar").firstChild);
  234. $(".InfoBar").appendChild($(".InfoBar__modActions"));
  235. $(".InfoBar").insertBefore($(".InfoBar__modActions"),$(".InfoBar").firstChild);
  236. if($(".InfoBar__banText"))
  237. $(".ThreadViewer__infobar").insertBefore($(".InfoBar__banText"),$(".ThreadViewer__infobar").firstChild);
  238. //Remove certain elements
  239. $$(".InfoBar__username")[1].outerHTML = "";
  240. $$(".InfoBar__age")[1].outerHTML = "";
  241. $$(".InfoBar__modActions")[1].outerHTML = "";
  242. };
  243. //Get user details
  244. xhr.open('GET', about);
  245. xhr.send();
  246. }
  247. //Appends the response template listbox to the page
  248. function addResponseBox() {
  249. //Hide real textarea and append a new one (so the text won't get removed by the sync feature)
  250. $(".ThreadViewerReplyForm__replyText").style.cssText += 'display: none';
  251. const txtArea = document.createElement("textarea");
  252. txtArea.setAttribute('class', 'Textarea ThreadViewerReplyForm__replyText ');
  253. txtArea.setAttribute('name', 'body');
  254. txtArea.setAttribute('placeholder', `${placeholderMessage}`);
  255. $(".ThreadViewerReplyForm").insertBefore(txtArea,$(".ThreadViewerReplyForm__replyFooter"));
  256. //Listbox element
  257. var responseBox = document.createElement('div');
  258. responseBox.classList.add("select");
  259. responseBox.innerHTML = `<h2 class="dataTitle">Response Templates</h2>
  260. <select id="responseListbox" onchange="listBoxChanged(this.value);" onfocus="this.selectedIndex = -1;"/>
  261. <span class="focus"></span>`;
  262. //Script element to head
  263. var headJS = document.createElement('script');
  264. headJS.innerHTML = `function listBoxChanged(message) {
  265. var messageBox = document.getElementsByClassName("Textarea ThreadViewerReplyForm__replyText")[1];
  266. var responses = ${JSON.stringify(responses)};
  267. var response = responses.find(x => x.content == message);
  268. response.replace ? messageBox.value = message : messageBox.value += message;
  269. console.log("[Modmail++] New messageBox value: %c" + messageBox.value,"color: orange");
  270. }`;
  271. function populate() {
  272. var select = $("#responseListbox");
  273. for(var i = 0; i < responses.length; i++) {
  274. select.options[select.options.length] = new Option(responses[i].name, responses[i].content);
  275. }
  276. }
  277. $(".ThreadViewer__replyContainer").prepend(responseBox);
  278. var head = $("head");
  279. head.appendChild(headJS);
  280.  
  281. $(".ThreadViewer__replyContainer").insertBefore($(".ThreadViewer__typingIndicator"),$(".select"));
  282.  
  283. populate();
  284. }
  285.  
  286. //Detects the current theme (dark/light) and applies the correct color (for the added elements)
  287. function themeColors() {
  288. var darkTheme = $$(".theme-dark").length ? true : false;
  289. if(darkTheme) {
  290. console.log("[Modmail++] Dark mode detected! Setting colors...");
  291. textColor = darkModeTextColor;
  292. titleColor = darkModeTitleColor;
  293. listBoxColor = darkModeListColor;
  294. } else {
  295. console.log("[Modmail++] Light mode detected! Setting colors...");
  296. textColor = lightModeTextColor;
  297. titleColor = lightModeTitleColor;
  298. listBoxColor = lightModeListColor;
  299. }
  300. }
  301.  
  302. themeColors();
  303.  
  304. //Took advice for the listbox CSS from moderncss.dev/custom-select-styles-with-pure-css, thanks!
  305. var css = `.profileIcon:hover {
  306. -ms-transform: scale(6);
  307. -webkit-transform: scale(6);
  308. transform: scale(6);
  309. }
  310. .profileIcon {
  311. position: relative;
  312. bottom: 4px;
  313. margin-bottom: 10px;
  314. float: left; border-radius: 50%;
  315. transition: transform .1s;
  316. }
  317. .InfoBar__recentsNone {
  318. color: #6e6e6e;
  319. }
  320. .InfoBar__metadata, .InfoBar__recents {
  321. margin: 6px 0;
  322. margin-left: 10px;
  323. }
  324. .value {
  325. color: ${dataColor};
  326. }
  327. .InfoBar__banText {
  328. padding-bottom: 15px;
  329. }
  330. .InfoBar__username, .InfoBar__username:visited {
  331. padding-left: 10px;
  332. }
  333. .ThreadViewer__infobarContainer {
  334. display: table;
  335. }
  336. .dataText {
  337. color: ${textColor};
  338. font-size: 13px;
  339. padding-left: 10px;
  340. }
  341. .dataTitle {
  342. color: ${titleColor};
  343. font-size: 15px;
  344. margin-bottom: 3px;
  345. margin-top: 5px;
  346. }
  347. .responseListbox {
  348. width: 50%;
  349. cursor: pointer;
  350. }
  351. :root {
  352. --select-border: #0079d3;
  353. --select-focus: blue;
  354. --select-arrow: var(--select-border);
  355. }
  356. *,
  357. *::before,
  358. *::after {
  359. box-sizing: border-box;
  360. }
  361. select {
  362. appearance: none;
  363. background-color: ${listBoxColor};
  364. color: ${textColor};
  365. border: none;
  366. padding: 0 1em 0 0;
  367. margin: 0;
  368. width: 100%;
  369. cursor: pointer;
  370. font-family: inherit;
  371. font-size: inherit;
  372. line-height: inherit;
  373. outline: none;
  374. position: relative;
  375. }
  376. .select {
  377. width: 100%;
  378. min-width: 15ch;
  379. max-width: 30ch;
  380. border: 1px solid var(--select-border);
  381. border-radius: 0.25em;
  382. padding: 0.3em 0.4em;
  383. font-size: 0.9rem;
  384. line-height: 1.1;
  385. background-color: ${listBoxColor};
  386. margin-bottom: 15px;
  387. }
  388. select::-ms-expand {
  389. display: none;
  390. }
  391. option {
  392. white-space: normal;
  393. outline-color: var(--select-focus);
  394. }
  395. select:focus + .focus {
  396. position: absolute;
  397. top: -1px;
  398. left: -1px;
  399. right: -1px;
  400. bottom: -1px;
  401. border: 2px solid var(--select-focus);
  402. border-radius: inherit;
  403. }
  404. .Author__text {
  405. padding: 6px 0;
  406. }
  407. .chatProfileIcon {
  408. margin-right: 7px;
  409. transition: transform .1s;
  410. border-radius: 50%;
  411. }
  412. .App__page {
  413. background: var(--color-tone-8);
  414. }
  415. ::-webkit-scrollbar {
  416. width: 10px;
  417. }
  418. ::-webkit-scrollbar-track {
  419. background: ${listBoxColor};
  420. }
  421. ::-webkit-scrollbar-thumb {
  422. background: #888;
  423. }
  424. ::-webkit-scrollbar-thumb:hover {
  425. background: #555;
  426. }`;
  427.  
  428. //Apply the custom css
  429. var styleSheet = document.createElement("style");
  430. styleSheet.type = "text/css";
  431. styleSheet.innerText = css;
  432. document.head.appendChild(styleSheet);
  433.  
  434. addInfo();
  435. if(enableCustomResponses && $("#responseListbox") == null) addResponseBox();
  436. console.log("[Modmail++] %cLoaded!", "color: lime");
  437.  
  438. } /* End of Main function */
  439.  
  440. /* Start Main function when visiting new modmail */
  441. var pageURLCheckTimer = setInterval (function () {
  442. if (this.lastPathStr !== location.pathname)
  443. {
  444. this.lastPathStr = location.pathname;
  445.  
  446. first = true;
  447.  
  448. let startInterval = setInterval (function () {
  449. if($(".InfoBar__username")) {
  450. if(first) main();
  451. first = false;
  452. clearInterval(startInterval);
  453. }
  454. }, 5);
  455. }
  456. }, 100);