From 61faf483032f40584b15c2907b20711a5b25d2ae Mon Sep 17 00:00:00 2001 From: shoopea Date: Fri, 3 May 2019 15:15:16 +0800 Subject: [PATCH] upd --- main.go | 15 +++++++++++++++ mq.go | 5 +++++ sql.go | 14 ++++++++++++++ 3 files changed, 34 insertions(+) diff --git a/main.go b/main.go index de267e8..4217041 100644 --- a/main.go +++ b/main.go @@ -37,6 +37,21 @@ type Config struct { } } +type MsgDirection string + +const ( + Incoming MsgDirection = `incoming` + Outgoing MsgDirection = `outgoing` +) + +type ChatWarsMessage struct { + MsgID64 int64 `json:"msg_id"` + UserID64 int64 `json:"user_id"` + Direction MsgDirection `json:"direction"` + MsgText string `json:"msg"` + MsgDate int32 `json:"date"` +} + var ( config = flag.String("config", "chirpnest.cfg", "config file path") initdb = flag.Bool("initdb", false, "initialize bot database") diff --git a/mq.go b/mq.go index 1b010ce..28b8d01 100644 --- a/mq.go +++ b/mq.go @@ -7,6 +7,7 @@ import ( ) func MQMainReceive() { + var m ChatWarsMessage conn, err := amqp.Dial("amqp://" + cfg.Rabbit.User + ":" + cfg.Rabbit.Password + "@" + cfg.Rabbit.Host + "/" + cfg.Rabbit.Queue) failOnError(err, "MQMainReceive : Failed to connect to RabbitMQ") defer conn.Close() @@ -41,6 +42,10 @@ func MQMainReceive() { go func() { for d := range msgs { log.Printf("MQMainReceive : Received a message: %s", d.Body) + if err = json.Unmarshal(d.Body, &m); err != nil { + failOnError(err, "MQMainReceive : Can't unmarshal") + } + putMsg(m) } }() diff --git a/sql.go b/sql.go index 6d89a33..3ad5429 100644 --- a/sql.go +++ b/sql.go @@ -68,6 +68,7 @@ func initDB() { id BIGINT UNSIGNED NOT NULL, user_id BIGINT UNSIGNED NOT NULL, direction ENUM('incoming', 'outgoing'), + date TIMESTAMP NOT NULL, text VARCHAR(4096) NOT NULL, FOREIGN KEY (user_id) REFERENCES user(id) ON DELETE CASCADE ) ENGINE = InnoDB CHARSET=utf8 COLLATE utf8_unicode_ci;`) @@ -77,3 +78,16 @@ func initDB() { log.Println("Database set up") } + +func putMsg(m *ChatWarsMessage) { + stmt, err := db.Prepare(`INSERT INTO msg (id, user_id, direction, date, text) + VALUES (?, ?, ?, FROM_UNIXTIME(?), ?);`) + if err != nil { + log.Fatal(err) + } + + _, err = stmt.Exec(m.MsgID64, m.UserID64, m.Direction, m.MsgDate, m.MsgText) + if err != nil { + log.Fatal(err) + } +}