feat: tg bot notify

This commit is contained in:
dean 2024-03-04 15:29:27 +08:00
parent 1212d3fc12
commit 2fbc2e451b
8 changed files with 117 additions and 7 deletions

View File

@ -198,7 +198,9 @@ Render can directly deploy docker images, no need to fork the repository: [Rende
14. `REQUEST_OUT_TIME=60` - [Optional] Request timeout for non-stream response in dialogue interface, **not recommended to use this environment variable**
15. `STREAM_REQUEST_OUT_TIME=60` - [Optional] Stream return timeout for each stream response in dialogue interface, **not recommended to use this environment variable**
16. `USER_AGENT=Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36` - [Optional] Discord user agent. Using your own may effectively prevent being banned. If not set, the author's default will be used. It is recommended to use this environment variable.
17. `PROXY_URL=http://127.0.0.1:10801` - [Optional] Proxy (only supports http)
17. `NOTIFY_TELEGRAM_BOT_TOKEN=6232***********Niz9c` [Optional] Functions as the token for the TelegramBot notification (Notification events include: 1. Unavailability of user_authorization; 2. Risk control trigger by the BOT associated with BOT_TOKEN)
18. `NOTIFY_TELEGRAM_USER_ID=10******35` [Optional] The Telegram-Bot linked with NOTIFY_TELEGRAM_BOT_TOKEN forwards notifications to the Telegram-User associated with this variable (This variable must not be empty when NOTIFY_TELEGRAM_BOT_TOKEN is populated)
19. `PROXY_URL=http://127.0.0.1:10801` - [Optional] Proxy (only supports http)
## Advanced Configuration

View File

@ -194,7 +194,9 @@ Render 可以直接部署 docker 镜像,不需要 fork 仓库:[Render](https:/
14. `REQUEST_OUT_TIME=60` [可选]对话接口非流响应下的请求超时时间,**推荐不使用此环境变量**
15. `STREAM_REQUEST_OUT_TIME=60` [可选]对话接口流响应下的每次流返回超时时间,**推荐不使用此环境变量**
16. `USER_AGENT=Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36` [可选]discord用户端Agent,使用自己的可能有效防止被ban,不设置时默认使用作者的 推荐使用此环境变量
17. `PROXY_URL=http://127.0.0.1:10801` [可选]代理(仅支持http)
17. `NOTIFY_TELEGRAM_BOT_TOKEN=6232***********Niz9c` [可选]作为通知TelegramBot的Token(通知事件:1.无可用`user_authorization`;2.`BOT_TOKEN`关联的BOT触发风控)
18. `NOTIFY_TELEGRAM_USER_ID=10******35` [可选]`NOTIFY_TELEGRAM_BOT_TOKEN`关联的`Telegram-Bot`推送至该变量关联的`Telegram-User`(**`NOTIFY_TELEGRAM_BOT_TOKEN`不为空时该变量也不可为空**)
19. `PROXY_URL=http://127.0.0.1:10801` [可选]代理(仅支持http)
## 进阶配置

View File

@ -74,7 +74,7 @@ func logHelper(ctx context.Context, level string, msg string) {
}
id := ctx.Value(RequestIdKey)
if id == nil {
id = "unknown"
id = "UNKNOWN"
}
now := time.Now()
_, _ = fmt.Fprintf(writer, "[%s] %v | %s | %s \n", level, now.Format("2006/01/02 - 15:04:05"), id, msg)

View File

@ -3,6 +3,7 @@ package discord
import (
"context"
"coze-discord-proxy/common"
"coze-discord-proxy/telegram"
"errors"
"fmt"
"github.com/bwmarrin/discordgo"
@ -132,6 +133,11 @@ func CreateChannelWithRetry(c *gin.Context, guildID, channelName string, channel
common.LogWarn(c, "Create channel timed out, retrying...")
}
}
// tg发送通知
if telegram.NotifyTelegramBotToken != "" && telegram.TgBot != nil {
go func() {
CreateChannelRiskChan <- "stop"
}()
}
return "", errors.New("failed to create channel after 3 attempts, please reset BOT_TOKEN")
}

View File

@ -5,12 +5,14 @@ import (
"context"
"coze-discord-proxy/common"
"coze-discord-proxy/model"
"coze-discord-proxy/telegram"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"github.com/bwmarrin/discordgo"
"github.com/gin-gonic/gin"
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
"github.com/h2non/filetype"
"golang.org/x/net/proxy"
"log"
@ -38,7 +40,8 @@ var UserAgent = os.Getenv("USER_AGENT")
var UserAuthorization = os.Getenv("USER_AUTHORIZATION")
var UserAuthorizations = strings.Split(UserAuthorization, ",")
//var UserId = os.Getenv("USER_ID")
var NoAvailableUserAuthChan = make(chan string)
var CreateChannelRiskChan = make(chan string)
var BotConfigList []model.BotConfig
@ -87,9 +90,15 @@ func StartBot(ctx context.Context, token string) {
go loadUserAuthTask()
if CozeBotStayActiveEnable == "1" || CozeBotStayActiveEnable == "" {
// 开启coze保活任务
go stayActiveMessageTask()
}
if telegram.NotifyTelegramBotToken != "" && telegram.TgBot != nil {
// 开启tgbot消息推送任务
go telegramNotifyMsgTask()
}
go func() {
<-ctx.Done()
if err := Session.Close(); err != nil {
@ -103,6 +112,38 @@ func StartBot(ctx context.Context, token string) {
<-sc
}
func telegramNotifyMsgTask() {
for NoAvailableUserAuthChan != nil || CreateChannelRiskChan != nil {
select {
case msg, ok := <-NoAvailableUserAuthChan:
if ok && msg == "stop" {
tgMsgConfig := tgbotapi.NewMessage(telegram.NotifyTelegramUserIdInt64, fmt.Sprintf("⚠【CDP-服务通知】\n服务已无可用USER_AUTHORIZATION,请及时更换!"))
err := telegram.SendMessage(&tgMsgConfig)
if err != nil {
common.LogWarn(nil, fmt.Sprintf("Telegram 推送消息异常 error:%s", err.Error()))
} else {
NoAvailableUserAuthChan = nil // 停止监听ch1
}
} else if !ok {
NoAvailableUserAuthChan = nil // 如果ch1已关闭停止监听
}
case msg, ok := <-CreateChannelRiskChan:
if ok && msg == "stop" {
tgMsgConfig := tgbotapi.NewMessage(telegram.NotifyTelegramUserIdInt64, fmt.Sprintf("⚠【CDP-服务通知】\n服务BOT_TOKEN关联的BOT已被风控,请及时ResetToken并更换!"))
err := telegram.SendMessage(&tgMsgConfig)
if err != nil {
common.LogWarn(nil, fmt.Sprintf("Telegram 推送消息异常 error:%s", err.Error()))
} else {
CreateChannelRiskChan = nil
}
} else if !ok {
CreateChannelRiskChan = nil
}
}
}
}
func loadUserAuthTask() {
for {
source := rand.NewSource(time.Now().UnixNano())
@ -156,11 +197,28 @@ func checkEnvVariable() {
}
}
if ChannelAutoDelTime != "" {
_, _err := strconv.Atoi(ChannelAutoDelTime)
if _err != nil {
_, err := strconv.Atoi(ChannelAutoDelTime)
if err != nil {
common.FatalLog("环境变量 CHANNEL_AUTO_DEL_TIME 设置有误")
}
}
if telegram.NotifyTelegramBotToken != "" {
err := telegram.InitTelegramBot()
if err != nil {
common.FatalLog(fmt.Sprintf("环境变量 NotifyTelegramBotToken 设置有误 error:%s", err.Error()))
}
if telegram.NotifyTelegramUserId == "" {
common.FatalLog("环境变量 NOTIFY_TELEGRAM_USER_ID 未设置")
} else {
telegram.NotifyTelegramUserIdInt64, err = strconv.ParseInt(telegram.NotifyTelegramUserId, 10, 64)
if err != nil {
common.FatalLog(fmt.Sprintf("环境变量 NOTIFY_TELEGRAM_USER_ID 设置有误 error:%s", err.Error()))
}
}
}
common.SysLog("Environment variable check passed.")
}
@ -388,6 +446,14 @@ func SendMessage(c *gin.Context, channelID, cozeBotId, message string) (*discord
if len(UserAuthorizations) == 0 {
//SetChannelDeleteTimer(channelID, 5*time.Second)
common.LogError(c.Request.Context(), fmt.Sprintf("无可用的 user_auth"))
// tg发送通知
if telegram.NotifyTelegramBotToken != "" && telegram.TgBot != nil {
go func() {
NoAvailableUserAuthChan <- "stop"
}()
}
return nil, "", fmt.Errorf("no_available_user_auth")
}

1
go.mod
View File

@ -10,6 +10,7 @@ require (
github.com/gin-contrib/cors v1.5.0
github.com/gin-gonic/gin v1.9.1
github.com/go-playground/validator/v10 v10.17.0
github.com/go-telegram-bot-api/telegram-bot-api/v5 v5.5.1
github.com/google/uuid v1.3.0
github.com/h2non/filetype v1.1.3
github.com/json-iterator/go v1.1.12

2
go.sum
View File

@ -43,6 +43,8 @@ github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJn
github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=
github.com/go-playground/validator/v10 v10.17.0 h1:SmVVlfAOtlZncTxRuinDPomC2DkXJ4E5T9gDA0AIH74=
github.com/go-playground/validator/v10 v10.17.0/go.mod h1:9iXMNT7sEkjXb0I+enO7QXmzG6QCsPWY4zveKFVRSyU=
github.com/go-telegram-bot-api/telegram-bot-api/v5 v5.5.1 h1:wG8n/XJQ07TmjbITcGiUaOtXxdrINDz1b0J1w0SzqDc=
github.com/go-telegram-bot-api/telegram-bot-api/v5 v5.5.1/go.mod h1:A2S0CWkNylc2phvKXWBBdD3K0iGnDBGbzRpISP2zBl8=
github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU=
github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I=
github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk=

31
telegram/bot.go Normal file
View File

@ -0,0 +1,31 @@
package telegram
import (
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
"os"
)
var NotifyTelegramBotToken = os.Getenv("NOTIFY_TELEGRAM_BOT_TOKEN")
var NotifyTelegramUserId = os.Getenv("NOTIFY_TELEGRAM_USER_ID")
var NotifyTelegramUserIdInt64 int64
var TgBot *tgbotapi.BotAPI
func InitTelegramBot() (err error) {
TgBot, err = tgbotapi.NewBotAPI(NotifyTelegramBotToken)
if err != nil {
return err
}
TgBot.Debug = false
return nil
}
func SendMessage(chattable tgbotapi.Chattable) (err error) {
_, err = TgBot.Send(chattable)
if err != nil {
return err
}
return nil
}