GPT Auto task

根据缓存中的task_queue自动在网页上与chat gpt对话

目前為 2023-06-28 提交的版本,檢視 最新版本

  1. // ==UserScript==
  2. // @namespace https://greasyfork.org/zh-CN/users/1106595-ikkem-lin
  3. // @name GPT Auto task
  4. // @author Mark
  5. // @description 根据缓存中的task_queue自动在网页上与chat gpt对话
  6. // @homepageURL https://github.com/IKKEM-Lin/gpt-auto-task
  7. // @version 0.0.20
  8. // @match *chat.openai.com/*
  9. // @run-at document-idle
  10. // ==/UserScript==
  11. (function () {
  12. "use strict";
  13. class GPT_ASK_LOOP {
  14. queue = [];
  15. abstract = [];
  16. responds = [];
  17. checkInterval = 20000;
  18. account = "";
  19. downloadBtn = null;
  20. retrying = false;
  21. defaultMode = 2;
  22.  
  23. constructor(account) {
  24. this.responds = JSON.parse(
  25. localStorage.getItem("reaction_responds") || "[]"
  26. );
  27. const queueCache = JSON.parse(localStorage.getItem("task_queue") || "[]");
  28. this.abstract = JSON.parse(localStorage.getItem("task_abstract") || "[]");
  29. const resSnippetIds = this.responds.map((respond) => respond.snippetId);
  30. this.queue = queueCache.filter((item) => !resSnippetIds.includes(item.id));
  31. this.account = account || Math.ceil(Math.random() * 1e10).toString(32);
  32. const btnWrap = document.createElement("div");
  33. btnWrap.innerHTML = `<button style="padding: 4px 8px;position: fixed;bottom: 20%;right: 8px;border-radius: 4px;background-color: #224466;color: #fff;">下载已生成结果(queue: ${this.queue.length}, res: ${this.responds.length})</button>`;
  34. this.downloadBtn = btnWrap.querySelector("button");
  35. this.downloadBtn.onclick = this.handleDownload.bind(this);
  36. document.body.appendChild(btnWrap);
  37. this.main();
  38. }
  39.  
  40. handleDownload() {
  41. const respond = JSON.parse(
  42. localStorage.getItem("reaction_responds") || "[]"
  43. );
  44. if (!respond.length) {
  45. return;
  46. }
  47. const result = respond.map((item) => {
  48. const ele = document.createElement("div");
  49. ele.innerHTML = item.reaction;
  50. const res = Array.from(ele.querySelectorAll("code")).map(
  51. (el) => el.innerText
  52. );
  53. return { ...item, reaction: res };
  54. });
  55. const now = new Date();
  56. this.downloadFile(
  57. JSON.stringify(result),
  58. `${now.getFullYear()}-${now.getMonth() + 1
  59. }-${now.getDate()}-${now.getHours()}${now.getMinutes()}${now.getSeconds()}-${result.length}.json`
  60. );
  61. }
  62.  
  63. downloadFile(data, fileName) {
  64. const a = document.createElement("a");
  65. document.body.appendChild(a);
  66. a.style = "display: none";
  67. const blob = new Blob([data], {
  68. type: "application/octet-stream",
  69. });
  70. const url = window.URL.createObjectURL(blob);
  71. a.href = url;
  72. a.download = fileName;
  73. a.click();
  74. window.URL.revokeObjectURL(url);
  75. }
  76.  
  77. async report(tip = "") {
  78. await fetch("https://gpt-hit.deno.dev/api/update", {
  79. method: "POST",
  80. body: JSON.stringify({
  81. account: this.account,
  82. reaction_count: this.responds.length,
  83. queue_count: this.queue.length,
  84. tip: tip,
  85. }),
  86. }).catch((err) => {
  87. console.error({ err });
  88. });
  89. }
  90.  
  91. genPrompt(content, step = 1) {
  92. return step === 1 ? `${localStorage.getItem("mock_prompt"+step)}
  93.  
  94. ''' ${content} ''' ` : localStorage.getItem("mock_prompt"+step);
  95. }
  96.  
  97. getTask() {
  98. if (this.downloadBtn) {
  99. this.downloadBtn.innerText = `下载已生成结果(queue: ${this.queue.length}, res: ${this.responds.length})`;
  100. }
  101. const task = this.queue[0];
  102. this.report(task && `Working on articleId: ${task.article_id}, snippetId: ${task.id}` || "");
  103. if (!task) {
  104. console.log("任务队列为空");
  105. return;
  106. }
  107. return async () => {
  108. const { article_id, id, content } = task;
  109. const relatedAbstract = this.abstract.find((item) => item.article_id === article_id)?.content || "";
  110. console.log(`开始触发 ${article_id}-${id}, ${new Date().toTimeString()}`);
  111. const promptContent = `
  112. ${relatedAbstract}
  113.  
  114. ${content}
  115. `
  116. const prompt1 = this.genPrompt(promptContent, 1);
  117. const prompt2 = this.genPrompt(promptContent, 2);
  118. const result1 = await this.trigger(prompt1).catch((err) => {
  119. return null
  120. });
  121. if (!result1) {
  122. return null;
  123. }
  124. const result2 = await this.trigger(prompt2).catch((err) => {
  125. return null
  126. });
  127. if (!result2) {
  128. return { articleId: article_id, snippetId: id, reaction: result1 };
  129. }
  130. return { articleId: article_id, snippetId: id, reaction: result2 };
  131. // console.log("result:", result);
  132. };
  133. }
  134.  
  135. saveRespond(respond) {
  136. const { snippetId } = respond;
  137. this.responds.push({...respond, createdTime: new Date().valueOf()});
  138. this.queue = this.queue.filter((item) => item.id !== snippetId);
  139. localStorage.setItem("task_queue", JSON.stringify(this.queue));
  140. localStorage.setItem("reaction_responds", JSON.stringify(this.responds));
  141. if (this.responds.length && ((this.responds.length % 10) === 0)) {
  142. this.handleDownload.bind(this)()
  143. }
  144. }
  145.  
  146. sleep(duration) {
  147. return new Promise((resolve, reject) => {
  148. setTimeout(() => {
  149. resolve(true);
  150. }, duration);
  151. });
  152. }
  153.  
  154. trigger(prompt, checkInterval = this.checkInterval) {
  155. return new Promise((resolve, reject) => {
  156. const textEl = document.querySelector("#prompt-textarea");
  157. const submitEl = document.querySelector("#prompt-textarea + button");
  158. textEl.value = prompt; //`你好, 帮我算下${Math.floor(Math.random() * 10000)}开平方的结果`;
  159. textEl.dispatchEvent(new Event("input", { bubbles: true }));
  160. setTimeout(() => {
  161. submitEl.click();
  162.  
  163. let resCache = null;
  164. let checkOutputCount = 0;
  165. (async () => {
  166. while (true) {
  167. await this.sleep(checkInterval);
  168. const result = Array.from(document.querySelectorAll("main .group"));
  169. const temp = result[result.length - 1];
  170. if (!temp) {
  171. if (checkOutputCount > 0) {
  172. console.log("检查结果超时");
  173. reject(null);
  174. break;
  175. }
  176. checkOutputCount++;
  177. continue;
  178. }
  179. if (resCache === temp.innerHTML) {
  180. // console.log("匹配,resCache:", resCache);
  181. const validateResult = await this.validate(resCache).catch(err => {
  182. reject(null);
  183. return;
  184. })
  185. if (validateResult === true) {
  186. resolve(resCache);
  187. break;
  188. } else if (validateResult === false) {
  189. continue;
  190. }
  191. reject(null);
  192. break;
  193. }
  194. resCache = temp.innerHTML;
  195. console.log(`${checkInterval / 1000}s后再次检查结果`);
  196. }
  197. })();
  198. }, 4000);
  199. });
  200. }
  201.  
  202. async validate(innerHTML) {
  203. const buttons = document.querySelectorAll("form div button.btn-neutral");
  204. const errorBtn = document.querySelectorAll("form div button.btn-primary");
  205. // 如果触发gpt-4 3小时25次限制
  206. if (!buttons[0] && !errorBtn[0] && innerHTML.includes("usage cap")) {
  207. console.error("触发gpt-4 3小时25次限制,等待10min后重试")
  208. await this.sleep(10 * 60 * 1000);
  209. throw new Error("触发gpt-4 3小时25次限制");
  210. }
  211. // 如果openAI服务器报错未返回结果
  212. if (errorBtn[0]) { // && innerHTML.includes("wrong")) {
  213. if (this.retrying) {
  214. this.retrying = false;
  215. return true;
  216. }
  217. errorBtn[0].click();
  218. this.retrying = true;
  219. return false;
  220. }
  221. // 如果输出结果未包含code标签
  222. if (!innerHTML.includes("</code>")) {
  223. if (this.retrying) {
  224. this.retrying = false;
  225. console.error("第二次还是未输出yaml结构")
  226. throw new Error("未返回yaml结构")
  227. }
  228. console.error("未输出yaml结构,重试一次")
  229. buttons[0].click();
  230. this.retrying = true;
  231. return false;
  232. }
  233. this.retrying = false;
  234. // 如果还未完全输出
  235. if (buttons.length > 1) {
  236. buttons[buttons.length - 1].click();
  237. return false;
  238. }
  239. return true;
  240. }
  241.  
  242. async main(sleepTime = 5000) {
  243. while (true) {
  244. // {0: gpt-3.5, 1: gpt-4, 2: gpt-4 mobile}
  245. const modelNum = +localStorage.getItem("model_number") || this.defaultMode;
  246. const gpt4btn = document.querySelectorAll("ul > li > button.cursor-pointer")[modelNum];
  247.  
  248. console.log(`当前模型为:${gpt4btn.innerText}`);
  249. if (gpt4btn) {
  250. gpt4btn.firstChild.click()
  251. }
  252. await this.sleep(sleepTime/2);
  253. if (modelNum===1 && !location.href.endsWith("gpt-4")) {
  254. console.log("未切换到gpt-4模式, 5分钟后重试");
  255. const maxTime = Math.max.apply(null, this.responds.map(item => item.createdTime).filter(item => item).concat([0]))
  256. const diff = new Date().valueOf() - maxTime;
  257. if (maxTime && diff > 1.5 * 60 * 60 * 1000) {
  258. console.log("超时未刷新, 5分钟后刷新页面");
  259. await this.sleep(5 * 60 * 1000);
  260. location.reload();
  261. break;
  262. }
  263. this.report(`触发gpt-4 3小时25次限制,上次运行时间:${new Date(maxTime).toLocaleString()}`);
  264. await this.sleep(5 * 60 * 1000);
  265. const newChatBtn = document.querySelector("nav>div.mb-1>a:first-child");
  266. newChatBtn.click();
  267. continue;
  268. }
  269. const task = this.getTask();
  270. if (!task) {
  271. await this.sleep(5 * 60 * 1000);
  272. continue;
  273. }
  274.  
  275. const result = await task();
  276. if (result) {
  277. this.saveRespond(result);
  278. }
  279. console.log(`${sleepTime / 1000}s后将再次触发`);
  280. const newChatBtn = document.querySelector("nav>div.mb-1>a:first-child");
  281. newChatBtn.click();
  282. await this.sleep(sleepTime/2);
  283. }
  284. }
  285. }
  286.  
  287. function secondInterval() {
  288. console.log("start secondInterval...")
  289. setInterval(async () => {
  290. const responds = JSON.parse(
  291. localStorage.getItem("reaction_responds") || "[]"
  292. );
  293. const maxTime = Math.max.apply(null, responds.map(item => item.createdTime).filter(item => item).concat([0]))
  294. const diff = new Date().valueOf() - maxTime;
  295.  
  296. console.log(`last updated at: ${maxTime}, diff is ${diff}`)
  297. if (maxTime && (diff > 30 * 60 * 1000)) {
  298. console.log("超时未刷新, 5分钟后刷新页面");
  299. location.reload();
  300. }
  301. }, 10*60*1000)
  302. }
  303.  
  304. function start() {
  305. const nameEl = document.querySelector(
  306. "nav > div:last-child > div:last-child"
  307. )
  308. const name = nameEl && nameEl.innerText;
  309. if (name) {
  310. new GPT_ASK_LOOP(name);
  311. secondInterval();
  312. } else {
  313. setTimeout(() => {
  314. start();
  315. }, 5000);
  316. }
  317. }
  318. start();
  319.  
  320. })();