chatgpt-plugin/utils/slack/slackClient.js

68 lines
2 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { Config } from '../config.js'
import slack from '@slack/bolt'
import delay from 'delay'
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')
}
}
export class SlackClaudeClient {
constructor (props) {
this.config = props
if (Config.slackSigningSecret && Config.slackBotUserToken && Config.slackUserToken) {
let option = {
signingSecret: Config.slackSigningSecret,
token: Config.slackBotUserToken,
// socketMode: true,
appToken: Config.slackUserToken
// port: 45912
}
if (Config.proxy) {
option.agent = proxy(Config.proxy)
}
this.app = new slack.App(option)
} else {
throw new Error('未配置Slack信息')
}
}
async sendMessage (prompt) {
let sendResponse = await this.app.client.chat.postMessage({
as_user: true,
text: `${prompt}`,
token: this.config.slackUserToken,
channel: this.config.slackChannelId
})
let ts = sendResponse.ts
let response = '_Typing…_'
let tryTimes = 0
while (response.trim().endsWith('_Typing…_')) {
let replies = await this.app.client.conversations.history({
token: this.config.slackUserToken,
channel: this.config.slackChannelId,
limit: 1,
oldest: ts
})
if (replies.messages.length > 0 && replies.messages[0].bot_profile) {
response = replies.messages[0].text
if (Config.debug) {
let text = response.replace('_Typing…_', '')
if (text) {
logger.info(response.replace('_Typing…_', ''))
}
}
}
await delay(500)
tryTimes++
if (tryTimes > 10 && response === '_Typing…_') {
// 过了5秒还没任何回复就重新发一下试试
logger.warn('claude没有响应重试中')
return await this.sendMessage(prompt)
}
}
return response
}
}