This commit is contained in:
shoopea 2019-05-03 15:15:16 +08:00
parent 0c431e1187
commit 61faf48303
3 changed files with 34 additions and 0 deletions

15
main.go
View File

@ -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 ( var (
config = flag.String("config", "chirpnest.cfg", "config file path") config = flag.String("config", "chirpnest.cfg", "config file path")
initdb = flag.Bool("initdb", false, "initialize bot database") initdb = flag.Bool("initdb", false, "initialize bot database")

5
mq.go
View File

@ -7,6 +7,7 @@ import (
) )
func MQMainReceive() { func MQMainReceive() {
var m ChatWarsMessage
conn, err := amqp.Dial("amqp://" + cfg.Rabbit.User + ":" + cfg.Rabbit.Password + "@" + cfg.Rabbit.Host + "/" + cfg.Rabbit.Queue) 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") failOnError(err, "MQMainReceive : Failed to connect to RabbitMQ")
defer conn.Close() defer conn.Close()
@ -41,6 +42,10 @@ func MQMainReceive() {
go func() { go func() {
for d := range msgs { for d := range msgs {
log.Printf("MQMainReceive : Received a message: %s", d.Body) 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)
} }
}() }()

14
sql.go
View File

@ -68,6 +68,7 @@ func initDB() {
id BIGINT UNSIGNED NOT NULL, id BIGINT UNSIGNED NOT NULL,
user_id BIGINT UNSIGNED NOT NULL, user_id BIGINT UNSIGNED NOT NULL,
direction ENUM('incoming', 'outgoing'), direction ENUM('incoming', 'outgoing'),
date TIMESTAMP NOT NULL,
text VARCHAR(4096) NOT NULL, text VARCHAR(4096) NOT NULL,
FOREIGN KEY (user_id) REFERENCES user(id) ON DELETE CASCADE FOREIGN KEY (user_id) REFERENCES user(id) ON DELETE CASCADE
) ENGINE = InnoDB CHARSET=utf8 COLLATE utf8_unicode_ci;`) ) ENGINE = InnoDB CHARSET=utf8 COLLATE utf8_unicode_ci;`)
@ -77,3 +78,16 @@ func initDB() {
log.Println("Database set up") 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)
}
}