diff --git a/.vscode/launch.json b/.vscode/launch.json new file mode 100644 index 0000000..f9f74e3 --- /dev/null +++ b/.vscode/launch.json @@ -0,0 +1,18 @@ +{ + // 使用 IntelliSense 了解相关属性。 + // 悬停以查看现有属性的描述。 + // 欲了解更多信息,请访问: https://go.microsoft.com/fwlink/?linkid=830387 + "version": "0.2.0", + "configurations": [ + { + "name": "Launch Package", + "type": "go", + "request": "launch", + "mode": "debug", + "program": "${workspaceRoot}", + "cwd": "${workspaceRoot}", + "env": {}, + "args": [] + } + ] +} \ No newline at end of file diff --git a/bootstrap/telegram.go b/bootstrap/telegram.go index f59d50d..6c12cd8 100644 --- a/bootstrap/telegram.go +++ b/bootstrap/telegram.go @@ -2,13 +2,14 @@ package bootstrap import ( "fmt" + "strings" + "time" + tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5" log "github.com/sirupsen/logrus" "github.com/wechatgpt/wechatbot/config" "github.com/wechatgpt/wechatbot/handler/telegram" "github.com/wechatgpt/wechatbot/utils" - "strings" - "time" ) func StartTelegramBot() { @@ -17,6 +18,7 @@ func StartTelegramBot() { log.Info("未找到tg token,不启动tg tot") return } + bot, err := tgbotapi.NewBotAPI(*telegramKey) if err != nil { log.Error("tg bot 启动失败:", err.Error()) @@ -37,6 +39,7 @@ func StartTelegramBot() { if update.Message == nil { continue } + text := update.Message.Text chatID := update.Message.Chat.ID chatUserName := update.Message.Chat.UserName @@ -68,26 +71,32 @@ func StartTelegramBot() { if len(key) == 0 { continue } + splitItems := strings.Split(content, key) if len(splitItems) < 2 { continue } + requestText := strings.TrimSpace(splitItems[1]) log.Println("问题:", requestText) reply = telegram.Handle(requestText) } else { reply = telegram.Handle(text) } + if reply == nil { continue } + msg := tgbotapi.NewMessage(chatID, *reply) send, err := bot.Send(msg) if err != nil { log.Errorf("发送消息出错:%s", err.Error()) continue } + fmt.Println(send.Text) } + select {} } diff --git a/bootstrap/wechat.go b/bootstrap/wechat.go index 037d277..1c995cf 100644 --- a/bootstrap/wechat.go +++ b/bootstrap/wechat.go @@ -1,10 +1,11 @@ package bootstrap import ( + "os" + "github.com/eatmoreapple/openwechat" log "github.com/sirupsen/logrus" "github.com/wechatgpt/wechatbot/handler/wechat" - "os" ) func StartWebChat() { @@ -19,6 +20,7 @@ func StartWebChat() { if err != nil { return } + reloadStorage = openwechat.NewJsonFileHotReloadStorage("token.json") err = bot.HotLogin(reloadStorage) if err != nil { @@ -34,14 +36,15 @@ func StartWebChat() { } friends, err := self.Friends() - for i, friend := range friends { log.Println(i, friend) } + groups, err := self.Groups() for i, group := range groups { log.Println(i, group) } + err = bot.Block() if err != nil { log.Fatal(err) diff --git a/config/config.go b/config/config.go index d1c933d..b5292a4 100644 --- a/config/config.go +++ b/config/config.go @@ -31,21 +31,24 @@ func LoadConfig() error { if err := viper.ReadInConfig(); err != nil { return err } + if err := viper.Unmarshal(&config); err != nil { return err } + return nil } func GetWechat() *string { wechat := getEnv("wechat") - if wechat != nil { return wechat } + if config == nil { return nil } + if wechat == nil { wechat = config.ChatGpt.Wechat } @@ -58,9 +61,11 @@ func GetWechatKeyword() *string { if keyword != nil { return keyword } + if config == nil { return nil } + if keyword == nil { keyword = config.ChatGpt.WechatKeyword } @@ -72,9 +77,11 @@ func GetTelegram() *string { if tg != nil { return tg } + if config == nil { return nil } + if tg == nil { tg = config.ChatGpt.Telegram } @@ -87,9 +94,11 @@ func GetTelegramKeyword() *string { if tgKeyword != nil { return tgKeyword } + if config == nil { return nil } + if tgKeyword == nil { tgKeyword = config.ChatGpt.TgKeyword } @@ -102,9 +111,11 @@ func GetTelegramWhitelist() *string { if tgWhitelist != nil { return tgWhitelist } + if config == nil { return nil } + if tgWhitelist == nil { tgWhitelist = config.ChatGpt.TgWhitelist } @@ -113,7 +124,6 @@ func GetTelegramWhitelist() *string { func GetOpenAiApiKey() *string { apiKey := getEnv("api_key") - if apiKey != nil { return apiKey } @@ -121,6 +131,7 @@ func GetOpenAiApiKey() *string { if config == nil { return nil } + if apiKey == nil { apiKey = &config.ChatGpt.Token } @@ -143,7 +154,9 @@ func getEnv(key string) *string { if len(value) > 0 { return &value - } else if config.ChatGpt.WechatKeyword != nil { + } + + if config.ChatGpt.WechatKeyword != nil { value = *config.ChatGpt.WechatKeyword } return nil diff --git a/handler/telegram/telegram.go b/handler/telegram/telegram.go index 3c8776e..881f94d 100644 --- a/handler/telegram/telegram.go +++ b/handler/telegram/telegram.go @@ -1,9 +1,10 @@ package telegram import ( + "strings" + log "github.com/sirupsen/logrus" "github.com/wechatgpt/wechatbot/openai" - "strings" ) func Handle(msg string) *string { diff --git a/handler/wechat/wechat_handler.go b/handler/wechat/wechat_handler.go index b6dc4cc..3e62f6b 100644 --- a/handler/wechat/wechat_handler.go +++ b/handler/wechat/wechat_handler.go @@ -2,12 +2,13 @@ package wechat import ( "fmt" + "strings" + "github.com/eatmoreapple/openwechat" log "github.com/sirupsen/logrus" "github.com/wechatgpt/wechatbot/config" "github.com/wechatgpt/wechatbot/openai" "github.com/wechatgpt/wechatbot/utils" - "strings" ) var _ MessageHandlerInterface = (*GroupMessageHandler)(nil) @@ -19,6 +20,7 @@ func (gmh *GroupMessageHandler) handle(msg *openwechat.Message) error { if !msg.IsText() { return nil } + return gmh.ReplyText(msg) } @@ -27,7 +29,6 @@ func NewGroupMessageHandler() MessageHandlerInterface { } func (gmh *GroupMessageHandler) ReplyText(msg *openwechat.Message) error { - sender, err := msg.Sender() group := openwechat.Group{User: sender} log.Printf("Received Group %v Text Msg : %v", group.NickName, msg.Content) @@ -39,10 +40,12 @@ func (gmh *GroupMessageHandler) ReplyText(msg *openwechat.Message) error { if len(key) == 0 { return nil } + splitItems := strings.Split(content, key) if len(splitItems) < 2 { return nil } + requestText = strings.TrimSpace(splitItems[1]) } @@ -61,18 +64,22 @@ func (gmh *GroupMessageHandler) ReplyText(msg *openwechat.Message) error { } } } + text, err := msg.ReplyText(fmt.Sprintf("bot error: %s", err.Error())) log.Println(text) return err } + // 如果在提问的时候没有包含?,AI会自动在开头补充个?看起来很奇怪 result := *reply if strings.HasPrefix(result, "?") { result = strings.Replace(result, "?", "", -1) } + if strings.HasPrefix(result, "?") { result = strings.Replace(result, "?", "", -1) } + // 微信不支持markdown格式,所以把反引号直接去掉 if strings.Contains(result, "`") { result = strings.Replace(result, "`", "", -1) diff --git a/main.go b/main.go index ee1fbf5..c1de36c 100644 --- a/main.go +++ b/main.go @@ -11,6 +11,7 @@ func main() { if err != nil { log.Warn("没有找到配置文件,尝试读取环境变量") } + wechatEnv := config.GetWechat() telegramEnv := config.GetTelegram() if wechatEnv != nil && *wechatEnv == "true" { diff --git a/openai/chatgpt.go b/openai/chatgpt.go index 46141bb..ee43c35 100644 --- a/openai/chatgpt.go +++ b/openai/chatgpt.go @@ -5,12 +5,13 @@ import ( "encoding/json" "errors" "fmt" - log "github.com/sirupsen/logrus" - "github.com/wechatgpt/wechatbot/config" "io" "io/ioutil" "net/http" "strings" + + log "github.com/sirupsen/logrus" + "github.com/wechatgpt/wechatbot/config" ) // ChatGPTResponseBody 请求体 @@ -24,7 +25,7 @@ type ChatGPTResponseBody struct { } type ChatGPTErrorBody struct { - Error map[string]interface{} `json:"error"` + Error map[string]interface{} `json:"error"` } // ChatGPTRequestBody 响应体 @@ -80,6 +81,7 @@ func Completions(msg string) (*string, error) { log.Println(err) return nil, err } + log.Printf("request openai json string : %v", string(requestData)) req, err := http.NewRequest("POST", "https://api.openai.com/v1/completions", bytes.NewBuffer(requestData)) if err != nil { @@ -94,6 +96,7 @@ func Completions(msg string) (*string, error) { if err != nil { return nil, err } + defer func(Body io.ReadCloser) { err := Body.Close() if err != nil { @@ -113,14 +116,15 @@ func Completions(msg string) (*string, error) { log.Println(err) return nil, err } + var reply string if len(gptResponseBody.Choices) > 0 { for _, v := range gptResponseBody.Choices { reply = v["text"].(string) break } - } - + } + gptErrorBody := &ChatGPTErrorBody{} err = json.Unmarshal(body, gptErrorBody) if err != nil { @@ -128,7 +132,7 @@ func Completions(msg string) (*string, error) { return nil, err } - if (len(reply) == 0) { + if len(reply) == 0 { reply = gptErrorBody.Error["message"].(string) } diff --git a/utils/string.go b/utils/string.go index 91c0501..326748b 100644 --- a/utils/string.go +++ b/utils/string.go @@ -7,6 +7,7 @@ func ContainsI(a string, b string) (string, string) { strings.ToLower(a), strings.ToLower(b), ) + if contain { return strings.ToLower(a), strings.ToLower(b) }