Skip to content

Commit

Permalink
fix: reload bot_config
Browse files Browse the repository at this point in the history
  • Loading branch information
deanxv committed Jul 3, 2024
1 parent 8934f14 commit 90e0cbc
Show file tree
Hide file tree
Showing 4 changed files with 86 additions and 21 deletions.
11 changes: 9 additions & 2 deletions common/constants.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
package common

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

const (
RequestIdKey = "X-Request-Id"
Expand Down Expand Up @@ -30,6 +30,13 @@ var CozeErrorMessages = []string{
"I'm sorry, but I can't assist with that.",
}

var CozeDailyLimitErrorMessages = []string{
var CozeUserDailyLimitErrorMessages = []string{
"Hi there! You've used up your free chat credits. To continue enjoying our service, please consider upgrading to our premium plan [Upgrade to Coze Premium to chat](https://www.coze.com/premium?connectID=10000028&botID=7376964308913422354)",
"You have exceeded the daily limit for sending messages to the bot. Please try again later.",
}

var CozeCreatorDailyLimitErrorMessages = []string{
"The bot's usage is covered by the developer, but due to the developer's message credits being exhausted, the bot is temporarily unavailable.",
}

var CozeDailyLimitErrorMessages = append(CozeUserDailyLimitErrorMessages, CozeCreatorDailyLimitErrorMessages...)
26 changes: 20 additions & 6 deletions controller/chat.go
Original file line number Diff line number Diff line change
Expand Up @@ -333,10 +333,14 @@ loop:
c.SSEvent("", " "+string(bytes))

if common.SliceContains(common.CozeErrorMessages, reply.Choices[0].Message.Content) {
if common.SliceContains(common.CozeDailyLimitErrorMessages, reply.Choices[0].Message.Content) {
if common.SliceContains(common.CozeUserDailyLimitErrorMessages, reply.Choices[0].Message.Content) {
common.LogWarn(c, fmt.Sprintf("USER_AUTHORIZATION:%s DAILY LIMIT", userAuth))
discord.UserAuthorizations = common.FilterSlice(discord.UserAuthorizations, userAuth)
}
if common.SliceContains(common.CozeCreatorDailyLimitErrorMessages, reply.Choices[0].Message.Content) {
common.LogWarn(c, fmt.Sprintf("BOT_ID:%s DAILY LIMIT", calledCozeBotId))
discord.BotConfigList = discord.FilterBotConfigByBotId(discord.BotConfigList, calledCozeBotId)
}
c.SSEvent("", " [DONE]")
return false // 关闭流式连接
}
Expand All @@ -357,10 +361,14 @@ loop:
select {
case reply := <-replyChan:
if common.SliceContains(common.CozeErrorMessages, reply.Choices[0].Message.Content) {
if common.SliceContains(common.CozeDailyLimitErrorMessages, reply.Choices[0].Message.Content) {
if common.SliceContains(common.CozeUserDailyLimitErrorMessages, reply.Choices[0].Message.Content) {
common.LogWarn(c, fmt.Sprintf("USER_AUTHORIZATION:%s DAILY LIMIT", userAuth))
discord.UserAuthorizations = common.FilterSlice(discord.UserAuthorizations, userAuth)
}
if common.SliceContains(common.CozeCreatorDailyLimitErrorMessages, reply.Choices[0].Message.Content) {
common.LogWarn(c, fmt.Sprintf("BOT_ID:%s DAILY LIMIT", calledCozeBotId))
discord.BotConfigList = discord.FilterBotConfigByBotId(discord.BotConfigList, calledCozeBotId)
}
c.JSON(http.StatusInternalServerError, model.OpenAIErrorResponse{
OpenAIError: model.OpenAIError{
Message: reply.Choices[0].Message.Content,
Expand Down Expand Up @@ -566,12 +574,18 @@ func ImagesForOpenAI(c *gin.Context) {
for {
select {
case reply := <-replyChan:
if reply.DailyLimit {
common.LogWarn(c, fmt.Sprintf("USER_AUTHORIZATION:%s DAILY LIMIT", userAuth))
discord.UserAuthorizations = common.FilterSlice(discord.UserAuthorizations, userAuth)
if common.SliceContains(common.CozeErrorMessages, reply.Data[0].RevisedPrompt) {
if common.SliceContains(common.CozeUserDailyLimitErrorMessages, reply.Data[0].RevisedPrompt) {
common.LogWarn(c, fmt.Sprintf("USER_AUTHORIZATION:%s DAILY LIMIT", userAuth))
discord.UserAuthorizations = common.FilterSlice(discord.UserAuthorizations, userAuth)
}
if common.SliceContains(common.CozeCreatorDailyLimitErrorMessages, reply.Data[0].RevisedPrompt) {
common.LogWarn(c, fmt.Sprintf("BOT_ID:%s DAILY LIMIT", calledCozeBotId))
discord.BotConfigList = discord.FilterBotConfigByBotId(discord.BotConfigList, calledCozeBotId)
}
c.JSON(http.StatusInternalServerError, model.OpenAIErrorResponse{
OpenAIError: model.OpenAIError{
Message: "daily limit for sending messages",
Message: reply.Data[0].RevisedPrompt,
Type: "request_error",
Code: "500",
},
Expand Down
48 changes: 43 additions & 5 deletions discord/discord.go
Original file line number Diff line number Diff line change
Expand Up @@ -90,11 +90,13 @@ func StartBot(ctx context.Context, token string) {
checkEnvVariable()
common.SysLog("Bot is now running. Enjoy It.")

// 每日9点 重新加载userAuth
// 每日9点 重新加载BotConfig
go loadBotConfigTask()
// 每日9.5点 重新加载userAuth
go loadUserAuthTask()

if CozeBotStayActiveEnable == "1" || CozeBotStayActiveEnable == "" {
// 开启coze保活任务
// 开启coze保活任务 每日9.10
go stayActiveMessageTask()
}

Expand All @@ -116,6 +118,32 @@ func StartBot(ctx context.Context, token string) {
<-sc
}

func loadBotConfigTask() {
for {
source := rand.NewSource(time.Now().UnixNano())
randomNumber := rand.New(source).Intn(60) // 生成0到60之间的随机整数

// 计算距离下一个时间间隔
now := time.Now()
next := time.Date(now.Year(), now.Month(), now.Day(), 9, 5, 0, 0, now.Location())

// 如果当前时间已经超过9点,那么等待到第二天的9点
if now.After(next) {
next = next.Add(24 * time.Hour)
}

delay := next.Sub(now)

// 等待直到下一个间隔
time.Sleep(delay + time.Duration(randomNumber)*time.Second)

common.SysLog("CDP Scheduled loadBotConfig Task Job Start!")
loadBotConfig()
common.SysLog("CDP Scheduled loadBotConfig Task Job End!")

}
}

func telegramNotifyMsgTask() {

for NoAvailableUserAuthChan != nil || CreateChannelRiskChan != nil {
Expand Down Expand Up @@ -158,7 +186,7 @@ func loadUserAuthTask() {

// 计算距离下一个时间间隔
now := time.Now()
next := time.Date(now.Year(), now.Month(), now.Day(), 9, 0, 0, 0, now.Location())
next := time.Date(now.Year(), now.Month(), now.Day(), 9, 5, 0, 0, now.Location())

// 如果当前时间已经超过9点,那么等待到第二天的9点
if now.After(next) {
Expand Down Expand Up @@ -567,8 +595,8 @@ func stayActiveMessageTask() {

// 计算距离下一个时间间隔
now := time.Now()
// 9点05分 为了保证loadUserAuthTask每日任务执行完毕
next := time.Date(now.Year(), now.Month(), now.Day(), 9, 5, 0, 0, now.Location())
// 9点10分 为了保证loadUserAuthTask每日任务执行完毕
next := time.Date(now.Year(), now.Month(), now.Day(), 9, 10, 0, 0, now.Location())

// 如果当前时间已经超过9点,那么等待到第二天的9点
if now.After(next) {
Expand Down Expand Up @@ -685,3 +713,13 @@ func FilterConfigs(configs []model.BotConfig, secret, gptModel string, channelId
}
return filteredConfigs
}

func FilterBotConfigByBotId(slice []model.BotConfig, filter string) []model.BotConfig {
var result []model.BotConfig
for _, value := range slice {
if value.CozeBotId != filter {
result = append(result, value)
}
}
return result
}
22 changes: 14 additions & 8 deletions discord/processmessage.go
Original file line number Diff line number Diff line change
Expand Up @@ -67,11 +67,14 @@ func processMessageUpdateForOpenAIImage(m *discordgo.MessageUpdate) model.OpenAI
var response model.OpenAIImagesGenerationResponse

if common.SliceContains(common.CozeDailyLimitErrorMessages, m.Content) {
return model.OpenAIImagesGenerationResponse{
Created: time.Now().Unix(),
Data: response.Data,
DailyLimit: true,
response.Data = append(response.Data, &model.OpenAIImagesGenerationDataResponse{
RevisedPrompt: m.Content,
})
res := model.OpenAIImagesGenerationResponse{
Created: time.Now().Unix(),
Data: response.Data,
}
return res
}

re := regexp.MustCompile(`\]\((https?://[^\s\)]+)\)`)
Expand Down Expand Up @@ -184,11 +187,14 @@ func processMessageCreateForOpenAIImage(m *discordgo.MessageCreate) model.OpenAI
var response model.OpenAIImagesGenerationResponse

if common.SliceContains(common.CozeDailyLimitErrorMessages, m.Content) {
return model.OpenAIImagesGenerationResponse{
Created: time.Now().Unix(),
Data: response.Data,
DailyLimit: true,
response.Data = append(response.Data, &model.OpenAIImagesGenerationDataResponse{
RevisedPrompt: m.Content,
})
res := model.OpenAIImagesGenerationResponse{
Created: time.Now().Unix(),
Data: response.Data,
}
return res
}

re := regexp.MustCompile(`\]\((https?://[^\s\)]+)\)`)
Expand Down

0 comments on commit 90e0cbc

Please sign in to comment.