This commit is contained in:
zyc404 2024-01-04 10:28:55 +08:00
commit 9229be62cb
9 changed files with 998 additions and 1009 deletions

View file

@ -1,8 +1,8 @@
import plugin from '../../../lib/plugins/plugin.js' import plugin from '../../../lib/plugins/plugin.js'
import common from '../../../lib/common/common.js'
import _ from 'lodash' import _ from 'lodash'
import { Config, defaultOpenAIAPI } from '../utils/config.js' import { Config, defaultOpenAIAPI } from '../utils/config.js'
import { v4 as uuid } from 'uuid' import { v4 as uuid } from 'uuid'
import delay from 'delay'
import { ChatGPTAPI } from '../utils/openai/chatgpt-api.js' import { ChatGPTAPI } from '../utils/openai/chatgpt-api.js'
import SydneyAIClient from '../utils/SydneyAIClient.js' import SydneyAIClient from '../utils/SydneyAIClient.js'
import { PoeClient } from '../utils/poe/index.js' import { PoeClient } from '../utils/poe/index.js'
@ -1041,7 +1041,7 @@ export class chatgpt extends plugin {
logger.info(`问题超时已弹出chatgpt队列前方还有${length}个问题。管理员可通过#清空队列来强制清除所有等待的问题。`) logger.info(`问题超时已弹出chatgpt队列前方还有${length}个问题。管理员可通过#清空队列来强制清除所有等待的问题。`)
} }
} }
await delay(1500) await common.sleep(1500)
} }
} }
} }
@ -1525,12 +1525,7 @@ export class chatgpt extends plugin {
} }
const userData = await getUserData(e.user_id) const userData = await getUserData(e.user_id)
const useCast = userData.cast || {} const useCast = userData.cast || {}
if (use === 'browser') { if (use === 'bing') {
{
return await this.chatgptBrowserBased(prompt, conversation)
}
} else if (use === 'bing') {
{
let throttledTokens = [] let throttledTokens = []
let { let {
bingToken, bingToken,
@ -1711,7 +1706,7 @@ export class chatgpt extends plugin {
retry = 0 retry = 0
} }
} else { } else {
// 未登录用户maxConv目前为5或10出验证码没救 // 未登录用户maxConv目前为5或10出验证码是ip或MUID问题
logger.warn(`token [${bingToken}] 出现必应验证码请前往网页版或app手动解决`) logger.warn(`token [${bingToken}] 出现必应验证码请前往网页版或app手动解决`)
errorMessage = message errorMessage = message
retry = 0 retry = 0
@ -1760,12 +1755,11 @@ export class chatgpt extends plugin {
} }
} while (retry > 0) } while (retry > 0)
if (errorMessage) { if (errorMessage) {
response = response || {}
if (errorMessage.includes('CaptchaChallenge')) { if (errorMessage.includes('CaptchaChallenge')) {
if (bingToken) { if (bingToken) {
errorMessage = '出现验证码请使用当前账户前往https://www.bing.com/chat或Edge侧边栏或移动端APP手动解除验证码' errorMessage = '出现验证码请使用当前账户前往https://www.bing.com/chat或Edge侧边栏或移动端APP手动解除验证码'
} else { } else {
errorMessage = '未配置必应账户,绑定必应账户再使用必应模式' errorMessage = '未配置必应账户,建议绑定必应账户再使用必应模式'
} }
} }
return { return {
@ -1790,9 +1784,7 @@ export class chatgpt extends plugin {
noMsg: true noMsg: true
} }
} }
}
} else if (use === 'api3') { } else if (use === 'api3') {
{
// official without cloudflare // official without cloudflare
let accessToken = await redis.get('CHATGPT:TOKEN') let accessToken = await redis.get('CHATGPT:TOKEN')
if (!accessToken) { if (!accessToken) {
@ -1815,9 +1807,7 @@ export class chatgpt extends plugin {
await redis.set(`CHATGPT:CONVERSATION_CREATER_NICK_NAME:${sendMessageResult.conversationId}`, e.sender.card) await redis.set(`CHATGPT:CONVERSATION_CREATER_NICK_NAME:${sendMessageResult.conversationId}`, e.sender.card)
} }
return sendMessageResult return sendMessageResult
}
} else if (use === 'chatglm') { } else if (use === 'chatglm') {
{
const cacheOptions = { const cacheOptions = {
namespace: 'chatglm_6b', namespace: 'chatglm_6b',
store: new KeyvFile({ filename: 'cache.json' }) store: new KeyvFile({ filename: 'cache.json' })
@ -1828,9 +1818,7 @@ export class chatgpt extends plugin {
}) })
let sendMessageResult = await this.chatGPTApi.sendMessage(prompt, conversation) let sendMessageResult = await this.chatGPTApi.sendMessage(prompt, conversation)
return sendMessageResult return sendMessageResult
}
} else if (use === 'poe') { } else if (use === 'poe') {
{
const cookie = await redis.get('CHATGPT:POE_TOKEN') const cookie = await redis.get('CHATGPT:POE_TOKEN')
if (!cookie) { if (!cookie) {
throw new Error('未绑定Poe Cookie请使用#chatgpt设置Poe token命令绑定cookie') throw new Error('未绑定Poe Cookie请使用#chatgpt设置Poe token命令绑定cookie')
@ -1847,9 +1835,7 @@ export class chatgpt extends plugin {
return { return {
text: response.data text: response.data
} }
}
} else if (use === 'claude') { } else if (use === 'claude') {
{
let client = new SlackClaudeClient({ let client = new SlackClaudeClient({
slackUserToken: Config.slackUserToken, slackUserToken: Config.slackUserToken,
slackChannelId: Config.slackChannelId slackChannelId: Config.slackChannelId
@ -1872,9 +1858,7 @@ export class chatgpt extends plugin {
return { return {
text text
} }
}
} else if (use === 'claude2') { } else if (use === 'claude2') {
{
let { conversationId } = conversation let { conversationId } = conversation
let client = new ClaudeAIClient({ let client = new ClaudeAIClient({
organizationId: Config.claudeAIOrganizationId, organizationId: Config.claudeAIOrganizationId,
@ -1913,9 +1897,7 @@ export class chatgpt extends plugin {
let conv = await client.createConversation() let conv = await client.createConversation()
return await client.sendMessage(prompt, conv.uuid, attachments) return await client.sendMessage(prompt, conv.uuid, attachments)
} }
}
} else if (use === 'xh') { } else if (use === 'xh') {
{
const cacheOptions = { const cacheOptions = {
namespace: 'xh', namespace: 'xh',
store: new KeyvFile({ filename: 'cache.json' }) store: new KeyvFile({ filename: 'cache.json' })
@ -1937,9 +1919,7 @@ export class chatgpt extends plugin {
image: image ? image[0] : undefined image: image ? image[0] : undefined
}) })
return response return response
}
} else if (use === 'azure') { } else if (use === 'azure') {
{
let azureModel let azureModel
try { try {
azureModel = await import('@azure/openai') azureModel = await import('@azure/openai')
@ -1962,9 +1942,7 @@ export class chatgpt extends plugin {
text: completion.content, text: completion.content,
message: completion message: completion
} }
}
} else if (use === 'qwen') { } else if (use === 'qwen') {
{
let completionParams = { let completionParams = {
parameters: { parameters: {
top_p: Config.qwenTopP || 0.5, top_p: Config.qwenTopP || 0.5,
@ -1979,11 +1957,11 @@ export class chatgpt extends plugin {
} }
const currentDate = new Date().toISOString().split('T')[0] const currentDate = new Date().toISOString().split('T')[0]
async function um(message) { async function um (message) {
return await upsertMessage(message, 'QWEN') return await upsertMessage(message, 'QWEN')
} }
async function gm(id) { async function gm (id) {
return await getMessageById(id, 'QWEN') return await getMessageById(id, 'QWEN')
} }
@ -2017,9 +1995,7 @@ export class chatgpt extends plugin {
throw new Error(err) throw new Error(err)
} }
return msg return msg
}
} else if (use === 'bard') { } else if (use === 'bard') {
{
// 处理cookie // 处理cookie
const matchesPSID = /__Secure-1PSID=([^;]+)/.exec(Config.bardPsid) const matchesPSID = /__Secure-1PSID=([^;]+)/.exec(Config.bardPsid)
const matchesPSIDTS = /__Secure-1PSIDTS=([^;]+)/.exec(Config.bardPsid) const matchesPSIDTS = /__Secure-1PSIDTS=([^;]+)/.exec(Config.bardPsid)
@ -2068,9 +2044,7 @@ export class chatgpt extends plugin {
text: response.content, text: response.content,
images: response.images images: response.images
} }
}
} else if (use === 'gemini') { } else if (use === 'gemini') {
{
let client = new CustomGoogleGeminiClient({ let client = new CustomGoogleGeminiClient({
e, e,
userId: e.sender.user_id, userId: e.sender.user_id,
@ -2185,9 +2159,7 @@ export class chatgpt extends plugin {
} }
option.system = system option.system = system
return await client.sendMessage(prompt, option) return await client.sendMessage(prompt, option)
}
} else { } else {
{
// openai api // openai api
let completionParams = {} let completionParams = {}
if (Config.model) { if (Config.model) {
@ -2432,7 +2404,7 @@ export class chatgpt extends plugin {
option.parentMessageId = msg.id option.parentMessageId = msg.id
option.name = name option.name = name
// 不然普通用户可能会被openai限速 // 不然普通用户可能会被openai限速
await delay(300) await common.sleep(300)
msg = await this.chatGPTApi.sendMessage(functionResult, option, 'function') msg = await this.chatGPTApi.sendMessage(functionResult, option, 'function')
logger.info(msg) logger.info(msg)
} }
@ -2469,7 +2441,6 @@ export class chatgpt extends plugin {
} }
} }
} }
}
async newClaudeConversation (e) { async newClaudeConversation (e) {
let presetName = e.msg.replace(/^#claude开启新对话/, '').trim() let presetName = e.msg.replace(/^#claude开启新对话/, '').trim()

View file

@ -171,17 +171,17 @@ export class ChatgptManagement extends plugin {
fnc: 'versionChatGPTPlugin' fnc: 'versionChatGPTPlugin'
}, },
{ {
reg: '^#chatgpt(本群)?(群\\d+)?(关闭|闭嘴|关机|休眠|下班)', reg: '^#chatgpt(本群)?(群\\d+)?(闭嘴|关机|休眠|下班)',
fnc: 'shutUp', fnc: 'shutUp',
permission: 'master' permission: 'master'
}, },
{ {
reg: '^#chatgpt(本群)?(群\\d+)?(开启|启动|激活|张嘴|开口|说话|上班)$', reg: '^#chatgpt(本群)?(群\\d+)?(张嘴|开口|说话|上班)$',
fnc: 'openMouth', fnc: 'openMouth',
permission: 'master' permission: 'master'
}, },
{ {
reg: '^#chatgpt查看?(关闭|闭嘴|关机|休眠|下班|休眠)列表$', reg: '^#chatgpt查看?(闭嘴|关机|休眠|下班)列表$',
fnc: 'listShutUp', fnc: 'listShutUp',
permission: 'master' permission: 'master'
}, },
@ -327,8 +327,8 @@ export class ChatgptManagement extends plugin {
permission: 'master' permission: 'master'
}, },
{ {
reg: '^#chatgpt修补Gemini$', reg: '^#chatgpt必应(禁用|禁止|关闭|启用|开启)搜索$',
fnc: 'patchGemini', fnc: 'switchBingSearch',
permission: 'master' permission: 'master'
} }
] ]
@ -1672,6 +1672,16 @@ azure语音Azure 语音是微软 Azure 平台提供的一项语音服务,
return false return false
} }
async switchBingSearch (e) {
if (e.msg.includes('启用') || e.msg.includes('开启')) {
Config.sydneyEnableSearch = true
await e.reply('已开启必应搜索')
} else {
Config.sydneyEnableSearch = false
await e.reply('已禁用必应搜索')
}
}
async saveXinghuoModel (e) { async saveXinghuoModel (e) {
if (!this.e.msg) return if (!this.e.msg) return
let token = this.e.msg let token = this.e.msg

View file

@ -374,6 +374,12 @@ export function supportGuoba () {
] ]
} }
}, },
{
field: 'sydneyEnableSearch',
label: '是否允许必应进行搜索',
bottomHelpMessage: '关闭后必应将禁用搜索',
component: 'Switch'
},
{ {
field: 'enableSuggestedResponses', field: 'enableSuggestedResponses',
label: '是否开启建议回复', label: '是否开启建议回复',

View file

@ -11,7 +11,6 @@
"@google/generative-ai": "^0.1.1", "@google/generative-ai": "^0.1.1",
"@slack/bolt": "^3.13.2", "@slack/bolt": "^3.13.2",
"asn1.js": "^5.0.0", "asn1.js": "^5.0.0",
"delay": "^6.0.0",
"diff": "^5.1.0", "diff": "^5.1.0",
"emoji-strip": "^1.0.1", "emoji-strip": "^1.0.1",
"eventsource": "^2.0.2", "eventsource": "^2.0.2",

View file

@ -8,10 +8,9 @@ import crypto from 'crypto'
import WebSocket from 'ws' import WebSocket from 'ws'
import { Config, pureSydneyInstruction } from './config.js' import { Config, pureSydneyInstruction } from './config.js'
import { formatDate, getMasterQQ, isCN, getUserData, limitString } from './common.js' import { formatDate, getMasterQQ, isCN, getUserData, limitString } from './common.js'
import delay from 'delay'
import moment from 'moment' import moment from 'moment'
import { getProxy } from './proxy.js' import { getProxy } from './proxy.js'
import Version from './version.js' import common from '../../../lib/common/common.js'
if (!globalThis.fetch) { if (!globalThis.fetch) {
globalThis.fetch = fetch globalThis.fetch = fetch
@ -87,9 +86,12 @@ export default class SydneyAIClient {
// 'x-forwarded-for': '1.1.1.1' // 'x-forwarded-for': '1.1.1.1'
} }
} }
if (this.opts.cookies || this.opts.userToken) { let initCk = 'SRCHD=AF=NOFORM; PPLState=1; SRCHHPGUSR=HV=' + new Date().getTime() + ';'
if (this.opts.userToken) {
// 疑似无需token了 // 疑似无需token了
fetchOptions.headers.cookie = this.opts.cookies || `_U=${this.opts.userToken}` fetchOptions.headers.cookie = `${initCk} _U=${this.opts.userToken}`
} else {
fetchOptions.headers.cookie = initCk
} }
if (this.opts.proxy) { if (this.opts.proxy) {
fetchOptions.agent = proxy(Config.proxy) fetchOptions.agent = proxy(Config.proxy)
@ -101,12 +103,12 @@ export default class SydneyAIClient {
this.opts.host = 'https://edgeservices.bing.com/edgesvc' this.opts.host = 'https://edgeservices.bing.com/edgesvc'
} }
logger.mark('使用host' + this.opts.host) logger.mark('使用host' + this.opts.host)
let response = await fetch(`${this.opts.host}/turing/conversation/create?bundleVersion=1.1366.5`, fetchOptions) let response = await fetch(`${this.opts.host}/turing/conversation/create?bundleVersion=1.1381.12`, fetchOptions)
let text = await response.text() let text = await response.text()
let retry = 10 let retry = 10
while (retry >= 0 && response.status === 200 && !text) { while (retry >= 0 && response.status === 200 && !text) {
await delay(400) await common.sleep(400)
response = await fetch(`${this.opts.host}/turing/conversation/create?bundleVersion=1.1366.5`, fetchOptions) response = await fetch(`${this.opts.host}/turing/conversation/create?bundleVersion=1.1381.12`, fetchOptions)
text = await response.text() text = await response.text()
retry-- retry--
} }
@ -308,8 +310,7 @@ export default class SydneyAIClient {
const text = (pureSydney ? pureSydneyInstruction : (useCast?.bing || Config.sydney)).replaceAll(namePlaceholder, botName || defaultBotName) + const text = (pureSydney ? pureSydneyInstruction : (useCast?.bing || Config.sydney)).replaceAll(namePlaceholder, botName || defaultBotName) +
((Config.enableGroupContext && groupId) ? groupContextTip : '') + ((Config.enableGroupContext && groupId) ? groupContextTip : '') +
((Config.enforceMaster && master) ? masterTip : '') + ((Config.enforceMaster && master) ? masterTip : '') +
(Config.sydneyMood ? moodTip : '') + (Config.sydneyMood ? moodTip : '')
(Config.sydneySystemCode ? '' : '')
// logger.info(text) // logger.info(text)
if (pureSydney) { if (pureSydney) {
previousMessages = invocationId === 0 previousMessages = invocationId === 0
@ -362,7 +363,7 @@ export default class SydneyAIClient {
// 'dagslnv1', // 'dagslnv1',
// 'sportsansgnd', // 'sportsansgnd',
// 'dl_edge_desc', // 'dl_edge_desc',
'noknowimg', // 'noknowimg',
// 'dtappid', // 'dtappid',
// 'cricinfo', // 'cricinfo',
// 'cricinfov2', // 'cricinfov2',
@ -370,21 +371,21 @@ export default class SydneyAIClient {
// 'gencontentv3', // 'gencontentv3',
'iycapbing', 'iycapbing',
'iyxapbing', 'iyxapbing',
'revimglnk', // 'revimglnk',
'revimgsrc1', // 'revimgsrc1',
'revimgur', // 'revimgur',
'clgalileo',
'eredirecturl' 'eredirecturl'
] ]
if (Config.enableGenerateContents) { if (Config.enableGenerateContents) {
optionsSets.push(...['gencontentv3']) optionsSets.push(...['gencontentv3'])
} }
if (!Config.sydneyEnableSearch || toSummaryFileContent?.content) {
optionsSets.push(...['nosearchall'])
}
let maxConv = Config.maxNumUserMessagesInConversation let maxConv = Config.maxNumUserMessagesInConversation
const currentDate = moment().format('YYYY-MM-DDTHH:mm:ssZ') const currentDate = moment().format('YYYY-MM-DDTHH:mm:ssZ')
const imageDate = await this.kblobImage(opts.imageUrl) const imageDate = await this.kblobImage(opts.imageUrl)
if (toSummaryFileContent?.content) {
// message = `请不要进行搜索,用户的问题是:"${message}"`
messageType = 'Chat'
}
let argument0 = { let argument0 = {
source: 'cib', source: 'cib',
optionsSets, optionsSets,
@ -392,17 +393,17 @@ export default class SydneyAIClient {
// 'InternalSearchQuery', 'InternalSearchResult', 'Disengaged', 'InternalLoaderMessage', 'Progress', 'RenderCardRequest', 'AdsQuery', // 'InternalSearchQuery', 'InternalSearchResult', 'Disengaged', 'InternalLoaderMessage', 'Progress', 'RenderCardRequest', 'AdsQuery',
'InvokeAction', 'SemanticSerp', 'GenerateContentQuery', 'SearchQuery'], 'InvokeAction', 'SemanticSerp', 'GenerateContentQuery', 'SearchQuery'],
sliceIds: [ sliceIds: [
'e2eperf', // 'e2eperf',
'gbacf', // 'gbacf',
'srchqryfix', // 'srchqryfix',
'caccnctacf', // 'caccnctacf',
'translref', // 'translref',
'fluxnosearchc', // 'fluxnosearchc',
'fluxnosearch', // 'fluxnosearch',
'1115rai289s0', // '1115rai289s0',
'1130deucs0', // '1130deucs0',
'1116pythons0', // '1116pythons0',
'cacmuidarb' // 'cacmuidarb'
], ],
requestId: crypto.randomUUID(), requestId: crypto.randomUUID(),
traceId: genRanHex(32), traceId: genRanHex(32),
@ -476,9 +477,9 @@ export default class SydneyAIClient {
conversationId, conversationId,
previousMessages, previousMessages,
plugins: [ plugins: [
{ // {
id: 'c310c353-b9f0-4d76-ab0d-1dd5e979cf68' // id: 'c310c353-b9f0-4d76-ab0d-1dd5e979cf68'
} // }
] ]
} }
if (encryptedconversationsignature) { if (encryptedconversationsignature) {
@ -799,6 +800,7 @@ export default class SydneyAIClient {
message, message,
conversationExpiryTime: event?.item?.conversationExpiryTime conversationExpiryTime: event?.item?.conversationExpiryTime
}) })
break
} }
default: default:
} }

View file

@ -2,8 +2,8 @@ import lodash from 'lodash'
import { Config } from '../utils/config.js' import { Config } from '../utils/config.js'
import StealthPlugin from 'puppeteer-extra-plugin-stealth' import StealthPlugin from 'puppeteer-extra-plugin-stealth'
import { getOpenAIAuth } from './openai-auth.js' import { getOpenAIAuth } from './openai-auth.js'
import delay from 'delay'
import { v4 as uuidv4 } from 'uuid' import { v4 as uuidv4 } from 'uuid'
import common from '../../../lib/common/common.js'
const chatUrl = 'https://chat.openai.com/chat' const chatUrl = 'https://chat.openai.com/chat'
let puppeteer = {} let puppeteer = {}
@ -181,7 +181,7 @@ export class ChatGPTPuppeteer extends Puppeteer {
if (Config['2captchaToken']) { if (Config['2captchaToken']) {
await this._page.solveRecaptchas() await this._page.solveRecaptchas()
} }
await delay(300) await common.sleep(300)
timeout = timeout - 300 timeout = timeout - 300
} }
} catch (e) { } catch (e) {
@ -243,7 +243,7 @@ export class ChatGPTPuppeteer extends Puppeteer {
break break
} }
await delay(300) await common.sleep(300)
} while (true) } while (true)
if (!await this.getIsAuthenticated()) { if (!await this.getIsAuthenticated()) {
@ -405,7 +405,7 @@ export class ChatGPTPuppeteer extends Puppeteer {
if (isAuthenticated) { if (isAuthenticated) {
while (!this._accessToken) { while (!this._accessToken) {
// wait for async response hook result // wait for async response hook result
await delay(300) await common.sleep(300)
timeout = timeout - 300 timeout = timeout - 300
if (timeout < 0) { if (timeout < 0) {
const error = new Error('Not signed in') const error = new Error('Not signed in')
@ -493,7 +493,7 @@ export class ChatGPTPuppeteer extends Puppeteer {
// const responseP = new Promise<string>(async (resolve, reject) => { // const responseP = new Promise<string>(async (resolve, reject) => {
// try { // try {
// do { // do {
// await delay(1000) // await common.sleep(1000)
// // TODO: this logic needs some work because we can have repeat messages... // // TODO: this logic needs some work because we can have repeat messages...
// const newLastMessage = await this.getLastMessage() // const newLastMessage = await this.getLastMessage()

View file

@ -42,6 +42,7 @@ const defaultConfig = {
sydneyImageRecognition: false, sydneyImageRecognition: false,
sydneyMoodTip: 'Your response should be divided into two parts, namely, the text and your mood. The mood available to you can only include: blandness, happy, shy, frustrated, disgusted, and frightened.All content should be replied in this format {"text": "", "mood": ""}.All content except mood should be placed in text, It is important to ensure that the content you reply to can be parsed by json.', sydneyMoodTip: 'Your response should be divided into two parts, namely, the text and your mood. The mood available to you can only include: blandness, happy, shy, frustrated, disgusted, and frightened.All content should be replied in this format {"text": "", "mood": ""}.All content except mood should be placed in text, It is important to ensure that the content you reply to can be parsed by json.',
enableSuggestedResponses: false, enableSuggestedResponses: false,
sydneyEnableSearch: false,
api: defaultChatGPTAPI, api: defaultChatGPTAPI,
apiBaseUrl: 'https://chat3.avocado.wiki/backend-api', apiBaseUrl: 'https://chat3.avocado.wiki/backend-api',
apiForceUseReverse: false, apiForceUseReverse: false,

View file

@ -1,6 +1,6 @@
import { Config } from '../utils/config.js' import { Config } from '../utils/config.js'
import delay from 'delay'
import random from 'random' import random from 'random'
import common from '../../../lib/common/common.js'
let hasRecaptchaPlugin = !!Config['2captchaToken'] let hasRecaptchaPlugin = !!Config['2captchaToken']
@ -58,7 +58,7 @@ export async function getOpenAIAuth (opt) {
await waitForConditionOrAtCapacity(page, () => await waitForConditionOrAtCapacity(page, () =>
page.waitForSelector('#__next .btn-primary', { timeout: timeoutMs / 3 }) page.waitForSelector('#__next .btn-primary', { timeout: timeoutMs / 3 })
) )
await delay(500) await common.sleep(500)
// click login button and wait for navigation to finish // click login button and wait for navigation to finish
do { do {
@ -69,7 +69,7 @@ export async function getOpenAIAuth (opt) {
}), }),
page.click('#__next .btn-primary') page.click('#__next .btn-primary')
]) ])
await delay(1000) await common.sleep(1000)
} while (page.url().endsWith('/auth/login')) } while (page.url().endsWith('/auth/login'))
logger.mark('进入登录页面') logger.mark('进入登录页面')
await checkForChatGPTAtCapacity(page) await checkForChatGPTAtCapacity(page)
@ -90,7 +90,7 @@ export async function getOpenAIAuth (opt) {
} else { } else {
await page.waitForSelector('#username') await page.waitForSelector('#username')
await page.type('#username', email, { delay: 20 }) await page.type('#username', email, { delay: 20 })
await delay(100) await common.sleep(100)
if (hasRecaptchaPlugin) { if (hasRecaptchaPlugin) {
// console.log('solveRecaptchas()') // console.log('solveRecaptchas()')
@ -114,7 +114,7 @@ export async function getOpenAIAuth (opt) {
submitP() submitP()
]) ])
} else { } else {
await delay(2000) await common.sleep(2000)
await checkForChatGPTAtCapacity(page) await checkForChatGPTAtCapacity(page)
} }
@ -183,7 +183,7 @@ async function checkForChatGPTAtCapacity (page, opts = {}) {
timeout: timeoutMs timeout: timeoutMs
}) })
await delay(pollingIntervalMs) await common.sleep(pollingIntervalMs)
} }
} catch (err) { } catch (err) {
// ignore errors likely due to navigation // ignore errors likely due to navigation
@ -251,29 +251,29 @@ async function solveSimpleCaptchas (page) {
const verifyYouAreHuman = await page.$('text=Verify you are human') const verifyYouAreHuman = await page.$('text=Verify you are human')
if (verifyYouAreHuman) { if (verifyYouAreHuman) {
logger.mark('encounter cloudflare simple captcha "Verify you are human"') logger.mark('encounter cloudflare simple captcha "Verify you are human"')
await delay(2000) await common.sleep(2000)
await verifyYouAreHuman.click({ await verifyYouAreHuman.click({
delay: random.int(5, 25) delay: random.int(5, 25)
}) })
await delay(1000) await common.sleep(1000)
} }
const verifyYouAreHumanCN = await page.$('text=确认您是真人') const verifyYouAreHumanCN = await page.$('text=确认您是真人')
if (verifyYouAreHumanCN) { if (verifyYouAreHumanCN) {
logger.mark('encounter cloudflare simple captcha "确认您是真人"') logger.mark('encounter cloudflare simple captcha "确认您是真人"')
await delay(2000) await common.sleep(2000)
await verifyYouAreHumanCN.click({ await verifyYouAreHumanCN.click({
delay: random.int(5, 25) delay: random.int(5, 25)
}) })
await delay(1000) await common.sleep(1000)
} }
const cloudflareButton = await page.$('.hcaptcha-box') const cloudflareButton = await page.$('.hcaptcha-box')
if (cloudflareButton) { if (cloudflareButton) {
await delay(2000) await common.sleep(2000)
await cloudflareButton.click({ await cloudflareButton.click({
delay: random.int(5, 25) delay: random.int(5, 25)
}) })
await delay(1000) await common.sleep(1000)
} }
} catch (err) { } catch (err) {
// ignore errors // ignore errors

View file

@ -1,7 +1,7 @@
import { Config } from '../config.js' import { Config } from '../config.js'
import slack from '@slack/bolt' import slack from '@slack/bolt'
import delay from 'delay'
import { limitString } from '../common.js' import { limitString } from '../common.js'
import common from '../../../../lib/common/common.js'
let proxy let proxy
if (Config.proxy) { if (Config.proxy) {
try { try {
@ -24,7 +24,7 @@ export class SlackClaudeClient {
if (Config.proxy) { if (Config.proxy) {
option.agent = proxy(Config.proxy) option.agent = proxy(Config.proxy)
} }
option.logLevel = Config.debug ? 'debug': 'info' option.logLevel = Config.debug ? 'debug' : 'info'
this.app = new slack.App(option) this.app = new slack.App(option)
} else { } else {
throw new Error('未配置Slack信息') throw new Error('未配置Slack信息')
@ -61,7 +61,7 @@ export class SlackClaudeClient {
channel: channel.id, channel: channel.id,
users: Config.slackClaudeUserId users: Config.slackClaudeUserId
}) })
await delay(1000) await common.sleep(1000)
} else { } else {
channel = channel[0] channel = channel[0]
} }
@ -78,7 +78,7 @@ export class SlackClaudeClient {
let response = '_Typing…_' let response = '_Typing…_'
let tryTimes = 0 let tryTimes = 0
// 发完先等3喵 // 发完先等3喵
await delay(3000) await common.sleep(3000)
while (response.trim().endsWith('_Typing…_')) { while (response.trim().endsWith('_Typing…_')) {
let replies = await this.app.client.conversations.replies({ let replies = await this.app.client.conversations.replies({
token: this.config.slackUserToken, token: this.config.slackUserToken,
@ -106,7 +106,7 @@ export class SlackClaudeClient {
} }
} }
} }
await delay(2000) await common.sleep(2000)
tryTimes++ tryTimes++
if (tryTimes > 3 && response === '_Typing…_') { if (tryTimes > 3 && response === '_Typing…_') {
// 过了6秒还没任何回复就重新发一下试试 // 过了6秒还没任何回复就重新发一下试试
@ -127,7 +127,7 @@ export class SlackClaudeClient {
let response = '_Typing…_' let response = '_Typing…_'
let tryTimes = 0 let tryTimes = 0
// 发完先等3喵 // 发完先等3喵
await delay(3000) await common.sleep(3000)
while (response.trim().endsWith('_Typing…_')) { while (response.trim().endsWith('_Typing…_')) {
let replies = await this.app.client.conversations.replies({ let replies = await this.app.client.conversations.replies({
token: this.config.slackUserToken, token: this.config.slackUserToken,
@ -156,7 +156,7 @@ export class SlackClaudeClient {
} }
} }
} }
await delay(2000) await common.sleep(2000)
tryTimes++ tryTimes++
if (tryTimes > 3 && response === '_Typing…_') { if (tryTimes > 3 && response === '_Typing…_') {
// 过了6秒还没任何回复就重新发一下试试 // 过了6秒还没任何回复就重新发一下试试