Skip to content

Commit

Permalink
feat: env support
Browse files Browse the repository at this point in the history
  • Loading branch information
trevorwang committed Mar 5, 2023
1 parent e9639d7 commit 1511108
Show file tree
Hide file tree
Showing 10 changed files with 79 additions and 39 deletions.
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -30,3 +30,5 @@ config.yaml


/code/target/
start-feishubot
.env
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

0 comments on commit 1511108

Please sign in to comment.