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.18
  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. 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. (async () => {
  165. while (true) {
  166. await this.sleep(checkInterval);
  167. const result = Array.from(document.querySelectorAll("main .group"));
  168. const temp = result[result.length - 1];
  169. if (!temp) {
  170. continue;
  171. }
  172. if (resCache === temp.innerHTML) {
  173. // console.log("匹配,resCache:", resCache);
  174. const validateResult = await this.validate(resCache).catch(err => {
  175. reject(null);
  176. return;
  177. })
  178. if (validateResult === true) {
  179. resolve(resCache);
  180. break;
  181. } else if (validateResult === false) {
  182. continue;
  183. }
  184. reject(null);
  185. break;
  186. }
  187. resCache = temp.innerHTML;
  188. console.log(`${checkInterval / 1000}s后再次检查结果`);
  189. }
  190. })();
  191. }, 4000);
  192. });
  193. }
  194.  
  195. async validate(innerHTML) {
  196. const buttons = document.querySelectorAll("form div button.btn-neutral");
  197. const errorBtn = document.querySelectorAll("form div button.btn-primary");
  198. // 如果触发gpt-4 3小时25次限制
  199. if (!buttons[0] && !errorBtn[0] && innerHTML.includes("usage cap")) {
  200. console.error("触发gpt-4 3小时25次限制,等待10min后重试")
  201. await this.sleep(10 * 60 * 1000);
  202. throw new Error("触发gpt-4 3小时25次限制");
  203. }
  204. // 如果openAI服务器报错未返回结果
  205. if (errorBtn[0]) { // && innerHTML.includes("wrong")) {
  206. if (this.retrying) {
  207. this.retrying = false;
  208. return true;
  209. }
  210. errorBtn[0].click();
  211. this.retrying = true;
  212. return false;
  213. }
  214. // 如果输出结果未包含code标签
  215. if (!innerHTML.includes("</code>")) {
  216. if (this.retrying) {
  217. this.retrying = false;
  218. console.error("第二次还是未输出yaml结构")
  219. throw new Error("未返回yaml结构")
  220. }
  221. console.error("未输出yaml结构,重试一次")
  222. buttons[0].click();
  223. this.retrying = true;
  224. return false;
  225. }
  226. this.retrying = false;
  227. // 如果还未完全输出
  228. if (buttons.length > 1) {
  229. buttons[buttons.length - 1].click();
  230. return false;
  231. }
  232. return true;
  233. }
  234.  
  235. async main(sleepTime = 5000) {
  236. while (true) {
  237. // {0: gpt-3.5, 1: gpt-4, 2: gpt-4 mobile}
  238. const modelNum = +localStorage.getItem("model_number") || this.defaultMode;
  239. const gpt4btn = document.querySelectorAll("ul > li > button.cursor-pointer")[modelNum];
  240.  
  241. console.log(`当前模型为:${gpt4btn.innerText}`);
  242. if (gpt4btn) {
  243. gpt4btn.firstChild.click()
  244. }
  245. await this.sleep(sleepTime/2);
  246. if (modelNum===1 && !location.href.endsWith("gpt-4")) {
  247. console.log("未切换到gpt-4模式, 5分钟后重试");
  248. const maxTime = Math.max.apply(null, this.responds.map(item => item.createdTime).filter(item => item).concat([0]))
  249. const diff = new Date().valueOf() - maxTime;
  250. if (maxTime && diff > 1.5 * 60 * 60 * 1000) {
  251. console.log("超时未刷新, 5分钟后刷新页面");
  252. await this.sleep(5 * 60 * 1000);
  253. location.reload();
  254. break;
  255. }
  256. this.report(`触发gpt-4 3小时25次限制,上次运行时间:${new Date(maxTime).toLocaleString()}`);
  257. await this.sleep(5 * 60 * 1000);
  258. const newChatBtn = document.querySelector("nav>div.mb-1>a:first-child");
  259. newChatBtn.click();
  260. continue;
  261. }
  262. const task = this.getTask();
  263. if (!task) {
  264. await this.sleep(5 * 60 * 1000);
  265. continue;
  266. }
  267.  
  268. const result = await task();
  269. if (result) {
  270. this.saveRespond(result);
  271. }
  272. console.log(`${sleepTime / 1000}s后将再次触发`);
  273. const newChatBtn = document.querySelector("nav>div.mb-1>a:first-child");
  274. newChatBtn.click();
  275. await this.sleep(sleepTime/2);
  276. }
  277. }
  278. }
  279.  
  280. function secondInterval() {
  281. console.log("start secondInterval...")
  282. setInterval(async () => {
  283. const responds = JSON.parse(
  284. localStorage.getItem("reaction_responds") || "[]"
  285. );
  286. const maxTime = Math.max.apply(null, responds.map(item => item.createdTime).filter(item => item).concat([0]))
  287. const diff = new Date().valueOf() - maxTime;
  288.  
  289. console.log(`last updated at: ${maxTime}, diff is ${diff}`)
  290. if (maxTime && (diff > 30 * 60 * 1000)) {
  291. console.log("超时未刷新, 5分钟后刷新页面");
  292. location.reload();
  293. }
  294. }, 10*60*1000)
  295. }
  296.  
  297. function start() {
  298. const nameEl = document.querySelector(
  299. "nav > div:last-child > div:last-child"
  300. )
  301. const name = nameEl && nameEl.innerText;
  302. if (name) {
  303. new GPT_ASK_LOOP(name);
  304. secondInterval();
  305. } else {
  306. setTimeout(() => {
  307. start();
  308. }, 5000);
  309. }
  310. }
  311. start();
  312.  
  313. })();