[Reddit] Modmail++

Additional tools and information to Reddit's Modmail

  1. // ==UserScript==
  2. // @name [Reddit] Modmail++
  3. // @namespace HKR
  4. // @match https://mod.reddit.com/mail/*
  5. // @grant none
  6. // @version 3.7.2
  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. // @require https://cdn.jsdelivr.net/npm/party-js@2.1.2/bundle/party.js#sha256-J9/UDCn536lyy03NDKIUT6WX3DU9FqZZ9ydg++UVUC0=
  12. // ==/UserScript==
  13.  
  14. (() => {
  15. console.log("[Modmail++] %cScript started!", "color: green");
  16.  
  17. class __settings__ {
  18. subTag = $(".ThreadTitle__community")?.href?.slice(23) || "r/subreddit"; //Format r/subreddit
  19. userTag = "u/" + $(".ModIdCard__UserNameLink")?.innerText || "u/username"; //Format u/username
  20. modmail = `[modmail](https://www.reddit.com/message/compose?to=/${keepPrefix(this.subTag, true)})`;
  21. rules = `https://www.reddit.com/${keepPrefix(this.subTag, true)}/about/rules`;
  22. /* Responses - Edit to your own liking, remove whatever you don't like!
  23. - name | The name of the response that will show on the listbox. (Example value: "Hello!")
  24. - replace | Replace all messagebox text if true, otherwise just add. (Example value: true)
  25. - subreddit | Visible only while on this subreddit's modmail. (Example value: "r/subreddit")
  26. - content | This text will be added to the messagebox once selected (Example value: "Hello world!")*/
  27. responses = [
  28. {
  29. "name":"Default Approved",
  30. "replace":true,
  31. "subreddit":"",
  32. "content":`Hey, approved the post!`
  33. },
  34. {
  35. "name":"Default Rule Broken",
  36. "replace":true,
  37. "subreddit":"",
  38. "content":`Your post broke our [rules](${this.rules}).\n\nThe action will not be reverted.`
  39. },
  40. {
  41. "name":"Add Rule Description",
  42. "replace":false,
  43. "subreddit":"",
  44. "content":`<open-rulelist-dialog>`
  45. },
  46. {
  47. "name":"Add Greetings",
  48. "replace":false,
  49. "subreddit":"",
  50. "content":`${randItem(["Greetings","Hello","Hi"])} ${this.userTag},\n\n`
  51. },
  52. {
  53. "name":"Add Subreddit Mention",
  54. "replace":false,
  55. "subreddit":"",
  56. "content":`${this.subTag}`
  57. },
  58. {
  59. "name":"Add User Mention",
  60. "replace":false,
  61. "subreddit":"",
  62. "content":`${this.userTag}`
  63. },
  64. {
  65. "name":"Add Modmail Link",
  66. "replace":false,
  67. "subreddit":"",
  68. "content":`${this.modmail}`
  69. },
  70. {
  71. "name":"Add Karma Link",
  72. "replace":false,
  73. "subreddit":"",
  74. "content":`[karma](https://reddit.zendesk.com/hc/en-us/articles/204511829-What-is-karma-)`
  75. },
  76. {
  77. "name":"Add Shadowban Link",
  78. "replace":false,
  79. "subreddit":"",
  80. "content":`[shadowbanned](https://www.reddit.com/r/ShadowBan/comments/8a2gpk/an_unofficial_guide_on_how_to_avoid_being/)`
  81. },
  82. {
  83. "name":"Add Content Policy",
  84. "replace":false,
  85. "subreddit":"",
  86. "content":`[Content Policy](https://www.redditinc.com/policies/content-policy)`
  87. },
  88. {
  89. "name":"Add User Agreement",
  90. "replace":false,
  91. "subreddit":"",
  92. "content":`[User Agreement](https://www.redditinc.com/policies/user-agreement)`
  93. },
  94. {
  95. "name":"Add Reddiquette",
  96. "replace":false,
  97. "subreddit":"",
  98. "content":`[Reddiquette](https://reddit.zendesk.com/hc/en-us/articles/205926439-Reddiquette)`
  99. },
  100. {
  101. "name":"Add Admin Modmail",
  102. "replace":false,
  103. "subreddit":"",
  104. "content":`[Admins](https://www.reddit.com/message/compose?to=%2Fr%2Freddit.com)`
  105. },
  106. {
  107. "name":"Add Rickroll",
  108. "replace":false,
  109. "subreddit":"",
  110. "content":`[link](https://www.youtube.com/watch?v=dQw4w9WgXcQ)`
  111. },
  112. {
  113. "name":"Invitation (New Message)",
  114. "replace":true,
  115. "subreddit":"",
  116. "subject": `Invitation to become a moderator of ${this.subTag}`,
  117. "content":`${randItem(["Greetings","Hello","Hi"])} ${this.userTag},\n\nWould you like to moderate ${this.subTag} with us? Please let us know as soon as possible!`
  118. }
  119. ];
  120.  
  121. themeMode = $$(".theme-dark").length ? true : false;
  122. textColor = this.themeMode ? "#757575" : "#6e6e6e"; // dark hex : light hex
  123. titleColor = this.themeMode ? "#a7a7a7" : "#2c2c2c"; // dark hex : light hex
  124. listBoxColor = this.themeMode ? "#242424" : "#f1f3f5"; // dark hex : light hex
  125.  
  126. dataColor = "#0079d3"; // data (numbers etc.) color
  127.  
  128. enableCustomResponses = true; // if to append the custom response box
  129.  
  130. chatProfileIcons = true; // if to append chat profile icons
  131.  
  132. placeholderMessage = randItem([
  133. "Message...",
  134. "Look, a bird! Message...",
  135. "What have you been up to today? Message...",
  136. "Beautiful day, isn't it? Message...",
  137. "Was the weather nice? Message...",
  138. "You look good today! Message...",
  139. "What dreams did you see last night? Message...",
  140. "What did you do today? Message...",
  141. "What did you eat today? Message...",
  142. "Have you drank enough water? Message...",
  143. "Remember to stretch! Message...",
  144. "≖‿≖ I live inside of your walls. Message...",
  145. "(✿◠‿◠) Message...",
  146. ]);
  147. }
  148. /*/////////////////////////////////////////////////
  149. \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
  150. DO NOT PROCEED IF YOU DO NOT KNOW WHAT YOU'RE DOING
  151. ///////////////////////////////////////////////////
  152. \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/
  153. const $ = document.querySelector.bind(document);
  154. const $$ = document.querySelectorAll.bind(document);
  155.  
  156. // returns a random item from array
  157. const randItem = itemArr => itemArr[Math.floor(Math.random() * itemArr.length)];
  158. // removes the Reddit prefix
  159. const removePrefix = username => ["r/","u/"].some(tag => username.includes(tag)) ? username.slice(2) : username;
  160. // adds the Reddit prefix if nonexistant
  161. const keepPrefix = (username, subreddit) => ["r/","u/"].some(tag => username.includes(tag)) ? username : subreddit ? `r/${username}` : `u/${username}`;
  162.  
  163. const recipientUsername = () => {
  164. const defaultUsernameElem = $(".ModIdCard__UserNameLink");
  165. if(defaultUsernameElem) {
  166. return removePrefix(defaultUsernameElem?.innerText);
  167. }
  168. else {
  169. return undefined;
  170. }
  171. };
  172. async function Get(url) {
  173. const response = await fetch(url);
  174.  
  175. if (!response.ok) {
  176. throw new Error(`HTTP error! status: ${response.status}`);
  177. }
  178.  
  179. const text = await response.text();
  180. return text;
  181. };
  182.  
  183. async function getUserInfo() {
  184. try
  185. {
  186. const about = await Get(`https://www.reddit.com/user/${recipientUsername()}/about.json`);
  187. return JSON.parse(about);
  188. }
  189. catch
  190. {
  191. console.log("[Modmail++] %cFailed to load user information.", "color: red");
  192. return 0;
  193. }
  194. };
  195. async function getRules(Settings) {
  196. try
  197. {
  198. const rules = await Get(Settings.rules + ".json");
  199. return JSON.parse(rules);
  200. }
  201. catch
  202. {
  203. console.log("[Modmail++] %cFailed to load subreddit rules, possibly a private subreddit?", "color: red");
  204. return 0;
  205. }
  206. };
  207.  
  208. // adds a zero suffix if x < 10
  209. const fixNumber = number => number < 10 ? "0" + number : number;
  210.  
  211. // returns a date string from UNIX timestamp
  212. function unixToDate(UNIX_timestamp) {
  213. const d = new Date(UNIX_timestamp * 1000);
  214. const months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
  215.  
  216. const year = d.getFullYear(),
  217. monthNum = d.getMonth() + 1,
  218. month = months[d.getMonth()],
  219. date = d.getDate(),
  220. hour = fixNumber(d.getHours()),
  221. min = fixNumber(d.getMinutes()),
  222. sec = fixNumber(d.getSeconds());
  223.  
  224. return `${date}.${monthNum}.${year} ${hour}:${min}:${sec}`; // (DD/MM/YY HH/MM/SS)
  225. };
  226.  
  227. // returns a string without evil HTML elements
  228. function sanitize(evilstring) {
  229. const decoder = document.createElement('div');
  230. decoder.innerHTML = evilstring;
  231. return decoder.textContent;
  232. };
  233.  
  234. // add a link to the Modmail text and change its name to Modmail++
  235. const sidebarTitle = $(".Sidebar__titleMessage");
  236. sidebarTitle.setAttribute("onclick","window.open('https://github.com/Hakorr/Userscripts/tree/main/Reddit.com/ModmailExtraInfo')");
  237. sidebarTitle.setAttribute("style","cursor: pointer");
  238. sidebarTitle.innerText = "Modmail++";
  239.  
  240. // apply the custom css
  241. function applyCSS(Settings) {
  242. //Took advice for the listbox CSS from moderncss.dev/custom-select-styles-with-pure-css, thanks!
  243. const css = `
  244. .dataTitle {
  245. color: ${Settings.titleColor};
  246. font-size: 15px;
  247. margin-bottom: 3px;
  248. margin-top: 5px;
  249. }
  250. .responseListbox {
  251. width: 50%;
  252. cursor: pointer;
  253. }
  254. :root {
  255. --select-border: #0079d3;
  256. --select-focus: blue;
  257. --select-arrow: var(--select-border);
  258. }
  259. select {
  260. appearance: none;
  261. background-color: ${Settings.listBoxColor};
  262. color: ${Settings.textColor};
  263. border: none;
  264. padding: 0 1em 0 0;
  265. margin: 0;
  266. width: 100%;
  267. cursor: pointer;
  268. font-family: inherit;
  269. font-size: inherit;
  270. line-height: inherit;
  271. outline: none;
  272. position: relative;
  273. }
  274. .select {
  275. width: 100%;
  276. min-width: 15ch;
  277. max-width: 30ch;
  278. border: 1px solid var(--select-border);
  279. border-radius: 0.25em;
  280. padding: 0.3em 0.4em;
  281. font-size: 0.9rem;
  282. line-height: 1.1;
  283. background-color: ${Settings.listBoxColor};
  284. margin-bottom: 15px;
  285. }
  286. select::-ms-expand {
  287. display: none;
  288. }
  289. option {
  290. white-space: normal;
  291. outline-color: var(--select-focus);
  292. }
  293. select:focus + .focus {
  294. position: absolute;
  295. top: -1px;
  296. left: -1px;
  297. right: -1px;
  298. bottom: -1px;
  299. border: 2px solid var(--select-focus);
  300. border-radius: inherit;
  301. }
  302. .Author__text {
  303. padding: 6px 0;
  304. }
  305. .chatProfileIcon {
  306. margin-right: 7px;
  307. transition: transform .1s;
  308. border-radius: 50%;
  309. }
  310. .App__page {
  311. background: var(--color-tone-8);
  312. }
  313. ::-webkit-scrollbar {
  314. width: 10px;
  315. }
  316. ::-webkit-scrollbar-track {
  317. background: ${Settings.listBoxColor};
  318. }
  319. ::-webkit-scrollbar-thumb {
  320. background: #888;
  321. }
  322. ::-webkit-scrollbar-thumb:hover {
  323. background: #555;
  324. }
  325. .subredditRuleList {
  326. --newRedditTheme-bodyText: ${Settings.titleColor};
  327. --newRedditTheme-metaText: ${Settings.textColor};
  328. --newRedditTheme-navIconFaded10: rgba(215,218,220,0.1);
  329. --newRedditTheme-actionIconTinted80: #9a9b9c;
  330. --newRedditTheme-activeShaded90: #006cbd;
  331. --newRedditTheme-actionIconAlpha20: rgba(129,131,132,0.2);
  332. --newCommunityTheme-actionIcon: #818384;
  333. --newRedditTheme-bodyTextAlpha03: ${Settings.listBoxColor};
  334. --newRedditTheme-navIcon: #D7DADC;
  335. --newCommunityTheme-line: #343536;
  336. --newCommunityTheme-body: #1A1A1B;
  337. }
  338. .ruleList {
  339. padding: 0 24px 0 20px;
  340. background: var(--newRedditTheme-bodyTextAlpha03);
  341. max-height: 100%;
  342. }
  343. .dialogWindow {
  344. pointer-events: auto;
  345. }
  346. .ruleDiv {
  347. -ms-flex-align: center;
  348. align-items: center;
  349. box-sizing: border-box;
  350. display: -ms-flexbox;
  351. display: flex;
  352. height: 100%;
  353. padding: 75px 30px 20px;
  354. pointer-events: none;
  355. position: fixed;
  356. top: 0;
  357. width: 100%;
  358. z-index: 55;
  359. }
  360. .dialogWindow {
  361. background-color: var(--newCommunityTheme-body);
  362. border: 1px solid var(--newCommunityTheme-line);
  363. border-radius: 4px;
  364. box-shadow: 0 2px 20px 0 rgb(0 0 0 / 30%);
  365. margin: auto;
  366. pointer-events: auto;
  367. z-index: 55;
  368. }
  369. .listWindow {
  370. width: 550px;
  371. position: relative;
  372. }
  373. .ruleHeader {
  374. height: 50px;
  375. border-bottom: 1px solid var(--newRedditTheme-bodyTextAlpha03);
  376. position: relative;
  377. display: -ms-flexbox;
  378. display: flex;
  379. -ms-flex-align: center;
  380. align-items: center;
  381. padding: 0 24px 0 20px;
  382. margin: 0 -24px 0 -20px;
  383. font-weight: 700;
  384. font-size: 14px;
  385. color: var(--newRedditTheme-metaText);
  386. }
  387. .infoIcon {
  388. background: #86848412;
  389. border-radius: 8px;
  390. padding: 10px 16px 10px 12px;
  391. display: -ms-flexbox;
  392. display: flex;
  393. box-sizing: border-box;
  394. margin-top: 16px;
  395. }
  396. .bottomFooter {
  397. box-shadow: 0 -1px 0 var(--newRedditTheme-bodyTextAlpha03);
  398. padding: 20px 0 16px;
  399. min-height: 80px;
  400. display: -ms-flexbox;
  401. display: flex;
  402. box-sizing: border-box;
  403. bottom: 0;
  404. left: 0;
  405. }
  406. .closeIconSVG {
  407. margin-left: auto;
  408. margin-right: -4px;
  409. cursor: pointer;
  410. height: 20px;
  411. padding: 4px;
  412. width: 20px;
  413. fill: var(--newCommunityTheme-actionIcon);
  414. }
  415. .infoIconSVG {
  416. -ms-flex: 0 0 20px;
  417. flex: 0 0 20px;
  418. width: 20px;
  419. margin-right: 12px;
  420. fill: #878a8c;
  421. }
  422. .selectButton:disabled {
  423. opacity: .5;
  424. }
  425. .selectButton {
  426. margin-top: 8px;
  427. -ms-flex: 0 0 150px;
  428. flex: 0 0 150px;
  429. background: var(--newRedditTheme-activeShaded90);
  430. height: 31px;
  431. border-radius: 100px;
  432. color: #fff;
  433. -ms-flex-item-align: end;
  434. align-self: flex-end;
  435. margin-left: auto;
  436. font-size: 12px;
  437. font-weight: 700;
  438. text-transform: uppercase;
  439. letter-spacing: .05em;
  440. outline: none!important;
  441. padding: initial;
  442. cursor: pointer;
  443. border: none;
  444. }
  445. .infoBox {
  446. -ms-flex: 0 1 auto;
  447. flex: 0 1 auto;
  448. font-size: 14px;
  449. line-height: 1.45;
  450. letter-spacing: -.01em;
  451. color: var(--newRedditTheme-metaText);
  452. }
  453. .infoBox a {
  454. color: #24a0ed;
  455. }
  456. .title {
  457. margin-top: 16px;
  458. font-size: 16px;
  459. line-height: 1.2;
  460. font-weight: 700;
  461. color: var(--newRedditTheme-bodyText);
  462. }
  463. .fieldSet {
  464. display: -ms-flexbox;
  465. display: flex;
  466. -ms-flex-direction: column;
  467. flex-direction: column;
  468. box-sizing: border-box;
  469. }
  470. .listValue label {
  471. padding: 0 72px 0 20px;
  472. display: -ms-flexbox;
  473. display: flex;
  474. height: 100%;
  475. -ms-flex-align: center;
  476. align-items: center;
  477. cursor: pointer;
  478. font-size: 14px;
  479. font-weight: 700;
  480. color: var(--newRedditTheme-metaText);
  481. position: relative;
  482. }
  483. .listValue {
  484. box-sizing: border-box;
  485. height: 64px;
  486. border-top: 1px solid var(--newRedditTheme-navIconFaded10);
  487. }
  488. .listBox {
  489. margin: 16px -24px 0 -20px;
  490. max-height: 60vh;
  491. min-height: 100px;
  492. overflow: auto;
  493. }
  494. .listValue input {
  495. visibility: hidden;
  496. display: none;
  497. }
  498. #currentlySelected {
  499. background-color: rgba(121, 121, 121, 0.35);
  500. }
  501. .ruleDiv {
  502. background-color: rgba(26, 26, 27, 0.6);
  503. visibility: hidden;
  504. }
  505. .ModmailPlusPlus__UserDescription {
  506. font-size: 11px;
  507. font-weight: 100;
  508. font-style: italic;
  509. line-height: 16px;
  510. letter-spacing: 0em;
  511. color: var(--color-tone-3);
  512. display: -ms-flexbox;
  513. display: flex;
  514. -ms-flex-pack: center;
  515. justify-content: center;
  516. -ms-flex-align: center;
  517. align-items: center;
  518. margin: 3;
  519. margin-left: 20px;
  520. margin-right: 20px;
  521. }
  522. .ModmailPlusPlus__Title {
  523. font-size: 15px;
  524. font-weight: 700;
  525. color: var(--color-tone-3);
  526. }
  527. `;
  528.  
  529. const styleSheet = document.createElement("style");
  530. styleSheet.type = "text/css";
  531. styleSheet.id = "modmailPlusSheet";
  532. styleSheet.innerText = css;
  533. if($$("#modmailPlusSheet").length == 0)
  534. document.head.appendChild(styleSheet);
  535. };
  536.  
  537. function initializeCore(Settings) {
  538. /* About the core
  539. * - it contains functions required for handling different in-page-actions, such as hiding a div
  540. * - references to variables outside the core and the document will not be recognized
  541. * */
  542. class Core {
  543. ruleListActivator = "<open-rulelist-dialog>";
  544.  
  545. listBoxChanged(responseIndex) {
  546. const message = document.ModmailPlus.responses[responseIndex].content;
  547.  
  548. if(message == this.ruleListActivator)
  549. {
  550. const ruleDiv = document.getElementsByClassName("ruleDiv")[0];
  551. ruleDiv.style.visibility = "visible";
  552. }
  553. else
  554. {
  555. const userVisitingCreatePostPage = document.querySelectorAll(".NewThread").length;
  556.  
  557. const messageBox = userVisitingCreatePostPage
  558. ? document.querySelector(".Textarea, NewThread__message")
  559. : document.getElementById("realTextarea");
  560.  
  561. const response = document.ModmailPlus.responses.find(x => x.content == message);
  562.  
  563. response.replace ? messageBox.value = message : messageBox.value += message;
  564.  
  565. if(response.subject) {
  566. document.querySelector(".NewThread__subject").value = response.subject;
  567. }
  568.  
  569. console.log("[Modmail++] Updated the message: %c" + messageBox.value,"color: orange");
  570. }
  571. }
  572.  
  573. // implement listbox select highlight
  574. selected(element) {
  575. const selectedElem = document.getElementById("currentlySelected");
  576.  
  577. // if an element already selected, reset the id and set its background color to nothing
  578. if(selectedElem)
  579. selectedElem.removeAttribute("id");
  580.  
  581. element.parentElement.id = "currentlySelected";
  582. document.getElementsByClassName("selectButton")[0].disabled = false;
  583. }
  584.  
  585. removeBreaks = text => text.replace(/(\r\n|\n|\r)/gm, "");
  586.  
  587. selectButtonClicked() {
  588. const selectedElem = document.getElementById("currentlySelected");
  589. const userVisitingCreatePostPage = document.querySelectorAll(".NewThread").length;
  590.  
  591. const messageBox = userVisitingCreatePostPage
  592. ? document.querySelector(".Textarea, NewThread__message")
  593. : document.getElementById("realTextarea");
  594.  
  595. if(selectedElem)
  596. {
  597. const selectedRule = document.ModmailPlus.rules[selectedElem.getAttribute('value')];
  598. const ruleName = selectedRule.short_name;
  599. const ruleDescription = selectedRule.description;
  600. const fixedDescription = ruleDescription.replaceAll("\n","\n> ") + '\n\n';
  601. const message = `> [**${ruleName}**]\n>\n> ${fixedDescription}`;
  602.  
  603. const response = document.ModmailPlus.responses.find(x => x.content == this.ruleListActivator);
  604. response.replace // if to replace or add text to the messagebox
  605. ? messageBox.value = message
  606. : messageBox.value += message;
  607.  
  608. console.log("[Modmail++] New messageBox value: %c" + messageBox.value,"color: orange");
  609.  
  610. this.closeIconClicked();
  611. }
  612. }
  613.  
  614. closeIconClicked() {
  615. const ruleDiv = document.querySelector(".ruleDiv");
  616. ruleDiv.style.visibility = "hidden";
  617. }
  618. divertQuoteText() {
  619. console.log("[Modmail++] %cDiverting quote text from original textbox to Modmail++'s", "color: orange");
  620. setTimeout(() => {
  621. const originalForm = document.querySelector(".Textarea, .ThreadViewerReplyForm__replyText");
  622. const originalValue = originalForm.value;
  623. let text = "";
  624.  
  625. if(originalValue.includes("\n\n"))
  626. text = originalValue.split("\n\n").filter(x => x.length > 0).pop();
  627. else
  628. text = originalValue;
  629.  
  630. if(text.indexOf("\n") == 0) text = text.slice(1);
  631.  
  632. if(text && text.includes("said:"))
  633. document.querySelector("#realTextarea").value += text + "\n\n";
  634. }, 50);
  635. }
  636. clearReplyForm() {
  637. setTimeout(() => {
  638. document.getElementById("realTextarea").value = "";
  639. console.log("[Modmail++] Cleared the textarea!");
  640. // set onclick variable again because the button refreshes itself
  641. document.querySelector(".ThreadViewerReplyForm__replyButton")
  642. .setAttribute("onclick", "document.ModmailPlus.Core.clearReplyForm()");
  643. }, 500);
  644. }
  645. };
  646. document.ModmailPlus.Core = new Core;
  647. document.ModmailPlus.responses = Settings.responses;
  648. };
  649.  
  650. async function appendChatProfileIcons() {
  651. const user = await getUserInfo();
  652.  
  653. // icon element
  654. const chatProfileIcon = document.createElement('div');
  655. chatProfileIcon.innerHTML = `<img class="chatProfileIcon" src="${user.data.icon_img}" width="25">`;
  656.  
  657. const authors = $$(".ThreadPreview__author");
  658. if(authors) {
  659. authors.forEach((author, index) => {
  660. // get username (u/xxxxxx)
  661. const name = $$(".Author__text")[index].innerText;
  662.  
  663. // check if there is an icon appended already
  664. const exists = author.childNodes.length == 1 ? false : true;
  665.  
  666. if(removePrefix(name) == recipientUsername() && !exists) // if the username is the user (non-mod)
  667. {
  668. // append the icon next to the username -> [icon] u/username
  669. author.insertBefore(chatProfileIcon.cloneNode(true), author.firstChild);
  670. }
  671. });
  672. }
  673. };
  674.  
  675. async function appendUserInfo(Settings) {
  676. const user = await getUserInfo();
  677.  
  678. if(user)
  679. {
  680. const userDetails = document.createElement('div');
  681. userDetails.id = "CustomMetadata";
  682. userDetails.classList.add("KarmaAndTrophies__userInfoGrid");
  683. userDetails.innerHTML = `
  684. <div class="KarmaAndTrophies__col"><span class="KarmaAndTrophies__count">${user.data.id}</span><span class="KarmaAndTrophies__label">User ID</span></div>
  685. <div class="KarmaAndTrophies__col"><span class="KarmaAndTrophies__count">${user.data.verified ? "🟢" : "🔴"}</span><span class="KarmaAndTrophies__label">Verified</span></div>
  686. <div class="KarmaAndTrophies__col"><span class="KarmaAndTrophies__count">${user.data.is_employee ? "🟢" : "🔴"}</span><span class="KarmaAndTrophies__label">Reddit Employee</span></div>
  687. <div class="KarmaAndTrophies__col"><span class="KarmaAndTrophies__count">${user.data.subreddit.over_18 ? "🟢" : "🔴"}</span><span class="KarmaAndTrophies__label">NSFW Profile</span></div>
  688. <div class="KarmaAndTrophies__col"><span class="KarmaAndTrophies__count">${user.data.subreddit.accept_followers ? "🟢" : "🔴"}</span><span class="KarmaAndTrophies__label">Accept Followers</span></div>
  689. <div class="KarmaAndTrophies__col"><span class="KarmaAndTrophies__count">${user.data.subreddit.hide_from_robots ? "🟢" : "🔴"}</span><span class="KarmaAndTrophies__label">Hide from bots</span></div>`;
  690. const links = document.createElement('div');
  691. links.classList.add("KarmaAndTrophies__userInfoGrid");
  692. links.innerHTML = `
  693. <div style="margin-bottom: 10px;">
  694. <a class="InfoBar__recent" href="https://redditmetis.com/user/${user.data.name}" target="_blank">RedditMetis ⧉</a>
  695. <a class="InfoBar__recent" href="https://www.reddit.com/search?q=${user.data.name}" target="_blank">Reddit Search ⧉</a>
  696. <a class="InfoBar__recent" href="https://www.google.com/search?q=%22${user.data.name}%22" target="_blank">Google Search ⧉</a>
  697. <div>`;
  698. const getTitleElement = titleText => {
  699. const title = document.createElement('h1');
  700. title.classList.add("KarmaAndTrophies__userInfoGrid");
  701. title.classList.add("ModmailPlusPlus__Title");
  702. title.innerText = titleText;
  703. return title;
  704. };
  705. if(!$("#CustomMetadata")) {
  706. const userCard = $(".ModIdCard");
  707. if(userCard && user.data.subreddit.public_description && !$(".ModmailPlusPlus__UserDescription")) {
  708. const description = document.createElement('h1');
  709. description.classList.add("ModmailPlusPlus__UserDescription");
  710. description.innerText = '“' + sanitize(user.data.subreddit.public_description) + '”';
  711. userCard.insertBefore(description, $(".ModIdCard__UserProfileLink"));
  712. }
  713. const banStatus = $(".KarmaAndTrophies__BanStatus");
  714. if(banStatus) {
  715. $(".KarmaAndTrophies").insertBefore(getTitleElement("Additional Information"), banStatus);
  716. $(".KarmaAndTrophies").insertBefore(userDetails, banStatus);
  717. $(".KarmaAndTrophies").insertBefore(getTitleElement("Additional Links"), banStatus);
  718. $(".KarmaAndTrophies").insertBefore(links, banStatus);
  719. } else {
  720. $(".KarmaAndTrophies").appendChild(getTitleElement("Additional Information"));
  721. $(".KarmaAndTrophies").appendChild(userDetails);
  722. $(".KarmaAndTrophies").appendChild(getTitleElement("Additional Links"));
  723. $(".KarmaAndTrophies").appendChild(links);
  724. }
  725. }
  726. const observer = new MutationObserver(() => {
  727. const overview = document.querySelector(".InfoBar__overviewContainer");
  728. if(overview) {
  729. observer.disconnect();
  730. appendUserInfo(Settings);
  731. }
  732. });
  733. observer.observe(document.querySelector(".InfoBar"), {
  734. attributes: false, characterData: false, childList: true
  735. });
  736. }
  737. };
  738.  
  739. function replaceReplyForm(Settings) {
  740. // hide the original replyform textarea
  741. $(".ThreadViewerReplyForm__replyText").style.cssText += 'display: none';
  742.  
  743. // create and append a new replyform textarea
  744. const newReplyForm = document.createElement("textarea");
  745. newReplyForm.setAttribute('class', 'Textarea ThreadViewerReplyForm__replyText ');
  746. newReplyForm.setAttribute('id', 'realTextarea');
  747. newReplyForm.setAttribute('name', 'body');
  748. newReplyForm.setAttribute('placeholder', `${Settings.placeholderMessage}`);
  749. $(".ThreadViewerReplyForm").insertBefore(newReplyForm, $(".ThreadViewerReplyForm__replyFooter"));
  750.  
  751. // make the reply button clear the new replyform
  752. $(".ThreadViewerReplyForm__replyButton").setAttribute("onclick", "document.ModmailPlus.Core.clearReplyForm()");
  753. };
  754.  
  755. async function appendResponseTemplateBox(Settings) {
  756. const responseTemplateElement =
  757. `<h2 class="dataTitle">Response Templates</h2>
  758. <select id="responseListbox" onchange="document.ModmailPlus.Core.listBoxChanged(this.value);" onfocus="this.selectedIndex = -1;"/>
  759. <option selected disabled hidden>Select a template</option>
  760. <span class="focus"></span>`;
  761.  
  762. const responseTemplateParent = document.createElement('div');
  763. responseTemplateParent.classList.add("select", "customResponseBox");
  764. responseTemplateParent.innerHTML = responseTemplateElement;
  765.  
  766. const userVisitingCreatePostPage = document.querySelectorAll(".NewThread").length;
  767.  
  768. if(typeof Settings.responses == "object" && Settings.responses.length) // if the responses variable exists and has responses
  769. {
  770. if(userVisitingCreatePostPage) // user visited mod.reddit.com/mail/create
  771. {
  772. // append the template box to the site
  773. $(".NewThread__fields").prepend(responseTemplateParent);
  774. $(".NewThread__fields").insertBefore($(".customResponseBox"), $(".Textarea, .NewThread__message"));
  775. }
  776. else // user visited modmail chat
  777. {
  778. // append the template box to the site
  779. $(".ThreadViewer__replyContainer").prepend(responseTemplateParent);
  780. $(".ThreadViewer__replyContainer").insertBefore($(".ThreadViewer__typingIndicator"), $(".select")); // append typing indicator before listbox
  781. }
  782. }
  783. // populates the response template listbox
  784. function populateListbox(listBoxId) {
  785. const listBox = $(listBoxId);
  786.  
  787. if(typeof Settings.responses == "object" && Settings.responses.length) // if the responses variable exists and has responses
  788. {
  789. Settings.responses.forEach((response, i) => {
  790. const responseSubreddit = keepPrefix(response.subreddit.toLowerCase(), true);
  791. const currentSubreddit = keepPrefix(Settings.subTag.toLowerCase(), true);
  792. const sameSubreddit = currentSubreddit == responseSubreddit;
  793.  
  794. if(sameSubreddit || response.subreddit.length == 0)
  795. {
  796. if(userVisitingCreatePostPage)
  797. {
  798. listBox.options[listBox.options.length] = new Option(response.name, i);
  799. }
  800. else
  801. {
  802. if(!response.subject)
  803. {
  804. listBox.options[listBox.options.length] = new Option(response.name, i);
  805. }
  806. }
  807. }
  808. });
  809. }
  810. };
  811.  
  812. populateListbox("#responseListbox"); // add all the responses to the response template listbox
  813.  
  814. // creates and returns a list element
  815. function makeListValue(index, rule) {
  816. document.ModmailPlus.rules.push(rule);
  817. return `<div value='${index}' class="listValue">
  818. <input onclick="document.ModmailPlus.Core.selected(this)" name="subredditRule" id='${"input_" + index}' type="radio">
  819. <label for='${"input_" + index}'>${rule.short_name}</label>
  820. </div>`;
  821. };
  822.  
  823. const ruleObj = await getRules(Settings);
  824.  
  825. if(ruleObj)
  826. {
  827. $$(".subredditRuleList").forEach(elem => elem.remove()); // remove all subredditRuleList elements
  828.  
  829. let listContent = "";
  830.  
  831. ruleObj.rules.forEach((rule, index) => {
  832. listContent += makeListValue(index, rule)
  833. });
  834.  
  835. // (Append) Div ruleList element to body
  836. const ruleList = document.createElement('div');
  837. ruleList.classList.add("subredditRuleList");
  838. ruleList.innerHTML = `<div class="ruleDiv">
  839. <div aria-modal="true" class="dialogWindow" role="dialog" tabindex="-1">
  840. <div class="listWindow">
  841. <div class="ruleList">
  842. <div class="ruleHeader">Select a rule<svg onclick="document.ModmailPlus.Core.closeIconClicked()" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg" class="closeIconSVG"><polygon fill="inherit" points="11.649 9.882 18.262 3.267 16.495 1.5 9.881 8.114 3.267 1.5 1.5 3.267 8.114 9.883 1.5 16.497 3.267 18.264 9.881 11.65 16.495 18.264 18.262 16.497"></polygon></svg></div>
  843. <fieldset class="fieldSet">
  844. <div class="title"><span>Which community rule did the user violate?</span></div>
  845. <div class="listBox">
  846. ${listContent}
  847. </div>
  848. <div class="infoIcon"><svg class="infoIconSVG" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg"><g><path d="M10,8.5 C10.553,8.5 11,8.948 11,9.5 L11,13.5 C11,14.052 10.553,14.5 10,14.5 C9.447,14.5 9,14.052 9,13.5 L9,9.5 C9,8.948 9.447,8.5 10,8.5 Z M10.7002,5.79 C10.8012,5.89 10.8702,6 10.9212,6.12 C10.9712,6.24 11.0002,6.37 11.0002,6.5 C11.0002,6.57 10.9902,6.63 10.9802,6.7 C10.9712,6.76 10.9502,6.82 10.9212,6.88 C10.9002,6.94 10.8702,7 10.8302,7.05 C10.7902,7.11 10.7502,7.16 10.7002,7.21 C10.6602,7.25 10.6102,7.29 10.5512,7.33 C10.5002,7.37 10.4402,7.4 10.3812,7.42 C10.3202,7.45 10.2612,7.47 10.1902,7.48 C10.1312,7.49 10.0602,7.5 10.0002,7.5 C9.7402,7.5 9.4802,7.39 9.2902,7.21 C9.1102,7.02 9.0002,6.77 9.0002,6.5 C9.0002,6.37 9.0302,6.24 9.0802,6.12 C9.1312,5.99 9.2002,5.89 9.2902,5.79 C9.5202,5.56 9.8702,5.46 10.1902,5.52 C10.2612,5.53 10.3202,5.55 10.3812,5.58 C10.4402,5.6 10.5002,5.63 10.5512,5.67 C10.6102,5.71 10.6602,5.75 10.7002,5.79 Z M10,16 C6.691,16 4,13.309 4,10 C4,6.691 6.691,4 10,4 C13.309,4 16,6.691 16,10 C16,13.309 13.309,16 10,16 M10,2 C5.589,2 2,5.589 2,10 C2,14.411 5.589,18 10,18 C14.411,18 18,14.411 18,10 C18,5.589 14.411,2 10,2"></path></g></svg>
  849. <div class="infoBox">
  850. <p><span>Not sure? </span><a href="https://www.reddit.com/${keepPrefix(Settings.subTag)}/about/rules" target="_blank" rel="noopener noreferrer">Read ${Settings.subTag}'s rules</a></p>
  851. </div>
  852. </div>
  853. <footer class="bottomFooter"><button type="button" disabled="" onclick="document.ModmailPlus.Core.selectButtonClicked()" class="selectButton">Select</button></footer>
  854. </fieldset>
  855. </div>
  856. </div>
  857. </div>
  858. </div>`;
  859. $("body").appendChild(ruleList);
  860. }
  861. };
  862.  
  863. function fixQuoteButtons() {
  864. /* On click, do this
  865. 1) take the text from the original form
  866. 2) split it by two new lines
  867. 3) take the last result (last quoted message)
  868. 4) paste the last result to the new form
  869. */
  870.  
  871. $$(".Message__quote").forEach(elem => {
  872. if(!elem.getAttribute("onclick"))
  873. elem.setAttribute("onclick", "document.ModmailPlus.Core.divertQuoteText()");
  874. });
  875. };
  876. function handleCreateMessagePage() {
  877. // e.g. wait for an input change, then update the template strings to have that subreddit or username
  878. function updateResponseTemplate(isPostFrom, lastValue, newValue) {
  879. const defaultValue = isPostFrom
  880. ? "r/subreddit"
  881. : "u/undefined";
  882. document.ModmailPlus.responses.forEach(response => {
  883. // update subject string
  884. if(response.subject) {
  885. response.subject = response.subject.replaceAll(
  886. lastValue || defaultValue,
  887. newValue
  888. );
  889. }
  890.  
  891. // update content string
  892. response.content = response.content.replaceAll(
  893. lastValue || defaultValue,
  894. newValue
  895. );
  896. });
  897. }
  898. (() => {
  899. let lastUsername = null;
  900.  
  901. // Handle change of "To User"
  902. const toUser = document.querySelector(".Radio__input[value=user]");
  903.  
  904. if(toUser) {
  905. toUser.onclick = () => {
  906. const waitForTextbox = setInterval(() => {
  907. const newThreadTextbox = document.querySelector(".NewThread__username");
  908.  
  909. if(newThreadTextbox) {
  910. clearInterval(waitForTextbox);
  911.  
  912. newThreadTextbox.onchange = e => {
  913. const username = "u/" + e.target.value;
  914.  
  915. updateResponseTemplate(false, lastUsername, username);
  916.  
  917. lastUsername = username;
  918. }
  919. }
  920. }, 100);
  921. }
  922. }
  923.  
  924. // Handle change of "To Subreddit"
  925. const toSubreddit = document.querySelector(".Radio__input[value=subreddit]");
  926.  
  927. if(toSubreddit) {
  928. toSubreddit.onclick = () => {
  929. const waitForTextbox = setInterval(() => {
  930. const newThreadTextbox = document.querySelector(".NewThread__subreddit");
  931.  
  932. if(newThreadTextbox) {
  933. clearInterval(waitForTextbox);
  934.  
  935. newThreadTextbox.onchange = e => {
  936. const subreddit = "r/" + e.target.value;
  937.  
  938. updateResponseTemplate(false, lastUsername, subreddit);
  939.  
  940. lastUsername = subreddit;
  941. }
  942. }
  943. }, 100);
  944. }
  945. }
  946. })();
  947. (() => {
  948. // Handle change of "Post from"
  949. const srName = document.querySelector("[name=srName]");
  950.  
  951. if(srName) {
  952. let lastSubreddit = null;
  953.  
  954. const postToChanges = setInterval(() => {
  955. const subreddit = "r/" + srName.value;
  956.  
  957. if(subreddit != lastSubreddit && subreddit != 'r/') {
  958. updateResponseTemplate(true, lastSubreddit, subreddit);
  959.  
  960. lastSubreddit = subreddit;
  961. }
  962. }, 500);
  963. }
  964. })();
  965. };
  966.  
  967. const __main__ = async () => {
  968. console.log("[Modmail++] %cMain function ran!", "color: grey");
  969. const Settings = new __settings__();
  970. document.ModmailPlus = {};
  971. document.ModmailPlus.rules = [];
  972.  
  973. // These will be executed in any page //
  974. if(!document.ModmailPlus.length)
  975. initializeCore(Settings);
  976. if(Settings.enableCustomResponses && !$("#responseListbox"))
  977. appendResponseTemplateBox(Settings);
  978. applyCSS(Settings);
  979. ////////////////////////////////////////
  980. if(!$(".NewThread")) // execute in chat page only
  981. {
  982. appendUserInfo(Settings); // if the element already exists will be checked before appending
  983. if(Settings.chatProfileIcons && !$(".chatProfileIcon"))
  984. appendChatProfileIcons();
  985. if(!$("#realTextarea"))
  986. replaceReplyForm(Settings);
  987. fixQuoteButtons();
  988. }
  989. else // execute in create message page only
  990. {
  991. handleCreateMessagePage();
  992. }
  993.  
  994. console.log("[Modmail++] %cLoaded!", "color: lime");
  995. console.log("[Modmail++]", document.ModmailPlus);
  996. };
  997.  
  998. let URLChangeDetectorActive = false;
  999.  
  1000. // this is a hot mess, please help me
  1001. setInterval (() => {
  1002. if(this.lastPathStr != location.pathname)
  1003. {
  1004. this.lastPathStr = location.pathname;
  1005.  
  1006. console.log("[Modmail++] %cNew page detected!", "color: gold");
  1007.  
  1008. URLChangeDetectorActive = true;
  1009.  
  1010. const waitForElements = setInterval (() => {
  1011. if($(".NoThreadMessage__generic") && URLChangeDetectorActive) // add confetti explosion if no mail
  1012. {
  1013. clearInterval(waitForElements);
  1014. URLChangeDetectorActive = false;
  1015.  
  1016. console.log("[Modmail++] %cNo modmail!", "color: lime");
  1017.  
  1018. party.confetti($(".NoThreadMessage__generic"), {
  1019. count: 15,
  1020. spread: 50
  1021. });
  1022. }
  1023.  
  1024. if($(".InfoBar") && URLChangeDetectorActive) // user is on modmail "chat" page
  1025. {
  1026. clearInterval(waitForElements);
  1027. URLChangeDetectorActive = false;
  1028.  
  1029. if($("body") && !$("#CustomMetadata"))
  1030. __main__();
  1031. }
  1032. if($(".NewThread") && URLChangeDetectorActive) // user is on the create new message page
  1033. {
  1034. clearInterval(waitForElements);
  1035. URLChangeDetectorActive = false;
  1036. __main__();
  1037. }
  1038. }, 5);
  1039. }
  1040. }, 100);
  1041. })();

QingJ © 2025

镜像随时可能失效,请加Q群300939539或关注我们的公众号极客氢云获取最新地址