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