Ranged Way Idle

死亡提醒、强制刷新MWITools的价格、私信提醒音、自动任务排序、显示购买预付金/出售可获金/待领取金额、显示任务价值、默哀法师助手

  1. // ==UserScript==
  2. // @name Ranged Way Idle
  3. // @namespace http://tampermonkey.net/
  4. // @version 2.7
  5. // @description 死亡提醒、强制刷新MWITools的价格、私信提醒音、自动任务排序、显示购买预付金/出售可获金/待领取金额、显示任务价值、默哀法师助手
  6. // @author AlphB
  7. // @match https://www.milkywayidle.com/*
  8. // @match https://test.milkywayidle.com/*
  9. // @grant GM_notification
  10. // @grant GM_getValue
  11. // @grant GM_setValue
  12. // @icon https://www.google.com/s2/favicons?sz=64&domain=milkywayidle.com
  13. // @grant none
  14. // @license CC-BY-NC-SA-4.0
  15. // ==/UserScript==
  16.  
  17. (function () {
  18. const config = {
  19. notifyDeath: {enable: true, desc: "战斗中角色死亡时发送通知"},
  20. forceUpdateMarketPrice: {enable: true, desc: "进入市场时,强制更新MWITools的市场价格(依赖MWITools)"},
  21. notifyWhisperMessages: {enable: false, desc: "接受到私信时播放提醒音"},
  22. listenKeywordMessages: {enable: false, desc: "中文频道消息含有关键词时播放提醒音"},
  23. matchByRegex: {enable: false, desc: "改用正则表达式匹配中文频道消息(依赖上一条功能)"},
  24. autoTaskSort: {enable: true, desc: "自动点击MWI TaskManager的任务排序按钮(依赖MWI TaskManager)"},
  25. showMarketListingsFunds: {enable: true, desc: "显示购买预付金/出售可获金/待领取金额"},
  26. mournForMagicWayIdle: {enable: true, desc: "在控制台默哀法师助手"},
  27. showTaskValue: {enable: true, desc: "显示任务期望奖励和任务代币的价值(依赖食用工具)"},
  28. keywords: [],
  29. }
  30. const globalVariable = {
  31. battleData: {
  32. players: null,
  33. lastNotifyTime: 0,
  34. },
  35. whisperAudio: new Audio(`https://upload.thbwiki.cc/d/d1/se_bonus2.mp3`),
  36. keywordAudio: new Audio(`https://upload.thbwiki.cc/c/c9/se_pldead00.mp3`),
  37. market: {
  38. hasFundsElement: false,
  39. sellValue: null,
  40. buyValue: null,
  41. unclaimedValue: null,
  42. sellListings: null,
  43. buyListings: null
  44. },
  45. task: {
  46. taskListElement: null,
  47. taskTokenValueData: null,
  48. hasTaskValueElement: false,
  49. taskValueElements: [],
  50. tokenValue: {
  51. Bid: null,
  52. Ask: null
  53. }
  54. }
  55. };
  56.  
  57.  
  58. init();
  59.  
  60. function init() {
  61. readConfig();
  62. // 任务代币计算功能需要食用工具
  63. if (!('Edible_Tools' in localStorage) ||
  64. !JSON.parse(localStorage.getItem('Edible_Tools')) ||
  65. (!("Chest_Drop_Data" in JSON.parse(localStorage.getItem('Edible_Tools'))))) {
  66. config.showTaskValue.enable = false;
  67. saveConfig({showTaskValue: false});
  68. }
  69. // 更新市场价格需要MWITools支持
  70. if (!('MWITools_marketAPI_json' in localStorage) ||
  71. !JSON.parse(localStorage.getItem('MWITools_marketAPI_json')) ||
  72. (!("marketData" in JSON.parse(localStorage.getItem('MWITools_marketAPI_json'))))) {
  73. config.forceUpdateMarketPrice.enable = false;
  74. saveConfig({forceUpdateMarketPrice: false});
  75. }
  76. globalVariable.whisperAudio.volume = 0.4;
  77. globalVariable.keywordAudio.volume = 0.4;
  78. let observer = new MutationObserver(function () {
  79. if (config.showMarketListingsFunds.enable) showMarketListingsFunds();
  80. if (config.autoTaskSort.enable) autoClickTaskSortButton();
  81. if (config.showTaskValue.enable) showTaskValue();
  82. showConfigMenu();
  83. });
  84. observer.observe(document, {childList: true, subtree: true});
  85. if (config.showTaskValue.enable) {
  86. globalVariable.task.taskTokenValueData = getTaskTokenValue();
  87. }
  88. if (config.mournForMagicWayIdle.enable) {
  89. console.log("为法师助手默哀");
  90. }
  91.  
  92. const oriGet = Object.getOwnPropertyDescriptor(MessageEvent.prototype, "data").get;
  93.  
  94. function hookedGet() {
  95. const socket = this.currentTarget;
  96. if (!(socket instanceof WebSocket) || !socket.url ||
  97. (socket.url.indexOf("api.milkywayidle.com/ws") === -1 && socket.url.indexOf("api-test.milkywayidle.com/ws") === -1)) {
  98. return oriGet.call(this);
  99. }
  100. const message = oriGet.call(this);
  101. return handleMessage(message);
  102. }
  103.  
  104. Object.defineProperty(MessageEvent.prototype, "data", {
  105. get: hookedGet,
  106. configurable: true,
  107. enumerable: true
  108. });
  109. }
  110.  
  111. function readConfig() {
  112. const localConfig = localStorage.getItem("ranged_way_idle_config");
  113. if (localConfig) {
  114. const localConfigObj = JSON.parse(localConfig);
  115. for (let key in localConfigObj) {
  116. if (config.hasOwnProperty(key) && key !== 'keywords') {
  117. config[key].enable = localConfigObj[key];
  118. }
  119. }
  120. config.keywords = localConfigObj.keywords;
  121. }
  122. }
  123.  
  124. function saveConfig(obj) {
  125. // 仅保存enable开关和keywords
  126. const saveConfigObj = {};
  127. const configMenu = document.querySelectorAll("div#ranged_way_idle_config_menu input");
  128. if (configMenu.length === 0) return;
  129. for (const checkbox of configMenu) {
  130. config[checkbox.id].enable = checkbox.checked;
  131. saveConfigObj[checkbox.id] = checkbox.checked;
  132. }
  133. for (let key in obj) {
  134. saveConfigObj[key] = obj[key];
  135. }
  136. saveConfigObj.keywords = config.keywords;
  137. localStorage.setItem("ranged_way_idle_config", JSON.stringify(saveConfigObj));
  138. }
  139.  
  140. function showConfigMenu() {
  141. const targetNode = document.querySelector("div.SettingsPanel_profileTab__214Bj");
  142. if (targetNode) {
  143. if (!targetNode.querySelector("#ranged_way_idle_config_menu")) {
  144. // enable开关部分
  145. targetNode.insertAdjacentHTML("beforeend", `<div id="ranged_way_idle_config_menu"></div>`);
  146. const insertElem = targetNode.querySelector("div#ranged_way_idle_config_menu");
  147. insertElem.insertAdjacentHTML(
  148. "beforeend",
  149. `<div style="float: left;" id="ranged_way_idle_config">${
  150. "Ranged Way Idle 设置(刷新后生效)"
  151. }</div></br>`
  152. );
  153. insertElem.insertAdjacentHTML(
  154. "beforeend",
  155. `<div style="float: left;" id="ranged_way_idle_config">${
  156. "若刷新后选项变化或仍不生效,说明插件不兼容,可能是因为未安装插件或版本过久"
  157. }</div></br>`
  158. );
  159. for (let key in config) {
  160. if (key === 'keywords') continue;
  161. insertElem.insertAdjacentHTML(
  162. "beforeend",
  163. `<div style="float: left;">
  164. <input type="checkbox" id="${key}" ${config[key].enable ? "checked" : ""}>${config[key].desc}
  165. </div></br>`
  166. );
  167. }
  168. insertElem.addEventListener("change", saveConfig);
  169.  
  170. // 控制 keywords 列表
  171. const container = document.createElement('div');
  172. container.style.marginTop = '20px';
  173. container.classList.add("ranged_way_idle_keywords_config_menu")
  174. const input = document.createElement('input');
  175. input.type = 'text';
  176. input.style.width = '200px';
  177. input.placeholder = 'Ranged Way Idle 监听' + (config.matchByRegex.enable ? '正则' : '关键词');
  178. const button = document.createElement('button');
  179. button.textContent = '添加';
  180. const listContainer = document.createElement('div');
  181. listContainer.style.marginTop = '10px';
  182. container.appendChild(input);
  183. container.appendChild(button);
  184. container.appendChild(listContainer);
  185. targetNode.insertBefore(container, targetNode.nextSibling);
  186.  
  187. function renderList() {
  188. listContainer.innerHTML = '';
  189. config.keywords.forEach((item, index) => {
  190. const itemDiv = document.createElement('div');
  191. itemDiv.textContent = item;
  192. itemDiv.style.margin = 'auto';
  193. itemDiv.style.width = '200px';
  194. itemDiv.style.cursor = 'pointer';
  195. itemDiv.addEventListener('click', () => {
  196. config.keywords.splice(index, 1);
  197. renderList();
  198. });
  199. listContainer.appendChild(itemDiv);
  200. });
  201. saveConfig();
  202. }
  203.  
  204. renderList();
  205. button.addEventListener('click', () => {
  206. const newItem = input.value.trim();
  207. if (newItem) {
  208. config.keywords.push(newItem);
  209. input.value = '';
  210. saveConfig();
  211. renderList();
  212. }
  213. });
  214. }
  215. }
  216. }
  217.  
  218. function handleMessage(message) {
  219. try {
  220. const obj = JSON.parse(message);
  221. if (!obj) return message;
  222. switch (obj.type) {
  223. case "init_character_data":
  224. globalVariable.market.sellListings = {};
  225. globalVariable.market.buyListings = {};
  226. updateMarketListings(obj.myMarketListings);
  227. break;
  228. case "market_listings_updated":
  229. updateMarketListings(obj.endMarketListings);
  230. break;
  231. case "new_battle":
  232. if (config.notifyDeath.enable) initBattle(obj);
  233. break;
  234. case "battle_updated":
  235. if (config.notifyDeath.enable) checkDeath(obj);
  236. break;
  237. case "market_item_order_books_updated":
  238. if (config.forceUpdateMarketPrice.enable) marketPriceUpdate(obj);
  239. break;
  240. case "quests_updated":
  241. for (let e of globalVariable.task.taskValueElements) {
  242. e.remove();
  243. }
  244. globalVariable.task.taskValueElements = [];
  245. globalVariable.task.hasTaskValueElement = false;
  246. break;
  247. case "chat_message_received":
  248. handleChatMessage(obj);
  249. break;
  250. }
  251. } catch (e) {
  252. console.error(e);
  253. }
  254. return message;
  255. }
  256.  
  257. function notifyDeath(name) {
  258. // 如果间隔小于60秒,强制不播报
  259. const nowTime = Date.now();
  260. if (nowTime - globalVariable.battleData.lastNotifyTime < 60000) return;
  261. globalVariable.battleData.lastNotifyTime = nowTime;
  262. new Notification('🎉🎉🎉喜报🎉🎉🎉', {body: `${name} 死了!`});
  263. }
  264.  
  265. function initBattle(obj) {
  266. // 处理战斗中各个玩家的角色名,供播报死亡信息
  267. globalVariable.battleData.players = [];
  268. for (let player of obj.players) {
  269. globalVariable.battleData.players.push({
  270. name: player.name, isAlive: player.currentHitpoints > 0,
  271. });
  272. if (player.currentHitpoints === 0) {
  273. notifyDeath(player.name);
  274. }
  275. }
  276. }
  277.  
  278. function checkDeath(obj) {
  279. // 检查玩家是否死亡
  280. if (!globalVariable.battleData.players) return;
  281. for (let key in obj.pMap) {
  282. const index = parseInt(key);
  283. if (globalVariable.battleData.players[index].isAlive && obj.pMap[key].cHP === 0) {
  284. // 角色 活->死 时发送提醒
  285. globalVariable.battleData.players[index].isAlive = false;
  286. notifyDeath(globalVariable.battleData.players[index].name);
  287. } else if (obj.pMap[key].cHP > 0) {
  288. globalVariable.battleData.players[index].isAlive = true;
  289. }
  290. }
  291. }
  292.  
  293. function marketPriceUpdate(obj) {
  294. // 强制刷新MWITools的市场价格数据
  295. if (config.showTaskValue.enable) {
  296. globalVariable.task.taskTokenValueData = getTaskTokenValue();
  297. }
  298. const marketAPIjson = JSON.parse(localStorage.getItem('MWITools_marketAPI_json'));
  299. if (!('MWITools_marketAPI_json' in localStorage) ||
  300. !JSON.parse(localStorage.getItem('MWITools_marketAPI_json')) ||
  301. (!("marketData" in JSON.parse(localStorage.getItem('MWITools_marketAPI_json'))))) return;
  302. const itemHrid = obj.marketItemOrderBooks.itemHrid;
  303. if (!(itemHrid in marketAPIjson.marketData)) return;
  304. const orderBooks = obj.marketItemOrderBooks.orderBooks;
  305. for (let enhanceLevel in orderBooks) {
  306. if (!(enhanceLevel in marketAPIjson.marketData[itemHrid])) {
  307. marketAPIjson.marketData[itemHrid][enhanceLevel] = {a: 0, b: 0};
  308. }
  309. const ask = orderBooks[enhanceLevel].asks;
  310. if (ask && ask.length) {
  311. marketAPIjson.marketData[itemHrid][enhanceLevel].a = Math.min(...ask.map(listing => listing.price));
  312. }
  313. const bid = orderBooks[enhanceLevel].bids;
  314. if (bid && ask.length) {
  315. marketAPIjson.marketData[itemHrid][enhanceLevel].b = Math.max(...bid.map(listing => listing.price));
  316. }
  317. }
  318. // 将修改后结果写回marketAPI缓存,完成对marketAPI价格的强制修改
  319. localStorage.setItem("MWITools_marketAPI_json", JSON.stringify(marketAPIjson));
  320. }
  321.  
  322. function handleChatMessage(obj) {
  323. // 处理聊天信息
  324. if (obj.message.chan === "/chat_channel_types/whisper") {
  325. if (config.notifyWhisperMessages.enable) {
  326. globalVariable.whisperAudio.play();
  327. }
  328. } else if (obj.message.chan === "/chat_channel_types/chinese") {
  329. if (config.listenKeywordMessages.enable) {
  330. for (let keyword of config.keywords) {
  331. if (!config.matchByRegex.enable && obj.message.m.includes(keyword)) {
  332. globalVariable.keywordAudio.play();
  333. } else if (config.matchByRegex.enable) {
  334. const regex = new RegExp(keyword, "g");
  335. if (regex.test(obj.message.m)) {
  336. globalVariable.keywordAudio.play();
  337. }
  338. }
  339. }
  340.  
  341. }
  342. }
  343. }
  344.  
  345. function autoClickTaskSortButton() {
  346. // 点击MWI TaskManager的任务排序按钮
  347. const targetElement = document.querySelector('#TaskSort');
  348. if (targetElement && targetElement.textContent !== '手动排序') {
  349. targetElement.click();
  350. targetElement.textContent = '手动排序';
  351. }
  352. }
  353.  
  354. function formatCoinValue(num) {
  355. if (isNaN(num)) return "NaN";
  356. if (num >= 1e13) {
  357. return Math.floor(num / 1e12) + "T";
  358. } else if (num >= 1e10) {
  359. return Math.floor(num / 1e9) + "B";
  360. } else if (num >= 1e7) {
  361. return Math.floor(num / 1e6) + "M";
  362. } else if (num >= 1e4) {
  363. return Math.floor(num / 1e3) + "K";
  364. }
  365. return num.toString();
  366. }
  367.  
  368. function updateMarketListings(obj) {
  369. // 更新市场价格
  370. for (let listing of obj) {
  371. console.log(listing);
  372. if (listing.status === "/market_listing_status/cancelled") {
  373. delete globalVariable.market[listing.isSell ? "sellListings" : "buyListings"][listing.id];
  374. continue
  375. }
  376. const tax = (listing.itemHrid === "/items/bag_of_10_cowbells") ? 0.82 : 0.98;
  377. globalVariable.market[listing.isSell ? "sellListings" : "buyListings"][listing.id] = {
  378. itemHrid: listing.itemHrid,
  379. price: (listing.orderQuantity - listing.filledQuantity) * (listing.isSell ? Math.floor(listing.price * tax) : listing.price),
  380. unclaimedCoinCount: listing.unclaimedCoinCount,
  381. }
  382. }
  383. globalVariable.market.buyValue = 0;
  384. globalVariable.market.sellValue = 0;
  385. globalVariable.market.unclaimedValue = 0;
  386. for (let id in globalVariable.market.buyListings) {
  387. const listing = globalVariable.market.buyListings[id];
  388. globalVariable.market.buyValue += listing.price;
  389. globalVariable.market.unclaimedValue += listing.unclaimedCoinCount;
  390. }
  391. for (let id in globalVariable.market.sellListings) {
  392. const listing = globalVariable.market.sellListings[id];
  393. globalVariable.market.sellValue += listing.price;
  394. globalVariable.market.unclaimedValue += listing.unclaimedCoinCount;
  395. }
  396. globalVariable.market.hasFundsElement = false;
  397. }
  398.  
  399. function showMarketListingsFunds() {
  400. // 如果已经存在节点,不必更新
  401. if (globalVariable.market.hasFundsElement) return;
  402. const coinStackElement = document.querySelector("div.MarketplacePanel_coinStack__1l0UD");
  403. // 不在市场面板,不必更新
  404. if (coinStackElement) {
  405. coinStackElement.style.top = "0px";
  406. coinStackElement.style.left = "0px";
  407. let fundsElement = coinStackElement.parentNode.querySelector("div.fundsElement");
  408. while (fundsElement) {
  409. fundsElement.remove();
  410. fundsElement = coinStackElement.parentNode.querySelector("div.fundsElement");
  411. }
  412. makeNode("购买预付金", globalVariable.market.buyValue, ["125px", "0px"]);
  413. makeNode("出售可获金", globalVariable.market.sellValue, ["125px", "22px"]);
  414. makeNode("待领取金额", globalVariable.market.unclaimedValue, ["0px", "22px"]);
  415. globalVariable.market.hasFundsElement = true;
  416. }
  417.  
  418. function makeNode(text, value, style) {
  419. let node = coinStackElement.cloneNode(true);
  420. node.classList.add("fundsElement");
  421. const countNode = node.querySelector("div.Item_count__1HVvv");
  422. const textNode = node.querySelector("div.Item_name__2C42x");
  423. if (countNode) countNode.textContent = formatCoinValue(value);
  424. if (textNode) textNode.innerHTML = `<span style="color: rgb(102,204,255); font-weight: bold;">${text}</span>`;
  425. node.style.left = style[0];
  426. node.style.top = style[1];
  427. coinStackElement.parentNode.insertBefore(node, coinStackElement.nextSibling);
  428. }
  429. }
  430.  
  431. function getTaskTokenValue() {
  432. const chestDropData = JSON.parse(localStorage.getItem("Edible_Tools")).Chest_Drop_Data;
  433. const lootsName = ["大陨石舱", "大工匠匣", "大宝箱"];
  434. const bidValueList = [
  435. parseFloat(chestDropData["Large Meteorite Cache"]["期望产出Bid"]),
  436. parseFloat(chestDropData["Large Artisan's Crate"]["期望产出Bid"]),
  437. parseFloat(chestDropData["Large Treasure Chest"]["期望产出Bid"]),
  438. ]
  439. const askValueList = [
  440. parseFloat(chestDropData["Large Meteorite Cache"]["期望产出Ask"]),
  441. parseFloat(chestDropData["Large Artisan's Crate"]["期望产出Ask"]),
  442. parseFloat(chestDropData["Large Treasure Chest"]["期望产出Ask"]),
  443. ]
  444. const res = {
  445. bidValue: Math.max(...bidValueList),
  446. askValue: Math.max(...askValueList)
  447. }
  448. // bid和ask的最佳兑换选项
  449. res.bidLoots = lootsName[bidValueList.indexOf(res.bidValue)];
  450. res.askLoots = lootsName[askValueList.indexOf(res.askValue)];
  451. // bid和ask的任务代币价值
  452. res.bidValue = Math.round(res.bidValue / 30);
  453. res.askValue = Math.round(res.askValue / 30);
  454. // 小紫牛的礼物的额外价值计算
  455. res.giftValueBid = Math.round(parseFloat(chestDropData["Purple's Gift"]["期望产出Bid"]));
  456. res.giftValueAsk = Math.round(parseFloat(chestDropData["Purple's Gift"]["期望产出Ask"]));
  457. if (config.forceUpdateMarketPrice.enable) {
  458. const marketJSON = JSON.parse(localStorage.getItem("MWITools_marketAPI_json"));
  459. marketJSON.marketData["/items/task_token"] = {"0": {a: res.askValue, b: res.bidValue}};
  460. localStorage.setItem("MWITools_marketAPI_json", JSON.stringify(marketJSON));
  461. }
  462. res.rewardValueBid = res.bidValue + res.giftValueBid / 50;
  463. res.rewardValueAsk = res.askValue + res.giftValueAsk / 50;
  464. return res;
  465. }
  466.  
  467. function showTaskValue() {
  468. globalVariable.task.taskListElement = document.querySelector("div.TasksPanel_taskList__2xh4k");
  469. // 如果不在任务面板,则销毁显示任务价值的元素
  470. if (!globalVariable.task.taskListElement) {
  471. globalVariable.task.taskValueElements = [];
  472. globalVariable.task.hasTaskValueElement = false;
  473. globalVariable.task.taskListElement = null;
  474. return;
  475. }
  476. // 如果已经存在任务价值的元素,不再更新
  477. if (globalVariable.task.hasTaskValueElement) return;
  478. globalVariable.task.hasTaskValueElement = true;
  479. const taskNodes = [...globalVariable.task.taskListElement.querySelectorAll("div.RandomTask_randomTask__3B9fA")];
  480.  
  481. function convertKEndStringToNumber(str) {
  482. if (str.endsWith('K') || str.endsWith('k')) {
  483. return Number(str.slice(0, -1)) * 1000;
  484. } else {
  485. return Number(str);
  486. }
  487. }
  488.  
  489. taskNodes.forEach(function (node) {
  490. const reward = node.querySelector("div.RandomTask_rewards__YZk7D");
  491. const coin = convertKEndStringToNumber(reward.querySelectorAll("div.Item_count__1HVvv")[0].innerText);
  492. const tokenCount = Number(reward.querySelectorAll("div.Item_count__1HVvv")[1].innerText);
  493. const newDiv = document.createElement("div");
  494. newDiv.textContent = `奖励期望收益:
  495. ${formatCoinValue(coin + tokenCount * globalVariable.task.taskTokenValueData.rewardValueAsk)} /
  496. ${formatCoinValue(coin + tokenCount * globalVariable.task.taskTokenValueData.rewardValueBid)}`;
  497. newDiv.style.color = "rgb(248,0,248)";
  498. newDiv.classList.add("rewardValue");
  499. node.querySelector("div.RandomTask_action__3eC6o").appendChild(newDiv);
  500. globalVariable.task.taskValueElements.push(newDiv);
  501. });
  502. }
  503. })();