Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: go包管理改成module方式;配置项增加gpt-model;gpt响应体、请求体更新。 #10

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
FROM golang:1.20.12-alpine AS builder

MAINTAINER hongyun

WORKDIR /work

COPY . /work

ENV GOPROXY=https://goproxy.cn,direct GO111MODULE=on

RUN GOOS=linux GOARCH=amd64 CGO_ENABLED=0 go build main.go

FROM alpine AS runner

WORKDIR /work

COPY --from=builder /work/main .

# 按需添加代理
# ENV http_proxy=http://192.168.0.101:7890 https_proxy=http://192.168.0.101:7890 all_proxy=socks5://192.168.0.101:7890

ENTRYPOINT ["./main"]
17 changes: 17 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,3 +24,20 @@ copy config.dev.json config.json
go run main.go

启动前需替换config中的api_key
````

# docker 部署

> - 注意修改 docker-compose.yml 文件中 config.json 挂载地址
> - 可在 Dockerfile 中增加代理地址,以此来访问 https://api.openai.com

```shell
# 获取项目
git clone https://github.com/869413421/wechatbot.git

# 进入项目目录
cd wechatbot

# docker-compose 启动
docker-compose up -d
```
17 changes: 12 additions & 5 deletions bootstrap/bootstrap.go
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
package bootstrap

import (
"github.com/869413421/wechatbot/handlers"
"github.com/eatmoreapple/openwechat"
"io"
"log"
"wechatbot/handlers"
)



func Run() {
//bot := openwechat.DefaultBot()
bot := openwechat.DefaultBot(openwechat.Desktop) // 桌面模式,上面登录不上的可以尝试切换这种模式
Expand All @@ -18,9 +17,17 @@ func Run() {
bot.UUIDCallback = openwechat.PrintlnQrcodeUrl

// 创建热存储容器对象
reloadStorage := openwechat.NewJsonFileHotReloadStorage("storage.json")
reloadStorage := openwechat.NewFileHotReloadStorage("storage.json")

defer func(reloadStorage io.ReadWriteCloser) {
err := reloadStorage.Close()
if err != nil {
log.Printf("storage.json close error: %v \n", err)
}
}(reloadStorage)

// 执行热登录
err := bot.HotLogin(reloadStorage)
err := bot.HotLogin(reloadStorage, openwechat.NewRetryLoginOption())
if err != nil {
if err = bot.Login(); err != nil {
log.Printf("login error: %v \n", err)
Expand Down
5 changes: 3 additions & 2 deletions config.dev.json
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
{
"api_key": "your api key",
"auto_pass": true
}
"auto_pass": true,
"gpt_model": "gpt-3.5-turbo"
}
6 changes: 6 additions & 0 deletions config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ type Configuration struct {
ApiKey string `json:"api_key"`
// 自动通过好友
AutoPass bool `json:"auto_pass"`
// gpt 版本
GptModel string `json:"gpt_model"`
}

var config *Configuration
Expand All @@ -39,12 +41,16 @@ func LoadConfig() *Configuration {
// 如果环境变量有配置,读取环境变量
ApiKey := os.Getenv("ApiKey")
AutoPass := os.Getenv("AutoPass")
GptModel := os.Getenv("GptModel")
if ApiKey != "" {
config.ApiKey = ApiKey
}
if AutoPass == "true" {
config.AutoPass = true
}
if AutoPass != "" {
config.GptModel = GptModel
}
})
return config
}
10 changes: 10 additions & 0 deletions docker-compose.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
version: '3.7'
services:
wechatbot:
build:
context: "."
container_name: "wechatbot"
network_mode: "bridge"
volumes:
- "/etc/localtime:/etc/localtime"
- "/volume1/docker/container/wechatbot/config.json:/work/config.json" # 按需填写
6 changes: 3 additions & 3 deletions go.mod
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
module github.com/869413421/wechatbot
module wechatbot

go 1.16
go 1.20

require github.com/eatmoreapple/openwechat v1.2.1
require github.com/eatmoreapple/openwechat v1.4.6 // indirect
4 changes: 2 additions & 2 deletions go.sum
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
github.com/eatmoreapple/openwechat v1.2.1 h1:ez4oqF/Y2NSEX/DbPV8lvj7JlfkYqvieeo4awx5lzfU=
github.com/eatmoreapple/openwechat v1.2.1/go.mod h1:61HOzTyvLobGdgWhL68jfGNwTJEv0mhQ1miCXQrvWU8=
github.com/eatmoreapple/openwechat v1.4.6 h1:m/Run2wN9zptKnoS8R3edLNWLlZOOgk13Bq8Y61zSTU=
github.com/eatmoreapple/openwechat v1.4.6/go.mod h1:h4m2N8m0XsUKlm7UR8BUGkV89GNuKHCnlGV3J8n9Mpw=
82 changes: 48 additions & 34 deletions gtp/gtp.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,52 +3,68 @@ package gtp
import (
"bytes"
"encoding/json"
"github.com/869413421/wechatbot/config"
"io/ioutil"
"log"
"net/http"
"wechatbot/config"
)

const BASEURL = "https://api.openai.com/v1/"
type Role int

// ChatGPTResponseBody 请求体
const (
User Role = iota // User = 0
System // System = 1
Assistant // Assistant = 2
)

func (r Role) String() string {
return []string{"user", "system", "assistant"}[r]
}

const BASEURL = "https://api.openai.com/v1/chat/"

// ChatGPTResponseBody 响应体
type ChatGPTResponseBody struct {
ID string `json:"id"`
Object string `json:"object"`
Created int `json:"created"`
Model string `json:"model"`
Choices []map[string]interface{} `json:"choices"`
Usage map[string]interface{} `json:"usage"`
ID string `json:"id"`
Object string `json:"object"`
Created int `json:"created"`
Model string `json:"model"`
Choices []ChoiceItem `json:"choices"`
Usage map[string]interface{} `json:"usage"`
}

type ChoiceItem struct {
Index int `json:"index"`
Message MessageItem `json:"message"`
FinishReason string `json:"finish_reason"`
}

type MessageItem struct {
Role string `json:"role"`
Content string `json:"content"`
}

// ChatGPTRequestBody 响应体
// ChatGPTRequestBody 请求体
type ChatGPTRequestBody struct {
Model string `json:"model"`
Prompt string `json:"prompt"`
MaxTokens int `json:"max_tokens"`
Temperature float32 `json:"temperature"`
TopP int `json:"top_p"`
FrequencyPenalty int `json:"frequency_penalty"`
PresencePenalty int `json:"presence_penalty"`
Model string `json:"model"`
Messages []MessageItem `json:"messages"`
}

// Completions gtp文本模型回复
//curl https://api.openai.com/v1/completions
//-H "Content-Type: application/json"
//-H "Authorization: Bearer your chatGPT key"
//-d '{"model": "text-davinci-003", "prompt": "give me good song", "temperature": 0, "max_tokens": 7}'
// curl https://api.openai.com/v1/chat/completions
// -H "Content-Type: application/json"
// -H "Authorization: Bearer your chatGPT key"
// -d '{"model": "gpt-3.5-turbo", "messages: [{"role": "user", "content": "your problem"}]"}'
func Completions(msg string) (string, error) {
gptModel := config.LoadConfig().GptModel
requestBody := ChatGPTRequestBody{
Model: "text-davinci-003",
Prompt: msg,
MaxTokens: 2048,
Temperature: 0.7,
TopP: 1,
FrequencyPenalty: 0,
PresencePenalty: 0,
Model: gptModel,
Messages: []MessageItem{
{
Role: Role(0).String(),
Content: msg,
},
},
}
requestData, err := json.Marshal(requestBody)

Expand Down Expand Up @@ -82,12 +98,10 @@ func Completions(msg string) (string, error) {
if err != nil {
return "", err
}
var reply string
if len(gptResponseBody.Choices) > 0 {
for _, v := range gptResponseBody.Choices {
reply = v["text"].(string)
break
}
reply := "暂无回复"
choicesLength := len(gptResponseBody.Choices)
if choicesLength > 0 {
reply = gptResponseBody.Choices[choicesLength-1].Message.Content
}
log.Printf("gpt response text: %s \n", reply)
return reply, nil
Expand Down
4 changes: 2 additions & 2 deletions handlers/group_msg_handler.go
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
package handlers

import (
"github.com/869413421/wechatbot/gtp"
"github.com/eatmoreapple/openwechat"
"log"
"strings"
"wechatbot/gtp"
)

var _ MessageHandlerInterface = (*GroupMessageHandler)(nil)
Expand Down Expand Up @@ -39,7 +39,7 @@ func (g *GroupMessageHandler) ReplyText(msg *openwechat.Message) error {
}

// 替换掉@文本,然后向GPT发起请求
replaceText := "@" + sender.Self.NickName
replaceText := "@" + sender.Self().NickName
requestText := strings.TrimSpace(strings.ReplaceAll(msg.Content, replaceText, ""))
reply, err := gtp.Completions(requestText)
if err != nil {
Expand Down
2 changes: 1 addition & 1 deletion handlers/handler.go
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
package handlers

import (
"github.com/869413421/wechatbot/config"
"github.com/eatmoreapple/openwechat"
"log"
"wechatbot/config"
)

// MessageHandlerInterface 消息处理接口
Expand Down
2 changes: 1 addition & 1 deletion handlers/user_msg_handler.go
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
package handlers

import (
"github.com/869413421/wechatbot/gtp"
"github.com/eatmoreapple/openwechat"
"log"
"strings"
"wechatbot/gtp"
)

var _ MessageHandlerInterface = (*UserMessageHandler)(nil)
Expand Down
4 changes: 1 addition & 3 deletions main.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
package main

import (
"github.com/869413421/wechatbot/bootstrap"
)
import "wechatbot/bootstrap"

func main() {
bootstrap.Run()
Expand Down