Skip to content

Commit

Permalink
Definite Version with complete Config
Browse files Browse the repository at this point in the history
  • Loading branch information
rust-kotlin committed Mar 14, 2023
1 parent b44e5d8 commit a05d7d3
Show file tree
Hide file tree
Showing 3 changed files with 84 additions and 52 deletions.
60 changes: 35 additions & 25 deletions connect/connect.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,23 +2,27 @@ package connect

import (
"fmt"
zero "github.com/wdvxdr1123/ZeroBot"
"github.com/wdvxdr1123/ZeroBot/driver"
"github.com/wdvxdr1123/ZeroBot/message"
"gpt-bot/chat"
"gpt-bot/client"
"gpt-bot/json"
"gpt-bot/jsonconfig"
"gpt-bot/plugins/weather"
"strings"
"time"

zero "github.com/wdvxdr1123/ZeroBot"
"github.com/wdvxdr1123/ZeroBot/driver"
"github.com/wdvxdr1123/ZeroBot/message"
)

var superUsers []int64

// Connect 连接到服务器
func Connect() {

zero.RunAndBlock(&zero.Config{
NickName: []string{"gpt-bot"},
CommandPrefix: "#",
SuperUsers: []int64{},
SuperUsers: superUsers,
Driver: []zero.Driver{
driver.NewWebSocketClient("ws://127.0.0.1:8080/", ""),
},
Expand All @@ -28,11 +32,12 @@ func Connect() {
func init() {
engine := zero.New()
// 读取配置文件
config, err := json.LoadConfig("config.json")
config, err := jsonconfig.LoadConfig("config.json")
if err != nil {
fmt.Println("Error loading config.json:", err)
return
}
superUsers = config.SuperUsers
// 创建客户端
aClient := client.CreateClient(config.Apikey, config.Proxy)
chat.SystemContent = chat.Dog
Expand All @@ -44,11 +49,10 @@ func init() {
#help 获取帮助信息
#time 获取当前时间
#weather 获取当前天气,命令后跟着城市名称,例如:#weather北京
#role 修改人工智能角色,目前支持的角色有:狗狗,猫娘,原版,默认为狗狗
gpt-bot将最晚在4月1日停止工作,且行且珍惜,感谢大家的使用!`))
#role 修改人工智能角色,目前支持的角色有:狗狗,猫娘,原版,默认为狗狗,注意,仅允许超级用户修改人工智能角色`))
})
// 修改角色
engine.OnCommand("role").SetBlock(true).Handle(func(ctx *zero.Ctx) {
engine.OnCommand("role", zero.SuperUserPermission).SetBlock(true).Handle(func(ctx *zero.Ctx) {
msg := ctx.MessageString()
if strings.TrimSpace(msg) == "#role" {
ctx.Send(message.Text("请输入角色名称,例如:#role猫娘"))
Expand Down Expand Up @@ -76,22 +80,28 @@ gpt-bot将最晚在4月1日停止工作,且行且珍惜,感谢大家的使
ctx.Send(message.Text("当前时间:" + currentTime.Format("2006年01月02日 15:04:05 ") + getChineseWeekday(currentTime.Weekday())))
})
// 天气
engine.OnCommand("weather").SetBlock(true).Handle(func(ctx *zero.Ctx) {
msg := ctx.MessageString()
if strings.TrimSpace(msg) == "#weather" {
ctx.Send(message.Text("请输入城市名称,例如:#weather北京"))
return
}
location := strings.TrimSpace(strings.Replace(msg, "#weather", "", 1))
ctx.Send(message.Text("正在获取天气信息,请稍等..."))
aWeather, err := weather.GetWeather(location)
if err != nil {
//fmt.Println("Error getting weather:", err)
ctx.Send(err)
return
}
ctx.Send(message.Text(aWeather))
})
if config.WeatherApikey != "" {
engine.OnCommand("weather").SetBlock(true).Handle(func(ctx *zero.Ctx) {
msg := ctx.MessageString()
if strings.TrimSpace(msg) == "#weather" {
ctx.Send(message.Text("请输入城市名称,例如:#weather北京"))
return
}
location := strings.TrimSpace(strings.Replace(msg, "#weather", "", 1))
ctx.Send(message.Text("正在获取天气信息,请稍等..."))
aWeather, err := weather.GetWeather(location, config.WeatherApikey)
if err != nil {
//fmt.Println("Error getting weather:", err)
ctx.Send(message.Text(err))
return
}
ctx.Send(message.Text(aWeather))
})
} else {
engine.OnCommand("weather").SetBlock(true).Handle(func(ctx *zero.Ctx) {
ctx.Send(message.Text("未配置天气API,无法获取天气信息"))
})
}
// 私发消息
engine.OnMessage(zero.OnlyToMe).Handle(func(ctx *zero.Ctx) {
qq := ctx.Event.UserID
Expand Down
24 changes: 14 additions & 10 deletions json/json.go → jsonconfig/jsonconfig.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package json
package jsonconfig

import (
"encoding/json"
Expand All @@ -7,27 +7,31 @@ import (
)

type Config struct {
Apikey string `json:"apikey"`
Model string `json:"model"`
Proxy string `json:"proxy"`
MaxTokens int `json:"max_tokens"`
Apikey string `json:"apikey"`
Model string `json:"model"`
Proxy string `json:"proxy"`
MaxTokens int `json:"max_tokens"`
SuperUsers []int64 `json:"super_users"`
WeatherApikey string `json:"weather_apikey"`
}

// LoadConfig 从文件中读取配置,如果文件不存在则返回默认配置
func LoadConfig(filename string) (*Config, error) {
config := &Config{
Apikey: "your api key",
Model: "gpt-3.5-turbo",
Proxy: "http://localhost:7890",
MaxTokens: 800,
Apikey: "your api key",
Model: "gpt-3.5-turbo",
Proxy: "http://localhost:7890",
MaxTokens: 800,
SuperUsers: []int64{},
WeatherApikey: "",
}

// 如果文件不存在,则创建文件并写入默认配置
if _, err := os.Stat(filename); os.IsNotExist(err) {
if err := SaveConfig(filename, config); err != nil {
return nil, err
}
panic("Please edit the config.json file and restart the program.")
return nil, err
}

// 读取文件并解析为配置项
Expand Down
52 changes: 35 additions & 17 deletions plugins/weather/weather.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,49 +2,58 @@ package weather

import (
"compress/gzip"
libjson "encoding/json"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"
"strings"
)

func GetWeather(location string) (string, error) {
// 构造API请求URL
apiKey := ""
locationID, locationName, err := getGeo(location)
func GetWeather(location, apiKey string) (string, error) {
locationID, locationName, err := getGeo(location, apiKey)
if err != nil {
//fmt.Println("获取地理位置信息失败:", err)
return "", err
}
url := fmt.Sprintf("https://devapi.qweather.com/v7/weather/3d?location=%s&key=%s", locationID, apiKey)
Url := fmt.Sprintf("https://devapi.qweather.com/v7/weather/3d?location=%s&key=%s", locationID, apiKey)
// 发送HTTP请求
resp, err := http.Get(url)
resp, err := http.Get(Url)
if err != nil {
//fmt.Println("发送HTTP请求失败:", err)
return "", err
}
defer resp.Body.Close()
defer func(Body io.ReadCloser) {
err := Body.Close()
if err != nil {
fmt.Println("关闭HTTP响应Body失败:", err)
}
}(resp.Body)
var data map[string]interface{}
if strings.Contains(resp.Header.Get("Content-Encoding"), "gzip") {
// 如果是gzip压缩,则使用gzip.Reader解压缩响应数据
gzipReader, err := gzip.NewReader(resp.Body)
if err != nil {
return "", fmt.Errorf("解压缩失败:%v", err)
}
defer gzipReader.Close()
defer func(gzipReader *gzip.Reader) {
err := gzipReader.Close()
if err != nil {
fmt.Println("关闭gzip.Reader失败:", err)
}
}(gzipReader)
jsonData, err := ioutil.ReadAll(gzipReader)
if err != nil {
return "", fmt.Errorf("读取API响应失败:%v", err)
}
err = libjson.Unmarshal(jsonData, &data)
err = json.Unmarshal(jsonData, &data)
if err != nil {
return "", fmt.Errorf("解析JSON失败:%v", err)
}
} else {
// 如果响应未经过gzip压缩,则直接读取并解析JSON
err = libjson.NewDecoder(resp.Body).Decode(&data)
err = json.NewDecoder(resp.Body).Decode(&data)
if err != nil {
return "", fmt.Errorf("解析JSON失败:%v", err)
}
Expand All @@ -71,16 +80,20 @@ func GetWeather(location string) (string, error) {
}
}

func getGeo(location string) (string, string, error) {
apiKey := ""
func getGeo(location, apiKey string) (string, string, error) {
// 构建请求URL
Url := fmt.Sprintf("https://geoapi.qweather.com/v2/city/lookup?location=%s&key=%s", url.QueryEscape(location), apiKey)
// 发送HTTP GET请求
resp, err := http.Get(Url)
if err != nil {
return "", "", fmt.Errorf("发送HTTP请求失败:%v", err)
}
defer resp.Body.Close()
defer func(Body io.ReadCloser) {
err := Body.Close()
if err != nil {
fmt.Println("关闭HTTP响应Body失败:", err)
}
}(resp.Body)
// 读取响应数据并解析JSON
var result map[string]interface{}
// 检查响应是否为gzip压缩
Expand All @@ -90,18 +103,23 @@ func getGeo(location string) (string, string, error) {
if err != nil {
return "", "", fmt.Errorf("解压缩失败:%v", err)
}
defer gzipReader.Close()
defer func(gzipReader *gzip.Reader) {
err := gzipReader.Close()
if err != nil {
fmt.Println("关闭gzip.Reader失败:", err)
}
}(gzipReader)
jsonData, err := ioutil.ReadAll(gzipReader)
if err != nil {
return "", "", fmt.Errorf("读取API响应失败:%v", err)
}
err = libjson.Unmarshal(jsonData, &result)
err = json.Unmarshal(jsonData, &result)
if err != nil {
return "", "", fmt.Errorf("解析JSON失败:%v", err)
}
} else {
// 如果响应未经过gzip压缩,则直接读取并解析JSON
err = libjson.NewDecoder(resp.Body).Decode(&result)
err = json.NewDecoder(resp.Body).Decode(&result)
if err != nil {
return "", "", fmt.Errorf("解析JSON失败:%v", err)
}
Expand Down

0 comments on commit a05d7d3

Please sign in to comment.