(message: any)
| 7 | |
| 8 | // 文档参考:https://open.bigmodel.cn/dev/api#nosdk |
| 9 | async function zhipu(message: any) { |
| 10 | // 智谱根据 token 获取 secret(签名密钥) 和 expiration |
| 11 | let token = config.token[services.zhipu]; |
| 12 | let secret, expiration; |
| 13 | config.extra[services.zhipu] && ({secret, expiration} = config.extra[services.zhipu]); |
| 14 | if (!secret || expiration <= Date.now()) { |
| 15 | secret = generateToken(token); |
| 16 | if (!secret) throw new Error('无法生成令牌'); |
| 17 | // 保存 secret 和 expiration |
| 18 | config.extra[services.zhipu] = {secret, expiration: Date.now() + 3600000 * 24}; |
| 19 | await storage.setItem('local:config', JSON.stringify(config)); |
| 20 | } |
| 21 | |
| 22 | // 构建请求头 |
| 23 | let headers = new Headers(); |
| 24 | headers.append('Content-Type', 'application/json'); |
| 25 | headers.append('Authorization', `Bearer ${secret}`); |
| 26 | |
| 27 | // 发起 fetch 请求 |
| 28 | const resp = await fetch(urls[services.zhipu], { |
| 29 | method: method.POST, |
| 30 | headers: headers, |
| 31 | body: commonMsgTemplate(message.origin) |
| 32 | }); |
| 33 | |
| 34 | if (resp.ok) { |
| 35 | let result = await resp.json(); |
| 36 | return result.choices[0].message.content; |
| 37 | } else { |
| 38 | console.log(resp) |
| 39 | throw new Error(`翻译失败: ${resp.status} ${resp.statusText} body: ${await resp.text()}`); |
| 40 | } |
| 41 | } |
| 42 | |
| 43 | function generateToken(APIKey: string) { |
| 44 | if (!APIKey || !APIKey.includes('.')) { |
nothing calls this directly
no test coverage detected