Skip to content

Commit

Permalink
适配Trss (#575)
Browse files Browse the repository at this point in the history
* fix: 修复星火api上下文

* 将无星火ck的情况降低为warn

* feat: 添加星火设定自定义代码功能

* 修复星火api模式的一些问题

* 修复导出配置问题

* feat:添加工具箱快捷登录接口

* 添加工具箱快捷登录指令

* 阻止群聊使用快捷登录

* 添加Azure配置支持,修复重复的配置项冲突

* 移除旧版本渲染和新版本帮助

* 添加工具箱

* 更新工具箱替换原有后台

* 更新工具箱适配代码

* 后台适配Trss

* 修复trss不支持sendPrivateMsg的问题

* 优化路由

* 修复路由

* 适配其他uin
  • Loading branch information
HalcyonAlcedo authored Oct 8, 2023
1 parent 64f2699 commit 0f9c8a7
Show file tree
Hide file tree
Showing 10 changed files with 73 additions and 37 deletions.
16 changes: 8 additions & 8 deletions apps/chat.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ import {
getUserReplySetting,
getImageOcrText,
getImg,
getMaxModelTokens, formatDate, generateAudio, formatDate2, mkdirs
getMaxModelTokens, formatDate, generateAudio, formatDate2, mkdirs, getUin
} from '../utils/common.js'
import { ChatGPTPuppeteer } from '../utils/browser.js'
import { KeyvFile } from 'keyv-file'
Expand Down Expand Up @@ -315,7 +315,7 @@ export class chatgpt extends plugin {
}
let ats = e.message.filter(m => m.type === 'at')
const isAtMode = Config.toggleMode === 'at'
if (isAtMode) ats = ats.filter(item => item.qq !== Bot.uin)
if (isAtMode) ats = ats.filter(item => item.qq !== getUin(e))
if (ats.length === 0) {
if (use === 'api3') {
await redis.del(`CHATGPT:QQ_CONVERSATION:${(e.isGroup && Config.groupMerge) ? e.group_id.toString() : e.sender.user_id}`)
Expand Down Expand Up @@ -764,11 +764,11 @@ export class chatgpt extends plugin {
if (e.isGroup && !e.atme) {
return false
}
if (e.user_id == Bot.uin) return false
if (e.user_id == getUin(e)) return false
prompt = e.raw_message.trim()
if (e.isGroup && typeof this.e.group.getMemberMap === 'function') {
let mm = await this.e.group.getMemberMap()
let me = mm.get(Bot.uin)
let me = mm.get(getUin(e))
let card = me.card
let nickname = me.nickname
if (nickname && card) {
Expand Down Expand Up @@ -1477,7 +1477,7 @@ export class chatgpt extends plugin {
chatViewBotName: Config.chatViewBotName || '',
entry: cacheData.file,
userImg: `https://q1.qlogo.cn/g?b=qq&s=0&nk=${e.sender.user_id}`,
botImg: `https://q1.qlogo.cn/g?b=qq&s=0&nk=${Bot.uin}`,
botImg: `https://q1.qlogo.cn/g?b=qq&s=0&nk=${getUin(e)}`,
cacheHost: Config.serverHost,
qq: e.sender.user_id
})
Expand Down Expand Up @@ -1586,7 +1586,7 @@ export class chatgpt extends plugin {
opt.qq = e.sender.user_id
opt.nickname = e.sender.card
opt.groupName = e.group.name
opt.botName = e.isGroup ? (e.group.pickMember(Bot.uin).card || e.group.pickMember(Bot.uin).nickname) : Bot.nickname
opt.botName = e.isGroup ? (e.group.pickMember(getUin(e)).card || e.group.pickMember(getUin(e)).nickname) : Bot.nickname
let master = (await getMasterQQ())[0]
if (master && e.group) {
opt.masterName = e.group.pickMember(parseInt(master)).card || e.group.pickMember(parseInt(master)).nickname
Expand Down Expand Up @@ -2019,7 +2019,7 @@ export class chatgpt extends plugin {
opt.qq = e.sender.user_id
opt.nickname = e.sender.card
opt.groupName = e.group.name
opt.botName = e.isGroup ? (e.group.pickMember(Bot.uin).card || e.group.pickMember(Bot.uin).nickname) : Bot.nickname
opt.botName = e.isGroup ? (e.group.pickMember(getUin(e)).card || e.group.pickMember(getUin(e)).nickname) : Bot.nickname
let master = (await getMasterQQ())[0]
if (master && e.group) {
opt.masterName = e.group.pickMember(parseInt(master)).card || e.group.pickMember(parseInt(master)).nickname
Expand Down Expand Up @@ -2191,7 +2191,7 @@ export class chatgpt extends plugin {
logger.mark(logger.green('【ChatGPT-Plugin】插件avocado-plugin未安装') + ',安装后可查看最近热映电影与体验可玩性更高的点歌工具。\n可前往 https://github.com/Qz-Sean/avocado-plugin 获取')
}
if (e.isGroup) {
let botInfo = await Bot.getGroupMemberInfo(e.group_id, Bot.uin, true)
let botInfo = await Bot.getGroupMemberInfo(e.group_id, getUin(e), true)
if (botInfo.role !== 'member') {
// 管理员才给这些工具
tools.push(...[new EditCardTool(), new JinyanTool(), new KickOutTool(), new HandleMessageMsgTool(), new SetTitleTool()])
Expand Down
6 changes: 3 additions & 3 deletions apps/history.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import plugin from '../../../lib/plugins/plugin.js'
import { render } from '../utils/common.js'
import { render, getUin } from '../utils/common.js'
import { Config } from '../utils/config.js'
import { KeyvFile } from 'keyv-file'

Expand Down Expand Up @@ -32,7 +32,7 @@ export class history extends plugin {
async history (e) {
let use = await redis.get('CHATGPT:USE') || 'api'
let chat = []
let filtered = e.message.filter(m => m.type === 'at').filter(m => m.qq !== Bot.uin)
let filtered = e.message.filter(m => m.type === 'at').filter(m => m.qq !== getUin(e))
let queryUser = e.sender.user_id
let user = e.sender
if (filtered.length > 0) {
Expand Down Expand Up @@ -99,7 +99,7 @@ export class history extends plugin {
name: user.card || user.nickname || user.user_id
},
bot: {
qq: Bot.uin,
qq: getUin(e),
name: Bot.nickname
},
chat
Expand Down
6 changes: 3 additions & 3 deletions apps/prompts.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import plugin from '../../../lib/plugins/plugin.js'
import fs from 'fs'
import _ from 'lodash'
import { Config } from '../utils/config.js'
import { getMasterQQ, limitString, makeForwardMsg, maskQQ } from '../utils/common.js'
import { getMasterQQ, limitString, makeForwardMsg, maskQQ, getUin } from '../utils/common.js'
import { deleteOnePrompt, getPromptByName, readPrompts, saveOnePrompt } from '../utils/prompts.js'
import AzureTTS from "../utils/tts/microsoft-azure.js";
export class help extends plugin {
Expand Down Expand Up @@ -246,7 +246,7 @@ export class help extends plugin {
async removeSharePrompt (e) {
let master = (await getMasterQQ())[0]
let name = e.msg.replace(/^#(chatgpt|ChatGPT)(删除|取消|撤销)共享设定/, '')
let response = await fetch(`https://chatgpt.roki.best/prompt?name=${name}&qq=${master || (Bot.uin + '')}`, {
let response = await fetch(`https://chatgpt.roki.best/prompt?name=${name}&qq=${master || (getUin(e) + '')}`, {
method: 'DELETE',
headers: {
'FROM-CHATGPT': 'ikechan8370'
Expand Down Expand Up @@ -354,7 +354,7 @@ export class help extends plugin {
let toUploadBody = {
title: currentUse,
prompt: content,
qq: master || (Bot.uin + ''), // 上传者设定为主人qq或机器人qq
qq: master || (getUin(this.e) + ''), // 上传者设定为主人qq或机器人qq
use: extraData.use === 'Custom' ? 'Sydney' : 'ChatGPT',
r18,
description
Expand Down
6 changes: 6 additions & 0 deletions resources/view/setting_view.json
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,12 @@
"label": "额外工具url",
"placeholder": "测试期间提供一个公益接口,一段时间后撤掉",
"data": "extraUrl"
},
{
"type": "text",
"label": "Trss主账号",
"placeholder": "用于Trss配置脚本时使用的主账号",
"data": "trssBotUin"
}
]
},
Expand Down
34 changes: 21 additions & 13 deletions server/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import websocketclient from 'ws'

import { Config } from '../utils/config.js'
import { UserInfo, GetUser, AddUser } from './modules/user_data.js'
import { getPublicIP, getUserData, getMasterQQ, randomString } from '../utils/common.js'
import { getPublicIP, getUserData, getMasterQQ, randomString, getUin } from '../utils/common.js'

import webRoute from './modules/web_route.js'
import webUser from './modules/user.js'
Expand Down Expand Up @@ -107,7 +107,7 @@ async function mediaLink() {
ws.on('open', () => {
ws.send(JSON.stringify({
command: 'register',
region: Bot.uin,
region: getUin(),
type: 'server',
}))
})
Expand All @@ -118,7 +118,11 @@ async function mediaLink() {
case 'register':
if (data.state) {
let master = (await getMasterQQ())[0]
Bot.sendPrivateMsg(master, `当前chatgpt插件服务无法被外网访问,已启用代理链接,访问代码:${data.token}`, false)
if (Array.isArray(Bot.uin)) {
Bot.pickFriend(master).sendMsg(`当前chatgpt插件服务无法被外网访问,已启用代理链接,访问代码:${data.token}`)
} else {
Bot.sendPrivateMsg(master, `当前chatgpt插件服务无法被外网访问,已启用代理链接,访问代码:${data.token}`, false)
}
} else {
console.log('注册区域失败')
}
Expand All @@ -128,30 +132,30 @@ async function mediaLink() {
const user = UserInfo(data.token)
if (user) {
ws.login = true
ws.send(JSON.stringify({ command: data.command, state: true, region: Bot.uin, type: 'server' }))
ws.send(JSON.stringify({ command: data.command, state: true, region: getUin(), type: 'server' }))
} else {
ws.send(JSON.stringify({ command: data.command, state: false, error: '权限验证失败', region: Bot.uin, type: 'server' }))
ws.send(JSON.stringify({ command: data.command, state: false, error: '权限验证失败', region: getUin(), type: 'server' }))
}
}
break
case 'post_login':
if (data.qq && data.passwd) {
const token = randomString(32)
if (data.qq == Bot.uin && await redis.get('CHATGPT:ADMIN_PASSWD') == data.passwd) {
if (data.qq == getUin() && await redis.get('CHATGPT:ADMIN_PASSWD') == data.passwd) {
AddUser({ user: data.qq, token: token, autho: 'admin' })
ws.send(JSON.stringify({ command: data.command, state: true, autho: 'admin', token: token, region: Bot.uin, type: 'server' }))
ws.send(JSON.stringify({ command: data.command, state: true, autho: 'admin', token: token, region: getUin(), type: 'server' }))

} else {
const user = await getUserData(data.qq)
if (user.passwd != '' && user.passwd === data.passwd) {
AddUser({ user: data.qq, token: token, autho: 'user' })
ws.send(JSON.stringify({ command: data.command, state: true, autho: 'user', token: token, region: Bot.uin, type: 'server' }))
ws.send(JSON.stringify({ command: data.command, state: true, autho: 'user', token: token, region: getUin(), type: 'server' }))
} else {
ws.send(JSON.stringify({ command: data.command, state: false, error: `用户名密码错误,如果忘记密码请私聊机器人输入 ${data.qq == Bot.uin ? '#修改管理密码' : '#修改用户密码'} 进行修改`, region: Bot.uin, type: 'server' }))
ws.send(JSON.stringify({ command: data.command, state: false, error: `用户名密码错误,如果忘记密码请私聊机器人输入 ${data.qq == getUin() ? '#修改管理密码' : '#修改用户密码'} 进行修改`, region: getUin(), type: 'server' }))
}
}
} else {
ws.send(JSON.stringify({ command: data.command, state: false, error: '未输入用户名或密码', region: Bot.uin, type: 'server' }))
ws.send(JSON.stringify({ command: data.command, state: false, error: '未输入用户名或密码', region: getUin(), type: 'server' }))
}
break
case 'post_command':
Expand All @@ -163,7 +167,7 @@ async function mediaLink() {
const response = await fetch(`http://localhost:${Config.serverPort || 3321}${data.postPath}`, fetchOptions)
if (response.ok) {
const json = await response.json()
ws.send(JSON.stringify({ command: data.command, state: true, region: Bot.uin, type: 'server', path: data.postPath, data: json }))
ws.send(JSON.stringify({ command: data.command, state: true, region: getUin(), type: 'server', path: data.postPath, data: json }))
}
break
}
Expand All @@ -189,7 +193,7 @@ export async function createServer() {
if (body.code) {
const pattern = /^[a-zA-Z0-9]+$/
if (!pattern.test(body.code)) {
reply.send({error: 'bad request'})
reply.send({ error: 'bad request' })
}
const dir = 'resources/ChatGPTCache/page'
const filename = body.code + '.json'
Expand Down Expand Up @@ -342,7 +346,11 @@ export async function createServer() {
if (data.group) {
Bot.sendGroupMsg(parseInt(data.id), data.message, data.quotable)
} else {
Bot.sendPrivateMsg(parseInt(data.id), data.message, data.quotable)
if (Array.isArray(Bot.uin)) {
Bot.pickFriend(parseInt(data.id)).sendMsg(data.message)
} else {
Bot.sendPrivateMsg(parseInt(data.id), data.message, data.quotable)
}
}
await connection.socket.send(JSON.stringify({ command: data.command, state: true, }))
} else {
Expand Down
16 changes: 10 additions & 6 deletions server/modules/user.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { UserInfo, AddUser } from './user_data.js'
import { randomString, getUserData, getMasterQQ } from '../../utils/common.js'
import { randomString, getUserData, getMasterQQ, getUin } from '../../utils/common.js'
import fs from 'fs'

async function User(fastify, options) {
Expand All @@ -8,7 +8,7 @@ async function User(fastify, options) {
const body = request.body || {}
if (body.qq && body.passwd) {
const token = randomString(32)
if (body.qq == Bot.uin && await redis.get('CHATGPT:ADMIN_PASSWD') == body.passwd) {
if (body.qq == getUin() && await redis.get('CHATGPT:ADMIN_PASSWD') == body.passwd) {
AddUser({ user: body.qq, token: token, autho: 'admin' })
reply.setCookie('token', token, { path: '/' })
reply.send({ login: true, autho: 'admin', token: token })
Expand All @@ -19,16 +19,16 @@ async function User(fastify, options) {
reply.setCookie('token', token, { path: '/' })
reply.send({ login: true, autho: 'user', token: token })
} else {
reply.send({ login: false, err: `用户名密码错误,如果忘记密码请私聊机器人输入 ${body.qq == Bot.uin ? '#修改管理密码' : '#修改用户密码'} 进行修改` })
reply.send({ login: false, err: `用户名密码错误,如果忘记密码请私聊机器人输入 ${body.qq == getUin() ? '#修改管理密码' : '#修改用户密码'} 进行修改` })
}
}
} else if (body.otp) {
const token = randomString(32)
const opt = await redis.get(`CHATGPT:SERVER_QUICK`)
if (opt && body.otp == opt) {
AddUser({ user: Bot.uin, token: token, autho: 'admin' })
AddUser({ user: getUin(), token: token, autho: 'admin' })
reply.setCookie('token', token, { path: '/' })
reply.send({ login: true, autho: 'admin', token: token, user: Bot.uin })
reply.send({ login: true, autho: 'admin', token: token, user: getUin() })
} else {
reply.send({ login: false, err: `快捷登录代码错误,请检查后重试` })
}
Expand All @@ -46,7 +46,11 @@ async function User(fastify, options) {
{ EX: 60000 }
)
const master = (await getMasterQQ())[0]
Bot.sendPrivateMsg(master, `收到工具箱快捷登录请求,1分钟内有效:${otp}`, false)
if (Array.isArray(Bot.uin)) {
Bot.pickFriend(master).sendMsg(`收到工具箱快捷登录请求,1分钟内有效:${otp}`)
} else {
Bot.sendPrivateMsg(master, `收到工具箱快捷登录请求,1分钟内有效:${otp}`, false)
}
reply.send({ state: true })
return reply
})
Expand Down
8 changes: 8 additions & 0 deletions server/modules/web_route.js
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,14 @@ async function routes(fastify, options) {
reply.type('text/html').send(stream)
return reply
})
fastify.setNotFoundHandler((request, reply) => {
if (request.method == 'GET') {
const stream = fs.createReadStream('plugins/chatgpt-plugin/server/static/index.html')
reply.type('text/html').send(stream)
} else {
reply.code(404).send(new Error('Not Found'))
}
})
}

export default routes
12 changes: 10 additions & 2 deletions utils/common.js
Original file line number Diff line number Diff line change
Expand Up @@ -84,14 +84,14 @@ export async function makeForwardMsg (e, msg = [], dec = '') {
let nickname = Bot.nickname
if (e.isGroup) {
try {
let info = await Bot.getGroupMemberInfo(e.group_id, Bot.uin)
let info = await Bot.getGroupMemberInfo(e.group_id, getUin(e))
nickname = info.card || info.nickname
} catch (err) {
console.error(`Failed to get group member info: ${err}`)
}
}
let userInfo = {
user_id: Bot.uin,
user_id: getUin(e),
nickname
}

Expand Down Expand Up @@ -821,6 +821,14 @@ export function getMaxModelTokens (model = 'gpt-3.5-turbo') {
}
}

export function getUin (e) {
if (e?.bot?.uin) return e.bot.uin
if (Array.isArray(Bot.uin)) {
if (Config.trssBotUin && Bot.uin.indexOf(Config.trssBotUin) > -1) return Config.trssBotUin
else return Bot.uin[0]
} else return Bot.uin
}

/**
* 生成当前语音模式下可发送的音频信息
* @param e - 上下文对象
Expand Down
2 changes: 2 additions & 0 deletions utils/config.js
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,8 @@ const defaultConfig = {
claudeAITimeout: 120,
claudeAIJA3: '772,4865-4866-4867-49195-49199-49196-49200-52393-52392-49171-49172-156-157-47-53,27-5-65281-13-35-0-51-18-16-43-10-45-11-17513-23,29-23-24,0',
claudeAIUA: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36',
// trss配置
trssBotUin: '',
version: 'v2.7.5'
}
const _path = process.cwd()
Expand Down
4 changes: 2 additions & 2 deletions utils/uploadRecord.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import crypto from 'crypto'
import child_process from 'child_process'
import { Config } from './config.js'
import path from 'path'
import { mkdirs } from './common.js'
import { mkdirs, getUin } from './common.js'
let module
try {
module = await import('oicq')
Expand Down Expand Up @@ -139,7 +139,7 @@ async function uploadRecord (recordUrl, ttsMode = 'vits-uma-genshin-honkai') {
2: 3,
5: {
1: Contactable.target,
2: Bot.uin,
2: getUin(e),
3: 0,
4: hash,
5: buf.length,
Expand Down

0 comments on commit 0f9c8a7

Please sign in to comment.