update go-bot

This commit is contained in:
liyp 2024-04-01 09:42:29 +08:00
commit 19c4673d98
11 changed files with 348 additions and 0 deletions

0
README.md Normal file
View file

9
config/config.go Normal file
View file

@ -0,0 +1,9 @@
package config
var APIURL string
var PORT string
func LoadConfig() {
// 读取配置文件等操作
}

3
go.mod Normal file
View file

@ -0,0 +1,3 @@
module go-bot
go 1.22.1

44
main.go Normal file
View file

@ -0,0 +1,44 @@
package main
import (
"encoding/json"
"fmt"
"go-bot/config"
"go-bot/utils"
"io"
"net/http"
)
func handlePost(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
body, err := io.ReadAll(r.Body)
if err != nil {
http.Error(w, "Error reading request body", http.StatusBadRequest)
return
}
// fmt.Println(string(body))
// 解码 JSON 数据到 map[string]interface{} 类型的变量
var data map[string]interface{}
err = json.Unmarshal(body, &data)
if err != nil {
fmt.Println("Error decoding JSON:", err)
return
}
utils.Router(data)
w.Write([]byte("JSON data received successfully!"))
}
func main() {
config.LoadConfig()
config.APIURL = "http://127.0.0.1:5700/"
config.PORT = ":5580"
http.HandleFunc("/", handlePost)
fmt.Println("Server listening on port 5580...")
http.ListenAndServe(config.PORT, nil)
}

41
utils/router.go Normal file
View file

@ -0,0 +1,41 @@
package utils
import (
"encoding/json"
"fmt"
"go-bot/workers"
"strings"
)
func Router(data map[string]interface{}) {
// 将map转换为格式化的JSON字符串
jsonString, err := json.MarshalIndent(data, "", " ")
if err != nil {
panic(err)
}
// 输出格式化后的JSON
fmt.Println(string(jsonString))
// 读取字段值
uid := data["user_id"].(float64)
gid := data["group_id"].(float64)
sender := data["sender"].(map[string]interface{})
role := sender["role"].(string)
mid := data["message_id"].(float64)
raw_msg := data["raw_message"].(string)[1:]
parms := strings.Split(raw_msg, " ")
worker := workers.NewWorker(parms, fmt.Sprintf("%d", int(uid)), fmt.Sprintf("%d", int(gid)), role, fmt.Sprintf("%d", int(mid)), raw_msg)
// fmt.Println("router:", parms[0])
fmt.Println(worker.CheckPermission())
// ans := NewStdAns(parms[0], fmt.Sprintf("%d", int(uid)), fmt.Sprintf("%d", int(gid)), role, fmt.Sprintf("%d", int(mid)), raw_msg)
message := worker.CheckPermission()
if message != "0" {
worker.SendMsg(message)
} else {
message = worker.GetMsg()
worker.SendMsg(message)
}
}

111
workers/core.go Normal file
View file

@ -0,0 +1,111 @@
package workers
import (
"bytes"
"encoding/json"
"fmt"
"go-bot/config"
"io"
"net/http"
)
type StdAns struct {
AllowGroup []string
AllowUser []string
AllowRole []string
BlockGroup []string
BlockUser []string
GroupNotAllow string
UserNotAllow string
RoleNotAllow string
Parms []string
UID string
GID string
Role string
MID string
RawMsg string
}
func NewStdAns(parms []string, uid, gid, role, mid, rawMsg string) *StdAns {
return &StdAns{
Parms: parms,
UID: uid,
GID: gid,
Role: role,
MID: mid,
RawMsg: rawMsg,
AllowGroup: []string{},
AllowUser: []string{},
AllowRole: []string{},
BlockGroup: []string{},
BlockUser: []string{},
GroupNotAllow: "汝所在的群组不被允许这样命令咱呢.",
UserNotAllow: "汝不被允许呢.",
RoleNotAllow: "汝的角色不被允许哦.",
}
}
func (s *StdAns) CheckPermission() string {
if (len(s.AllowGroup) > 0 && !contains(s.AllowGroup, s.GID)) || contains(s.BlockGroup, s.GID) {
return s.GroupNotAllow
}
if (len(s.AllowUser) > 0 && !contains(s.AllowUser, s.UID)) || contains(s.BlockUser, s.UID) {
return s.UserNotAllow
}
if len(s.AllowRole) > 0 && !contains(s.AllowRole, s.Role) {
return s.RoleNotAllow
}
return "0"
}
func contains(slice []string, value string) bool {
for _, item := range slice {
if item == value {
return true
}
}
return false
}
func (s *StdAns) GetMsg() string {
if s.Parms[0] != "" {
return "咱也不知道 " + s.Parms[0] + "是啥呢!"
} else {
return "汝再调戏咱,咱可就生气了!!"
}
}
func (s *StdAns) SendMsg(msg string) bool {
requestBody, err := json.Marshal(map[string]interface{}{
"action": "send_msg",
"params": map[string]interface{}{
"group_id": s.GID,
"message": msg,
},
})
if err != nil {
fmt.Println("Error marshaling JSON:", err)
return false
}
re, err := json.MarshalIndent(requestBody, "", " ")
if err != nil {
fmt.Println("Error marshaling JSON:", err)
return false
}
fmt.Println(string(re))
config.LoadConfig()
url := config.APIURL
fmt.Println("请求地址:", url)
fmt.Println("响应信息:", msg)
resp, err := http.Post(url, "application/json", bytes.NewBuffer(requestBody))
if err != nil {
fmt.Println("Error sending request:", err)
return false
}
defer resp.Body.Close()
res, _ := io.ReadAll(resp.Body)
fmt.Println("响应返回:", string(res))
return true
}

17
workers/emm.go Normal file
View file

@ -0,0 +1,17 @@
package workers
import "fmt"
type Emmm struct {
*StdAns
}
func (a *Emmm) GetMsg() string {
a.BlockGroup = []string{"874769998"}
fmt.Println(a.CheckPermission())
if a.CheckPermission() != "0" {
return a.CheckPermission()
}
return "咱也不知道" + a.Parms[0] + "是啥呢~"
}

21
workers/newworker.go Normal file
View file

@ -0,0 +1,21 @@
package workers
import "fmt"
func NewWorker(parms []string, uid, gid, role, mid, rawMsg string) Worker {
fmt.Println("NewWorker:", parms)
switch parms[0] {
case "ping":
return &Ping{
StdAns: NewStdAns(parms, uid, gid, role, mid, rawMsg),
}
// 在这里添加其他 worker 的 case
case "pkg":
return &Pkg{
StdAns: NewStdAns(parms, uid, gid, role, mid, rawMsg),
}
default:
return &Emmm{
StdAns: NewStdAns(parms, uid, gid, role, mid, rawMsg)}
}
}

9
workers/ping.go Normal file
View file

@ -0,0 +1,9 @@
package workers
type Ping struct {
*StdAns
}
func (a *Ping) GetMsg() string {
return "Pong!"
}

85
workers/pkg.go Normal file
View file

@ -0,0 +1,85 @@
package workers
import (
"encoding/json"
"io"
"net/http"
"time"
)
type Package struct {
Version int `json:"version"`
Limit int `json:"limit"`
Valid bool `json:"valid"`
Results []Result `json:"results"`
}
type Result struct {
Pkgname string `json:"pkgname"`
Pkgbase string `json:"pkgbase"`
Repo string `json:"repo"`
Arch string `json:"arch"`
Pkgver string `json:"pkgver"`
Pkgrel string `json:"pkgrel"`
Epoch int `json:"epoch"`
Pkgdesc string `json:"pkgdesc"`
Url string `json:"url"`
Filename string `json:"filename"`
CompressedSize int `json:"compressed_size"`
InstalledSize int `json:"installed_size"`
BuildDate time.Time `json:"build_date"`
LastUpdate time.Time `json:"last_update"`
FlagDate time.Time `json:"flag_date"`
Maintainers []string `json:"maintainers"`
Packager string `json:"packager"`
Groups []string `json:"groups"`
Licenses []string `json:"licenses"`
}
type Pkg struct {
*StdAns
}
func (a *Pkg) GetMsg() string {
if len(a.Parms) < 2 {
return "请输入包名 如:/pkg linux 查询 linux 相关软件"
}
url := "https://archlinux.org/packages/search/json/?name=" + a.Parms[0]
if len(a.Parms) > 1 {
url += "&arch=" + a.Parms[1]
}
req, err := http.Get(url)
if err != nil {
return err.Error()
}
defer req.Body.Close()
body, err := io.ReadAll(req.Body)
if err != nil {
return err.Error()
}
var pkg []Package
// var data map[string]interface{}
err = json.Unmarshal(body, &pkg)
if err != nil {
return err.Error()
}
if pkg[0].Results != nil {
var msg string
for _, v := range pkg[0].Results {
msg += "仓库:" + v.Repo + "\n"
msg += "包名:" + v.Pkgname + "\n"
msg += "版本:" + v.Pkgver + "\n"
msg += "描述:" + v.Pkgdesc + "\n"
msg += "打包:" + v.Packager + "\n"
msg += "链接:" + v.Url + "\n"
msg += "更新日期:" + v.LastUpdate.String() + "\n"
msg += "----------"
}
} else if pkg[0].Results == nil {
// req, _ := http.Get("https://aur.tuna.tsinghua.edu.cn/rpc/?v=5&type=info&arg=" + a.parms[1])
return "没有找到相关软件"
}
return ""
}

8
workers/worker.go Normal file
View file

@ -0,0 +1,8 @@
package workers
// Worker 接口描述了不同类的共同行为
type Worker interface {
CheckPermission() string
GetMsg() string
SendMsg(msg string) bool
}