Skip to content

Commit

Permalink
Merge branch 'master' of github.com:toeasy/Feishu-OpenAI into toeasy-…
Browse files Browse the repository at this point in the history
…master
  • Loading branch information
Leizhenpeng committed Jun 28, 2023
2 parents d736dd1 + 73d849f commit 7ff4856
Show file tree
Hide file tree
Showing 16 changed files with 170 additions and 21 deletions.
1 change: 1 addition & 0 deletions code/go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ require (
github.com/pandodao/tokenizer-go v0.2.0
github.com/patrickmn/go-cache v2.1.0+incompatible
github.com/pion/opus v0.0.0-20230123082803-1052c3e89e58
github.com/sirupsen/logrus v1.9.0
github.com/spf13/pflag v1.0.5
github.com/spf13/viper v1.14.0
gopkg.in/yaml.v2 v2.4.0
Expand Down
3 changes: 3 additions & 0 deletions code/go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -217,6 +217,8 @@ github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFR
github.com/rogpeppe/go-internal v1.6.1/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTEfhy4qGm1nDQc=
github.com/rogpeppe/go-internal v1.8.0 h1:FCbCCtXNOY3UtUuHUYaghJg4y7Fd14rXifAYUAtL9R8=
github.com/rogpeppe/go-internal v1.8.0/go.mod h1:WmiCO8CzOY8rg0OYDC4/i/2WRWAB6poM+XZ2dLUbcbE=
github.com/sirupsen/logrus v1.9.0 h1:trlNQbNUG3OdDrDil03MCb1H2o9nJ1x4/5LYw7byDE0=
github.com/sirupsen/logrus v1.9.0/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ=
github.com/spf13/afero v1.9.3 h1:41FoI0fD7OR7mGcKE/aOiLkGreyf8ifIOQmJANWogMk=
github.com/spf13/afero v1.9.3/go.mod h1:iUV7ddyEEZPO5gA3zD4fJt6iStLlL+Lg4m2cihcDf8Y=
github.com/spf13/cast v1.5.0 h1:rj3WzYc11XZaIZMPKmwP96zkFEnnAmV8s6XbB2aY32w=
Expand Down Expand Up @@ -396,6 +398,7 @@ golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBc
golang.org/x/sys v0.0.0-20210806184541-e5e7981a1069/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220310020820-b874c991c1a5/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220908164124-27713097b956/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
Expand Down
8 changes: 4 additions & 4 deletions code/handlers/card_clear_action.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,9 @@ package handlers

import (
"context"

"start-feishubot/services"

larkcard "github.com/larksuite/oapi-sdk-go/v3/card"
"start-feishubot/logger"
"start-feishubot/services"
)

func NewClearCardHandler(cardMsg CardMsg, m MessageHandler) CardHandlerFunc {
Expand All @@ -23,14 +22,15 @@ func NewClearCardHandler(cardMsg CardMsg, m MessageHandler) CardHandlerFunc {

func CommonProcessClearCache(cardMsg CardMsg, session services.SessionServiceCacheInterface) (
interface{}, error, bool) {
logger.Debugf("card msg value %v", cardMsg.Value)
if cardMsg.Value == "1" {
session.Clear(cardMsg.SessionId)
newCard, _ := newSendCard(
withHeader("️🆑 机器人提醒", larkcard.TemplateGrey),
withMainMd("已删除此话题的上下文信息"),
withNote("我们可以开始一个全新的话题,继续找我聊天吧"),
)
//fmt.Printf("session: %v", newCard)
logger.Debugf("session %v", newCard)
return newCard, nil, true
}
if cardMsg.Value == "0" {
Expand Down
2 changes: 2 additions & 0 deletions code/handlers/card_common_action.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"context"
"encoding/json"
"fmt"
"start-feishubot/logger"

larkcard "github.com/larksuite/oapi-sdk-go/v3/card"
)
Expand Down Expand Up @@ -34,6 +35,7 @@ func NewCardHandler(m MessageHandler) CardHandlerFunc {
return nil, err
}
//pp.Println(cardMsg)
logger.Debug("cardMsg ", cardMsg)
for _, handler := range handlers {
h := handler(cardMsg, m)
i, err := h(ctx, cardAction)
Expand Down
10 changes: 7 additions & 3 deletions code/handlers/card_pic_action.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@ package handlers

import (
"context"
"fmt"
larkcore "github.com/larksuite/oapi-sdk-go/v3/core"
"start-feishubot/logger"

"start-feishubot/services"

Expand Down Expand Up @@ -47,7 +50,7 @@ func CommonProcessPicResolution(msg CardMsg,
cardAction *larkcard.CardAction,
cache services.SessionServiceCacheInterface) {
option := cardAction.Action.Option
//fmt.Println(larkcore.Prettify(msg))
fmt.Println(larkcore.Prettify(msg))
cache.SetPicResolution(msg.SessionId, services.Resolution(option))
//send text
replyMsg(context.Background(), "已更新图片分辨率为"+option,
Expand All @@ -56,8 +59,9 @@ func CommonProcessPicResolution(msg CardMsg,

func (m MessageHandler) CommonProcessPicMore(msg CardMsg) {
resolution := m.sessionCache.GetPicResolution(msg.SessionId)
//fmt.Println("resolution: ", resolution)
//fmt.Println("msg: ", msg)

logger.Debugf("resolution: %v", resolution)
logger.Debug("msg: %v", msg)
question := msg.Value.(string)
bs64, _ := m.gpt.GenerateOneImage(question, resolution)
replayImageCardByBase64(context.Background(), bs64, &msg.MsgId,
Expand Down
1 change: 1 addition & 0 deletions code/handlers/event_common_action.go
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@ func (*EmptyAction) Execute(a *ActionInfo) bool {
sendMsg(*a.ctx, "🤖️:你想知道什么呢~", a.info.chatId)
fmt.Println("msgId", *a.info.msgId,
"message.text is empty")

return false
}
return true
Expand Down
3 changes: 2 additions & 1 deletion code/handlers/event_pic_action.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"context"
"fmt"
"os"
"start-feishubot/logger"

"start-feishubot/initialization"
"start-feishubot/services"
Expand Down Expand Up @@ -36,7 +37,7 @@ func (*PicAction) Execute(a *ActionInfo) bool {

mode := a.handler.sessionCache.GetMode(*a.info.sessionId)
//fmt.Println("mode: ", mode)

logger.Debug("MODE:", mode)
// 收到一张图片,且不在图片创作模式下, 提醒是否切换到图片创作模式
if a.info.msgType == "image" && mode != services.ModePicCreate {
sendPicModeCheckCard(*a.ctx, a.info.sessionId, a.info.msgId)
Expand Down
5 changes: 4 additions & 1 deletion code/handlers/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ package handlers
import (
"context"
"fmt"
larkcore "github.com/larksuite/oapi-sdk-go/v3/core"
"start-feishubot/logger"
"strings"

"start-feishubot/initialization"
Expand Down Expand Up @@ -49,11 +51,12 @@ func judgeMsgType(event *larkim.P2MessageReceiveV1) (string, error) {

func (m MessageHandler) msgReceivedHandler(ctx context.Context, event *larkim.P2MessageReceiveV1) error {
handlerType := judgeChatType(event)
logger.Debug("handlerType", handlerType)
if handlerType == "otherChat" {
fmt.Println("unknown chat type")
return nil
}
//fmt.Println(larkcore.Prettify(event.Event.Message))
logger.Debug("收到消息:", larkcore.Prettify(event.Event.Message))

msgType, err := judgeMsgType(event)
if err != nil {
Expand Down
5 changes: 4 additions & 1 deletion code/handlers/init.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package handlers

import (
"context"
"start-feishubot/logger"

"start-feishubot/initialization"
"start-feishubot/services/openai"
Expand Down Expand Up @@ -34,8 +35,10 @@ func Handler(ctx context.Context, event *larkim.P2MessageReceiveV1) error {
}

func ReadHandler(ctx context.Context, event *larkim.P2MessageReadV1) error {
_ = event.Event.Reader.ReaderId.OpenId
readerId := event.Event.Reader.ReaderId.OpenId
//fmt.Printf("msg is read by : %v \n", *readerId)
logger.Debugf("msg is read by : %v \n", *readerId)

return nil
}

Expand Down
8 changes: 6 additions & 2 deletions code/handlers/msg.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"encoding/base64"
"errors"
"fmt"
"start-feishubot/logger"

"start-feishubot/initialization"
"start-feishubot/services"
Expand Down Expand Up @@ -70,7 +71,7 @@ func replyCard(ctx context.Context,

// 服务端错误处理
if !resp.Success() {
fmt.Println(resp.Code, resp.Msg, resp.RequestId())
logger.Errorf("服务端错误 resp code[%v], msg [%v] requestId [%v] ", resp.Code, resp.Msg, resp.RequestId())
return errors.New(resp.Msg)
}
return nil
Expand Down Expand Up @@ -758,7 +759,10 @@ func SendRoleTagsCard(ctx context.Context,
withHeader("🛖 请选择角色类别", larkcard.TemplateIndigo),
withRoleTagsBtn(sessionId, roleTags...),
withNote("提醒:选择角色所属分类,以便我们为您推荐更多相关角色。"))
replyCard(ctx, msgId, newCard)
err := replyCard(ctx, msgId, newCard)
if err != nil {
logger.Errorf("选择角色出错 %v", err)
}
}

func SendRoleListCard(ctx context.Context,
Expand Down
3 changes: 2 additions & 1 deletion code/initialization/gin.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"fmt"
"log"
"net/http"
//"start-feishubot/logger"
"time"

"github.com/gin-gonic/gin"
Expand Down Expand Up @@ -35,7 +36,7 @@ func loadCertificate(config Config) (cert tls.Certificate, err error) {
}

func startHTTPServer(config Config, r *gin.Engine) (err error) {
log.Printf("http server started: http://localhost:%d/webhook/event\n", config.HttpPort)
log.Printf("http server started: http://localhost:%d/webhook/event\n\n", config.HttpPort)
err = r.Run(fmt.Sprintf(":%d", config.HttpPort))
if err != nil {
return fmt.Errorf("failed to start http server: %v", err)
Expand Down
6 changes: 5 additions & 1 deletion code/initialization/lark_client.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,16 @@ package initialization

import (
lark "github.com/larksuite/oapi-sdk-go/v3"
larkcore "github.com/larksuite/oapi-sdk-go/v3/core"
)

var larkClient *lark.Client

func LoadLarkClient(config Config) {
larkClient = lark.NewClient(config.FeishuAppId, config.FeishuAppSecret)

option := lark.WithLogLevel(larkcore.LogLevelDebug)
larkClient = lark.NewClient(config.FeishuAppId, config.FeishuAppSecret, option)

}

func GetLarkClient() *lark.Client {
Expand Down
115 changes: 115 additions & 0 deletions code/logger/logger.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
package logger

import (
"bytes"
"github.com/gin-gonic/gin"
"github.com/sirupsen/logrus"
"strings"
)

var logger = logrus.New()

func init() {

logger.SetFormatter(&formatter{})

logger.SetReportCaller(true)

gin.DefaultWriter = logger.Out

logger.Level = logrus.DebugLevel

}

type Fields logrus.Fields

// Debugf logs a message at level Debug on the standard logger.
func Debugf(format string, args ...interface{}) {
if logger.Level >= logrus.DebugLevel {
entry := logger.WithFields(logrus.Fields{})
entry.Debugf(format, args...)
}
}

// Warnf logs a message at level Warn on the standard logger.
func Warnf(format string, args ...interface{}) {
if logger.Level >= logrus.WarnLevel {
entry := logger.WithFields(logrus.Fields{})
entry.Warnf(format, args...)
}
}

// Errorf logs a message at level Error on the standard logger.
func Errorf(format string, args ...interface{}) {
if logger.Level >= logrus.ErrorLevel {
entry := logger.WithFields(logrus.Fields{})
entry.Errorf(format, args...)
}
}

// Fatalf logs a message at level Fatal on the standard logger.
func Fatalf(format string, args ...interface{}) {
if logger.Level >= logrus.FatalLevel {
entry := logger.WithFields(logrus.Fields{})
entry.Fatalf(format, args...)
}
}

func Debug(format string, args ...interface{}) {
if logger.Level >= logrus.DebugLevel {
entry := logger.WithFields(logrus.Fields{})
entry.Debug(format, args)
}
}

// Info logs a message at level Info on the standard logger.
func Info(format string, args ...interface{}) {
if logger.Level >= logrus.InfoLevel {
entry := logger.WithFields(logrus.Fields{})
entry.Info(format, args)
}
}

// Warn logs a message at level Warn on the standard logger.
func Warn(format string, args ...interface{}) {
if logger.Level >= logrus.WarnLevel {
entry := logger.WithFields(logrus.Fields{})
entry.Warn(format, args)
}
}

// Error logs a message at level Error on the standard logger.
func Error(format string, args ...interface{}) {
if logger.Level >= logrus.ErrorLevel {
entry := logger.WithFields(logrus.Fields{})
entry.Error(format, args)
}
}

// Fatal logs a message at level Fatal on the standard logger.
func Fatal(format string, args ...interface{}) {
if logger.Level >= logrus.FatalLevel {
entry := logger.WithFields(logrus.Fields{})
entry.Fatal(format, args)
}
}

// Formatter implements logrus.Formatter interface.
type formatter struct {
prefix string
}

// Format building log message.
func (f *formatter) Format(entry *logrus.Entry) ([]byte, error) {
var sb bytes.Buffer

sb.WriteString("[" + strings.ToUpper(entry.Level.String()) + "]")
sb.WriteString(entry.Time.Format("2006-01-02 15:04:05"))
sb.WriteString(" ")
//sb.WriteString(" ")
//sb.WriteString(f.prefix)
sb.WriteString(entry.Message)
sb.WriteString("\n")

return sb.Bytes(), nil
}
8 changes: 4 additions & 4 deletions code/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,17 @@ package main

import (
"context"
"log"

"start-feishubot/handlers"
"start-feishubot/initialization"
"start-feishubot/services/openai"
"start-feishubot/logger"

"github.com/gin-gonic/gin"
sdkginext "github.com/larksuite/oapi-sdk-gin"
larkcard "github.com/larksuite/oapi-sdk-go/v3/card"
"github.com/larksuite/oapi-sdk-go/v3/event/dispatcher"
larkim "github.com/larksuite/oapi-sdk-go/v3/service/im/v1"
"github.com/spf13/pflag"
"start-feishubot/services/openai"
)

var (
Expand All @@ -32,6 +31,7 @@ func main() {
config.FeishuAppVerificationToken, config.FeishuAppEncryptKey).
OnP2MessageReceiveV1(handlers.Handler).
OnP2MessageReadV1(func(ctx context.Context, event *larkim.P2MessageReadV1) error {
logger.Debugf("收到请求 %v", event.RequestURI)
return handlers.ReadHandler(ctx, event)
})

Expand All @@ -52,6 +52,6 @@ func main() {
cardHandler))

if err := initialization.StartServer(*config, r); err != nil {
log.Fatalf("failed to start server: %v", err)
logger.Fatalf("failed to start server: %v", err)
}
}
Loading

0 comments on commit 7ff4856

Please sign in to comment.