From 5c08899d256ab3c69a11d36b57dabc4b7123c5f5 Mon Sep 17 00:00:00 2001 From: Vladimir Hodakov Date: Mon, 13 Nov 2017 22:51:50 +0400 Subject: [PATCH] Work on squads, alerts on new user with empty or spy profile Closes #1 Closes #2 --- cmd/i2_bot/i2_bot.go | 2 + config.yml.example | 2 + lib/appcontext/appcontext.go | 7 ++ lib/config/config.go | 10 ++- lib/dbmapping/players.go | 1 - lib/dbmapping/squads.go | 24 +++++++ lib/dbmapping/squads_players.go | 18 +++++ lib/getters/chat.go | 44 +++++++++++++ .../gettersinterface/gettersinterface.go | 2 + lib/getters/player.go | 3 +- lib/migrations/20_create_squads.go | 65 +++++++++++++++++++ lib/migrations/migrations.go | 1 + lib/parsers/profile.go | 3 +- lib/router/group_request.go | 2 +- lib/router/private_request.go | 8 +++ lib/talkers/chats.go | 39 +++++++++++ lib/talkers/help.go | 1 + lib/talkers/pokedex.go | 8 +++ .../talkersinterface/talkersinterface.go | 2 +- lib/welcomer/exported.go | 31 +++++++++ lib/welcomer/notifications.go | 49 ++++++++++++++ .../welcome.go => welcomer/welcomer.go} | 20 +++--- .../welcomerinterface/welcomerinterface.go | 15 +++++ 23 files changed, 338 insertions(+), 19 deletions(-) create mode 100644 lib/dbmapping/squads.go create mode 100644 lib/dbmapping/squads_players.go create mode 100644 lib/migrations/20_create_squads.go create mode 100644 lib/talkers/chats.go create mode 100644 lib/welcomer/exported.go create mode 100644 lib/welcomer/notifications.go rename lib/{talkers/welcome.go => welcomer/welcomer.go} (83%) create mode 100644 lib/welcomer/welcomerinterface/welcomerinterface.go diff --git a/cmd/i2_bot/i2_bot.go b/cmd/i2_bot/i2_bot.go index fe982e5..328997d 100644 --- a/cmd/i2_bot/i2_bot.go +++ b/cmd/i2_bot/i2_bot.go @@ -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 diff --git a/config.yml.example b/config.yml.example index 0d3e589..147fd4e 100644 --- a/config.yml.example +++ b/config.yml.example @@ -6,3 +6,5 @@ database_connection: user: "i2_bot" password: "i2_bot" database: "i2_bot" +notifications: + group_id: "group_id" diff --git a/lib/appcontext/appcontext.go b/lib/appcontext/appcontext.go index 4167d07..438fa51 100644 --- a/lib/appcontext/appcontext.go +++ b/lib/appcontext/appcontext.go @@ -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") diff --git a/lib/config/config.go b/lib/config/config.go index 6e69e0a..ae33124 100644 --- a/lib/config/config.go +++ b/lib/config/config.go @@ -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 diff --git a/lib/dbmapping/players.go b/lib/dbmapping/players.go index dad549a..e6ff4ff 100644 --- a/lib/dbmapping/players.go +++ b/lib/dbmapping/players.go @@ -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"` diff --git a/lib/dbmapping/squads.go b/lib/dbmapping/squads.go new file mode 100644 index 0000000..33087f5 --- /dev/null +++ b/lib/dbmapping/squads.go @@ -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 +} diff --git a/lib/dbmapping/squads_players.go b/lib/dbmapping/squads_players.go new file mode 100644 index 0000000..61781f8 --- /dev/null +++ b/lib/dbmapping/squads_players.go @@ -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"` +} diff --git a/lib/getters/chat.go b/lib/getters/chat.go index cdab57a..d1ecdf8 100644 --- a/lib/getters/chat.go +++ b/lib/getters/chat.go @@ -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 diff --git a/lib/getters/gettersinterface/gettersinterface.go b/lib/getters/gettersinterface/gettersinterface.go index ede0a8b..cab612f 100644 --- a/lib/getters/gettersinterface/gettersinterface.go +++ b/lib/getters/gettersinterface/gettersinterface.go @@ -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) diff --git a/lib/getters/player.go b/lib/getters/player.go index d5b06c9..db48d38 100644 --- a/lib/getters/player.go +++ b/lib/getters/player.go @@ -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 diff --git a/lib/migrations/20_create_squads.go b/lib/migrations/20_create_squads.go new file mode 100644 index 0000000..1888c72 --- /dev/null +++ b/lib/migrations/20_create_squads.go @@ -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 +} diff --git a/lib/migrations/migrations.go b/lib/migrations/migrations.go index 1ff01be..3029d71 100644 --- a/lib/migrations/migrations.go +++ b/lib/migrations/migrations.go @@ -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 { diff --git a/lib/parsers/profile.go b/lib/parsers/profile.go index 32b5d4b..ad327dd 100644 --- a/lib/parsers/profile.go +++ b/lib/parsers/profile.go @@ -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" diff --git a/lib/router/group_request.go b/lib/router/group_request.go index 6d2f21c..2305f73 100644 --- a/lib/router/group_request.go +++ b/lib/router/group_request.go @@ -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 != "" { diff --git a/lib/router/private_request.go b/lib/router/private_request.go index 3076efc..598e5f5 100644 --- a/lib/router/private_request.go +++ b/lib/router/private_request.go @@ -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" } diff --git a/lib/talkers/chats.go b/lib/talkers/chats.go new file mode 100644 index 0000000..b1d1aad --- /dev/null +++ b/lib/talkers/chats.go @@ -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" +} diff --git a/lib/talkers/help.go b/lib/talkers/help.go index 21b4e22..5d16ddd 100644 --- a/lib/talkers/help.go +++ b/lib/talkers/help.go @@ -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" diff --git a/lib/talkers/pokedex.go b/lib/talkers/pokedex.go index 1710327..a66622d 100644 --- a/lib/talkers/pokedex.go +++ b/lib/talkers/pokedex.go @@ -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" diff --git a/lib/talkers/talkersinterface/talkersinterface.go b/lib/talkers/talkersinterface/talkersinterface.go index b8759b1..821b4e3 100644 --- a/lib/talkers/talkersinterface/talkersinterface.go +++ b/lib/talkers/talkersinterface/talkersinterface.go @@ -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) diff --git a/lib/welcomer/exported.go b/lib/welcomer/exported.go new file mode 100644 index 0000000..b0ab5d6 --- /dev/null +++ b/lib/welcomer/exported.go @@ -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...") +} diff --git a/lib/welcomer/notifications.go b/lib/welcomer/notifications.go new file mode 100644 index 0000000..09ac8c2 --- /dev/null +++ b/lib/welcomer/notifications.go @@ -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" +} diff --git a/lib/talkers/welcome.go b/lib/welcomer/welcomer.go similarity index 83% rename from lib/talkers/welcome.go rename to lib/welcomer/welcomer.go index 043112c..0eaa4c6 100644 --- a/lib/talkers/welcome.go +++ b/lib/welcomer/welcomer.go @@ -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) } diff --git a/lib/welcomer/welcomerinterface/welcomerinterface.go b/lib/welcomer/welcomerinterface/welcomerinterface.go new file mode 100644 index 0000000..4683a62 --- /dev/null +++ b/lib/welcomer/welcomerinterface/welcomerinterface.go @@ -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 +}