Ranged Way Idle

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

当前为 2025-06-07 提交的版本,查看 最新版本

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

QingJ © 2025

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