Ranged Way Idle

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

目前為 2025-06-07 提交的版本,檢視 最新版本

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