Skip to content

Commit

Permalink
fix: 优化频道删除逻辑
Browse files Browse the repository at this point in the history
  • Loading branch information
deanxv committed Mar 2, 2024
1 parent 1eb0712 commit 10baa71
Show file tree
Hide file tree
Showing 3 changed files with 88 additions and 54 deletions.
2 changes: 1 addition & 1 deletion common/constants.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ var StreamRequestOutTime = os.Getenv("STREAM_REQUEST_OUT_TIME")

var DebugEnabled = os.Getenv("DEBUG") == "true"

var Version = "v4.3.1" // this hard coding will be replaced automatically when building, no need to manually change
var Version = "v4.3.2" // this hard coding will be replaced automatically when building, no need to manually change

const (
RequestIdKey = "X-Request-Id"
Expand Down
72 changes: 53 additions & 19 deletions controller/chat.go
Original file line number Diff line number Diff line change
Expand Up @@ -149,7 +149,7 @@ func ChatForOpenAI(c *gin.Context) {
return
}

sendChannelId, calledCozeBotId, err := getSendChannelIdAndCozeBotId(c, request.ChannelId, request.Model, true)
sendChannelId, calledCozeBotId, isNewChannel, err := getSendChannelIdAndCozeBotId(c, request.ChannelId, request.Model, true)

if err != nil {
common.LogError(c.Request.Context(), err.Error())
Expand All @@ -163,6 +163,23 @@ func ChatForOpenAI(c *gin.Context) {
return
}

if isNewChannel {
defer func() {
if discord.ChannelAutoDelTime != "" {
delTime, _ := strconv.Atoi(discord.ChannelAutoDelTime)
if delTime == 0 {
discord.CancelChannelDeleteTimer(sendChannelId)
} else if delTime > 0 {
// 删除该频道
discord.SetChannelDeleteTimer(sendChannelId, time.Duration(delTime)*time.Second)
}
} else {
// 删除该频道
discord.SetChannelDeleteTimer(sendChannelId, 5*time.Second)
}
}()
}

content := "Hi!"
messages := request.Messages

Expand Down Expand Up @@ -337,15 +354,15 @@ loop:
common.LogWarn(c, fmt.Sprintf("USER_AUTHORIZATION:%s DAILY LIMIT", userAuth))
discord.UserAuthorizations = common.FilterSlice(discord.UserAuthorizations, userAuth)
}
discord.SetChannelDeleteTimer(sendChannelId, 5*time.Second)
//discord.SetChannelDeleteTimer(sendChannelId, 5*time.Second)
c.SSEvent("", " [DONE]")
return false // 关闭流式连接
}

return true // 继续保持流式连接
case <-timer.C:
// 定时器到期时,关闭流
discord.SetChannelDeleteTimer(sendChannelId, 5*time.Second)
//discord.SetChannelDeleteTimer(sendChannelId, 5*time.Second)
c.SSEvent("", " [DONE]")
return false
case <-stopChan:
Expand All @@ -363,7 +380,7 @@ loop:
common.LogWarn(c, fmt.Sprintf("USER_AUTHORIZATION:%s DAILY LIMIT", userAuth))
discord.UserAuthorizations = common.FilterSlice(discord.UserAuthorizations, userAuth)
}
discord.SetChannelDeleteTimer(sendChannelId, 5*time.Second)
//discord.SetChannelDeleteTimer(sendChannelId, 5*time.Second)
c.JSON(http.StatusOK, model.OpenAIErrorResponse{
OpenAIError: model.OpenAIError{
Message: reply.Choices[0].Message.Content,
Expand All @@ -375,7 +392,7 @@ loop:
}
replyResp = reply
case <-timer.C:
discord.SetChannelDeleteTimer(sendChannelId, 5*time.Second)
//discord.SetChannelDeleteTimer(sendChannelId, 5*time.Second)
c.JSON(http.StatusOK, model.OpenAIErrorResponse{
OpenAIError: model.OpenAIError{
Message: "Request timeout",
Expand Down Expand Up @@ -469,7 +486,7 @@ func ImagesForOpenAI(c *gin.Context) {
return
}

sendChannelId, calledCozeBotId, err := getSendChannelIdAndCozeBotId(c, request.ChannelId, request.Model, true)
sendChannelId, calledCozeBotId, isNewChannel, err := getSendChannelIdAndCozeBotId(c, request.ChannelId, request.Model, true)
if err != nil {
common.LogError(c.Request.Context(), err.Error())
c.JSON(http.StatusOK, model.OpenAIErrorResponse{
Expand All @@ -482,6 +499,23 @@ func ImagesForOpenAI(c *gin.Context) {
return
}

if isNewChannel {
defer func() {
if discord.ChannelAutoDelTime != "" {
delTime, _ := strconv.Atoi(discord.ChannelAutoDelTime)
if delTime == 0 {
discord.CancelChannelDeleteTimer(sendChannelId)
} else if delTime > 0 {
// 删除该频道
discord.SetChannelDeleteTimer(sendChannelId, time.Duration(delTime)*time.Second)
}
} else {
// 删除该频道
discord.SetChannelDeleteTimer(sendChannelId, 5*time.Second)
}
}()
}

sentMsg, userAuth, err := discord.SendMessage(c, sendChannelId, calledCozeBotId, request.Prompt)
if err != nil {
c.JSON(http.StatusOK, model.OpenAIErrorResponse{
Expand Down Expand Up @@ -518,7 +552,7 @@ func ImagesForOpenAI(c *gin.Context) {
if reply.DailyLimit {
common.LogWarn(c, fmt.Sprintf("USER_AUTHORIZATION:%s DAILY LIMIT", userAuth))
discord.UserAuthorizations = common.FilterSlice(discord.UserAuthorizations, userAuth)
discord.SetChannelDeleteTimer(sendChannelId, 5*time.Second)
//discord.SetChannelDeleteTimer(sendChannelId, 5*time.Second)
c.JSON(http.StatusOK, model.OpenAIErrorResponse{
OpenAIError: model.OpenAIError{
Message: "daily limit for sending messages",
Expand All @@ -530,7 +564,7 @@ func ImagesForOpenAI(c *gin.Context) {
}
replyResp = reply
case <-timer.C:
discord.SetChannelDeleteTimer(sendChannelId, 5*time.Second)
//discord.SetChannelDeleteTimer(sendChannelId, 5*time.Second)
c.JSON(http.StatusOK, model.OpenAIErrorResponse{
OpenAIError: model.OpenAIError{
Message: "Request timed out, please try again later.",
Expand All @@ -557,7 +591,7 @@ func ImagesForOpenAI(c *gin.Context) {

}

func getSendChannelIdAndCozeBotId(c *gin.Context, channelId *string, model string, isOpenAIAPI bool) (sendChannelId string, calledCozeBotId string, err error) {
func getSendChannelIdAndCozeBotId(c *gin.Context, channelId *string, model string, isOpenAIAPI bool) (sendChannelId string, calledCozeBotId string, isNewChannel bool, err error) {
secret := ""
if isOpenAIAPI {
if secret = c.Request.Header.Get("Authorization"); secret != "" {
Expand All @@ -575,37 +609,37 @@ func getSendChannelIdAndCozeBotId(c *gin.Context, channelId *string, model strin
// 有值则随机一个
botConfig, err := common.RandomElement(botConfigs)
if err != nil {
return "", "", err
return "", "", false, err
}

if channelId != nil && *channelId != "" {
return *channelId, botConfig.CozeBotId, nil
return *channelId, botConfig.CozeBotId, false, nil
}

if discord.DefaultChannelEnable == "1" {
return botConfig.ChannelId, botConfig.CozeBotId, nil
return botConfig.ChannelId, botConfig.CozeBotId, false, nil
} else {
var sendChannelId string
sendChannelId, _ = discord.ChannelCreate(discord.GuildId, fmt.Sprintf("cdp-对话%s", c.Request.Context().Value(common.RequestIdKey)), 0)
discord.SetChannelDeleteTimer(sendChannelId, 5*time.Minute)
return sendChannelId, botConfig.CozeBotId, nil
//discord.SetChannelDeleteTimer(sendChannelId, 5*time.Minute)
return sendChannelId, botConfig.CozeBotId, true, nil
}

}
// 没有值抛出异常
return "", "", fmt.Errorf("[proxy-secret]+[model]未匹配到有效bot")
return "", "", false, fmt.Errorf("[proxy-secret]+[model]未匹配到有效bot")
} else {

if channelId != nil && *channelId != "" {
return *channelId, discord.CozeBotId, nil
return *channelId, discord.CozeBotId, false, nil
}

if discord.DefaultChannelEnable == "1" {
return discord.ChannelId, discord.CozeBotId, nil
return discord.ChannelId, discord.CozeBotId, false, nil
} else {
channelCreateId, _ := discord.ChannelCreate(discord.GuildId, fmt.Sprintf("cdp-对话%s", c.Request.Context().Value(common.RequestIdKey)), 0)
discord.SetChannelDeleteTimer(channelCreateId, 5*time.Minute)
return channelCreateId, discord.CozeBotId, nil
//discord.SetChannelDeleteTimer(channelCreateId, 5*time.Minute)
return channelCreateId, discord.CozeBotId, true, nil
}
}
}
Expand Down
68 changes: 34 additions & 34 deletions discord/discord.go
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,7 @@ func checkEnvVariable() {
if GuildId == "" {
common.FatalLog("环境变量 GUILD_ID 未设置")
}
if ChannelId == "" {
if DefaultChannelEnable == "1" && ChannelId == "" {
common.FatalLog("环境变量 CHANNEL_ID 未设置")
}
if CozeBotId == "" {
Expand Down Expand Up @@ -206,17 +206,17 @@ func messageCreate(s *discordgo.Session, m *discordgo.MessageCreate) {
// 尝试获取 stopChan
stopChan, exists := ReplyStopChans[m.ReferencedMessage.ID]
if !exists {
channel, err := Session.Channel(m.ChannelID)
//channel, err := Session.Channel(m.ChannelID)
// 不存在则直接删除频道
if err != nil || strings.HasPrefix(channel.Name, "cdp-对话") {
SetChannelDeleteTimer(m.ChannelID, 5*time.Minute)
return
}
//if err != nil || strings.HasPrefix(channel.Name, "cdp-对话") {
//SetChannelDeleteTimer(m.ChannelID, 5*time.Minute)
return
//}
}

// 如果作者为 nil 或消息来自 bot 本身,则发送停止信号
if m.Author == nil || m.Author.ID == s.State.User.ID {
SetChannelDeleteTimer(m.ChannelID, 5*time.Minute)
//SetChannelDeleteTimer(m.ChannelID, 5*time.Minute)
stopChan <- model.ChannelStopChan{
Id: m.ChannelID,
}
Expand Down Expand Up @@ -255,18 +255,18 @@ func messageCreate(s *discordgo.Session, m *discordgo.MessageCreate) {
replyOpenAIChan <- reply
}

if ChannelAutoDelTime != "" {
delTime, _ := strconv.Atoi(ChannelAutoDelTime)
if delTime == 0 {
CancelChannelDeleteTimer(m.ChannelID)
} else if delTime > 0 {
// 删除该频道
SetChannelDeleteTimer(m.ChannelID, time.Duration(delTime)*time.Second)
}
} else {
// 删除该频道
SetChannelDeleteTimer(m.ChannelID, 5*time.Second)
}
//if ChannelAutoDelTime != "" {
// delTime, _ := strconv.Atoi(ChannelAutoDelTime)
// if delTime == 0 {
// CancelChannelDeleteTimer(m.ChannelID)
// } else if delTime > 0 {
// // 删除该频道
// SetChannelDeleteTimer(m.ChannelID, time.Duration(delTime)*time.Second)
// }
//} else {
// // 删除该频道
// SetChannelDeleteTimer(m.ChannelID, 5*time.Second)
//}
stopChan <- model.ChannelStopChan{
Id: m.ChannelID,
}
Expand All @@ -288,14 +288,14 @@ func messageUpdate(s *discordgo.Session, m *discordgo.MessageUpdate) {
channel, err := Session.Channel(m.ChannelID)
// 不存在则直接删除频道
if err != nil || strings.HasPrefix(channel.Name, "cdp-对话") {
SetChannelDeleteTimer(m.ChannelID, 5*time.Minute)
//SetChannelDeleteTimer(m.ChannelID, 5*time.Minute)
return
}
}

// 如果作者为 nil 或消息来自 bot 本身,则发送停止信号
if m.Author == nil || m.Author.ID == s.State.User.ID {
SetChannelDeleteTimer(m.ChannelID, 5*time.Minute)
//SetChannelDeleteTimer(m.ChannelID, 5*time.Minute)
stopChan <- model.ChannelStopChan{
Id: m.ChannelID,
}
Expand Down Expand Up @@ -334,18 +334,18 @@ func messageUpdate(s *discordgo.Session, m *discordgo.MessageUpdate) {
replyOpenAIChan <- reply
}

if ChannelAutoDelTime != "" {
delTime, _ := strconv.Atoi(ChannelAutoDelTime)
if delTime == 0 {
CancelChannelDeleteTimer(m.ChannelID)
} else if delTime > 0 {
// 删除该频道
SetChannelDeleteTimer(m.ChannelID, time.Duration(delTime)*time.Second)
}
} else {
// 删除该频道
SetChannelDeleteTimer(m.ChannelID, 5*time.Second)
}
//if ChannelAutoDelTime != "" {
// delTime, _ := strconv.Atoi(ChannelAutoDelTime)
// if delTime == 0 {
// CancelChannelDeleteTimer(m.ChannelID)
// } else if delTime > 0 {
// // 删除该频道
// SetChannelDeleteTimer(m.ChannelID, time.Duration(delTime)*time.Second)
// }
//} else {
// // 删除该频道
// SetChannelDeleteTimer(m.ChannelID, 5*time.Second)
//}
stopChan <- model.ChannelStopChan{
Id: m.ChannelID,
}
Expand Down Expand Up @@ -381,7 +381,7 @@ func SendMessage(c *gin.Context, channelID, cozeBotId, message string) (*discord
}

if len(UserAuthorizations) == 0 {
SetChannelDeleteTimer(channelID, 5*time.Second)
//SetChannelDeleteTimer(channelID, 5*time.Second)
common.LogError(c.Request.Context(), fmt.Sprintf("无可用的 user_auth"))
return nil, "", fmt.Errorf("no_available_user_auth")
}
Expand Down

0 comments on commit 10baa71

Please sign in to comment.