This commit is contained in:
shoopea 2019-05-03 11:58:36 +08:00
parent 09439ce697
commit a465276246
5 changed files with 249 additions and 192 deletions

130
bot.go
View File

@ -1,65 +1,65 @@
package main package main
import ( import (
"time" "fmt"
"log" tb "gopkg.in/tucnak/telebot.v2"
"fmt" "log"
tb "gopkg.in/tucnak/telebot.v2" "time"
) )
var ( var (
b *tb.Bot b *tb.Bot
) )
func StartBot() { func StartBot() {
// Registering bot // Registering bot
b, err := tb.NewBot(tb.Settings{ b, err := tb.NewBot(tb.Settings{
Token: cfg.Telegram.Token, Token: cfg.Telegram.Token,
URL: cfg.Telegram.URL, URL: cfg.Telegram.URL,
Poller: &tb.LongPoller{Timeout: 10 * time.Second}, Poller: &tb.LongPoller{Timeout: 10 * time.Second},
}) })
if err != nil { if err != nil {
log.Fatal(err) log.Fatal(err)
return return
} }
b.Handle("/hello", botHello) b.Handle("/hello", botHello)
b.Handle(tb.OnPhoto, botPhoto) b.Handle(tb.OnPhoto, botPhoto)
b.Handle(tb.OnChannelPost, botChannelPost) b.Handle(tb.OnChannelPost, botChannelPost)
b.Handle(tb.OnQuery, botQuery) b.Handle(tb.OnQuery, botQuery)
b.Handle(tb.OnText, botText) b.Handle(tb.OnText, botText)
b.Start() b.Start()
} }
func botPhoto(m *tb.Message) { func botPhoto(m *tb.Message) {
fmt.Println("OnPhoto :", m.Text) fmt.Println("OnPhoto :", m.Text)
// photos only // photos only
} }
func botHello(m *tb.Message) { func botHello(m *tb.Message) {
if !m.Private() { if !m.Private() {
return return
} }
// fmt.Println("Hello payload :", m.Payload) // <PAYLOAD> // fmt.Println("Hello payload :", m.Payload) // <PAYLOAD>
PrintText(m) PrintText(m)
b.Send(m.Sender, "hello world") b.Send(m.Sender, "hello world")
} }
func botChannelPost(m *tb.Message) { func botChannelPost(m *tb.Message) {
fmt.Println("OnChannelPost :", m.Text) fmt.Println("OnChannelPost :", m.Text)
PrintText(m) PrintText(m)
// channel posts only // channel posts only
} }
func botQuery(q *tb.Query) { func botQuery(q *tb.Query) {
fmt.Println("Query ?") fmt.Println("Query ?")
// incoming inline queries // incoming inline queries
} }
func botText(m *tb.Message) { func botText(m *tb.Message) {
PrintText(m) PrintText(m)
// all the text messages that weren't // all the text messages that weren't
// captured by existing handlers // captured by existing handlers
} }

90
main.go
View File

@ -1,49 +1,49 @@
package main package main
import ( import (
"time"
"log"
"flag"
"fmt"
"database/sql" "database/sql"
"flag"
"fmt"
_ "github.com/go-sql-driver/mysql" _ "github.com/go-sql-driver/mysql"
"gopkg.in/gcfg.v1" "gopkg.in/gcfg.v1"
tb "gopkg.in/tucnak/telebot.v2" tb "gopkg.in/tucnak/telebot.v2"
"log"
"time"
) )
type Config struct { type Config struct {
Telegram struct { Telegram struct {
URL string URL string
Token string Token string
} }
SQL struct { SQL struct {
Driver string Driver string
Type string Type string
Address string Address string
Username string Username string
Password string Password string
Database string Database string
} }
Rabbit struct { Rabbit struct {
User string User string
Password string Password string
Host string Host string
Queue string Queue string
} }
Bot struct { Bot struct {
Admin uint64 Admin uint64
Guildname string Guildname string
Guild string Guild string
} }
} }
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")
db *sql.DB
cfg Config db *sql.DB
cfg Config
) )
func PrintText(m *tb.Message) { func PrintText(m *tb.Message) {
@ -53,26 +53,26 @@ func PrintText(m *tb.Message) {
func main() { func main() {
log.Println("Starting Chirpnest...") log.Println("Starting Chirpnest...")
// Parsing config // Parsing config
flag.Parse() flag.Parse()
err := gcfg.ReadFileInto(&cfg, *config) err := gcfg.ReadFileInto(&cfg, *config)
if err != nil { if err != nil {
log.Fatalf("Failed to parse gcfg data: %s", err) log.Fatalf("Failed to parse gcfg data: %s", err)
} }
// Connecting to DB // Connecting to DB
switch cfg.SQL.Driver { switch cfg.SQL.Driver {
case "mysql": case "mysql":
db, err = sql.Open("mysql",cfg.SQL.Username + ":" + cfg.SQL.Password + "@" + cfg.SQL.Type + "(" + cfg.SQL.Address + ")/" + cfg.SQL.Database) db, err = sql.Open("mysql", cfg.SQL.Username+":"+cfg.SQL.Password+"@"+cfg.SQL.Type+"("+cfg.SQL.Address+")/"+cfg.SQL.Database)
if err != nil { if err != nil {
log.Fatal(err) log.Fatal(err)
} }
defer db.Close() defer db.Close()
} }
// Check if any issue // Check if any issue
err = db.Ping() err = db.Ping()
if err != nil { if err != nil {
@ -80,18 +80,18 @@ func main() {
} else { } else {
log.Println("SQL connection initialized") log.Println("SQL connection initialized")
} }
if (*initdb) { if *initdb {
initDB() initDB()
} }
go StartBot() go StartBot()
fmt.Println("Started !") fmt.Println("Started !")
// Main loop // Main loop
for { for {
time.Sleep(1 * time.Second) time.Sleep(1 * time.Second)
} }
} }

49
mq.go Normal file
View File

@ -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
}

161
sql.go
View File

@ -1,82 +1,79 @@
package main package main
import ( import (
"log" "log"
)
)
func initDB() {
log.Println("Setting up database...")
func initDB() {
log.Println("Setting up database...") tx, err := db.Begin()
if err != nil {
tx, err := db.Begin() log.Fatal(err)
if err != nil { }
log.Fatal(err) defer tx.Rollback()
}
defer tx.Rollback() _, err = tx.Exec("set foreign_key_checks = 0")
if err != nil {
_, err = tx.Exec("set foreign_key_checks = 0") log.Fatal(err)
if err != nil { }
log.Fatal(err)
} var name string
rows, err := db.Query("show tables")
var name string if err != nil {
rows, err := db.Query("show tables") log.Fatal(err)
if err != nil { }
log.Fatal(err) for rows.Next() {
} err = rows.Scan(&name)
for rows.Next() { if err != nil {
err = rows.Scan(&name) log.Fatal(err)
if err != nil { }
log.Fatal(err) _, err = tx.Exec("drop table " + name)
} if err != nil {
_, err = tx.Exec("drop table " + name) log.Fatal(err)
if err != nil { }
log.Fatal(err) }
} err = rows.Err()
} if err != nil {
err = rows.Err() log.Fatal(err)
if err != nil { }
log.Fatal(err) rows.Close()
}
rows.Close() _, err = tx.Exec("set foreign_key_checks = 1")
if err != nil {
_, err = tx.Exec("set foreign_key_checks = 1") log.Fatal(err)
if err != nil { }
log.Fatal(err)
} err = tx.Commit()
if err != nil {
err = tx.Commit() log.Fatal(err)
if err != nil { }
log.Fatal(err)
} log.Println("Database cleaned up")
_, err = db.Exec(`CREATE TABLE user (
log.Println("Database cleaned up") id BIGINT UNSIGNED NOT NULL,
_, err = db.Exec( `CREATE TABLE user ( user_id VARCHAR(32) NOT NULL,
id BIGINT UNSIGNED NOT NULL, name VARCHAR(80) NOT NULL,
user_id VARCHAR(32) NOT NULL, guild_id SMALLINT(5),
name VARCHAR(80) NOT NULL, last_msg TIMESTAMP,
guild_id SMALLINT(5), busy_until TIMESTAMP,
last_msg TIMESTAMP, role ENUM('commander', 'bartebder', 'squire', 'none'),
busy_until TIMESTAMP, PRIMARY KEY (id)
role ENUM('commander', 'bartebder', 'squire', 'none'), ) ENGINE = InnoDB CHARSET=utf8 COLLATE utf8_unicode_ci;`)
PRIMARY KEY (id) if err != nil {
) ENGINE = InnoDB CHARSET=utf8 COLLATE utf8_unicode_ci;`) log.Fatal(err)
if err != nil { }
log.Fatal(err)
} _, err = db.Exec(`CREATE TABLE msg (
id BIGINT UNSIGNED NOT NULL,
_, err = db.Exec( `CREATE TABLE msg ( user_id BIGINT UNSIGNED NOT NULL,
id BIGINT UNSIGNED NOT NULL, direction ENUM('incoming', 'outgoing'),
user_id BIGINT UNSIGNED NOT NULL, text VARCHAR(4096) NOT NULL,
direction ENUM('incoming', 'outgoing'), FOREIGN KEY (user_id) REFERENCES user(id) ON DELETE CASCADE
text VARCHAR(4096) NOT NULL, ) ENGINE = InnoDB CHARSET=utf8 COLLATE utf8_unicode_ci;`)
FOREIGN KEY (user_id) REFERENCES user(id) ON DELETE CASCADE if err != nil {
) ENGINE = InnoDB CHARSET=utf8 COLLATE utf8_unicode_ci;`) log.Fatal(err)
if err != nil { }
log.Fatal(err)
} log.Println("Database set up")
}
log.Println("Database set up")
}

11
utils.go Normal file
View File

@ -0,0 +1,11 @@
package main
import (
"log"
)
func failOnError(err error, msg string) {
if err != nil {
log.Fatalf("%s: %s", msg, err)
}
}