From b1570d6126b132ce4b3f20e8914e0f7a918b9ea1 Mon Sep 17 00:00:00 2001 From: ikechan8370 Date: Sun, 23 Jul 2023 21:21:32 +0800 Subject: [PATCH] =?UTF-8?q?fix:=20=E5=9B=9E=E9=80=80=E9=83=A8=E5=88=86?= =?UTF-8?q?=E4=BF=AE=E6=94=B9=EF=BC=9B=E5=A2=9E=E5=8A=A0=E9=AA=8C=E8=AF=81?= =?UTF-8?q?=E7=A0=81=E6=8F=90=E7=A4=BA=E8=AF=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- apps/chat.js | 122 ++++++++++++++++++++++++---------------- utils/SydneyAIClient.js | 80 ++++++++++++-------------- utils/bingCaptcha.js | 15 +++-- 3 files changed, 123 insertions(+), 94 deletions(-) diff --git a/apps/chat.js b/apps/chat.js index ae09432..e20c942 100644 --- a/apps/chat.js +++ b/apps/chat.js @@ -234,15 +234,20 @@ export class chatgpt extends plugin { fnc: 'deleteConversation', permission: 'master' }, - { - reg: '^#chatgpt必应验证码', - fnc: 'bingCaptcha' - } + // { + // reg: '^#chatgpt必应验证码', + // fnc: 'bingCaptcha' + // } ] }) this.toggleMode = toggleMode } + /** + * deprecated + * @param e + * @returns {Promise} + */ async bingCaptcha (e) { let bingTokens = JSON.parse(await redis.get('CHATGPT:BING_TOKENS')) if (!bingTokens) { @@ -257,8 +262,9 @@ export class chatgpt extends plugin { } index = parseInt(index) - 1 let bingToken = bingTokens[index] - let { id, image } = await createCaptcha(e, bingToken) + let { id, regionId, image } = await createCaptcha(e, bingToken) e.bingCaptchaId = id + e.regionId = regionId e.token = bingToken await e.reply(['请崽60秒内输入下面图片以通过必应人机验证', segment.image(`base64://${image}`)]) this.setContext('solveBingCaptcha', false, 60) @@ -1672,27 +1678,31 @@ export class chatgpt extends plugin { } catch (error) { logger.error(error) const message = error?.message || error?.data?.message || error || '出错了' - if (message && typeof message === 'string' && message.indexOf('CaptchaChallenge') > -1) { - let { id, image } = await createCaptcha(e, bingToken) - e.bingCaptchaId = id - e.token = bingToken - const { - conversationSignature, - conversationId, - clientId - } = error?.data - e.bingConversation = { - conversationSignature, - conversationId, - clientId - } - return { - text: '请崽60秒内输入下面图片以通过必应人机验证', - image, - error: true, - token: bingToken - } - } else if (message && typeof message === 'string' && message.indexOf('限流') > -1) { + // if (message && typeof message === 'string' && message.indexOf('CaptchaChallenge') > -1) { + // if (bingToken) { + // // let { id, regionId, image } = await createCaptcha(e, bingToken) + // // e.bingCaptchaId = id + // // e.token = bingToken + // // e.regionId = regionId + // // const { + // // conversationSignature, + // // conversationId, + // // clientId + // // } = error?.conversation + // // e.bingConversation = { + // // conversationSignature, + // // conversationId, + // // clientId + // // } + // return { + // text: '请在60秒内输入下面图片以通过必应人机验证', + // image, + // error: true, + // token: bingToken + // } + // } + // } else + if (message && typeof message === 'string' && message.indexOf('限流') > -1) { throttledTokens.push(bingToken) let bingTokens = JSON.parse(await redis.get('CHATGPT:BING_TOKENS')) const badBingToken = bingTokens.findIndex(element => element.Token === bingToken) @@ -1729,6 +1739,13 @@ export class chatgpt extends plugin { } while (retry > 0) if (errorMessage) { response = response || {} + if (errorMessage.includes('CaptchaChallenge')) { + if (bingToken) { + errorMessage = '出现验证码,请使用当前账户前往https://www.bing.com/chat或Edge侧边栏手动解除验证码' + } else { + errorMessage = '出现验证码,且未配置必应账户,请尝试更换代理/反代或绑定必应账户以解除验证码' + } + } return { text: errorMessage, error: true @@ -2336,29 +2353,40 @@ export class chatgpt extends plugin { } async solveBingCaptcha (e) { - let id = e.bingCaptchaId - let text = this.e.msg - let solveResult = await solveCaptcha(id, text, e.token) - if (solveResult.result) { - const cacheOptions = { - namespace: Config.toneStyle, - store: new KeyvFile({ filename: 'chatgpt:bing:temp.json' }) - } - const bingAIClient = new SydneyAIClient({ - userToken: e.token, // "_U" cookie from bing.com - debug: false, - cache: cacheOptions, - user: e.sender.user_id, - proxy: Config.proxy - }) - let response = await bingAIClient.sendMessage('hello', e.bingConversation) - if (response.response) { - await e.reply('验证码已通过') + try { + let id = e.bingCaptchaId + let regionId = e.regionId + let text = this.e.msg + let solveResult = await solveCaptcha(id, regionId, text, e.token) + if (solveResult.result) { + logger.mark('验证码正确:' + JSON.stringify(solveResult.detail)) + const cacheOptions = { + namespace: Config.toneStyle, + store: new KeyvFile({ filename: 'cache.json' }) + } + const bingAIClient = new SydneyAIClient({ + userToken: e.token, // "_U" cookie from bing.com + debug: Config.debug, + cache: cacheOptions, + user: e.sender.user_id, + proxy: Config.proxy + }) + try { + let response = await bingAIClient.sendMessage('hello', Object.assign({ invocationId: '1' }, e.bingConversation)) + if (response.response) { + await e.reply('验证码已通过') + } else { + await e.reply('验证码正确,但账户未解决验证码') + } + } catch (err) { + logger.error(err) + await e.reply('验证码正确,但账户未解决验证码') + } } else { - await e.reply('验证码正确,但账户未解决验证码') + await e.reply('验证码失败:' + JSON.stringify(solveResult.detail)) } - } else { - await e.reply('验证码失败:' + JSON.stringify(solveResult.detail)) + } catch (err) { + this.finish('solveBingCaptcha') } this.finish('solveBingCaptcha') } diff --git a/utils/SydneyAIClient.js b/utils/SydneyAIClient.js index e57d64b..51db267 100644 --- a/utils/SydneyAIClient.js +++ b/utils/SydneyAIClient.js @@ -18,19 +18,6 @@ if (!globalThis.fetch) { globalThis.Request = Request globalThis.Response = Response } -try { - await import('ws') -} catch (error) { - logger.warn('【ChatGPT-Plugin】依赖ws未安装,可能影响Sydney模式下Bing对话,建议使用pnpm install ws安装') -} -let proxy -if (Config.proxy) { - try { - proxy = (await import('https-proxy-agent')).default - } catch (e) { - console.warn('未安装https-proxy-agent,请在插件目录下执行pnpm add https-proxy-agent') - } -} // async function getWebSocket () { // let WebSocket @@ -111,7 +98,7 @@ export default class SydneyAIClient { fetchOptions.headers.cookie = this.opts.cookies || `_U=${this.opts.userToken}` } if (this.opts.proxy) { - fetchOptions.agent = proxy(Config.proxy) + fetchOptions.agent = HttpsProxyAgent(Config.proxy) } let accessible = !(await isCN()) || this.opts.proxy if (accessible && !Config.sydneyForceUseReverse) { @@ -243,7 +230,7 @@ export default class SydneyAIClient { onProgress = () => { } } let master = (await getMasterQQ())[0] - if (parentMessageId || !conversationSignature || !conversationId || !clientId) { + if (!conversationSignature || !conversationId || !clientId) { const createNewConversationResponse = await this.createNewConversation() if (this.debug) { console.debug(createNewConversationResponse) @@ -292,7 +279,7 @@ export default class SydneyAIClient { } }) pm = pm.reverse() - let previousMessages + let previousMessages = [] let whoAmI = '' if (Config.enforceMaster && master && qq) { // 加强主人人知 @@ -328,7 +315,7 @@ export default class SydneyAIClient { }, ...pm ] - : undefined + : [] } else { previousMessages = invocationId === 0 ? [ @@ -342,7 +329,7 @@ export default class SydneyAIClient { }, ...pm ] - : undefined + : [] } const userMessage = { @@ -363,9 +350,9 @@ export default class SydneyAIClient { 'responsible_ai_policy_235', 'enablemm', toneOption, - 'dagslnv1', - 'sportsansgnd', - 'dl_edge_desc', + // 'dagslnv1', + // 'sportsansgnd', + // 'dl_edge_desc', 'noknowimg', // 'dtappid', // 'cricinfo', @@ -380,7 +367,7 @@ export default class SydneyAIClient { } const currentDate = moment().format('YYYY-MM-DDTHH:mm:ssZ') const imageDate = await this.kblobImage(opts.imageUrl) - console.log(imageDate) + // console.log(imageDate) const obj = { arguments: [ { @@ -389,30 +376,30 @@ export default class SydneyAIClient { allowedMessageTypes: ['ActionRequest', 'Chat', 'Context', // 'InternalSearchQuery', 'InternalSearchResult', 'Disengaged', 'InternalLoaderMessage', 'Progress', 'RenderCardRequest', 'AdsQuery', 'SemanticSerp', 'GenerateContentQuery', 'SearchQuery'], - sliceIds: [], + sliceIds: [ + + ], traceId: genRanHex(32), + scenario: 'Underside', + verbosity: 'verbose', isStartOfSession: invocationId === 0, message: { locale: 'zh-CN', market: 'zh-CN', - region: 'HK', + region: 'WW', location: 'lat:47.639557;long:-122.128159;re=1000m;', locationHints: [ { + country: 'Macedonia', + state: 'Centar', + city: 'Skopje', + zipcode: '1004', + timezoneoffset: 1, + countryConfidence: 8, + cityConfidence: 5, Center: { - Latitude: 39.971031896331, - Longitude: 116.33522679576237 - }, - RegionType: 2, - SourceType: 11 - }, - { - country: 'Hong Kong', - timezoneoffset: 8, - countryConfidence: 9, - Center: { - Latitude: 22.15, - Longitude: 114.1 + Latitude: 41.9961, + Longitude: 21.4317 }, RegionType: 2, SourceType: 1 @@ -499,10 +486,15 @@ export default class SydneyAIClient { messageType: 'Context', messageId: 'discover-web--page-ping-mriduna-----' }) + } else { + obj.arguments[0].previousMessages.push({ + author: 'user', + description: '', + contextType: 'WebPage', + messageType: 'Context' + }) } - if (obj.arguments[0].previousMessages.length === 0) { - delete obj.arguments[0].previousMessages - } + let apology = false const messagePromise = new Promise((resolve, reject) => { let replySoFar = [''] @@ -671,7 +663,9 @@ export default class SydneyAIClient { logger.warn('该账户的SERP请求已被限流') logger.warn(JSON.stringify(event.item?.result)) } else { - reject(`${event.item?.result.value}\n${event.item?.result.error}\n${event.item?.result.exception}`) + reject({ + message: `${event.item?.result.value}\n${event.item?.result.error}\n${event.item?.result.exception}` + }) } } else { reject('Unexpected message author.') @@ -803,7 +797,7 @@ export default class SydneyAIClient { body: formData } if (this.opts.proxy) { - fetchOptions.agent = proxy(Config.proxy) + fetchOptions.agent = HttpsProxyAgent(Config.proxy) } let accessible = !(await isCN()) || this.opts.proxy let response = await fetch(`${accessible ? 'https://www.bing.com' : this.opts.host}/images/kblob`, fetchOptions) @@ -843,7 +837,7 @@ async function generateRandomIP () { if (ip) { return ip } - const baseIP = '104.28.215.' + const baseIP = '62.77.140.' const subnetSize = 254 // 2^8 - 2 const randomIPSuffix = Math.floor(Math.random() * subnetSize) + 1 ip = baseIP + randomIPSuffix diff --git a/utils/bingCaptcha.js b/utils/bingCaptcha.js index a05ff26..3a6fe23 100644 --- a/utils/bingCaptcha.js +++ b/utils/bingCaptcha.js @@ -1,4 +1,7 @@ import fetch from 'node-fetch' + +// this file is deprecated + import { Config } from './config.js' import HttpsProxyAgent from 'https-proxy-agent' const newFetch = (url, options = {}) => { @@ -21,23 +24,27 @@ export async function createCaptcha (e, tokenU) { Cookie: `_U=${tokenU};`, 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36 Edg/114.0.1823.82', Accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7', + Referer: 'https://edgeservices.bing.com/edgesvc/chat?udsframed=1&form=SHORUN&clientscopes=chat,noheader,channelstable,&shellsig=ddb7b7dc7a56d0c5350f37b3653696bbeb77496e&setlang=zh-CN&lightschemeovr=1' } }) const blob = await imageResponse.blob() let id = imageResponse.headers.get('id') + let regionId = imageResponse.headers.get('Regionid') const arrayBuffer = await blob.arrayBuffer() const buffer = Buffer.from(arrayBuffer) const base64String = buffer.toString('base64') // await e.reply(segment.image(base64String)) - return { id, image: base64String } + return { id, regionId, image: base64String } } -export async function solveCaptcha (id, text, token) { +export async function solveCaptcha (id, regionId, text, token) { let baseUrl = Config.sydneyReverseProxy - let url = `${baseUrl}/edgesvc/turing/captcha/verify?type=visual&id=${id}®ionId=0&value=${text}` + let url = `${baseUrl}/edgesvc/turing/captcha/verify?type=visual&id=${id}®ionId=${regionId}&value=${text}` let res = await newFetch(url, { headers: { - Cookie: '_U=' + token + Cookie: '_U=' + token, + 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36 Edg/114.0.1823.82', + Referer: 'https://edgeservices.bing.com/edgesvc/chat?udsframed=1&form=SHORUN&clientscopes=chat,noheader,channelstable,&shellsig=ddb7b7dc7a56d0c5350f37b3653696bbeb77496e&setlang=zh-CN&lightschemeovr=1' } }) res = await res.json()