Skip to content

Commit

Permalink
增加可配置文件
Browse files Browse the repository at this point in the history
  • Loading branch information
869413421 committed Dec 7, 2022
1 parent 0dc428f commit b015333
Show file tree
Hide file tree
Showing 8 changed files with 173 additions and 45 deletions.
24 changes: 4 additions & 20 deletions bootstrap/bootstrap.go
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
package bootstrap

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



func Run() {
//bot := openwechat.DefaultBot()
bot := openwechat.DefaultBot(openwechat.Desktop) // 桌面模式,上面登录不上的可以尝试切换这种模式
Expand All @@ -15,34 +17,16 @@ func Run() {
// 注册登陆二维码回调
bot.UUIDCallback = openwechat.PrintlnQrcodeUrl

// 登陆
// 创建热存储容器对象
reloadStorage := openwechat.NewJsonFileHotReloadStorage("storage.json")
// 执行热登录
err := bot.HotLogin(reloadStorage)
if err != nil {
if err = bot.Login(); err != nil {
fmt.Println(err)
log.Printf("login error: %v \n", err)
return
}
}


// 获取登陆的用户
self, err := bot.GetCurrentUser()
if err != nil {
fmt.Println(err)
return
}

// 获取所有的好友
friends, err := self.Friends()
fmt.Println(friends, err)

// 获取所有的群组
groups, err := self.Groups()
fmt.Println(groups, err)

// 阻塞主goroutine, 直到发生异常或者用户主动退出
bot.Block()
}
4 changes: 4 additions & 0 deletions config.dev.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"api_key": "your api key",
"auto_pass": true
}
50 changes: 50 additions & 0 deletions config/config.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
package config

import (
"encoding/json"
"log"
"os"
"sync"
)

// Configuration 项目配置
type Configuration struct {
// gtp apikey
ApiKey string `json:"api_key"`
// 自动通过好友
AutoPass bool `json:"auto_pass"`
}

var config *Configuration
var once sync.Once

// LoadConfig 加载配置
func LoadConfig() *Configuration {
once.Do(func() {
// 从文件中读取
config = &Configuration{}
f, err := os.Open("config.json")
if err != nil {
log.Fatalf("open config err: %v", err)
return
}
defer f.Close()
encoder := json.NewDecoder(f)
err = encoder.Decode(config)
if err != nil {
log.Fatalf("decode config err: %v", err)
return
}

// 如果环境变量有配置,读取环境变量
ApiKey := os.Getenv("ApiKey")
AutoPass := os.Getenv("AutoPass")
if ApiKey != "" {
config.ApiKey = ApiKey
}
if AutoPass == "true" {
config.AutoPass = true
}
})
return config
}
16 changes: 10 additions & 6 deletions gtp/gtp.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,14 @@ package gtp
import (
"bytes"
"encoding/json"
"github.com/869413421/wechatbot/config"
"io/ioutil"
"log"
"net/http"
)

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

// ChatGPTResponseBody 请求体
type ChatGPTResponseBody struct {
ID string `json:"id"`
Expand All @@ -18,6 +21,9 @@ type ChatGPTResponseBody struct {
Usage map[string]interface{} `json:"usage"`
}

type ChoiceItem struct {
}

// ChatGPTRequestBody 响应体
type ChatGPTRequestBody struct {
Model string `json:"model"`
Expand All @@ -29,11 +35,11 @@ type ChatGPTRequestBody struct {
PresencePenalty int `json:"presence_penalty"`
}

// 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}'
// Completions gtp文本模型回复
func Completions(msg string) (string, error) {
requestBody := ChatGPTRequestBody{
Model: "text-davinci-003",
Expand All @@ -47,18 +53,17 @@ func Completions(msg string) (string, error) {
requestData, err := json.Marshal(requestBody)

if err != nil {
log.Println(err)
return "", err
}
log.Printf("request gtp json string : %v", string(requestData))
req, err := http.NewRequest("POST", "https://api.openai.com/v1/completions", bytes.NewBuffer(requestData))
req, err := http.NewRequest("POST", BASEURL+"completions", bytes.NewBuffer(requestData))
if err != nil {
log.Println(err)
return "", err
}

apiKey := config.LoadConfig().ApiKey
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer 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")
req.Header.Set("Authorization", "Bearer "+apiKey)
client := &http.Client{}
response, err := client.Do(req)
if err != nil {
Expand All @@ -75,7 +80,6 @@ func Completions(msg string) (string, error) {
log.Println(string(body))
err = json.Unmarshal(body, gptResponseBody)
if err != nil {
log.Println(err)
return "", err
}
var reply string
Expand Down
35 changes: 25 additions & 10 deletions handlers/group_msg_handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,24 +33,39 @@ func (g *GroupMessageHandler) ReplyText(msg *openwechat.Message) error {
group := openwechat.Group{sender}
log.Printf("Received Group %v Text Msg : %v", group.NickName, msg.Content)

if !strings.Contains(msg.Content, "向大兄弟提问") {
// 不是@的不处理
if !msg.IsAt() {
return nil
}
splitItems := strings.Split(msg.Content, "向大兄弟提问")
if len(splitItems) < 2 {
return nil
}
requestText := strings.TrimSpace(splitItems[1])

// 替换掉@文本,然后向GPT发起请求
replaceText := "@" + sender.Self.NickName
requestText := strings.TrimSpace(strings.ReplaceAll(msg.Content, replaceText, ""))
reply, err := gtp.Completions(requestText)
if err != nil {
log.Println(err)
log.Printf("gtp request error: %v \n", err)
msg.ReplyText("机器人神了,我一会发现了就去修。")
return err
}
if reply == "" {
return nil
}

// 获取@我的用户
groupSender, err := msg.SenderInGroup()
if err != nil {
log.Printf("get sender in group error :%v \n", err)
return err
}

_, err = msg.ReplyText(strings.TrimSpace(reply))
if err != nil{
log.Println(err)
// 回复@我的用户
reply = strings.TrimSpace(reply)
reply = strings.Trim(reply, "\n")
atText := "@" + groupSender.NickName
replyText := atText + reply
_, err = msg.ReplyText(replyText)
if err != nil {
log.Printf("response group error: %v \n", err)
}
return err
}
29 changes: 21 additions & 8 deletions handlers/handler.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
package handlers

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

// MessageHandlerInterface 消息处理接口
Expand All @@ -14,27 +16,38 @@ type HandlerType string

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

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

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

// Handler 全局处理入口
func Handler(msg *openwechat.Message) {
//if msg.IsSendBySelf() {
// return
//}
//sender, err := msg.Sender()
//if err != nil {
// log.Println(err)
// return
//}
log.Printf("hadler Received msg : %v", msg.Content)
// 处理群消息
if msg.IsSendByGroup() {
handlers[GroupHandler].handle(msg)
return
}

// 好友申请
if msg.IsFriendAdd() {
if config.LoadConfig().AutoPass {
_, err := msg.Agree("你好我是基于chatGPT引擎开发的微信机器人,你可以向我提问任何问题。")
if err != nil {
log.Fatalf("add friend agree error : %v", err)
return
}
}
}

// 私聊
handlers[UserHandler].handle(msg)
}
56 changes: 56 additions & 0 deletions handlers/user_msg_handler.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
package handlers

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

var _ MessageHandlerInterface = (*UserMessageHandler)(nil)

// UserMessageHandler 私聊消息处理
type UserMessageHandler struct {
}

// handle 处理消息
func (g *UserMessageHandler) handle(msg *openwechat.Message) error {
if msg.IsText() {
return g.ReplyText(msg)
}
return nil
}

// NewUserMessageHandler 创建私聊处理器
func NewUserMessageHandler() MessageHandlerInterface {
return &UserMessageHandler{}
}

// ReplyText 发送文本消息到群
func (g *UserMessageHandler) ReplyText(msg *openwechat.Message) error {
// 接收私聊消息
sender, err := msg.Sender()
log.Printf("Received User %v Text Msg : %v", sender.NickName, msg.Content)

// 向GPT发起请求
requestText := strings.TrimSpace(msg.Content)
requestText = strings.Trim(msg.Content, "\n")
reply, err := gtp.Completions(requestText)
if err != nil {
log.Printf("gtp request error: %v \n", err)
msg.ReplyText("机器人神了,我一会发现了就去修。")
return err
}
if reply == "" {
return nil
}

// 回复用户
reply = strings.TrimSpace(reply)
reply = strings.Trim(reply, "\n")
_, err = msg.ReplyText(reply)
if err != nil {
log.Printf("response user error: %v \n", err)
}
return err
}
4 changes: 3 additions & 1 deletion main.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package main

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

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

0 comments on commit b015333

Please sign in to comment.