GPT Auto task

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

当前为 2023-06-27 提交的版本,查看 最新版本

  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.17
  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()}.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. autoBackup() {
  78. const respond = JSON.parse(
  79. localStorage.getItem("reaction_responds") || "[]"
  80. );
  81. if (!respond.length) {
  82. return;
  83. }
  84. const result = respond.map((item) => {
  85. const ele = document.createElement("div");
  86. ele.innerHTML = item.reaction;
  87. const res = Array.from(ele.querySelectorAll("code")).map(
  88. (el) => el.innerText
  89. );
  90. return { ...item, reaction: res };
  91. });
  92. const blob = new Blob([JSON.stringify(result)], {
  93. type: "application/octet-stream",
  94. });
  95. const url = window.URL.createObjectURL(blob);
  96. window.open(url);
  97. window.URL.revokeObjectURL(url);
  98. }
  99.  
  100. async report(tip = "") {
  101. await fetch("https://gpt-hit.deno.dev/api/update", {
  102. method: "POST",
  103. body: JSON.stringify({
  104. account: this.account,
  105. reaction_count: this.responds.length,
  106. queue_count: this.queue.length,
  107. tip: tip,
  108. }),
  109. }).catch((err) => {
  110. console.error({ err });
  111. });
  112. }
  113.  
  114. genPrompt(content, step = 1) {
  115. return step === 1 ? `${localStorage.getItem("mock_prompt"+step)}
  116.  
  117. ''' ${content} ''' ` : localStorage.getItem("mock_prompt"+step);
  118. }
  119.  
  120. getTask() {
  121. if (this.downloadBtn) {
  122. this.downloadBtn.innerText = `下载已生成结果(queue: ${this.queue.length}, res: ${this.responds.length})`;
  123. }
  124. const task = this.queue[0];
  125. this.report(task && `Working on articleId: ${task.article_id}, snippetId: ${task.id}` || "");
  126. if (!task) {
  127. console.log("任务队列为空");
  128. return;
  129. }
  130. return async () => {
  131. const { article_id, id, content } = task;
  132. const relatedAbstract = this.abstract.find((item) => item.article_id === article_id)?.content || "";
  133. console.log(`开始触发 ${article_id}-${id}, ${new Date().toTimeString()}`);
  134. const promptContent = `
  135. ${relatedAbstract}
  136.  
  137. ${content}
  138. `
  139. const prompt1 = this.genPrompt(promptContent, 1);
  140. const prompt2 = this.genPrompt(promptContent, 2);
  141. const result1 = await this.trigger(prompt1).catch((err) => {
  142. return null
  143. });
  144. if (!result1) {
  145. return null;
  146. }
  147. const result2 = await this.trigger(prompt2).catch((err) => {
  148. return null
  149. });
  150. if (!result2) {
  151. return { articleId: article_id, snippetId: id, reaction: result1 };
  152. }
  153. return { articleId: article_id, snippetId: id, reaction: result2 };
  154. // console.log("result:", result);
  155. };
  156. }
  157.  
  158. saveRespond(respond) {
  159. const { snippetId } = respond;
  160. this.responds.push({...respond, createdTime: new Date().valueOf()});
  161. this.queue = this.queue.filter((item) => item.id !== snippetId);
  162. localStorage.setItem("task_queue", JSON.stringify(this.queue));
  163. localStorage.setItem("reaction_responds", JSON.stringify(this.responds));
  164. if (this.responds.length && this.responds.length % 20 === 0) {
  165. this.autoBackup()
  166. }
  167. }
  168.  
  169. sleep(duration) {
  170. return new Promise((resolve, reject) => {
  171. setTimeout(() => {
  172. resolve(true);
  173. }, duration);
  174. });
  175. }
  176.  
  177. trigger(prompt, checkInterval = this.checkInterval) {
  178. return new Promise((resolve, reject) => {
  179. const textEl = document.querySelector("#prompt-textarea");
  180. const submitEl = document.querySelector("#prompt-textarea + button");
  181. textEl.value = prompt; //`你好, 帮我算下${Math.floor(Math.random() * 10000)}开平方的结果`;
  182. textEl.dispatchEvent(new Event("input", { bubbles: true }));
  183. setTimeout(() => {
  184. submitEl.click();
  185.  
  186. let resCache = null;
  187. (async () => {
  188. while (true) {
  189. await this.sleep(checkInterval);
  190. const result = Array.from(document.querySelectorAll("main .group"));
  191. const temp = result[result.length - 1];
  192. if (!temp) {
  193. continue;
  194. }
  195. if (resCache === temp.innerHTML) {
  196. // console.log("匹配,resCache:", resCache);
  197. const validateResult = await this.validate(resCache).catch(err => {
  198. reject(null);
  199. return;
  200. })
  201. if (validateResult === true) {
  202. resolve(resCache);
  203. break;
  204. } else if (validateResult === false) {
  205. continue;
  206. }
  207. reject(null);
  208. break;
  209. }
  210. resCache = temp.innerHTML;
  211. console.log(`${checkInterval / 1000}s后再次检查结果`);
  212. }
  213. })();
  214. }, 4000);
  215. });
  216. }
  217.  
  218. async validate(innerHTML) {
  219. const buttons = document.querySelectorAll("form div button.btn-neutral");
  220. const errorBtn = document.querySelectorAll("form div button.btn-primary");
  221. // 如果触发gpt-4 3小时25次限制
  222. if (!buttons[0] && !errorBtn[0] && innerHTML.includes("usage cap")) {
  223. console.error("触发gpt-4 3小时25次限制,等待10min后重试")
  224. await this.sleep(10 * 60 * 1000);
  225. throw new Error("触发gpt-4 3小时25次限制");
  226. }
  227. // 如果openAI服务器报错未返回结果
  228. if (errorBtn[0]) { // && innerHTML.includes("wrong")) {
  229. if (this.retrying) {
  230. this.retrying = false;
  231. return true;
  232. }
  233. errorBtn[0].click();
  234. this.retrying = true;
  235. return false;
  236. }
  237. // 如果输出结果未包含code标签
  238. if (!innerHTML.includes("</code>")) {
  239. if (this.retrying) {
  240. this.retrying = false;
  241. console.error("第二次还是未输出yaml结构")
  242. throw new Error("未返回yaml结构")
  243. }
  244. console.error("未输出yaml结构,重试一次")
  245. buttons[0].click();
  246. this.retrying = true;
  247. return false;
  248. }
  249. this.retrying = false;
  250. // 如果还未完全输出
  251. if (buttons.length > 1) {
  252. buttons[buttons.length - 1].click();
  253. return false;
  254. }
  255. return true;
  256. }
  257.  
  258. async main(sleepTime = 5000) {
  259. while (true) {
  260. // {0: gpt-3.5, 1: gpt-4, 2: gpt-4 mobile}
  261. const modelNum = +localStorage.getItem("model_number") || this.defaultMode;
  262. const gpt4btn = document.querySelectorAll("ul > li > button.cursor-pointer")[modelNum];
  263.  
  264. console.log(`当前模型为:${gpt4btn.innerText}`);
  265. if (gpt4btn) {
  266. gpt4btn.firstChild.click()
  267. }
  268. await this.sleep(sleepTime/2);
  269. if (modelNum===1 && !location.href.endsWith("gpt-4")) {
  270. console.log("未切换到gpt-4模式, 5分钟后重试");
  271. const maxTime = Math.max.apply(null, this.responds.map(item => item.createdTime).filter(item => item).concat([0]))
  272. const diff = new Date().valueOf() - maxTime;
  273. if (maxTime && diff > 1.5 * 60 * 60 * 1000) {
  274. console.log("超时未刷新, 5分钟后刷新页面");
  275. await this.sleep(5 * 60 * 1000);
  276. location.reload();
  277. break;
  278. }
  279. this.report(`触发gpt-4 3小时25次限制,上次运行时间:${new Date(maxTime).toLocaleString()}`);
  280. await this.sleep(5 * 60 * 1000);
  281. const newChatBtn = document.querySelector("nav>div.mb-1>a:first-child");
  282. newChatBtn.click();
  283. continue;
  284. }
  285. const task = this.getTask();
  286. if (!task) {
  287. await this.sleep(5 * 60 * 1000);
  288. continue;
  289. }
  290.  
  291. const result = await task();
  292. if (result) {
  293. this.saveRespond(result);
  294. }
  295. console.log(`${sleepTime / 1000}s后将再次触发`);
  296. const newChatBtn = document.querySelector("nav>div.mb-1>a:first-child");
  297. newChatBtn.click();
  298. await this.sleep(sleepTime/2);
  299. }
  300. }
  301. }
  302.  
  303. function start() {
  304. const nameEl = document.querySelector(
  305. "nav > div:last-child > div:last-child"
  306. )
  307. const name = nameEl && nameEl.innerText;
  308. if (name) {
  309. new GPT_ASK_LOOP(name);
  310. } else {
  311. setTimeout(() => {
  312. start();
  313. }, 5000);
  314. }
  315. }
  316. start();
  317.  
  318. })();