mirror of
https://github.com/ikechan8370/chatgpt-plugin.git
synced 2025-12-18 14:27:10 +00:00
fix: format code
This commit is contained in:
parent
2679206be9
commit
414eb1b098
12 changed files with 819 additions and 908 deletions
36
apps/chat.js
36
apps/chat.js
|
|
@ -57,10 +57,10 @@ try {
|
||||||
const defaultPropmtPrefix = ', a large language model trained by OpenAI. You answer as concisely as possible for each response (e.g. don’t be verbose). It is very important that you answer as concisely as possible, so please remember this. If you are generating a list, do not have too many items. Keep the number of items short.'
|
const defaultPropmtPrefix = ', a large language model trained by OpenAI. You answer as concisely as possible for each response (e.g. don’t be verbose). It is very important that you answer as concisely as possible, so please remember this. If you are generating a list, do not have too many items. Keep the number of items short.'
|
||||||
const newFetch = (url, options = {}) => {
|
const newFetch = (url, options = {}) => {
|
||||||
const defaultOptions = Config.proxy
|
const defaultOptions = Config.proxy
|
||||||
? {
|
? {
|
||||||
agent: proxy(Config.proxy)
|
agent: proxy(Config.proxy)
|
||||||
}
|
}
|
||||||
: {}
|
: {}
|
||||||
const mergedOptions = {
|
const mergedOptions = {
|
||||||
...defaultOptions,
|
...defaultOptions,
|
||||||
...options
|
...options
|
||||||
|
|
@ -848,7 +848,7 @@ export class chatgpt extends plugin {
|
||||||
ttsResponse = response.replace(ttsRegex, '')
|
ttsResponse = response.replace(ttsRegex, '')
|
||||||
// 先把文字回复发出去,避免过久等待合成语音
|
// 先把文字回复发出去,避免过久等待合成语音
|
||||||
if (Config.alsoSendText || ttsResponse.length > Config.ttsAutoFallbackThreshold) {
|
if (Config.alsoSendText || ttsResponse.length > Config.ttsAutoFallbackThreshold) {
|
||||||
if(ttsResponse.length > Config.ttsAutoFallbackThreshold){
|
if (ttsResponse.length > Config.ttsAutoFallbackThreshold) {
|
||||||
await this.reply('回复的内容过长,已转为文本模式')
|
await this.reply('回复的内容过长,已转为文本模式')
|
||||||
}
|
}
|
||||||
await this.reply(await convertFaces(response, Config.enableRobotAt, e), e.isGroup)
|
await this.reply(await convertFaces(response, Config.enableRobotAt, e), e.isGroup)
|
||||||
|
|
@ -876,7 +876,7 @@ export class chatgpt extends plugin {
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
await this.reply('合成语音发生错误~')
|
await this.reply('合成语音发生错误~')
|
||||||
}
|
}
|
||||||
} else if(!Config.ttsSpace){
|
} else if (!Config.ttsSpace) {
|
||||||
await this.reply('你没有配置转语音API哦')
|
await this.reply('你没有配置转语音API哦')
|
||||||
}
|
}
|
||||||
} else if (userSetting.usePicture || (Config.autoUsePicture && response.length > Config.autoUsePictureThreshold)) {
|
} else if (userSetting.usePicture || (Config.autoUsePicture && response.length > Config.autoUsePictureThreshold)) {
|
||||||
|
|
@ -918,7 +918,7 @@ export class chatgpt extends plugin {
|
||||||
await this.reply(`出现错误:${err}`, true, { recallMsg: e.isGroup ? 10 : 0 })
|
await this.reply(`出现错误:${err}`, true, { recallMsg: e.isGroup ? 10 : 0 })
|
||||||
} else {
|
} else {
|
||||||
// 这里是否还需要上传到缓存服务器呐?多半是代理服务器的问题,本地也修不了,应该不用吧。
|
// 这里是否还需要上传到缓存服务器呐?多半是代理服务器的问题,本地也修不了,应该不用吧。
|
||||||
await this.renderImage(e, use !== 'bing' ? 'content/ChatGPT/index' : 'content/Bing/index', `通信异常,错误信息如下 ${err?.message || err?.data?.message || (typeof(err) === 'object' ? JSON.stringify(err) : err) || '未能确认错误类型!'}`, prompt)
|
await this.renderImage(e, use !== 'bing' ? 'content/ChatGPT/index' : 'content/Bing/index', `通信异常,错误信息如下 ${err?.message || err?.data?.message || (typeof (err) === 'object' ? JSON.stringify(err) : err) || '未能确认错误类型!'}`, prompt)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -1481,19 +1481,19 @@ export class chatgpt extends plugin {
|
||||||
Authorization: 'Bearer ' + Config.apiKey
|
Authorization: 'Bearer ' + Config.apiKey
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
.then(response => response.json())
|
.then(response => response.json())
|
||||||
.then(data => {
|
.then(data => {
|
||||||
if (data.error) {
|
if (data.error) {
|
||||||
this.reply('获取失败:' + data.error.code)
|
this.reply('获取失败:' + data.error.code)
|
||||||
return false
|
return false
|
||||||
} else {
|
} else {
|
||||||
let total_granted = data.total_granted.toFixed(2)
|
let total_granted = data.total_granted.toFixed(2)
|
||||||
let total_used = data.total_used.toFixed(2)
|
let total_used = data.total_used.toFixed(2)
|
||||||
let total_available = data.total_available.toFixed(2)
|
let total_available = data.total_available.toFixed(2)
|
||||||
let expires_at = new Date(data.grants.data[0].expires_at * 1000).toLocaleDateString().replace(/\//g, '-')
|
let expires_at = new Date(data.grants.data[0].expires_at * 1000).toLocaleDateString().replace(/\//g, '-')
|
||||||
this.reply('总额度:$' + total_granted + '\n已经使用额度:$' + total_used + '\n当前剩余额度:$' + total_available + '\n到期日期(UTC):' + expires_at)
|
this.reply('总额度:$' + total_granted + '\n已经使用额度:$' + total_used + '\n当前剩余额度:$' + total_available + '\n到期日期(UTC):' + expires_at)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|
|
||||||
|
|
@ -251,7 +251,6 @@ export class dalle extends plugin {
|
||||||
})
|
})
|
||||||
bingToken = minElement.Token
|
bingToken = minElement.Token
|
||||||
} else if (restricted.length > 0) {
|
} else if (restricted.length > 0) {
|
||||||
allThrottled = true
|
|
||||||
const minElement = restricted.reduce((min, current) => {
|
const minElement = restricted.reduce((min, current) => {
|
||||||
return current.Usage < min.Usage ? current : min
|
return current.Usage < min.Usage ? current : min
|
||||||
})
|
})
|
||||||
|
|
|
||||||
|
|
@ -221,8 +221,8 @@ export class Entertainment extends plugin {
|
||||||
return false
|
return false
|
||||||
} else {
|
} else {
|
||||||
Config.initiativeChatGroups = Config.initiativeChatGroups
|
Config.initiativeChatGroups = Config.initiativeChatGroups
|
||||||
.filter(group => group.trim() !== '')
|
.filter(group => group.trim() !== '')
|
||||||
.concat(validGroups)
|
.concat(validGroups)
|
||||||
}
|
}
|
||||||
if (typeof paramArray[2] === 'undefined' && typeof paramArray[3] === 'undefined') {
|
if (typeof paramArray[2] === 'undefined' && typeof paramArray[3] === 'undefined') {
|
||||||
replyMsg = `已更新打招呼设置:\n${!e.isGroup ? '群号:' + Config.initiativeChatGroups.join(', ') + '\n' : ''}间隔时间:${Config.helloInterval}小时\n触发概率:${Config.helloProbability}%`
|
replyMsg = `已更新打招呼设置:\n${!e.isGroup ? '群号:' + Config.initiativeChatGroups.join(', ') + '\n' : ''}间隔时间:${Config.helloInterval}小时\n触发概率:${Config.helloProbability}%`
|
||||||
|
|
|
||||||
|
|
@ -321,6 +321,6 @@ export class help extends plugin {
|
||||||
|
|
||||||
async newHelp (e) {
|
async newHelp (e) {
|
||||||
let use = e.msg.replace(/^#帮助-/, '').toUpperCase().trim()
|
let use = e.msg.replace(/^#帮助-/, '').toUpperCase().trim()
|
||||||
await renderUrl(e, `http://127.0.0.1:${Config.serverPort || 3321}/help/` + use, {Viewport: {width: 800, height: 600}})
|
await renderUrl(e, `http://127.0.0.1:${Config.serverPort || 3321}/help/` + use, { Viewport: { width: 800, height: 600 } })
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -179,7 +179,7 @@ export class ChatgptManagement extends plugin {
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
reg: '^#(设置|修改)用户密码',
|
reg: '^#(设置|修改)用户密码',
|
||||||
fnc: 'setUserPassword',
|
fnc: 'setUserPassword'
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
reg: '^#chatgpt系统(设置|配置|管理)',
|
reg: '^#chatgpt系统(设置|配置|管理)',
|
||||||
|
|
@ -188,7 +188,7 @@ export class ChatgptManagement extends plugin {
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
reg: '^#chatgpt用户(设置|配置|管理)',
|
reg: '^#chatgpt用户(设置|配置|管理)',
|
||||||
fnc: 'userPage',
|
fnc: 'userPage'
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
})
|
})
|
||||||
|
|
@ -228,12 +228,12 @@ export class ChatgptManagement extends plugin {
|
||||||
} else {
|
} else {
|
||||||
if (isWhiteList) {
|
if (isWhiteList) {
|
||||||
Config.groupWhitelist = Config.groupWhitelist
|
Config.groupWhitelist = Config.groupWhitelist
|
||||||
.filter(group => group.trim() !== '')
|
.filter(group => group.trim() !== '')
|
||||||
.concat(whitelist)
|
.concat(whitelist)
|
||||||
} else {
|
} else {
|
||||||
Config.groupBlacklist = Config.groupBlacklist
|
Config.groupBlacklist = Config.groupBlacklist
|
||||||
.filter(group => group.trim() !== '')
|
.filter(group => group.trim() !== '')
|
||||||
.concat(blacklist)
|
.concat(blacklist)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
await this.reply(`群聊${isWhiteList ? '白' : '黑'}名单已更新,可通过\n'#chatgpt查看群聊${isWhiteList ? '白' : '黑'}名单'查看最新名单\n#chatgpt移除群聊${isWhiteList ? '白' : '黑'}名单'管理名单`, e.isGroup)
|
await this.reply(`群聊${isWhiteList ? '白' : '黑'}名单已更新,可通过\n'#chatgpt查看群聊${isWhiteList ? '白' : '黑'}名单'查看最新名单\n#chatgpt移除群聊${isWhiteList ? '白' : '黑'}名单'管理名单`, e.isGroup)
|
||||||
|
|
@ -300,6 +300,7 @@ export class ChatgptManagement extends plugin {
|
||||||
await this.reply('设置成功', e.isGroup)
|
await this.reply('设置成功', e.isGroup)
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
async enableGroupContext (e) {
|
async enableGroupContext (e) {
|
||||||
const reg = /(关闭|打开)/
|
const reg = /(关闭|打开)/
|
||||||
const match = e.msg.match(reg)
|
const match = e.msg.match(reg)
|
||||||
|
|
@ -417,7 +418,7 @@ export class ChatgptManagement extends plugin {
|
||||||
{
|
{
|
||||||
Token: item,
|
Token: item,
|
||||||
State: '正常',
|
State: '正常',
|
||||||
Usage: 0,
|
Usage: 0
|
||||||
}
|
}
|
||||||
))
|
))
|
||||||
} else {
|
} else {
|
||||||
|
|
@ -430,16 +431,18 @@ export class ChatgptManagement extends plugin {
|
||||||
tokens = []
|
tokens = []
|
||||||
}
|
}
|
||||||
await redis.set('CHATGPT:BING_TOKENS', JSON.stringify([...token, ...tokens]))
|
await redis.set('CHATGPT:BING_TOKENS', JSON.stringify([...token, ...tokens]))
|
||||||
await this.reply(`迁移完成`, true)
|
await this.reply('迁移完成', true)
|
||||||
}
|
}
|
||||||
|
|
||||||
async getBingAccessToken (e) {
|
async getBingAccessToken (e) {
|
||||||
let tokens = await redis.get('CHATGPT:BING_TOKENS')
|
let tokens = await redis.get('CHATGPT:BING_TOKENS')
|
||||||
if (tokens) tokens = JSON.parse(tokens)
|
if (tokens) tokens = JSON.parse(tokens)
|
||||||
else tokens = []
|
else tokens = []
|
||||||
tokens = tokens.length > 0 ? tokens.map((item, index) => (
|
tokens = tokens.length > 0
|
||||||
|
? tokens.map((item, index) => (
|
||||||
`【${index}】 Token:${item.Token.substring(0, 5 / 2) + '...' + item.Token.substring(item.Token.length - 5 / 2, item.Token.length)}`
|
`【${index}】 Token:${item.Token.substring(0, 5 / 2) + '...' + item.Token.substring(item.Token.length - 5 / 2, item.Token.length)}`
|
||||||
)).join('\n') : '无必应Token记录'
|
)).join('\n')
|
||||||
|
: '无必应Token记录'
|
||||||
await this.reply(`${tokens}`, true)
|
await this.reply(`${tokens}`, true)
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
@ -449,9 +452,11 @@ export class ChatgptManagement extends plugin {
|
||||||
let tokens = await redis.get('CHATGPT:BING_TOKENS')
|
let tokens = await redis.get('CHATGPT:BING_TOKENS')
|
||||||
if (tokens) tokens = JSON.parse(tokens)
|
if (tokens) tokens = JSON.parse(tokens)
|
||||||
else tokens = []
|
else tokens = []
|
||||||
tokens = tokens.length > 0 ? tokens.map((item, index) => (
|
tokens = tokens.length > 0
|
||||||
|
? tokens.map((item, index) => (
|
||||||
`【${index}】 Token:${item.Token.substring(0, 5 / 2) + '...' + item.Token.substring(item.Token.length - 5 / 2, item.Token.length)}`
|
`【${index}】 Token:${item.Token.substring(0, 5 / 2) + '...' + item.Token.substring(item.Token.length - 5 / 2, item.Token.length)}`
|
||||||
)).join('\n') : '无必应Token记录'
|
)).join('\n')
|
||||||
|
: '无必应Token记录'
|
||||||
await this.reply(`请发送要删除的token编号\n${tokens}`, true)
|
await this.reply(`请发送要删除的token编号\n${tokens}`, true)
|
||||||
if (tokens.length == 0) this.finish('saveBingToken')
|
if (tokens.length == 0) this.finish('saveBingToken')
|
||||||
return false
|
return false
|
||||||
|
|
@ -495,16 +500,18 @@ export class ChatgptManagement extends plugin {
|
||||||
let bingToken = []
|
let bingToken = []
|
||||||
if (await redis.exists('CHATGPT:BING_TOKENS') != 0) {
|
if (await redis.exists('CHATGPT:BING_TOKENS') != 0) {
|
||||||
bingToken = JSON.parse(await redis.get('CHATGPT:BING_TOKENS'))
|
bingToken = JSON.parse(await redis.get('CHATGPT:BING_TOKENS'))
|
||||||
if (!bingToken.some(element => element.token === token)) bingToken.push({
|
if (!bingToken.some(element => element.token === token)) {
|
||||||
Token: token,
|
bingToken.push({
|
||||||
State: '正常',
|
Token: token,
|
||||||
Usage: 0,
|
State: '正常',
|
||||||
})
|
Usage: 0
|
||||||
|
})
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
bingToken = [{
|
bingToken = [{
|
||||||
Token: token,
|
Token: token,
|
||||||
State: '正常',
|
State: '正常',
|
||||||
Usage: 0,
|
Usage: 0
|
||||||
}]
|
}]
|
||||||
}
|
}
|
||||||
await redis.set('CHATGPT:BING_TOKENS', JSON.stringify(bingToken))
|
await redis.set('CHATGPT:BING_TOKENS', JSON.stringify(bingToken))
|
||||||
|
|
@ -519,14 +526,13 @@ export class ChatgptManagement extends plugin {
|
||||||
let bingToken = JSON.parse(await redis.get('CHATGPT:BING_TOKENS'))
|
let bingToken = JSON.parse(await redis.get('CHATGPT:BING_TOKENS'))
|
||||||
if (tokenId >= 0 && tokenId < bingToken.length) {
|
if (tokenId >= 0 && tokenId < bingToken.length) {
|
||||||
const removeToken = bingToken[tokenId].Token
|
const removeToken = bingToken[tokenId].Token
|
||||||
bingToken.splice(tokenId,1)
|
bingToken.splice(tokenId, 1)
|
||||||
await redis.set('CHATGPT:BING_TOKENS', JSON.stringify(bingToken))
|
await redis.set('CHATGPT:BING_TOKENS', JSON.stringify(bingToken))
|
||||||
await this.reply(`Token ${removeToken.substring(0, 5 / 2) + '...' + removeToken.substring(removeToken.length - 5 / 2, removeToken.length)} 移除成功`, true)
|
await this.reply(`Token ${removeToken.substring(0, 5 / 2) + '...' + removeToken.substring(removeToken.length - 5 / 2, removeToken.length)} 移除成功`, true)
|
||||||
this.finish('deleteBingToken')
|
this.finish('deleteBingToken')
|
||||||
} else {
|
} else {
|
||||||
await this.reply('Token编号错误!', true)
|
await this.reply('Token编号错误!', true)
|
||||||
this.finish('deleteBingToken')
|
this.finish('deleteBingToken')
|
||||||
return
|
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
await this.reply('Token记录异常', true)
|
await this.reply('Token记录异常', true)
|
||||||
|
|
@ -929,7 +935,7 @@ export class ChatgptManagement extends plugin {
|
||||||
}
|
}
|
||||||
|
|
||||||
async setAdminPassword (e) {
|
async setAdminPassword (e) {
|
||||||
if (e.isGroup || e.isPrivate) {
|
if (e.isGroup || !e.isPrivate) {
|
||||||
await this.reply('请私聊发生命令', true)
|
await this.reply('请私聊发生命令', true)
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
|
|
@ -937,8 +943,9 @@ export class ChatgptManagement extends plugin {
|
||||||
await this.reply('请发送系统管理密码', true)
|
await this.reply('请发送系统管理密码', true)
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
async setUserPassword (e) {
|
async setUserPassword (e) {
|
||||||
if (e.isGroup || e.isPrivate) {
|
if (e.isGroup || !e.isPrivate) {
|
||||||
await this.reply('请私聊发生命令', true)
|
await this.reply('请私聊发生命令', true)
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
|
|
@ -954,6 +961,7 @@ export class ChatgptManagement extends plugin {
|
||||||
await this.reply('设置成功', true)
|
await this.reply('设置成功', true)
|
||||||
this.finish('saveAdminPassword')
|
this.finish('saveAdminPassword')
|
||||||
}
|
}
|
||||||
|
|
||||||
async saveUserPassword (e) {
|
async saveUserPassword (e) {
|
||||||
if (!this.e.msg) return
|
if (!this.e.msg) return
|
||||||
const passwd = this.e.msg
|
const passwd = this.e.msg
|
||||||
|
|
@ -972,7 +980,6 @@ export class ChatgptManagement extends plugin {
|
||||||
fs.writeFile(filepath, JSON.stringify(config), 'utf8', (err) => {
|
fs.writeFile(filepath, JSON.stringify(config), 'utf8', (err) => {
|
||||||
if (err) {
|
if (err) {
|
||||||
console.error(err)
|
console.error(err)
|
||||||
return
|
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
@ -984,7 +991,6 @@ export class ChatgptManagement extends plugin {
|
||||||
}), 'utf8', (err) => {
|
}), 'utf8', (err) => {
|
||||||
if (err) {
|
if (err) {
|
||||||
console.error(err)
|
console.error(err)
|
||||||
return
|
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
@ -1009,5 +1015,4 @@ export class ChatgptManagement extends plugin {
|
||||||
const viewHost = Config.serverHost ? `http://${Config.serverHost}/` : `http://${await getPublicIP()}:${Config.serverPort || 3321}/`
|
const viewHost = Config.serverHost ? `http://${Config.serverHost}/` : `http://${await getPublicIP()}:${Config.serverPort || 3321}/`
|
||||||
await this.reply(`请登录${viewHost + 'admin/dashboard'}进行系统配置`, true)
|
await this.reply(`请登录${viewHost + 'admin/dashboard'}进行系统配置`, true)
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -11,7 +11,6 @@ import schedule from 'node-schedule'
|
||||||
import { Config } from '../utils/config.js'
|
import { Config } from '../utils/config.js'
|
||||||
import { randomString, getPublicIP } from '../utils/common.js'
|
import { randomString, getPublicIP } from '../utils/common.js'
|
||||||
|
|
||||||
|
|
||||||
const __dirname = path.resolve()
|
const __dirname = path.resolve()
|
||||||
const server = fastify({
|
const server = fastify({
|
||||||
logger: Config.debug
|
logger: Config.debug
|
||||||
|
|
@ -37,13 +36,13 @@ let Statistics = {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function getLoad() {
|
async function getLoad () {
|
||||||
// 获取当前操作系统平台
|
// 获取当前操作系统平台
|
||||||
const platform = os.platform();
|
const platform = os.platform()
|
||||||
// 判断平台是Linux还是Windows
|
// 判断平台是Linux还是Windows
|
||||||
if (platform === 'linux') {
|
if (platform === 'linux') {
|
||||||
// 如果是Linux,使用os.loadavg()方法获取负载平均值
|
// 如果是Linux,使用os.loadavg()方法获取负载平均值
|
||||||
const loadAvg = os.loadavg();
|
const loadAvg = os.loadavg()
|
||||||
return loadAvg[0] * 100
|
return loadAvg[0] * 100
|
||||||
} else if (platform === 'win32') {
|
} else if (platform === 'win32') {
|
||||||
// 如果是Windows不获取性能
|
// 如果是Windows不获取性能
|
||||||
|
|
@ -53,7 +52,7 @@ async function getLoad() {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function getUserData(qq) {
|
async function getUserData (qq) {
|
||||||
const dir = 'resources/ChatGPTCache/user'
|
const dir = 'resources/ChatGPTCache/user'
|
||||||
const filename = `${qq}.json`
|
const filename = `${qq}.json`
|
||||||
const filepath = path.join(dir, filename)
|
const filepath = path.join(dir, filename)
|
||||||
|
|
@ -69,7 +68,7 @@ async function getUserData(qq) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function setUserData(qq, data) {
|
async function setUserData (qq, data) {
|
||||||
const dir = 'resources/ChatGPTCache/user'
|
const dir = 'resources/ChatGPTCache/user'
|
||||||
const filename = `${qq}.json`
|
const filename = `${qq}.json`
|
||||||
const filepath = path.join(dir, filename)
|
const filepath = path.join(dir, filename)
|
||||||
|
|
@ -77,12 +76,12 @@ async function setUserData(qq, data) {
|
||||||
fs.writeFileSync(filepath, JSON.stringify(data))
|
fs.writeFileSync(filepath, JSON.stringify(data))
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function createServer() {
|
export async function createServer () {
|
||||||
await server.register(cors, {
|
await server.register(cors, {
|
||||||
origin: '*',
|
origin: '*'
|
||||||
})
|
})
|
||||||
await server.register(fstatic, {
|
await server.register(fstatic, {
|
||||||
root: path.join(__dirname, 'plugins/chatgpt-plugin/server/static/'),
|
root: path.join(__dirname, 'plugins/chatgpt-plugin/server/static/')
|
||||||
})
|
})
|
||||||
await server.register(fastifyCookie)
|
await server.register(fastifyCookie)
|
||||||
await server.get('/page/*', (request, reply) => {
|
await server.get('/page/*', (request, reply) => {
|
||||||
|
|
@ -133,21 +132,21 @@ export async function createServer() {
|
||||||
if (body.qq && body.passwd) {
|
if (body.qq && body.passwd) {
|
||||||
const token = randomString(32)
|
const token = randomString(32)
|
||||||
if (body.qq == Bot.uin && await redis.get('CHATGPT:ADMIN_PASSWD') == body.passwd) {
|
if (body.qq == Bot.uin && await redis.get('CHATGPT:ADMIN_PASSWD') == body.passwd) {
|
||||||
usertoken.push({user: body.qq, token: token, autho: 'admin'})
|
usertoken.push({ user: body.qq, token, autho: 'admin' })
|
||||||
reply.setCookie('token', token, {path: '/'})
|
reply.setCookie('token', token, { path: '/' })
|
||||||
reply.send({login:true, autho: 'admin'})
|
reply.send({ login: true, autho: 'admin' })
|
||||||
} else {
|
} else {
|
||||||
const user = await getUserData(body.qq)
|
const user = await getUserData(body.qq)
|
||||||
if (user.passwd != '' && user.passwd === body.passwd) {
|
if (user.passwd != '' && user.passwd === body.passwd) {
|
||||||
usertoken.push({user: body.qq, token: token, autho: 'user'})
|
usertoken.push({ user: body.qq, token, autho: 'user' })
|
||||||
reply.setCookie('token', token, {path: '/'})
|
reply.setCookie('token', token, { path: '/' })
|
||||||
reply.send({login: true, autho: 'user'})
|
reply.send({ login: true, autho: 'user' })
|
||||||
} else {
|
} else {
|
||||||
reply.send({login:false,err:`用户名密码错误,如果忘记密码请私聊机器人输入 ${body.qq == Bot.uin ? '#修改管理密码' : '#修改用户密码'} 进行修改`})
|
reply.send({ login: false, err: `用户名密码错误,如果忘记密码请私聊机器人输入 ${body.qq == Bot.uin ? '#修改管理密码' : '#修改用户密码'} 进行修改` })
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
reply.send({login:false,err:'未输入用户名或密码'})
|
reply.send({ login: false, err: '未输入用户名或密码' })
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
// 页面数据获取
|
// 页面数据获取
|
||||||
|
|
@ -183,7 +182,7 @@ export async function createServer() {
|
||||||
const regexUrl = /\b((?:https?|ftp|file):\/\/[-a-zA-Z0-9+&@#\/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#\/%=~_|])/g
|
const regexUrl = /\b((?:https?|ftp|file):\/\/[-a-zA-Z0-9+&@#\/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#\/%=~_|])/g
|
||||||
const ip = await getPublicIP()
|
const ip = await getPublicIP()
|
||||||
try {
|
try {
|
||||||
fs.mkdirSync(dir, { recursive: true });
|
fs.mkdirSync(dir, { recursive: true })
|
||||||
const data = {
|
const data = {
|
||||||
user: body.content.senderName,
|
user: body.content.senderName,
|
||||||
bot: Config.chatViewBotName || (body.bing ? 'Bing' : 'ChatGPT'),
|
bot: Config.chatViewBotName || (body.bing ? 'Bing' : 'ChatGPT'),
|
||||||
|
|
@ -207,7 +206,7 @@ export async function createServer() {
|
||||||
group: data.group,
|
group: data.group,
|
||||||
herf: data.herf,
|
herf: data.herf,
|
||||||
model: data.model,
|
model: data.model,
|
||||||
time: data.time,
|
time: data.time
|
||||||
})
|
})
|
||||||
await setUserData(body.qq, user)
|
await setUserData(body.qq, user)
|
||||||
Statistics.CacheFile.count += 1
|
Statistics.CacheFile.count += 1
|
||||||
|
|
@ -228,26 +227,26 @@ export async function createServer() {
|
||||||
server.post('/userData', async (request, reply) => {
|
server.post('/userData', async (request, reply) => {
|
||||||
const token = request.cookies.token || 'unknown'
|
const token = request.cookies.token || 'unknown'
|
||||||
let user = usertoken.find(user => user.token === token)
|
let user = usertoken.find(user => user.token === token)
|
||||||
if (!user) user = {user: ''}
|
if (!user) user = { user: '' }
|
||||||
const userData = await getUserData(user.user)
|
const userData = await getUserData(user.user)
|
||||||
reply.send(userData.chat)
|
reply.send(userData.chat)
|
||||||
})
|
})
|
||||||
|
|
||||||
//清除缓存数据
|
// 清除缓存数据
|
||||||
server.post('/cleanCache', async (request, reply) => {
|
server.post('/cleanCache', async (request, reply) => {
|
||||||
const token = request.cookies.token || 'unknown'
|
const token = request.cookies.token || 'unknown'
|
||||||
let user = usertoken.find(user => user.token === token)
|
let user = usertoken.find(user => user.token === token)
|
||||||
if (!user) user = {user: ''}
|
if (!user) user = { user: '' }
|
||||||
const userData = await getUserData(user.user)
|
const userData = await getUserData(user.user)
|
||||||
const dir = 'resources/ChatGPTCache/page'
|
const dir = 'resources/ChatGPTCache/page'
|
||||||
userData.chat.forEach(function (item, index) {
|
userData.chat.forEach(function (item, index) {
|
||||||
const filename = item.herf.substring(item.herf.lastIndexOf("/") + 1) + '.json'
|
const filename = item.herf.substring(item.herf.lastIndexOf('/') + 1) + '.json'
|
||||||
const filepath = path.join(dir, filename)
|
const filepath = path.join(dir, filename)
|
||||||
fs.unlinkSync(filepath)
|
fs.unlinkSync(filepath)
|
||||||
})
|
})
|
||||||
userData.chat = []
|
userData.chat = []
|
||||||
await setUserData(user.user, userData)
|
await setUserData(user.user, userData)
|
||||||
reply.send({state: true})
|
reply.send({ state: true })
|
||||||
})
|
})
|
||||||
|
|
||||||
// 获取系统参数
|
// 获取系统参数
|
||||||
|
|
@ -255,14 +254,12 @@ export async function createServer() {
|
||||||
const token = request.cookies.token || 'unknown'
|
const token = request.cookies.token || 'unknown'
|
||||||
const user = usertoken.find(user => user.token === token)
|
const user = usertoken.find(user => user.token === token)
|
||||||
if (!user) {
|
if (!user) {
|
||||||
reply.send({err: '未登录'})
|
reply.send({ err: '未登录' })
|
||||||
} else if(user.autho === 'admin') {
|
} else if (user.autho === 'admin') {
|
||||||
let redisConfig = {}
|
let redisConfig = {}
|
||||||
if (await redis.exists('CHATGPT:BING_TOKENS') != 0) {
|
if (await redis.exists('CHATGPT:BING_TOKENS') != 0) {
|
||||||
let bingTokens = await redis.get('CHATGPT:BING_TOKENS')
|
let bingTokens = await redis.get('CHATGPT:BING_TOKENS')
|
||||||
if (bingTokens)
|
if (bingTokens) { bingTokens = JSON.parse(bingTokens) } else bingTokens = []
|
||||||
bingTokens = JSON.parse(bingTokens)
|
|
||||||
else bingTokens = []
|
|
||||||
redisConfig.bingTokens = bingTokens
|
redisConfig.bingTokens = bingTokens
|
||||||
} else {
|
} else {
|
||||||
redisConfig.bingTokens = []
|
redisConfig.bingTokens = []
|
||||||
|
|
@ -272,7 +269,7 @@ export async function createServer() {
|
||||||
}
|
}
|
||||||
reply.send({
|
reply.send({
|
||||||
chatConfig: Config,
|
chatConfig: Config,
|
||||||
redisConfig: redisConfig
|
redisConfig
|
||||||
})
|
})
|
||||||
} else {
|
} else {
|
||||||
let userSetting = await redis.get(`CHATGPT:USER:${user.user}`)
|
let userSetting = await redis.get(`CHATGPT:USER:${user.user}`)
|
||||||
|
|
@ -286,7 +283,7 @@ export async function createServer() {
|
||||||
userSetting = JSON.parse(userSetting)
|
userSetting = JSON.parse(userSetting)
|
||||||
}
|
}
|
||||||
reply.send({
|
reply.send({
|
||||||
userSetting: userSetting
|
userSetting
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
@ -297,8 +294,8 @@ export async function createServer() {
|
||||||
const user = usertoken.find(user => user.token === token)
|
const user = usertoken.find(user => user.token === token)
|
||||||
const body = request.body || {}
|
const body = request.body || {}
|
||||||
if (!user) {
|
if (!user) {
|
||||||
reply.send({err: '未登录'})
|
reply.send({ err: '未登录' })
|
||||||
} else if(user.autho === 'admin') {
|
} else if (user.autho === 'admin') {
|
||||||
const chatdata = body.chatConfig || {}
|
const chatdata = body.chatConfig || {}
|
||||||
for (let [keyPath, value] of Object.entries(chatdata)) {
|
for (let [keyPath, value] of Object.entries(chatdata)) {
|
||||||
if (keyPath === 'blockWords' || keyPath === 'promptBlockWords' || keyPath === 'initiativeChatGroups') { value = value.toString().split(/[,,;;\|]/) }
|
if (keyPath === 'blockWords' || keyPath === 'promptBlockWords' || keyPath === 'initiativeChatGroups') { value = value.toString().split(/[,,;;\|]/) }
|
||||||
|
|
@ -312,36 +309,33 @@ export async function createServer() {
|
||||||
await redis.set('CHATGPT:CONFIRM', redisConfig.turnConfirm ? 'on' : 'off')
|
await redis.set('CHATGPT:CONFIRM', redisConfig.turnConfirm ? 'on' : 'off')
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
if (body.userSetting){
|
if (body.userSetting) {
|
||||||
await redis.set(`CHATGPT:USER:${user.user}`, JSON.stringify(body.userSetting))
|
await redis.set(`CHATGPT:USER:${user.user}`, JSON.stringify(body.userSetting))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
server.addHook('onRequest', (request, reply, done) => {
|
server.addHook('onRequest', (request, reply, done) => {
|
||||||
if(request.method == 'POST')
|
if (request.method == 'POST') { Statistics.SystemAccess.count += 1 }
|
||||||
Statistics.SystemAccess.count += 1
|
if (request.method == 'GET') { Statistics.WebAccess.count += 1 }
|
||||||
if(request.method == 'GET')
|
|
||||||
Statistics.WebAccess.count += 1
|
|
||||||
done()
|
done()
|
||||||
|
|
||||||
})
|
})
|
||||||
//定时任务
|
// 定时任务
|
||||||
var rule = new schedule.RecurrenceRule();
|
let rule = new schedule.RecurrenceRule()
|
||||||
rule.hour = 0;
|
rule.hour = 0
|
||||||
rule.minute = 0;
|
rule.minute = 0
|
||||||
let job_Statistics = schedule.scheduleJob(rule, function() {
|
let job_Statistics = schedule.scheduleJob(rule, function () {
|
||||||
Statistics.SystemAccess.oldCount = Statistics.SystemAccess.count
|
Statistics.SystemAccess.oldCount = Statistics.SystemAccess.count
|
||||||
Statistics.CacheFile.oldCount = Statistics.CacheFile.count
|
Statistics.CacheFile.oldCount = Statistics.CacheFile.count
|
||||||
Statistics.WebAccess.oldCount = Statistics.WebAccess.count
|
Statistics.WebAccess.oldCount = Statistics.WebAccess.count
|
||||||
Statistics.SystemAccess.count = 0
|
Statistics.SystemAccess.count = 0
|
||||||
Statistics.CacheFile.count = 0
|
Statistics.CacheFile.count = 0
|
||||||
Statistics.WebAccess.count = 0
|
Statistics.WebAccess.count = 0
|
||||||
});
|
})
|
||||||
let job_Statistics_SystemLoad = schedule.scheduleJob('0 * * * *', async function(){
|
let job_Statistics_SystemLoad = schedule.scheduleJob('0 * * * *', async function () {
|
||||||
Statistics.SystemLoad.count = await getLoad()
|
Statistics.SystemLoad.count = await getLoad()
|
||||||
Statistics.SystemLoad.oldCount = Statistics.SystemLoad.count
|
Statistics.SystemLoad.oldCount = Statistics.SystemLoad.count
|
||||||
});
|
})
|
||||||
|
|
||||||
server.listen({
|
server.listen({
|
||||||
port: Config.serverPort || 3321,
|
port: Config.serverPort || 3321,
|
||||||
|
|
|
||||||
File diff suppressed because it is too large
Load diff
|
|
@ -594,7 +594,7 @@ export async function isImage (link) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function getPublicIP() {
|
export async function getPublicIP () {
|
||||||
try {
|
try {
|
||||||
if (localIP === '') {
|
if (localIP === '') {
|
||||||
const res = await fetch('https://api.ipify.org?format=json')
|
const res = await fetch('https://api.ipify.org?format=json')
|
||||||
|
|
@ -605,5 +605,4 @@ export async function getPublicIP() {
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
return '127.0.0.1'
|
return '127.0.0.1'
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -92,7 +92,7 @@ const defaultConfig = {
|
||||||
groupWhitelist: [],
|
groupWhitelist: [],
|
||||||
groupBlacklist: [],
|
groupBlacklist: [],
|
||||||
ttsRegex: '/匹配规则/匹配模式',
|
ttsRegex: '/匹配规则/匹配模式',
|
||||||
version: 'v2.5.1'
|
version: 'v2.5.2'
|
||||||
}
|
}
|
||||||
const _path = process.cwd()
|
const _path = process.cwd()
|
||||||
let config = {}
|
let config = {}
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,5 @@
|
||||||
import fetch from 'node-fetch'
|
import fetch from 'node-fetch'
|
||||||
import { Config } from '../utils/config.js'
|
import { Config } from './config.js'
|
||||||
|
|
||||||
export async function getConversations (qq = '', fetchFn = fetch) {
|
export async function getConversations (qq = '', fetchFn = fetch) {
|
||||||
let accessToken = await redis.get('CHATGPT:TOKEN')
|
let accessToken = await redis.get('CHATGPT:TOKEN')
|
||||||
|
|
|
||||||
|
|
@ -47,4 +47,3 @@ export function deleteOnePrompt (name) {
|
||||||
let filePath = `${_path}/plugins/chatgpt-plugin/prompts/${name}.txt`
|
let filePath = `${_path}/plugins/chatgpt-plugin/prompts/${name}.txt`
|
||||||
fs.unlinkSync(filePath)
|
fs.unlinkSync(filePath)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -175,43 +175,6 @@ function uuid () {
|
||||||
let hex = crypto.randomBytes(16).toString('hex')
|
let hex = crypto.randomBytes(16).toString('hex')
|
||||||
return hex.substr(0, 8) + '-' + hex.substr(8, 4) + '-' + hex.substr(12, 4) + '-' + hex.substr(16, 4) + '-' + hex.substr(20)
|
return hex.substr(0, 8) + '-' + hex.substr(8, 4) + '-' + hex.substr(12, 4) + '-' + hex.substr(16, 4) + '-' + hex.substr(20)
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 计算流的md5 */
|
|
||||||
function md5Stream (readable) {
|
|
||||||
return new Promise((resolve, reject) => {
|
|
||||||
readable.on('error', reject)
|
|
||||||
readable.pipe(crypto.createHash('md5')
|
|
||||||
.on('error', reject)
|
|
||||||
.on('data', resolve))
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 计算文件的md5和sha */
|
|
||||||
function fileHash (filepath) {
|
|
||||||
const readable = fs.createReadStream(filepath)
|
|
||||||
const sha = new Promise((resolve, reject) => {
|
|
||||||
readable.on('error', reject)
|
|
||||||
readable.pipe(crypto.createHash('sha1')
|
|
||||||
.on('error', reject)
|
|
||||||
.on('data', resolve))
|
|
||||||
})
|
|
||||||
return Promise.all([md5Stream(readable), sha])
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 群号转uin */
|
|
||||||
function code2uin (code) {
|
|
||||||
let left = Math.floor(code / 1000000)
|
|
||||||
if (left >= 0 && left <= 10) { left += 202 } else if (left >= 11 && left <= 19) { left += 469 } else if (left >= 20 && left <= 66) { left += 2080 } else if (left >= 67 && left <= 156) { left += 1943 } else if (left >= 157 && left <= 209) { left += 1990 } else if (left >= 210 && left <= 309) { left += 3890 } else if (left >= 310 && left <= 335) { left += 3490 } else if (left >= 336 && left <= 386) { left += 2265 } else if (left >= 387 && left <= 499) { left += 3490 }
|
|
||||||
return left * 1000000 + code % 1000000
|
|
||||||
}
|
|
||||||
|
|
||||||
/** uin转群号 */
|
|
||||||
function uin2code (uin) {
|
|
||||||
let left = Math.floor(uin / 1000000)
|
|
||||||
if (left >= 202 && left <= 212) { left -= 202 } else if (left >= 480 && left <= 488) { left -= 469 } else if (left >= 2100 && left <= 2146) { left -= 2080 } else if (left >= 2010 && left <= 2099) { left -= 1943 } else if (left >= 2147 && left <= 2199) { left -= 1990 } else if (left >= 2600 && left <= 2651) { left -= 2265 } else if (left >= 3800 && left <= 3989) { left -= 3490 } else if (left >= 4100 && left <= 4199) { left -= 3890 }
|
|
||||||
return left * 1000000 + uin % 1000000
|
|
||||||
}
|
|
||||||
|
|
||||||
function int32ip2str (ip) {
|
function int32ip2str (ip) {
|
||||||
if (typeof ip === 'string') { return ip }
|
if (typeof ip === 'string') { return ip }
|
||||||
ip = ip & 0xffffffff
|
ip = ip & 0xffffffff
|
||||||
|
|
@ -222,60 +185,12 @@ function int32ip2str (ip) {
|
||||||
(ip & 0xff000000) >> 24 & 0xff
|
(ip & 0xff000000) >> 24 & 0xff
|
||||||
].join('.')
|
].join('.')
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 解析彩色群名片 */
|
|
||||||
function parseFunString (buf) {
|
|
||||||
if (buf[0] === 0xA) {
|
|
||||||
let res = ''
|
|
||||||
try {
|
|
||||||
let arr = core.pb.decode(buf)[1]
|
|
||||||
if (!Array.isArray(arr)) { arr = [arr] }
|
|
||||||
for (let v of arr) {
|
|
||||||
if (v[2]) { res += String(v[2]) }
|
|
||||||
}
|
|
||||||
} catch { }
|
|
||||||
return res
|
|
||||||
} else {
|
|
||||||
return String(buf)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** xml转义 */
|
|
||||||
function escapeXml (str) {
|
|
||||||
return str.replace(/[&"><]/g, function (s) {
|
|
||||||
if (s === '&') { return '&' }
|
|
||||||
if (s === '<') { return '<' }
|
|
||||||
if (s === '>') { return '>' }
|
|
||||||
if (s === '"') { return '"' }
|
|
||||||
return ''
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 用于下载限量 */
|
|
||||||
class DownloadTransform extends stream.Transform {
|
|
||||||
constructor () {
|
|
||||||
super(...arguments)
|
|
||||||
this._size = 0
|
|
||||||
}
|
|
||||||
|
|
||||||
_transform (data, encoding, callback) {
|
|
||||||
this._size += data.length
|
|
||||||
let error = null
|
|
||||||
if (this._size <= MAX_UPLOAD_SIZE) { this.push(data) } else { error = new Error('downloading over 30MB is refused') }
|
|
||||||
callback(error)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
const IS_WIN = os.platform() === 'win32'
|
const IS_WIN = os.platform() === 'win32'
|
||||||
/** 系统临时目录,用于临时存放下载的图片等内容 */
|
/** 系统临时目录,用于临时存放下载的图片等内容 */
|
||||||
const TMP_DIR = os.tmpdir()
|
const TMP_DIR = os.tmpdir()
|
||||||
/** 最大上传和下载大小,以图片上传限制为准:30MB */
|
|
||||||
const MAX_UPLOAD_SIZE = 31457280
|
|
||||||
|
|
||||||
/** no operation */
|
/** no operation */
|
||||||
const NOOP = () => { }
|
const NOOP = () => { }
|
||||||
|
(0, util.promisify)(stream.pipeline)
|
||||||
/** promisified pipeline */
|
|
||||||
const pipeline = (0, util.promisify)(stream.pipeline)
|
|
||||||
/** md5 hash */
|
/** md5 hash */
|
||||||
const md5 = (data) => (0, crypto.createHash)('md5').update(data).digest()
|
const md5 = (data) => (0, crypto.createHash)('md5').update(data).digest()
|
||||||
|
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue