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