Skip to content

Commit

Permalink
feat: add gpt support by third package
Browse files Browse the repository at this point in the history
  • Loading branch information
Leizhenpeng committed Feb 7, 2023
0 parents commit f4a0bc3
Show file tree
Hide file tree
Showing 17 changed files with 1,110 additions and 0 deletions.
30 changes: 30 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
### Go template
# If you prefer the allow list template instead of the deny list, see community template:
# https://github.com/github/gitignore/blob/main/community/Golang/Go.AllowList.gitignore
#
# Binaries for programs and plugins
*.exe
*.exe~
*.dll
*.so
*.dylib

# Test binary, built with `go test -c`
*.test

# Output of the go coverage tool, specifically when used with LiteIDE
*.out

# Dependency directories (remove the comment below to include it)
# vendor/

# Go workspace file
go.work

.idea
.vscode
.s

./code/feishu_config.yaml


24 changes: 24 additions & 0 deletions code/calc/calc.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package calc

import (
"fmt"

"gopkg.in/Knetic/govaluate.v2"
)

func CalcStr(str string) (float64, error) {
fmt.Println(str)

expression, _ := govaluate.NewEvaluableExpression(str)
out, _ := expression.Evaluate(nil)
fmt.Println(out)
return out.(float64), nil
}

func FormatMathOut(out float64) string {
//if is int
if out == float64(int(out)) {
return fmt.Sprintf("%d", int(out))
}
return fmt.Sprintf("%f", out)
}
41 changes: 41 additions & 0 deletions code/calc/calc_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
package calc

import (
"testing"
)

func TestCalc(t *testing.T) {

out, err := CalcStr("1+1")
if err != nil {
t.Error(err)
}

if out != 2 {
t.Error("1+1 should be 2")
}
}

func TestCalc2(t *testing.T) {

out, err := CalcStr("1+2")
if err != nil {
t.Error(err)
}

if out != 3 {
t.Error("1+2 should be 3")
}
}

func TestCalc3(t *testing.T) {
//22*32
out, err := CalcStr("22*32")
if err != nil {
t.Error(err)
}

if out != 704 {
t.Error("22*32 should be 704")
}
}
47 changes: 47 additions & 0 deletions code/go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
module start-feishubot

go 1.18

require github.com/larksuite/oapi-sdk-go/v3 v3.0.14

require (
github.com/gin-gonic/gin v1.8.2
github.com/larksuite/oapi-sdk-gin v1.0.0
github.com/spf13/viper v1.14.0
gopkg.in/Knetic/govaluate.v2 v2.3.0
)

require (
github.com/PullRequestInc/go-gpt3 v1.1.11 // indirect
github.com/fsnotify/fsnotify v1.6.0 // indirect
github.com/gin-contrib/sse v0.1.0 // indirect
github.com/go-playground/locales v0.14.1 // indirect
github.com/go-playground/universal-translator v0.18.0 // indirect
github.com/go-playground/validator/v10 v10.11.1 // indirect
github.com/goccy/go-json v0.10.0 // indirect
github.com/hashicorp/hcl v1.0.0 // indirect
github.com/json-iterator/go v1.1.12 // indirect
github.com/leodido/go-urn v1.2.1 // indirect
github.com/magiconair/properties v1.8.7 // indirect
github.com/mattn/go-isatty v0.0.17 // indirect
github.com/mitchellh/mapstructure v1.5.0 // indirect
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/patrickmn/go-cache v2.1.0+incompatible // indirect
github.com/pelletier/go-toml v1.9.5 // indirect
github.com/pelletier/go-toml/v2 v2.0.6 // indirect
github.com/spf13/afero v1.9.3 // indirect
github.com/spf13/cast v1.5.0 // indirect
github.com/spf13/jwalterweatherman v1.1.0 // indirect
github.com/spf13/pflag v1.0.5 // indirect
github.com/subosito/gotenv v1.4.1 // indirect
github.com/ugorji/go/codec v1.2.8 // indirect
golang.org/x/crypto v0.5.0 // indirect
golang.org/x/net v0.5.0 // indirect
golang.org/x/sys v0.4.0 // indirect
golang.org/x/text v0.6.0 // indirect
google.golang.org/protobuf v1.28.1 // indirect
gopkg.in/ini.v1 v1.67.0 // indirect
gopkg.in/yaml.v2 v2.4.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)
564 changes: 564 additions & 0 deletions code/go.sum

Large diffs are not rendered by default.

63 changes: 63 additions & 0 deletions code/handlers/common.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
package handlers

import (
"context"
"encoding/json"
"fmt"
larkim "github.com/larksuite/oapi-sdk-go/v3/service/im/v1"
"regexp"
"start-feishubot/initialization"
"strings"
)

func sendMsg(ctx context.Context, msg string, chatId *string) {
msg = strings.Trim(msg, " ")
msg = strings.Trim(msg, "\n")
msg = strings.Trim(msg, "\r")
msg = strings.Trim(msg, "\t")
//只保留中文和英文
regex := regexp.MustCompile("i[^a-zA-Z0-9\u4e00-\u9fa5]")
msg = regex.ReplaceAllString(msg, "")
fmt.Println("sendMsg", msg, chatId)
client := initialization.GetLarkClient()
content := larkim.NewTextMsgBuilder().
Text(msg).
Build()
fmt.Println("content", content)

resp, err := client.Im.Message.Create(ctx, larkim.NewCreateMessageReqBuilder().
ReceiveIdType(larkim.ReceiveIdTypeChatId).
Body(larkim.NewCreateMessageReqBodyBuilder().
MsgType(larkim.MsgTypeText).
ReceiveId(*chatId).
Content(content).
Build()).
Build())

// 处理错误
if err != nil {
fmt.Println(err)
}

// 服务端错误处理
if !resp.Success() {
fmt.Println(resp.Code, resp.Msg, resp.RequestId())
}
}
func msgFilter(msg string) string {
//replace @到下一个非空的字段 为 ''
regex := regexp.MustCompile(`@[^ ]*`)
return regex.ReplaceAllString(msg, "")

}
func parseContent(content string) string {
//"{\"text\":\"@_user_1 hahaha\"}",
//only get text content hahaha
var contentMap map[string]interface{}
err := json.Unmarshal([]byte(content), &contentMap)
if err != nil {
fmt.Println(err)
}
text := contentMap["text"].(string)
return msgFilter(text)
}
30 changes: 30 additions & 0 deletions code/handlers/init.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package handlers

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

type MessageHandlerInterface interface {
handle(ctx context.Context, event *larkim.P2MessageReceiveV1) error
}

type HandlerType string

const (
GroupHandler = "group"
UserHandler = "personal"
)

// handlers 所有消息类型类型的处理器
var handlers map[HandlerType]MessageHandlerInterface

func init() {
handlers = make(map[HandlerType]MessageHandlerInterface)
//handlers[GroupHandler] = NewGroupMessageHandler()
handlers[UserHandler] = NewPersonalMessageHandler()
}

func Handler(ctx context.Context, event *larkim.P2MessageReceiveV1) error {
return handlers[UserHandler].handle(ctx, event)
}
47 changes: 47 additions & 0 deletions code/handlers/personal.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
package handlers

import (
"context"
"fmt"
larkcore "github.com/larksuite/oapi-sdk-go/v3/core"
larkim "github.com/larksuite/oapi-sdk-go/v3/service/im/v1"
"start-feishubot/services"
)

type PersonalMessageHandler struct {
cache services.UserCacheInterface
}

func (p PersonalMessageHandler) handle(ctx context.Context, event *larkim.P2MessageReceiveV1) error {

fmt.Println(larkcore.Prettify(event))
content := event.Event.Message.Content
q := parseContent(*content)
fmt.Println("q", q)
//sender := event.Event.Sender
//openId := sender.SenderId.OpenId
//cacheContent := p.cache.Get(*openId)
qEnd := q
//if cacheContent != "" {
// qEnd = cacheContent + q
//}
fmt.Println("qEnd", qEnd)
ok := true
reply, ok := services.GetAnswer(qEnd)
fmt.Println("reply", reply, ok)
if ok {
sendMsg(ctx, reply, event.Event.Message.ChatId)
//p.cache.Set(*openId, q, "nihao")
return nil
}

return nil
}

var _ MessageHandlerInterface = (*PersonalMessageHandler)(nil)

func NewPersonalMessageHandler() MessageHandlerInterface {
return &PersonalMessageHandler{
cache: services.GetUserCache(),
}
}
14 changes: 14 additions & 0 deletions code/initialization/config.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package initialization

import (
"fmt"
"github.com/spf13/viper"
)

func LoadConfig() {
viper.SetConfigFile("./feishu_config.yaml")
err := viper.ReadInConfig()
if err != nil {
panic(fmt.Errorf("Fatal error config file: %s \n", err))
}
}
17 changes: 17 additions & 0 deletions code/initialization/lark_client.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
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 GetLarkClient() *lark.Client {
return larkClient
}
43 changes: 43 additions & 0 deletions code/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
package main

import (
"fmt"
"start-feishubot/handlers"
"start-feishubot/initialization"

"github.com/spf13/viper"

"github.com/gin-gonic/gin"

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

"github.com/larksuite/oapi-sdk-go/v3/event/dispatcher"
)

func init() {
initialization.LoadConfig()
initialization.LoadLarkClient()
}

func main() {

handler := dispatcher.NewEventDispatcher(viper.GetString(
"APP_VERIFICATION_TOKEN"), viper.GetString("APP_ENCRYPT_KEY")).
OnP2MessageReceiveV1(handlers.Handler)

r := gin.Default()
r.GET("/ping", func(c *gin.Context) {
c.JSON(200, gin.H{
"message": "pong",
})
})

// 在已有 Gin 实例上注册消息处理路由
r.POST("/webhook/event", sdkginext.NewEventHandlerFunc(handler))

fmt.Println("http server started",
"http://localhost:9000/webhook/event")

r.Run(":9000")

}
Loading

0 comments on commit f4a0bc3

Please sign in to comment.