fix: use full browser mode

This commit is contained in:
葛胤池 2022-12-16 19:59:57 +08:00
parent c734d68a9c
commit 33c87054c7
3 changed files with 42 additions and 89 deletions

View file

@ -1,12 +1,11 @@
import plugin from '../../../lib/plugins/plugin.js' import plugin from '../../../lib/plugins/plugin.js'
import { ChatGPTAPI, getOpenAIAuth } from 'chatgpt' import { ChatGPTAPIBrowser } from 'chatgpt'
import _ from 'lodash' import _ from 'lodash'
import { Config } from '../config/index.js' import { Config } from '../config/index.js'
import showdown from 'showdown' import showdown from 'showdown'
import mjAPI from 'mathjax-node' import mjAPI from 'mathjax-node'
import puppeteer from '../utils/browser.js' // import puppeteer from '../utils/browser.js'
// import showdownKatex from 'showdown-katex' // import showdownKatex from 'showdown-katex'
const SESSION_TOKEN = Config.token
const blockWords = '屏蔽词1,屏蔽词2,屏蔽词3' const blockWords = '屏蔽词1,屏蔽词2,屏蔽词3'
const converter = new showdown.Converter({ const converter = new showdown.Converter({
extensions: [ extensions: [
@ -175,72 +174,33 @@ export class chatgpt extends plugin {
} }
let api = await redis.get('CHATGPT:API_OPTION') let api = await redis.get('CHATGPT:API_OPTION')
if (!api) { if (!api) {
let browser = await puppeteer.getBrowser() let option = { markdown: true }
const openAIAuth = await getOpenAIAuth((Config.username && Config.password) if (Config['2captchaToken']) {
? { option.captchaToken = Config['2captchaToken']
email: Config.username,
password: Config.password,
browser
}
: {
browser
})
const userAgent = await browser.userAgent()
let config = { markdown: true, userAgent }
let option
if (Config.username && Config.password) {
option = { ...Object.assign(config, openAIAuth) }
this.chatGPTApi = new ChatGPTAPI(option)
} else {
config.sessionToken = Config.token
option = { ...Object.assign(config, openAIAuth) }
this.chatGPTApi = new ChatGPTAPI(option)
}
try {
await this.chatGPTApi.ensureAuth()
await redis.set('CHATGPT:API_OPTION', JSON.stringify(option))
} catch (e) {
logger.error(e)
await this.reply(`OpenAI认证失败请检查Token${e}`, true)
return
} }
// option.debug = true
option.email = Config.username
option.password = Config.password
this.chatGPTApi = new ChatGPTAPIBrowser(option)
await redis.set('CHATGPT:API_OPTION', JSON.stringify(option))
} else { } else {
let option = JSON.parse(api) let option = JSON.parse(api)
this.chatGPTApi = new ChatGPTAPI(option) this.chatGPTApi = new ChatGPTAPIBrowser(option)
try {
await this.chatGPTApi.ensureAuth()
} catch (e) {
let browser = await puppeteer.getBrowser()
const openAIAuth = await getOpenAIAuth({
email: Config.username,
password: Config.password,
browser
})
const userAgent = await browser.userAgent()
let config = { markdown: true, userAgent }
let option = { ...Object.assign(config, openAIAuth) }
this.chatGPTApi = new ChatGPTAPI(option)
try {
await this.chatGPTApi.ensureAuth()
await redis.set('CHATGPT:API_OPTION', JSON.stringify(option))
} catch (e) {
logger.error(e)
await this.reply(`OpenAI认证失败请检查Token${e}`, true)
return
}
}
} }
let question = e.msg.trimStart() let question = e.msg.trimStart()
await this.reply('我正在思考如何回复你,请稍等', true, { recallMsg: 5 }) await this.reply('我正在思考如何回复你,请稍等', true, { recallMsg: 5 })
let c
logger.info(`chatgpt question: ${question}`) logger.info(`chatgpt question: ${question}`)
try {
await this.chatGPTApi.init()
} catch (e) {
await this.reply('chatgpt初始化出错' + e.msg, true)
}
let previousConversation = await redis.get(`CHATGPT:CONVERSATIONS:${e.sender.user_id}`) let previousConversation = await redis.get(`CHATGPT:CONVERSATIONS:${e.sender.user_id}`)
let conversation = null
if (!previousConversation) { if (!previousConversation) {
c = this.chatGPTApi.getConversation()
let ctime = new Date() let ctime = new Date()
previousConversation = { previousConversation = {
sender: e.sender, sender: e.sender,
conversation: c,
ctime, ctime,
utime: ctime, utime: ctime,
num: 0 num: 0
@ -248,25 +208,28 @@ export class chatgpt extends plugin {
await redis.set(`CHATGPT:CONVERSATIONS:${e.sender.user_id}`, JSON.stringify(previousConversation), { EX: CONVERSATION_PRESERVE_TIME }) await redis.set(`CHATGPT:CONVERSATIONS:${e.sender.user_id}`, JSON.stringify(previousConversation), { EX: CONVERSATION_PRESERVE_TIME })
} else { } else {
previousConversation = JSON.parse(previousConversation) previousConversation = JSON.parse(previousConversation)
c = this.chatGPTApi.getConversation({ conversation = {
conversationId: previousConversation.conversation.conversationId, conversationId: previousConversation.conversation.conversationId,
parentMessageId: previousConversation.conversation.parentMessageId parentMessageId: previousConversation.conversation.parentMessageId
}) }
} }
try { try {
// console.log({ c }) let option = {
let response = await c.sendMessage(question) onConversationResponse: function (c) {
// console.log({c}) let pc = _.clone(previousConversation)
// console.log(response) pc.conversation = {
// 更新redis中的conversation对象因为send后c已经被自动更新了 conversationId: c.conversation_id,
await redis.set(`CHATGPT:CONVERSATIONS:${e.sender.user_id}`, JSON.stringify({ parentMessageId: c.message.id
sender: e.sender, }
conversation: c, redis.set(`CHATGPT:CONVERSATIONS:${e.sender.user_id}`, JSON.stringify(pc), { EX: CONVERSATION_PRESERVE_TIME }).then(res => {
ctime: previousConversation.ctime, logger.debug('redis set conversation')
utime: new Date(), })
num: previousConversation.num + 1 }
}), { EX: CONVERSATION_PRESERVE_TIME }) }
if (conversation) {
option = Object.assign(option, conversation)
}
let response = await this.chatGPTApi.sendMessage(question, option)
// 检索是否有屏蔽词 // 检索是否有屏蔽词
const blockWord = blockWords.split(',').find(word => response.toLowerCase().includes(word.toLowerCase())) const blockWord = blockWords.split(',').find(word => response.toLowerCase().includes(word.toLowerCase()))
if (blockWord) { if (blockWord) {
@ -284,12 +247,8 @@ export class chatgpt extends plugin {
if (userSetting.usePicture) { if (userSetting.usePicture) {
let endTokens = ['.', '。', '……', '!', '', ']', ')', '', '】', '?', '', '~', '"', "'"] let endTokens = ['.', '。', '……', '!', '', ']', ')', '', '】', '?', '', '~', '"', "'"]
while (!endTokens.find(token => response.trimEnd().endsWith(token))) { while (!endTokens.find(token => response.trimEnd().endsWith(token))) {
// while (!response.trimEnd().endsWith('.') && !response.trimEnd().endsWith('。') && !response.trimEnd().endsWith('……') &&
// !response.trimEnd().endsWith('') && !response.trimEnd().endsWith('!') && !response.trimEnd().endsWith(']') && !response.trimEnd().endsWith('】')
// ) {
await this.reply('内容有点多,我正在奋笔疾书,请再等一会', true, { recallMsg: 5 }) await this.reply('内容有点多,我正在奋笔疾书,请再等一会', true, { recallMsg: 5 })
const responseAppend = await c.sendMessage('Continue') const responseAppend = await this.chatGPTApi.sendMessage('Continue')
// console.log(responseAppend)
// 检索是否有屏蔽词 // 检索是否有屏蔽词
const blockWord = blockWords.split(',').find(word => responseAppend.toLowerCase().includes(word.toLowerCase())) const blockWord = blockWords.split(',').find(word => responseAppend.toLowerCase().includes(word.toLowerCase()))
if (blockWord) { if (blockWord) {
@ -300,15 +259,6 @@ export class chatgpt extends plugin {
logger.warn('chatgpt might forget what it had said') logger.warn('chatgpt might forget what it had said')
break break
} }
// 更新redis中的conversation对象因为send后c已经被自动更新了
await redis.set(`CHATGPT:CONVERSATIONS:${e.sender.user_id}`, JSON.stringify({
sender: e.sender,
conversation: c,
ctime: previousConversation.ctime,
utime: new Date(),
num: previousConversation.num + 1
}), { EX: CONVERSATION_PRESERVE_TIME })
response = response + responseAppend response = response + responseAppend
} }
// logger.info(response) // logger.info(response)

View file

@ -63,7 +63,7 @@ export class help extends plugin {
priority: 500, priority: 500,
rule: [ rule: [
{ {
reg: '^(#|[chatgpt|ChatGPT])*(命令|帮助|菜单|help|说明|功能|指令|使用说明)$', reg: '#(chatgpt|ChatGPT)(命令|帮助|菜单|help|说明|功能|指令|使用说明)',
fnc: 'help' fnc: 'help'
} }
] ]

View file

@ -17,7 +17,10 @@ export const Config = {
// 每个人发起的对话保留时长。超过这个时长没有进行对话,再进行对话将开启新的对话。单位:秒 // 每个人发起的对话保留时长。超过这个时长没有进行对话,再进行对话将开启新的对话。单位:秒
conversationPreserveTime: 600, conversationPreserveTime: 600,
// UA: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36', // UA: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36',
headless: false, // headless: false,
// 为空使用默认puppeteer的chromium也可以传递自己本机安装的Chrome可执行文件地址提高通过率 // 为空使用默认puppeteer的chromium也可以传递自己本机安装的Chrome可执行文件地址提高通过率
chromePath: 'C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe' // 目前库暂时不支持指定chrome
// chromePath: 'C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe',
// 可注册2captcha实现跳过验证码收费服务但很便宜
'2captchaToken': ''
} }