Skip to content

Commit

Permalink
fix: 优化频道删除
Browse files Browse the repository at this point in the history
  • Loading branch information
xjd committed Feb 7, 2024
1 parent dad1e63 commit cff0bbe
Show file tree
Hide file tree
Showing 5 changed files with 59 additions and 46 deletions.
9 changes: 4 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -138,8 +138,7 @@ deanxv/coze-discord-proxy

`CHANNEL_ID:119xxxxxx24` # 默认频道-(目前版本下该参数仅用来活跃机器人)

`PROXY_SECRET:123456` [可选]接口密钥-修改此行为请求头校验的值(多个请以,分隔)
,配置此参数后,每次发起请求时请求头加上`proxy-secret`参数,即`header`中添加 `proxy-secret:123456`
`PROXY_SECRET:123456` [可选]接口密钥-修改此行为请求头校验的值(多个请以,分隔)(与openai-API-KEY用法一致)

保存。

Expand Down Expand Up @@ -171,7 +170,7 @@ Render 可以直接部署 docker 镜像,不需要 fork 仓库:[Render](https:/
4. `CHANNEL_ID:119xxxxxx24` 默认频道-(目前版本下该参数仅用来活跃机器人)
5. `CHANNEL_AUTO_DEL_TIME:60` [可选]频道自动删除时间(秒) 此参数为每次对话完成后自动删除频道的时间(默认为5s),为空或0时则不删除,推荐不设置
6. `PORT:7077` [可选]端口
7. `PROXY_SECRET:123456` [可选]接口密钥-修改此行为请求头校验的值(多个请以,分隔),配置此参数后,每次发起请求时请求头加上`proxy-secret`参数,即`header`中添加 `proxy-secret:123456`
7. `PROXY_SECRET:123456` [可选]接口密钥-修改此行为请求头校验的值(多个请以,分隔)(与openai-API-KEY用法一致)
8. `REQUEST_OUT_TIME:60` [可选]对话接口非流响应下的请求超时时间,推荐不设置
9. `STREAM_REQUEST_OUT_TIME:60` [可选]对话接口流响应下的每次流返回超时时间,推荐不设置
10. `PROXY_URL:http://127.0.0.1:10801` [可选]代理
Expand Down Expand Up @@ -211,9 +210,9 @@ Render 可以直接部署 docker 镜像,不需要 fork 仓库:[Render](https:/

## Q&A

##### Q: 我们如何使用该服务托管多个Bot去请求多个由coze托管的Bot?
Q: 我们如何使用该服务托管多个Bot去请求多个由coze托管的Bot?

###### A: 首先用不同的端口部署多个`coze-discord-proxy`服务,对每个服务都[配置多机器人](#配置多机器人),并对每个服务设置不同的`BOT_TOKEN`,再部署[one-api](https://github.com/songquanpeng/one-api)[添加多个渠道](#如何集成one-api),利用[one-api](https://github.com/songquanpeng/one-api)的轮询去请求我们的`coze-discord-proxy`服务。
A: 首先用不同的端口部署多个`coze-discord-proxy`服务,对每个服务都[配置多机器人](#配置多机器人),并对每个服务设置不同的`BOT_TOKEN`,再部署[one-api](https://github.com/songquanpeng/one-api)[添加多个渠道](#如何集成one-api),利用[one-api](https://github.com/songquanpeng/one-api)的轮询去请求我们的`coze-discord-proxy`服务。

## ⭐ Star History

Expand Down
2 changes: 1 addition & 1 deletion common/tiktoken.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ var (
)

func init() {
// gpt-3.5-turbo encoding
// gpt-4-turbo encoding
tke, err := tiktoken.GetEncoding("cl100k_base")
if err != nil {
FatalLog(err.Error())
Expand Down
16 changes: 2 additions & 14 deletions controller/chat.go
Original file line number Diff line number Diff line change
Expand Up @@ -474,27 +474,15 @@ func getSendChannelIdAndCozeBotId(c *gin.Context, isOpenAIAPI bool) (sendChannel
return "", "", err
}
var sendChannelId string
//if channelId := botConfig.ChannelId; channelId != "" {
// sendChannelId = channelId
//} else {
// 创建新频道
sendChannelId, _ = discord.ChannelCreate(discord.GuildId, fmt.Sprintf("对话%s", c.Request.Context().Value(common.RequestIdKey)), 0)
//}
discord.SetChannelDeleteTimer(sendChannelId, 5*time.Minute)
return sendChannelId, botConfig.CozeBotId, nil
}
// 没有值抛出异常
return "", "", fmt.Errorf("secret匹配不到有效bot")
} else {
// botConfigs为空
//channelId := request.GetChannelId()
//if channelId == nil || *channelId == "" {
// if discord.ChannelId != "" {
// channelId = &discord.ChannelId
// } else {
channelCreateId, _ := discord.ChannelCreate(discord.GuildId, fmt.Sprintf("对话%s", c.Request.Context().Value(common.RequestIdKey)), 0)
//channelId = &channelCreateId
//}
//}
discord.SetChannelDeleteTimer(channelCreateId, 5*time.Minute)
return channelCreateId, discord.CozeBotId, nil
}
}
Expand Down
45 changes: 45 additions & 0 deletions discord/channel.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package discord

import (
"coze-discord-proxy/common"
"fmt"
"sync"
"time"
)

var (
channelTimers sync.Map // 用于存储频道ID和对应的定时器
)

// SetChannelDeleteTimer 设置或重置频道的删除定时器
func SetChannelDeleteTimer(channelId string, duration time.Duration) {
// 检查是否已存在定时器
if timer, ok := channelTimers.Load(channelId); ok {
timer.(*time.Timer).Stop() // 停止现有定时器
}

// 设置新的定时器
newTimer := time.AfterFunc(duration, func() {
ChannelDel(channelId)
channelTimers.Delete(channelId) // 删除完成后从map中移除
})

// 存储新的定时器
channelTimers.Store(channelId, newTimer)
}

// CancelChannelDeleteTimer 取消频道的删除定时器
func CancelChannelDeleteTimer(channelId string) {
// 尝试从映射中获取定时器
if timer, ok := channelTimers.Load(channelId); ok {
// 如果定时器存在,尝试停止它
if timer.(*time.Timer).Stop() {
// 定时器成功停止后,从映射中移除
channelTimers.Delete(channelId)
} else {
common.SysError(fmt.Sprintf("定时器无法停止或已触发,频道可能已被删除:%s", channelId))
}
} else {
common.SysError(fmt.Sprintf("频道无定时删除:%s", channelId))
}
}
33 changes: 7 additions & 26 deletions discord/discord.go
Original file line number Diff line number Diff line change
Expand Up @@ -191,7 +191,7 @@ func messageUpdate(s *discordgo.Session, m *discordgo.MessageUpdate) {
}
}
}
// data: {"id":"chatcmpl-8lho2xvdDFyBdFkRwWAcMpWWAgymJ","object":"chat.completion.chunk","created":1706380498,"model":"gpt-3.5-turbo-0613","system_fingerprint":null,"choices":[{"index":0,"delta":{"content":"?"},"logprobs":null,"finish_reason":null}]}
// data: {"id":"chatcmpl-8lho2xvdDFyBdFkRwWAcMpWWAgymJ","object":"chat.completion.chunk","created":1706380498,"model":"gpt-4-turbo-0613","system_fingerprint":null,"choices":[{"index":0,"delta":{"content":"?"},"logprobs":null,"finish_reason":null}]}
// data :{"id":"1200873365351698694","object":"chat.completion.chunk","created":1706380922,"model":"COZE","choices":[{"index":0,"message":{"role":"assistant","content":"你好!有什么我可以帮您的吗?如果有任"},"logprobs":null,"finish_reason":"","delta":{"content":"吗?如果有任"}}],"usage":{"prompt_tokens":13,"completion_tokens":19,"total_tokens":32},"system_fingerprint":null}

// 如果消息包含组件或嵌入,则发送停止信号
Expand All @@ -206,21 +206,16 @@ func messageUpdate(s *discordgo.Session, m *discordgo.MessageUpdate) {

if ChannelAutoDelTime != "" {
delTime, _ := strconv.Atoi(ChannelAutoDelTime)
if delTime > 0 {
if delTime == 0 {
CancelChannelDeleteTimer(m.ChannelID)
} else if delTime > 0 {
// 删除该频道
go func() {
time.Sleep(time.Duration(delTime) * time.Second)
ChannelDel(m.ChannelID)
}()
SetChannelDeleteTimer(m.ChannelID, time.Duration(delTime)*time.Second)
}
} else {
// 删除该频道
go func() {
time.Sleep(5 * time.Second)
ChannelDel(m.ChannelID)
}()
SetChannelDeleteTimer(m.ChannelID, 5*time.Second)
}

stopChan <- model.ChannelStopChan{
Id: m.ChannelID,
}
Expand Down Expand Up @@ -266,7 +261,7 @@ func processMessageForOpenAI(m *discordgo.MessageUpdate) model.OpenAIChatComplet
ID: m.ID,
Object: "chat.completion",
Created: time.Now().Unix(),
Model: "gpt-3.5-turbo",
Model: "gpt-4-turbo",
Choices: []model.OpenAIChoice{
{
Index: 0,
Expand Down Expand Up @@ -341,20 +336,6 @@ func SendMessage(c *gin.Context, channelID, cozeBotId, message string) (*discord
return sentMsg, nil
}
}

//content := fmt.Sprintf("<@%s> %s", cozeBotId, message)
//
//if runeCount := len([]rune(content)); runeCount > 2000 {
// common.LogError(ctx, fmt.Sprintf("prompt已超过限制,请分段发送 [%v] %s", runeCount, content))
// return nil, fmt.Errorf("prompt已超过限制,请分段发送 [%v]", runeCount)
//}
//
//// 添加@机器人逻辑
//sentMsg, err := Session.ChannelMessageSend(channelID, content)
//if err != nil {
// common.LogError(ctx, fmt.Sprintf("error sending message: %s", err))
// return nil, fmt.Errorf("error sending message")
//}
return sentMsg, nil
}

Expand Down

0 comments on commit cff0bbe

Please sign in to comment.