go-bot/main.go

154 lines
4.2 KiB
Go
Raw Normal View History

2024-04-01 09:42:29 +08:00
package main
import (
2024-04-20 15:11:49 +08:00
"database/sql"
2024-04-01 09:42:29 +08:00
"go-bot/config"
"go-bot/utils"
"net"
2024-04-01 09:42:29 +08:00
"net/http"
"strings"
2024-04-20 15:11:49 +08:00
"time"
"github.com/gin-gonic/gin"
2024-04-20 15:11:49 +08:00
_ "github.com/mattn/go-sqlite3"
"github.com/sirupsen/logrus"
2024-04-01 09:42:29 +08:00
)
type App struct {
DB *sql.DB
Logger *logrus.Logger
}
func NewApp() (*App, error) {
db, err := sql.Open("sqlite3", "./data.db")
if err != nil {
return nil, err
}
logger := logrus.New()
return &App{
DB: db,
Logger: logger,
}, nil
}
func (app *App) initDB() error {
_, err := app.DB.Exec(`CREATE TABLE IF NOT EXISTS messages (
id INTEGER PRIMARY KEY AUTOINCREMENT,
post_type TEXT,
message_type TEXT,
time DATETIME,
group_id INTEGER,
message_id INTEGER UNIQUE NOT NULL,
raw_message TEXT,
sender_user_id INTEGER,
sender_nickname TEXT,
sender_card TEXT,
sender_role TEXT,
message_seq INTEGER
)`)
return err
}
func (app *App) insertMessage(data map[string]interface{}) error {
if data["post_type"] == "message" || data["post_type"] == "message_sent" {
2024-04-20 15:11:49 +08:00
post_type := data["post_type"].(string)
message_type := data["message_type"].(string)
2024-04-21 11:05:23 +08:00
loc, err := time.LoadLocation("Asia/Shanghai")
if err != nil {
return err
2024-04-21 11:05:23 +08:00
}
message_time := (time.Unix(int64(data["time"].(float64)), 0).In(loc)).Format("2006-01-02 15:04:05")
2024-04-20 15:11:49 +08:00
group_id := data["group_id"].(float64)
message_id := data["message_id"].(float64)
raw_message := data["raw_message"].(string)
sender := data["sender"].(map[string]interface{})
sender_user_id := sender["user_id"].(float64)
sender_nickname := sender["nickname"].(string)
sender_card := sender["card"].(string)
if sender_card == "" {
sender_card = sender_nickname
}
sender_role := sender["role"].(string)
2024-04-21 12:22:35 +08:00
message_seq := data["message_seq"].(float64)
app.Logger.Infof("消息类型:%s 发送时间:%s 群号:%d 消息id%d 原始消息:%s 发送者id%d 发送者昵称:%s 发送者名片:%s 发送者角色:%s 消息序列:%d",
post_type, message_time, int64(group_id), int64(message_id), raw_message, int64(sender_user_id), sender_nickname, sender_card, sender_role, int64(message_seq))
_, err = app.DB.Exec("INSERT INTO messages (post_type, message_type, time, group_id, message_id, raw_message, sender_user_id, sender_nickname, sender_card, sender_role, message_seq) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
2024-04-21 12:22:35 +08:00
post_type, message_type, message_time, group_id, message_id, raw_message, sender_user_id, sender_nickname, sender_card, sender_role, message_seq)
2024-04-20 15:11:49 +08:00
if err != nil {
return err
2024-04-20 15:11:49 +08:00
}
}
return nil
}
// handlePost 处理 POST 请求
func handlePost(c *gin.Context, app *App) {
2024-04-01 09:42:29 +08:00
var data map[string]interface{}
err := c.BindJSON(&data)
2024-04-01 09:42:29 +08:00
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": gin.H{
"message": "Request must be proper JSON",
"type": "invalid_request_error",
"param": nil,
"code": err.Error(),
}})
2024-04-01 09:42:29 +08:00
return
}
// 插入数据
err = app.insertMessage(data)
2024-04-20 15:11:49 +08:00
if err != nil {
app.Logger.Error("Failed to insert message: ", err)
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to insert message"})
return
2024-04-20 15:11:49 +08:00
}
// 调用路由处理函数
2024-07-14 21:38:39 +08:00
if data["post_type"] == "message" || data["post_type"] == "message_sent" {
utils.Router(data)
// c.JSON(http.StatusOK, gin.H{"message": data})
2024-07-14 21:38:39 +08:00
}
2024-04-01 09:42:29 +08:00
}
func main() {
// 使用自定义 Logger 处理 App 初始化中的错误
app, err := NewApp()
if err != nil {
logrus.Fatalf("Failed to initialize app: %v", err)
}
cfg := config.GetConfig()
APIURL, ok := cfg["APIURL"].(string)
if !ok {
logrus.Fatalf("加载配置失败!")
}
// config.PrintConfig(cfg, "")
// 在 App 初始化后统一使用 app.Logger
if err := app.initDB(); err != nil {
app.Logger.Fatalf("Failed to initialize database: %v", err)
}
gin.SetMode(gin.ReleaseMode)
r := gin.Default()
r.POST("/", func(c *gin.Context) {
handlePost(c, app)
})
2024-04-01 09:42:29 +08:00
app.Logger.Infof("Server listening on %s...", APIURL)
if err := r.Run(APIURL); err != nil {
if opError, ok := err.(*net.OpError); ok && opError.Op == "listen" {
app.Logger.Fatal("服务器启动失败:端口被占用。")
} else if strings.Contains(err.Error(), "address already in use") {
app.Logger.Fatal("服务器启动失败:端口被占用。")
} else {
app.Logger.Fatal("服务器启动失败:", err)
}
}
2024-04-01 09:42:29 +08:00
}