From a46527624650b576c395cff6c494d6d964d73a82 Mon Sep 17 00:00:00 2001 From: shoopea Date: Fri, 3 May 2019 11:58:36 +0800 Subject: [PATCH] upd --- bot.go | 130 ++++++++++++++++++++++---------------------- main.go | 90 +++++++++++++++---------------- mq.go | 49 +++++++++++++++++ sql.go | 161 +++++++++++++++++++++++++++---------------------------- utils.go | 11 ++++ 5 files changed, 249 insertions(+), 192 deletions(-) create mode 100644 mq.go create mode 100644 utils.go diff --git a/bot.go b/bot.go index 1d2330b..bd1bddf 100644 --- a/bot.go +++ b/bot.go @@ -1,65 +1,65 @@ -package main - -import ( - "time" - "log" - "fmt" - tb "gopkg.in/tucnak/telebot.v2" -) - -var ( - b *tb.Bot -) - -func StartBot() { - // Registering bot - b, err := tb.NewBot(tb.Settings{ - Token: cfg.Telegram.Token, - URL: cfg.Telegram.URL, - Poller: &tb.LongPoller{Timeout: 10 * time.Second}, - }) - - if err != nil { - log.Fatal(err) - return - } - - b.Handle("/hello", botHello) - b.Handle(tb.OnPhoto, botPhoto) - b.Handle(tb.OnChannelPost, botChannelPost) - b.Handle(tb.OnQuery, botQuery) - b.Handle(tb.OnText, botText) - - b.Start() -} - -func botPhoto(m *tb.Message) { - fmt.Println("OnPhoto :", m.Text) -// photos only -} - -func botHello(m *tb.Message) { - if !m.Private() { - return - } -// fmt.Println("Hello payload :", m.Payload) // - PrintText(m) - b.Send(m.Sender, "hello world") -} - -func botChannelPost(m *tb.Message) { - fmt.Println("OnChannelPost :", m.Text) - PrintText(m) -// channel posts only -} - -func botQuery(q *tb.Query) { - fmt.Println("Query ?") -// incoming inline queries -} - -func botText(m *tb.Message) { - PrintText(m) - // all the text messages that weren't - // captured by existing handlers -} \ No newline at end of file +package main + +import ( + "fmt" + tb "gopkg.in/tucnak/telebot.v2" + "log" + "time" +) + +var ( + b *tb.Bot +) + +func StartBot() { + // Registering bot + b, err := tb.NewBot(tb.Settings{ + Token: cfg.Telegram.Token, + URL: cfg.Telegram.URL, + Poller: &tb.LongPoller{Timeout: 10 * time.Second}, + }) + + if err != nil { + log.Fatal(err) + return + } + + b.Handle("/hello", botHello) + b.Handle(tb.OnPhoto, botPhoto) + b.Handle(tb.OnChannelPost, botChannelPost) + b.Handle(tb.OnQuery, botQuery) + b.Handle(tb.OnText, botText) + + b.Start() +} + +func botPhoto(m *tb.Message) { + fmt.Println("OnPhoto :", m.Text) + // photos only +} + +func botHello(m *tb.Message) { + if !m.Private() { + return + } + // fmt.Println("Hello payload :", m.Payload) // + PrintText(m) + b.Send(m.Sender, "hello world") +} + +func botChannelPost(m *tb.Message) { + fmt.Println("OnChannelPost :", m.Text) + PrintText(m) + // channel posts only +} + +func botQuery(q *tb.Query) { + fmt.Println("Query ?") + // incoming inline queries +} + +func botText(m *tb.Message) { + PrintText(m) + // all the text messages that weren't + // captured by existing handlers +} diff --git a/main.go b/main.go index f20433e..0262b53 100644 --- a/main.go +++ b/main.go @@ -1,49 +1,49 @@ package main import ( - "time" - "log" - "flag" - "fmt" "database/sql" + "flag" + "fmt" _ "github.com/go-sql-driver/mysql" "gopkg.in/gcfg.v1" tb "gopkg.in/tucnak/telebot.v2" + "log" + "time" ) type Config struct { Telegram struct { - URL string - Token string + URL string + Token string } SQL struct { - Driver string - Type string - Address string - Username string - Password string - Database string + Driver string + Type string + Address string + Username string + Password string + Database string } Rabbit struct { - User string - Password string - Host string - Queue string + User string + Password string + Host string + Queue string } Bot struct { - Admin uint64 - Guildname string - Guild string + Admin uint64 + Guildname string + Guild string } } var ( - config = flag.String("config", "chirpnest.cfg", "config file path") - initdb = flag.Bool("initdb", false, "initialize bot database") - - db *sql.DB + config = flag.String("config", "chirpnest.cfg", "config file path") + initdb = flag.Bool("initdb", false, "initialize bot database") - cfg Config + db *sql.DB + + cfg Config ) func PrintText(m *tb.Message) { @@ -53,26 +53,26 @@ func PrintText(m *tb.Message) { func main() { log.Println("Starting Chirpnest...") - + // Parsing config - flag.Parse() - + flag.Parse() + err := gcfg.ReadFileInto(&cfg, *config) if err != nil { log.Fatalf("Failed to parse gcfg data: %s", err) } - + // Connecting to DB switch cfg.SQL.Driver { - case "mysql": - db, err = sql.Open("mysql",cfg.SQL.Username + ":" + cfg.SQL.Password + "@" + cfg.SQL.Type + "(" + cfg.SQL.Address + ")/" + cfg.SQL.Database) - if err != nil { - log.Fatal(err) - } - defer db.Close() - + case "mysql": + db, err = sql.Open("mysql", cfg.SQL.Username+":"+cfg.SQL.Password+"@"+cfg.SQL.Type+"("+cfg.SQL.Address+")/"+cfg.SQL.Database) + if err != nil { + log.Fatal(err) + } + defer db.Close() + } - + // Check if any issue err = db.Ping() if err != nil { @@ -80,18 +80,18 @@ func main() { } else { log.Println("SQL connection initialized") } - - if (*initdb) { + + if *initdb { initDB() } - + go StartBot() - fmt.Println("Started !") + fmt.Println("Started !") - // Main loop - for { - time.Sleep(1 * time.Second) - } + // Main loop + for { + time.Sleep(1 * time.Second) + } -} \ No newline at end of file +} diff --git a/mq.go b/mq.go new file mode 100644 index 0000000..9774388 --- /dev/null +++ b/mq.go @@ -0,0 +1,49 @@ +package main + +import ( + "log" + + "github.com/streadway/amqp" +) + +func MQMainReceive() { + conn, err := amqp.Dial("amqp://shoopea:UmDd5g4WRa2MzqOHsG2T@localhost:5672/chatwars") + failOnError(err, "MQMainReceive : Failed to connect to RabbitMQ") + defer conn.Close() + + ch, err := conn.Channel() + failOnError(err, "MQMainReceive : Failed to open a channel") + defer ch.Close() + + q, err := ch.QueueDeclare( + "msg", // name + false, // durable + false, // delete when unused + false, // exclusive + false, // no-wait + nil, // arguments + ) + failOnError(err, "MQMainReceive : Failed to declare a queue") + + msgs, err := ch.Consume( + q.Name, // queue + "", // consumer + true, // auto-ack + false, // exclusive + false, // no-local + false, // no-wait + nil, // args + ) + failOnError(err, "MQMainReceive : Failed to register a consumer") + + forever := make(chan bool) + + go func() { + for d := range msgs { + log.Printf("MQMainReceive : Received a message: %s", d.Body) + } + }() + + <-forever + +} diff --git a/sql.go b/sql.go index 29f3b3d..6d89a33 100644 --- a/sql.go +++ b/sql.go @@ -1,82 +1,79 @@ -package main - -import ( - "log" - -) - - -func initDB() { - log.Println("Setting up database...") - - tx, err := db.Begin() - if err != nil { - log.Fatal(err) - } - defer tx.Rollback() - - _, err = tx.Exec("set foreign_key_checks = 0") - if err != nil { - log.Fatal(err) - } - - var name string - rows, err := db.Query("show tables") - if err != nil { - log.Fatal(err) - } - for rows.Next() { - err = rows.Scan(&name) - if err != nil { - log.Fatal(err) - } - _, err = tx.Exec("drop table " + name) - if err != nil { - log.Fatal(err) - } - } - err = rows.Err() - if err != nil { - log.Fatal(err) - } - rows.Close() - - _, err = tx.Exec("set foreign_key_checks = 1") - if err != nil { - log.Fatal(err) - } - - err = tx.Commit() - if err != nil { - log.Fatal(err) - } - - log.Println("Database cleaned up") - _, err = db.Exec( `CREATE TABLE user ( - id BIGINT UNSIGNED NOT NULL, - user_id VARCHAR(32) NOT NULL, - name VARCHAR(80) NOT NULL, - guild_id SMALLINT(5), - last_msg TIMESTAMP, - busy_until TIMESTAMP, - role ENUM('commander', 'bartebder', 'squire', 'none'), - PRIMARY KEY (id) - ) ENGINE = InnoDB CHARSET=utf8 COLLATE utf8_unicode_ci;`) - if err != nil { - log.Fatal(err) - } - - _, err = db.Exec( `CREATE TABLE msg ( - id BIGINT UNSIGNED NOT NULL, - user_id BIGINT UNSIGNED NOT NULL, - direction ENUM('incoming', 'outgoing'), - text VARCHAR(4096) NOT NULL, - FOREIGN KEY (user_id) REFERENCES user(id) ON DELETE CASCADE - ) ENGINE = InnoDB CHARSET=utf8 COLLATE utf8_unicode_ci;`) - if err != nil { - log.Fatal(err) - } - - log.Println("Database set up") -} - +package main + +import ( + "log" +) + +func initDB() { + log.Println("Setting up database...") + + tx, err := db.Begin() + if err != nil { + log.Fatal(err) + } + defer tx.Rollback() + + _, err = tx.Exec("set foreign_key_checks = 0") + if err != nil { + log.Fatal(err) + } + + var name string + rows, err := db.Query("show tables") + if err != nil { + log.Fatal(err) + } + for rows.Next() { + err = rows.Scan(&name) + if err != nil { + log.Fatal(err) + } + _, err = tx.Exec("drop table " + name) + if err != nil { + log.Fatal(err) + } + } + err = rows.Err() + if err != nil { + log.Fatal(err) + } + rows.Close() + + _, err = tx.Exec("set foreign_key_checks = 1") + if err != nil { + log.Fatal(err) + } + + err = tx.Commit() + if err != nil { + log.Fatal(err) + } + + log.Println("Database cleaned up") + _, err = db.Exec(`CREATE TABLE user ( + id BIGINT UNSIGNED NOT NULL, + user_id VARCHAR(32) NOT NULL, + name VARCHAR(80) NOT NULL, + guild_id SMALLINT(5), + last_msg TIMESTAMP, + busy_until TIMESTAMP, + role ENUM('commander', 'bartebder', 'squire', 'none'), + PRIMARY KEY (id) + ) ENGINE = InnoDB CHARSET=utf8 COLLATE utf8_unicode_ci;`) + if err != nil { + log.Fatal(err) + } + + _, err = db.Exec(`CREATE TABLE msg ( + id BIGINT UNSIGNED NOT NULL, + user_id BIGINT UNSIGNED NOT NULL, + direction ENUM('incoming', 'outgoing'), + text VARCHAR(4096) NOT NULL, + FOREIGN KEY (user_id) REFERENCES user(id) ON DELETE CASCADE + ) ENGINE = InnoDB CHARSET=utf8 COLLATE utf8_unicode_ci;`) + if err != nil { + log.Fatal(err) + } + + log.Println("Database set up") +} diff --git a/utils.go b/utils.go new file mode 100644 index 0000000..56154b2 --- /dev/null +++ b/utils.go @@ -0,0 +1,11 @@ +package main + +import ( + "log" +) + +func failOnError(err error, msg string) { + if err != nil { + log.Fatalf("%s: %s", msg, err) + } +}