Archived
1

Work on squads, alerts on new user with empty or spy profile

Closes #1
Closes #2
This commit is contained in:
Vladimir Hodakov 2017-11-13 22:51:50 +04:00
parent 76b6245b8e
commit 5c08899d25
23 changed files with 338 additions and 19 deletions

View File

@ -15,6 +15,7 @@ import (
"lab.pztrn.name/fat0troll/i2_bot/lib/parsers"
"lab.pztrn.name/fat0troll/i2_bot/lib/router"
"lab.pztrn.name/fat0troll/i2_bot/lib/talkers"
"lab.pztrn.name/fat0troll/i2_bot/lib/welcomer"
)
var (
@ -30,6 +31,7 @@ func main() {
parsers.New(c)
talkers.New(c)
getters.New(c)
welcomer.New(c)
u := tgbotapi.NewUpdate(0)
u.Timeout = 60

View File

@ -6,3 +6,5 @@ database_connection:
user: "i2_bot"
password: "i2_bot"
database: "i2_bot"
notifications:
group_id: "group_id"

View File

@ -16,6 +16,7 @@ import (
"lab.pztrn.name/fat0troll/i2_bot/lib/parsers/parsersinterface"
"lab.pztrn.name/fat0troll/i2_bot/lib/router/routerinterface"
"lab.pztrn.name/fat0troll/i2_bot/lib/talkers/talkersinterface"
"lab.pztrn.name/fat0troll/i2_bot/lib/welcomer/welcomerinterface"
)
// Context is an application context struct
@ -28,6 +29,7 @@ type Context struct {
Db *sqlx.DB
Talkers talkersinterface.TalkersInterface
Getters gettersinterface.GettersInterface
Welcomer welcomerinterface.WelcomerInterface
}
// Init is a initialization function for context
@ -65,6 +67,11 @@ func (c *Context) RegisterGettersInterface(gi gettersinterface.GettersInterface)
c.Getters = gi
}
// RegisterWelcomerInterface registering welcomer interface in application
func (c *Context) RegisterWelcomerInterface(wi welcomerinterface.WelcomerInterface) {
c.Welcomer = wi
}
// RunDatabaseMigrations applies migrations on bot's startup
func (c *Context) RunDatabaseMigrations() {
c.Migrations.SetDialect("mysql")

View File

@ -28,10 +28,16 @@ type TelegramConnection struct {
APIToken string `yaml:"api_token"`
}
// NotificationsConnection handles settings for notifications
type NotificationsConnection struct {
GroupID string `yaml:"group_id"`
}
// Config is a struct which represents config.yaml structure
type Config struct {
Telegram TelegramConnection `yaml:"telegram_connection"`
Database DatabaseConnection `yaml:"database_connection"`
Telegram TelegramConnection `yaml:"telegram_connection"`
Database DatabaseConnection `yaml:"database_connection"`
Notifications NotificationsConnection `yaml:"notifications"`
}
// Init is a configuration initializer

View File

@ -13,7 +13,6 @@ type Player struct {
ID int `db:"id"`
TelegramID int `db:"telegram_id"`
LeagueID int `db:"league_id"`
SquadID int `db:"squad_id"`
Status string `db:"status"`
CreatedAt time.Time `db:"created_at"`
UpdatedAt time.Time `db:"updated_at"`

24
lib/dbmapping/squads.go Normal file
View File

@ -0,0 +1,24 @@
// i2_bot Instinct PokememBro Bot
// Copyright (c) 2017 Vladimir "fat0troll" Hodakov
package dbmapping
import (
// stdlib
"time"
)
// Squad is a struct, which represents `squads` table item in databse.
type Squad struct {
ID int `db:"id"`
ChatID int `db:"chat_id"`
AuthorID int `db:"author_id"`
CreatedAt time.Time `db:"created_at"`
}
// SquadChat is a stuct, which combines information about chats and squads
type SquadChat struct {
Squad Squad
Chat Chat
IsSquad bool
}

View File

@ -0,0 +1,18 @@
// i2_bot Instinct PokememBro Bot
// Copyright (c) 2017 Vladimir "fat0troll" Hodakov
package dbmapping
import (
// stdlib
"time"
)
// SquadPlayer is a struct, which represents `squads_players` table item in databse.
type SquadPlayer struct {
ID int `db:"id"`
SquadID int `db:"squad_id"`
PlayerID int `db:"player_id"`
AuthorID int `db:"author_id"`
CreatedAt time.Time `db:"created_at"`
}

View File

@ -84,6 +84,50 @@ func (g *Getters) GetAllPrivateChats() ([]dbmapping.Chat, bool) {
return privateChats, true
}
// GetAllGroupChats returns all group chats
func (g *Getters) GetAllGroupChats() ([]dbmapping.Chat, bool) {
groupChats := []dbmapping.Chat{}
err := c.Db.Select(&groupChats, "SELECT * FROM chats WHERE chat_type IN ('group', 'supergroup')")
if err != nil {
log.Println(err)
return groupChats, false
}
return groupChats, true
}
// GetAllGroupChatsWithSquads returns all group chats with squads
func (g *Getters) GetAllGroupChatsWithSquads() ([]dbmapping.SquadChat, bool) {
chatsSquads := []dbmapping.SquadChat{}
groupChats := []dbmapping.Chat{}
err := c.Db.Select(&groupChats, "SELECT * FROM chats WHERE chat_type IN ('group', 'supergroup')")
if err != nil {
log.Println(err)
return chatsSquads, false
}
for i := range groupChats {
chatSquad := dbmapping.SquadChat{}
squad := dbmapping.Squad{}
err = c.Db.Select(&squad, c.Db.Rebind("SELECT * FROM squads WHERE chat_id="), groupChats[i].ID)
if err != nil {
log.Println(err)
chatSquad.IsSquad = false
} else {
chatSquad.IsSquad = true
}
chatSquad.Squad = squad
chatSquad.Chat = groupChats[i]
chatsSquads = append(chatsSquads, chatSquad)
}
return chatsSquads, true
}
// UpdateChatTitle updates chat title in database
func (g *Getters) UpdateChatTitle(chatRaw dbmapping.Chat, newTitle string) (dbmapping.Chat, bool) {
chatRaw.Name = newTitle

View File

@ -19,6 +19,8 @@ type GettersInterface interface {
GetOrCreateChat(update *tgbotapi.Update) (dbmapping.Chat, bool)
GetChatByID(chatID int64) (dbmapping.Chat, bool)
GetAllPrivateChats() ([]dbmapping.Chat, bool)
GetAllGroupChats() ([]dbmapping.Chat, bool)
GetAllGroupChatsWithSquads() ([]dbmapping.SquadChat, bool)
UpdateChatTitle(chatRaw dbmapping.Chat, newTitle string) (dbmapping.Chat, bool)
GetOrCreatePlayer(telegramID int) (dbmapping.Player, bool)
GetPlayerByID(playerID int) (dbmapping.Player, bool)

View File

@ -35,11 +35,10 @@ func (g *Getters) GetOrCreatePlayer(telegramID int) (dbmapping.Player, bool) {
// Create "nobody" user
playerRaw.TelegramID = telegramID
playerRaw.LeagueID = 0
playerRaw.SquadID = 0
playerRaw.Status = "nobody"
playerRaw.CreatedAt = time.Now().UTC()
playerRaw.UpdatedAt = time.Now().UTC()
_, err = c.Db.NamedExec("INSERT INTO players VALUES(NULL, :telegram_id, :league_id, :squad_id, :status, :created_at, :updated_at)", &playerRaw)
_, err = c.Db.NamedExec("INSERT INTO players VALUES(NULL, :telegram_id, :league_id, :status, :created_at, :updated_at)", &playerRaw)
if err != nil {
log.Printf(err.Error())
return playerRaw, false

View File

@ -0,0 +1,65 @@
// i2_bot Instinct PokememBro Bot
// Copyright (c) 2017 Vladimir "fat0troll" Hodakov
package migrations
import (
// stdlib
"database/sql"
)
func CreateSquadsUp(tx *sql.Tx) error {
request := "CREATE TABLE `squads` ("
request += "`id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'ID отряда',"
request += "`chat_id` int(11) NOT NULL COMMENT 'ID чата в базе',"
request += "`author_id` int(11) NOT NULL COMMENT 'ID автора отряда',"
request += "`created_at` datetime NOT NULL COMMENT 'Добавлено в базу',"
request += "PRIMARY KEY (`id`),"
request += "UNIQUE KEY `id` (`id`),"
request += "KEY `squads_created_at` (`created_at`)"
request += ") ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 COMMENT='Отряды';"
_, err := tx.Exec(request)
if err != nil {
return err
}
request = "CREATE TABLE `squads_players` ("
request += "`id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'ID связи',"
request += "`squad_id` int(11) NOT NULL COMMENT 'ID отряда в базе',"
request += "`player_id` int(11) NOT NULL COMMENT 'ID игрока',"
request += "`author_id` int(11) NOT NULL COMMENT 'ID добавившего в отряд',"
request += "`created_at` datetime NOT NULL COMMENT 'Добавлено в базу',"
request += "PRIMARY KEY (`id`),"
request += "UNIQUE KEY `id` (`id`),"
request += "KEY `squads_players_created_at` (`created_at`)"
request += ") ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 COMMENT='Связь Отряды-Игроки';"
_, err = tx.Exec(request)
if err != nil {
return err
}
request = "ALTER TABLE `players` DROP COLUMN `squad_id`"
_, err = tx.Exec(request)
if err != nil {
return err
}
return nil
}
func CreateSquadsDown(tx *sql.Tx) error {
_, err := tx.Exec("DROP TABLE `squads`;")
if err != nil {
return err
}
_, err = tx.Exec("DROP TABLE `squads_players`;")
if err != nil {
return err
}
_, err = tx.Exec("MODIFY TABLE `players` ADD COLUMN `league_id` int(11) COMMENT 'ID лиги' DEFAULT 0")
if err != nil {
return err
}
return nil
}

View File

@ -34,6 +34,7 @@ func (m *Migrations) Init() {
goose.AddNamedMigration("17_change_profile_pokememes_columns.go", ChangeProfilePokememesColumnsUp, ChangeProfilePokememesColumnsDown)
goose.AddNamedMigration("18_add_pokememes_wealth.go", AddPokememesWealthUp, AddPokememesWealthDown)
goose.AddNamedMigration("19_create_broadcasts.go", CreateBroadcastsUp, CreateBroadcastsDown)
goose.AddNamedMigration("20_create_squads.go", CreateSquadsUp, CreateSquadsDown)
}
func (m *Migrations) Migrate() error {

View File

@ -219,10 +219,9 @@ func (p *Parsers) ParseProfile(update tgbotapi.Update, playerRaw dbmapping.Playe
} else if playerRaw.LeagueID != league.ID {
// Duplicate profile: user changed league, beware!
playerRaw.LeagueID = league.ID
playerRaw.SquadID = 0
playerRaw.Status = "league_changed"
playerRaw.CreatedAt = time.Now().UTC()
_, err5 := c.Db.NamedExec("INSERT INTO players VALUES(NULL, :telegram_id, :league_id, :squad_id, :status, :created_at, :updated_at)", &playerRaw)
_, err5 := c.Db.NamedExec("INSERT INTO players VALUES(NULL, :telegram_id, :league_id, :status, :created_at, :updated_at)", &playerRaw)
if err5 != nil {
log.Println(err5)
return "fail"

View File

@ -23,7 +23,7 @@ func (r *Router) routeGroupRequest(update tgbotapi.Update, playerRaw dbmapping.P
// Welcomes
if update.Message.NewChatMember != nil {
return c.Talkers.WelcomeMessage(update)
return c.Welcomer.WelcomeMessage(update)
}
// New chat names
if update.Message.NewChatTitle != "" {

View File

@ -133,6 +133,14 @@ func (r *Router) routePrivateRequest(update tgbotapi.Update, playerRaw dbmapping
return "ok"
}
c.Talkers.AnyMessageUnauthorized(update)
return "fail"
case update.Message.Command() == "group_chats":
if c.Getters.PlayerBetterThan(&playerRaw, "admin") {
c.Talkers.GroupsList(update)
return "ok"
}
c.Talkers.AnyMessageUnauthorized(update)
return "fail"
}

39
lib/talkers/chats.go Normal file
View File

@ -0,0 +1,39 @@
// i2_bot Instinct PokememBro Bot
// Copyright (c) 2017 Vladimir "fat0troll" Hodakov
package talkers
import (
// stdlib
"strconv"
// 3rd party
"github.com/go-telegram-bot-api/telegram-bot-api"
)
// GroupsList lists all known pokememes
func (t *Talkers) GroupsList(update tgbotapi.Update) string {
groupChats, ok := c.Getters.GetAllGroupChatsWithSquads()
if !ok {
return "fail"
}
message := "*Бот состоит в следующих групповых чатах:*\n"
for i := range groupChats {
message += "---\n"
message += "[#" + strconv.Itoa(groupChats[i].Chat.ID) + "] _" + groupChats[i].Chat.Name + "_\n"
message += "Telegram ID: " + strconv.FormatInt(groupChats[i].Chat.TelegramID, 10) + "\n"
if groupChats[i].IsSquad {
message += "Является отрядом <статистика>\n"
} else {
message += "Не является отрядом. Сделать отрядом: /make\\_squad" + strconv.Itoa(groupChats[i].Chat.ID) + "\n"
}
}
msg := tgbotapi.NewMessage(update.Message.Chat.ID, message)
msg.ParseMode = "Markdown"
c.Bot.Send(msg)
return "ok"
}

View File

@ -21,6 +21,7 @@ func (t *Talkers) HelpMessage(update tgbotapi.Update, playerRaw *dbmapping.Playe
message += "+ /pokedeks получить список известных боту покемемов\n"
if c.Getters.PlayerBetterThan(playerRaw, "admin") {
message += "+ /send\\_all _текст_ — отправить сообщение всем пользователям бота\n"
message += "+ /group\\_chats — получить список групп, в которых работает бот.\n"
}
message += "+ /help выводит данное сообщение\n"

View File

@ -44,6 +44,14 @@ func (t *Talkers) pokememesListing(update tgbotapi.Update, page int, pokememesAr
}
}
if len(pokememesArray) > page*50 {
message += "\n"
message += "Переход на следующую страницу: /pokedeks" + strconv.Itoa(page+1)
}
if page > 1 {
message += "\nПереход на предыдущую страницу: /pokedeks" + strconv.Itoa(page-1)
}
msg := tgbotapi.NewMessage(update.Message.Chat.ID, message)
msg.ParseMode = "Markdown"

View File

@ -33,7 +33,7 @@ type TalkersInterface interface {
AdminBroadcastMessageCompose(update tgbotapi.Update, playerRaw *dbmapping.Player) string
AdminBroadcastMessageSend(update tgbotapi.Update, playerRaw *dbmapping.Player) string
WelcomeMessage(update tgbotapi.Update) string
GroupsList(update tgbotapi.Update) string
DurakMessage(update tgbotapi.Update)
MatMessage(update tgbotapi.Update)

31
lib/welcomer/exported.go Normal file
View File

@ -0,0 +1,31 @@
// i2_bot Instinct PokememBro Bot
// Copyright (c) 2017 Vladimir "fat0troll" Hodakov
package welcomer
import (
// stdlib
"log"
// local
"lab.pztrn.name/fat0troll/i2_bot/lib/appcontext"
"lab.pztrn.name/fat0troll/i2_bot/lib/welcomer/welcomerinterface"
)
var (
c *appcontext.Context
)
// Welcomer is a function-handling struct for talkers
type Welcomer struct{}
// New is a appcontext initialization function
func New(ac *appcontext.Context) {
c = ac
m := &Welcomer{}
c.RegisterWelcomerInterface(welcomerinterface.WelcomerInterface(m))
}
// Init is an initialization function for talkers
func (w *Welcomer) Init() {
log.Printf("Initializing Welcomer...")
}

View File

@ -0,0 +1,49 @@
// i2_bot Instinct PokememBro Bot
// Copyright (c) 2017 Vladimir "fat0troll" Hodakov
package welcomer
import (
// stdlib
"strconv"
// 3rd party
"github.com/go-telegram-bot-api/telegram-bot-api"
)
func (w *Welcomer) alertUserWithoutProfile(update tgbotapi.Update) string {
alertGroupID, _ := strconv.ParseInt(c.Cfg.Notifications.GroupID, 10, 64)
chat, ok := c.Getters.GetOrCreateChat(&update)
if !ok {
return "fail"
}
message := "*Новый вход пользователя без профиля в чат с ботом!*\n"
message += "В чат _" + chat.Name + "_ вошёл некто @" + update.Message.NewChatMember.UserName
message += ". Он получил уведомление о том, что ему нужно создать профиль в боте."
msg := tgbotapi.NewMessage(alertGroupID, message)
msg.ParseMode = "Markdown"
c.Bot.Send(msg)
return "ok"
}
func (w *Welcomer) alertSpyUser(update tgbotapi.Update) string {
alertGroupID, _ := strconv.ParseInt(c.Cfg.Notifications.GroupID, 10, 64)
chat, ok := c.Getters.GetOrCreateChat(&update)
if !ok {
return "fail"
}
message := "*Шпион в деле!*\n"
message += "В чат _" + chat.Name + "_ вошёл некто @" + update.Message.NewChatMember.UserName
message += ". У него профиль другой лиги. Ждём обновлений."
msg := tgbotapi.NewMessage(alertGroupID, message)
msg.ParseMode = "Markdown"
c.Bot.Send(msg)
return "ok"
}

View File

@ -1,18 +1,16 @@
// i2_bot Instinct PokememBro Bot
// Copyright (c) 2017 Vladimir "fat0troll" Hodakov
package talkers
package welcomer
import (
// stdlib
"time"
// 3rd party
"github.com/go-telegram-bot-api/telegram-bot-api"
// local
// "lab.pztrn.name/fat0troll/i2_bot/lib/dbmapping"
)
func (t *Talkers) groupWelcomeUser(update tgbotapi.Update) string {
func (w *Welcomer) groupWelcomeUser(update tgbotapi.Update) string {
playerRaw, ok := c.Getters.GetOrCreatePlayer(update.Message.NewChatMember.ID)
if !ok {
return "fail"
@ -30,10 +28,14 @@ func (t *Talkers) groupWelcomeUser(update tgbotapi.Update) string {
message += "Последнее обновление твоего профиля: " + profileRaw.CreatedAt.Format("02.01.2006 15:04:05") + "."
} else {
message += "Обнови профиль, отправив его боту в личку. Так надо."
w.alertSpyUser(update)
}
} else {
// newbie
message += "Добавь себе бота @i2\\_bot в список контактов и скинь в него игровой профиль. Это важно для успешной игры!\n"
w.alertUserWithoutProfile(update)
}
msg := tgbotapi.NewMessage(update.Message.Chat.ID, message)
@ -44,7 +46,7 @@ func (t *Talkers) groupWelcomeUser(update tgbotapi.Update) string {
return "ok"
}
func (t *Talkers) groupStartMessage(update tgbotapi.Update) string {
func (w *Welcomer) groupStartMessage(update tgbotapi.Update) string {
message := "*Бот Инстинкта приветствует этот чатик!*\n\n"
message += "На слубже здравого смысла с " + time.Now().Format("02.01.2006 15:04:05") + "."
@ -57,12 +59,10 @@ func (t *Talkers) groupStartMessage(update tgbotapi.Update) string {
}
// WelcomeMessage welcomes new user on group or bot itself
func (t *Talkers) WelcomeMessage(update tgbotapi.Update) string {
func (w *Welcomer) WelcomeMessage(update tgbotapi.Update) string {
if (update.Message.NewChatMember.UserName == "i2_bot") || (update.Message.NewChatMember.UserName == "i2_dev_bot") {
return t.groupStartMessage(update)
} else {
return t.groupWelcomeUser(update)
return w.groupStartMessage(update)
}
return "fail"
return w.groupWelcomeUser(update)
}

View File

@ -0,0 +1,15 @@
// i2_bot Instinct PokememBro Bot
// Copyright (c) 2017 Vladimir "fat0troll" Hodakov
package welcomerinterface
import (
// 3rd party
"github.com/go-telegram-bot-api/telegram-bot-api"
)
// WelcomerInterface implements Welcomer for importing via appcontex
type WelcomerInterface interface {
Init()
WelcomeMessage(update tgbotapi.Update) string
}