Skip to content

Commit

Permalink
feat: enhances the readability of configuration
Browse files Browse the repository at this point in the history
  • Loading branch information
Leizhenpeng committed Mar 5, 2023
2 parents e07027e + 1511108 commit 56a1725
Show file tree
Hide file tree
Showing 12 changed files with 94 additions and 48 deletions.
4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -30,3 +30,7 @@ config.yaml


/code/target/
start-feishubot
.env

docker.md
19 changes: 12 additions & 7 deletions code/handlers/group.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,18 +4,21 @@ import (
"context"
"encoding/json"
"fmt"
larkcard "github.com/larksuite/oapi-sdk-go/v3/card"
"start-feishubot/initialization"
"start-feishubot/services"
"start-feishubot/utils"
"strings"

larkcard "github.com/larksuite/oapi-sdk-go/v3/card"

larkim "github.com/larksuite/oapi-sdk-go/v3/service/im/v1"
"github.com/spf13/viper"
)

type GroupMessageHandler struct {
sessionCache services.SessionServiceCacheInterface
msgCache services.MsgCacheInterface
gpt services.ChatGPT
config initialization.Config
}

func (p GroupMessageHandler) cardHandler(_ context.Context,
Expand All @@ -34,7 +37,7 @@ func (p GroupMessageHandler) cardHandler(_ context.Context,
}

func (p GroupMessageHandler) handle(ctx context.Context, event *larkim.P2MessageReceiveV1) error {
ifMention := judgeIfMentionMe(event)
ifMention := p.judgeIfMentionMe(event)
if !ifMention {
return nil
}
Expand Down Expand Up @@ -83,7 +86,7 @@ func (p GroupMessageHandler) handle(ctx context.Context, event *larkim.P2Message
msg = append(msg, services.Messages{
Role: "user", Content: qParsed,
})
completions, err := services.Completions(msg)
completions, err := p.gpt.Completions(msg)
if err != nil {
replyMsg(ctx, fmt.Sprintf("🤖️:消息机器人摆烂了,请稍后再试~\n错误信息: %v", err), msgId)
return nil
Expand All @@ -105,17 +108,19 @@ func (p GroupMessageHandler) handle(ctx context.Context, event *larkim.P2Message

var _ MessageHandlerInterface = (*GroupMessageHandler)(nil)

func NewGroupMessageHandler() MessageHandlerInterface {
func NewGroupMessageHandler(gpt services.ChatGPT, config initialization.Config) MessageHandlerInterface {
return &GroupMessageHandler{
sessionCache: services.GetSessionCache(),
msgCache: services.GetMsgCache(),
gpt: gpt,
config: config,
}
}

func judgeIfMentionMe(event *larkim.P2MessageReceiveV1) bool {
func (p GroupMessageHandler) judgeIfMentionMe(event *larkim.P2MessageReceiveV1) bool {
mention := event.Event.Message.Mentions
if len(mention) != 1 {
return false
}
return *mention[0].Name == viper.GetString("BOT_NAME")
return *mention[0].Name == p.config.FeishuBotName
}
9 changes: 6 additions & 3 deletions code/handlers/init.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@ package handlers
import (
"context"
"fmt"
"start-feishubot/initialization"
"start-feishubot/services"

larkcard "github.com/larksuite/oapi-sdk-go/v3/card"
larkim "github.com/larksuite/oapi-sdk-go/v3/service/im/v1"
)
Expand All @@ -22,10 +25,10 @@ const (
// handlers 所有消息类型类型的处理器
var handlers map[HandlerType]MessageHandlerInterface

func init() {
func InitHanders(gpt services.ChatGPT, config initialization.Config) {
handlers = make(map[HandlerType]MessageHandlerInterface)
handlers[GroupHandler] = NewGroupMessageHandler()
handlers[UserHandler] = NewPersonalMessageHandler()
handlers[GroupHandler] = NewGroupMessageHandler(gpt, config)
handlers[UserHandler] = NewPersonalMessageHandler(gpt)

}

Expand Down
7 changes: 4 additions & 3 deletions code/handlers/msg.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,11 @@ package handlers
import (
"context"
"fmt"
"github.com/google/uuid"
"github.com/larksuite/oapi-sdk-go/v3/card"
"github.com/larksuite/oapi-sdk-go/v3/service/im/v1"
"start-feishubot/initialization"

"github.com/google/uuid"
larkcard "github.com/larksuite/oapi-sdk-go/v3/card"
larkim "github.com/larksuite/oapi-sdk-go/v3/service/im/v1"
)

type CardKind string
Expand Down
9 changes: 6 additions & 3 deletions code/handlers/personal.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,19 @@ import (
"context"
"encoding/json"
"fmt"
larkcard "github.com/larksuite/oapi-sdk-go/v3/card"
"start-feishubot/services"
"start-feishubot/utils"
"strings"

larkcard "github.com/larksuite/oapi-sdk-go/v3/card"

larkim "github.com/larksuite/oapi-sdk-go/v3/service/im/v1"
)

type PersonalMessageHandler struct {
sessionCache services.SessionServiceCacheInterface
msgCache services.MsgCacheInterface
gpt services.ChatGPT
}

func (p PersonalMessageHandler) cardHandler(
Expand Down Expand Up @@ -101,7 +103,7 @@ func (p PersonalMessageHandler) handle(ctx context.Context, event *larkim.P2Mess
msg = append(msg, services.Messages{
Role: "user", Content: qParsed,
})
completions, err := services.Completions(msg)
completions, err := p.gpt.Completions(msg)
if err != nil {
replyMsg(ctx, fmt.Sprintf("🤖️:消息机器人摆烂了,请稍后再试~\n错误信息: %v", err), msgId)
return nil
Expand All @@ -125,9 +127,10 @@ func (p PersonalMessageHandler) handle(ctx context.Context, event *larkim.P2Mess

var _ MessageHandlerInterface = (*PersonalMessageHandler)(nil)

func NewPersonalMessageHandler() MessageHandlerInterface {
func NewPersonalMessageHandler(gpt services.ChatGPT) MessageHandlerInterface {
return &PersonalMessageHandler{
sessionCache: services.GetSessionCache(),
msgCache: services.GetMsgCache(),
gpt: gpt,
}
}
33 changes: 29 additions & 4 deletions code/initialization/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,35 @@ import (
"github.com/spf13/viper"
)

func LoadConfig(cfg string) {
type Config struct {
FeishuAppId string
FeishuAppSecret string
FeishuAppEncryptKey string
FeishuAppVerificationToken string
FeishuBotName string
OpenaiApiKey string
}

func LoadConfig(cfg string) *Config {
viper.SetConfigFile(cfg)
err := viper.ReadInConfig()
if err != nil {
panic(fmt.Errorf("Fatal error config file: %s \n", err))
viper.ReadInConfig()
viper.AutomaticEnv()

return &Config{
FeishuAppId: getViperStringValue("APP_ID"),
FeishuAppSecret: getViperStringValue("APP_SECRET"),
FeishuAppEncryptKey: getViperStringValue("APP_ENCRYPT_KEY"),
FeishuAppVerificationToken: getViperStringValue("APP_VERIFICATION_TOKEN"),
FeishuBotName: getViperStringValue("BOT_NAME"),
OpenaiApiKey: getViperStringValue("OPENAI_KEY"),
}

}

func getViperStringValue(key string) string {
value := viper.GetString(key)
if value == "" {
panic(fmt.Errorf("%s MUST be provided in environment or config.yaml file", key))
}
return value
}
6 changes: 2 additions & 4 deletions code/initialization/lark_client.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,12 @@ package initialization

import (
lark "github.com/larksuite/oapi-sdk-go/v3"
"github.com/spf13/viper"
)

var larkClient *lark.Client

func LoadLarkClient() {
larkClient = lark.NewClient(viper.GetString("APP_ID"),
viper.GetString("APP_SECRET"))
func LoadLarkClient(config Config) {
larkClient = lark.NewClient(config.FeishuAppId, config.FeishuAppSecret)
}

func GetLarkClient() *lark.Client {
Expand Down
18 changes: 10 additions & 8 deletions code/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,14 @@ package main

import (
"fmt"
larkcard "github.com/larksuite/oapi-sdk-go/v3/card"
"start-feishubot/handlers"
"start-feishubot/initialization"
"start-feishubot/services"

larkcard "github.com/larksuite/oapi-sdk-go/v3/card"

"github.com/gin-gonic/gin"
"github.com/spf13/pflag"
"github.com/spf13/viper"

sdkginext "github.com/larksuite/oapi-sdk-gin"

Expand All @@ -21,17 +22,18 @@ var (

func main() {
pflag.Parse()
initialization.LoadConfig(*cfg)
initialization.LoadLarkClient()
config := initialization.LoadConfig(*cfg)
initialization.LoadLarkClient(*config)

gpt := &services.ChatGPT{ApiKey: config.OpenaiApiKey}
handlers.InitHanders(*gpt, *config)

eventHandler := dispatcher.NewEventDispatcher(
viper.GetString("APP_VERIFICATION_TOKEN"),
viper.GetString("APP_ENCRYPT_KEY")).
config.FeishuAppVerificationToken, config.FeishuAppEncryptKey).
OnP2MessageReceiveV1(handlers.Handler)

cardHandler := larkcard.NewCardActionHandler(
viper.GetString("APP_VERIFICATION_TOKEN"),
viper.GetString("APP_ENCRYPT_KEY"),
config.FeishuAppVerificationToken, config.FeishuAppEncryptKey,
handlers.CardHandler())

r := gin.Default()
Expand Down
10 changes: 5 additions & 5 deletions code/services/gpt3.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,6 @@ import (
"log"
"net/http"
"time"

"github.com/spf13/viper"
)

const (
Expand Down Expand Up @@ -49,8 +47,11 @@ type ChatGPTRequestBody struct {
FrequencyPenalty int `json:"frequency_penalty"`
PresencePenalty int `json:"presence_penalty"`
}
type ChatGPT struct {
ApiKey string
}

func Completions(msg []Messages) (resp Messages, err error) {
func (gpt ChatGPT) Completions(msg []Messages) (resp Messages, err error) {
requestBody := ChatGPTRequestBody{
Model: engine,
Messages: msg,
Expand All @@ -71,9 +72,8 @@ func Completions(msg []Messages) (resp Messages, err error) {
return resp, err
}

apiKey := viper.GetString("OPENAI_KEY")
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+apiKey)
req.Header.Set("Authorization", "Bearer "+gpt.ApiKey)
client := &http.Client{Timeout: 110 * time.Second}
response, err := client.Do(req)
if err != nil {
Expand Down
5 changes: 3 additions & 2 deletions code/services/gpt3_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,13 @@ import (
)

func TestCompletions(t *testing.T) {
initialization.LoadConfig("../config.yaml")
config := initialization.LoadConfig("../config.yaml")
msg := []Messages{
{Role: "system", Content: "你是一个专业的翻译官,负责中英文翻译。"},
{Role: "user", Content: "翻译这段话: The assistant messages help store prior responses. They can also be written by a developer to help give examples of desired behavior."},
}
resp, err := Completions(msg)
chatGpt := &ChatGPT{ApiKey: config.OpenaiApiKey}
resp, err := chatGpt.Completions(msg)
if err != nil {
t.Error(err)
}
Expand Down
2 changes: 2 additions & 0 deletions entrypoint.sh
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@ fi

if [ "$APP_ENCRYPT_KEY" != "" ] ; then
sed -i "4c APP_ENCRYPT_KEY: $APP_ENCRYPT_KEY" $CONFIG_PATH
else
echo -e "\033[31m[Warning] You need to set APP_ENCRYPT_KEY before running!\033[0m"
fi

if [ "$APP_VERIFICATION_TOKEN" != "" ] ; then
Expand Down
20 changes: 11 additions & 9 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@
## 项目部署


###### 有关飞书具体的配置文件说明**[➡︎ 点击查看](#详细配置步骤)**
###### 有关飞书具的配置文件说明**[➡︎ 点击查看](#详细配置步骤)**


``` bash
Expand Down Expand Up @@ -114,28 +114,30 @@ docker build -t feishu-chatgpt:latest .
docker run -d --name feishu-chatgpt -p 9000:9000 \
--env APP_ID=xxx \
--env APP_SECRET=xxx \
--env APP_ENCRYPT_KEY=xxx \
--env APP_VERIFICATION_TOKEN=xxx \
--env OPENAI_KEY=sk-xxx \
feishu-chatgpt:latest
```
------------
小白简易化docker部署版

``` bash
docker地址:https://hub.docker.com/r/w779945/feishu-chatgpt3.5
docker地址: https://hub.docker.com/r/cfxks1989/feishu-chatgpt
小白简易化docker部署

docker run -d --restart=always --name feishu-chatgpt2 -p 9500:9000 -v /etc/localtime:/etc/localtim:ro \
- docker地址: https://hub.docker.com/r/leizhenpeng/feishu-chatgpt
``` bash
docker run -d --restart=always --name feishu-chatgpt2 -p 9000:9000 -v /etc/localtime:/etc/localtim:ro \
--env APP_ID=xxx \
--env APP_SECRET=xxx \
--env APP_ENCRYPT_KEY=xxx \
--env APP_VERIFICATION_TOKEN=xxx \
--env OPENAI_KEY=sk-xxx \
cfxks1989/feishu-chatgpt:latest
leizhenpeng/feishu-chatgpt:latest

最后回调地址是: http://IP:9500/webhook/event
```
事件回调地址是: http://IP:9000/webhook/event
卡片回调地址是: http://IP:9000/webhook/card

把它填入飞书后台
```
<br>

</details>
Expand Down

0 comments on commit 56a1725

Please sign in to comment.