Archived
1

Broadcast message to all Instinkt players

Closes #7
This commit is contained in:
Vladimir Hodakov 2017-11-25 03:00:34 +04:00
parent b038d5b10d
commit ac0292ab6f
12 changed files with 81 additions and 50 deletions

View File

@ -7,17 +7,25 @@ import (
"github.com/go-telegram-bot-api/telegram-bot-api" "github.com/go-telegram-bot-api/telegram-bot-api"
"lab.pztrn.name/fat0troll/i2_bot/lib/dbmapping" "lab.pztrn.name/fat0troll/i2_bot/lib/dbmapping"
"strconv" "strconv"
"strings"
) )
// AdminBroadcastMessageCompose saves message for future broadcast // AdminBroadcastMessageCompose saves message for future broadcast
func (b *Broadcaster) AdminBroadcastMessageCompose(update *tgbotapi.Update, playerRaw *dbmapping.Player) string { func (b *Broadcaster) AdminBroadcastMessageCompose(update *tgbotapi.Update, playerRaw *dbmapping.Player) string {
broadcastingMessageBody := strings.Replace(update.Message.Text, "/send_all ", "", 1) broadcastingMessageBody := update.Message.CommandArguments()
messageRaw, ok := dbmapping.Broadcast{}, false
messageRaw, ok := b.createBroadcastMessage(playerRaw, broadcastingMessageBody, "all") switch update.Message.Command() {
case "send_all":
messageRaw, ok = b.createBroadcastMessage(playerRaw, broadcastingMessageBody, "all")
if !ok { if !ok {
return "fail" return "fail"
} }
case "send_league":
messageRaw, ok = b.createBroadcastMessage(playerRaw, broadcastingMessageBody, "league")
if !ok {
return "fail"
}
}
message := "Сообщение сохранено в базу.\n" message := "Сообщение сохранено в базу.\n"
message += "Выглядеть оно будет так:" message += "Выглядеть оно будет так:"
@ -36,7 +44,12 @@ func (b *Broadcaster) AdminBroadcastMessageCompose(update *tgbotapi.Update, play
c.Bot.Send(msg) c.Bot.Send(msg)
switch update.Message.Command() {
case "send_all":
message = "Чтобы отправить сообщение всем, отправь команду /send\\_confirm " + strconv.Itoa(messageRaw.ID) message = "Чтобы отправить сообщение всем, отправь команду /send\\_confirm " + strconv.Itoa(messageRaw.ID)
case "send_league":
message = "Чтобы отправить сообщение всем игрокам лиги Инстинкт, отправь команду /send\\_confirm " + strconv.Itoa(messageRaw.ID)
}
msg = tgbotapi.NewMessage(update.Message.Chat.ID, message) msg = tgbotapi.NewMessage(update.Message.Chat.ID, message)
msg.ParseMode = "Markdown" msg.ParseMode = "Markdown"

View File

@ -7,12 +7,11 @@ import (
"github.com/go-telegram-bot-api/telegram-bot-api" "github.com/go-telegram-bot-api/telegram-bot-api"
"lab.pztrn.name/fat0troll/i2_bot/lib/dbmapping" "lab.pztrn.name/fat0troll/i2_bot/lib/dbmapping"
"strconv" "strconv"
"strings"
) )
// AdminBroadcastMessageSend sends saved message to all private chats // AdminBroadcastMessageSend sends saved message to all private chats
func (b *Broadcaster) AdminBroadcastMessageSend(update *tgbotapi.Update, playerRaw *dbmapping.Player) string { func (b *Broadcaster) AdminBroadcastMessageSend(update *tgbotapi.Update, playerRaw *dbmapping.Player) string {
messageNum := strings.Replace(update.Message.Text, "/send_confirm ", "", 1) messageNum := update.Message.CommandArguments()
messageNumInt, _ := strconv.Atoi(messageNum) messageNumInt, _ := strconv.Atoi(messageNum)
messageRaw, ok := b.getBroadcastMessageByID(messageNumInt) messageRaw, ok := b.getBroadcastMessageByID(messageNumInt)
if !ok { if !ok {
@ -27,10 +26,19 @@ func (b *Broadcaster) AdminBroadcastMessageSend(update *tgbotapi.Update, playerR
broadcastingMessageBody := messageRaw.Text broadcastingMessageBody := messageRaw.Text
privateChats, ok := c.Chatter.GetAllPrivateChats() privateChats := []dbmapping.Chat{}
switch messageRaw.BroadcastType {
case "all":
privateChats, ok = c.Chatter.GetAllPrivateChats()
if !ok { if !ok {
return "fail" return "fail"
} }
case "league":
privateChats, ok = c.Chatter.GetLeaguePrivateChats()
if !ok {
return "fail"
}
}
for i := range privateChats { for i := range privateChats {
chat := privateChats[i] chat := privateChats[i]
@ -48,7 +56,7 @@ func (b *Broadcaster) AdminBroadcastMessageSend(update *tgbotapi.Update, playerR
return "fail" return "fail"
} }
message := "Сообщение всем отправлено. Надеюсь, пользователи бота за него тебя не убьют.\n" message := "Сообщение отправлено. Надеюсь, пользователи бота за него тебя не убьют.\n"
msg := tgbotapi.NewMessage(update.Message.Chat.ID, message) msg := tgbotapi.NewMessage(update.Message.Chat.ID, message)
msg.ParseMode = "Markdown" msg.ParseMode = "Markdown"

View File

@ -15,6 +15,7 @@ type ChatterInterface interface {
GetOrCreateChat(update *tgbotapi.Update) (dbmapping.Chat, bool) GetOrCreateChat(update *tgbotapi.Update) (dbmapping.Chat, bool)
GetChatByID(chatID int64) (dbmapping.Chat, bool) GetChatByID(chatID int64) (dbmapping.Chat, bool)
GetAllPrivateChats() ([]dbmapping.Chat, bool) GetAllPrivateChats() ([]dbmapping.Chat, bool)
GetLeaguePrivateChats() ([]dbmapping.Chat, bool)
GetAllGroupChats() ([]dbmapping.Chat, bool) GetAllGroupChats() ([]dbmapping.Chat, bool)
UpdateChatTitle(chatRaw *dbmapping.Chat, newTitle string) (*dbmapping.Chat, bool) UpdateChatTitle(chatRaw *dbmapping.Chat, newTitle string) (*dbmapping.Chat, bool)

View File

@ -115,6 +115,19 @@ func (ct *Chatter) GetAllPrivateChats() ([]dbmapping.Chat, bool) {
return privateChats, true return privateChats, true
} }
// GetLeaguePrivateChats returns all private chats which profiles are in our league
func (ct *Chatter) GetLeaguePrivateChats() ([]dbmapping.Chat, bool) {
privateChats := []dbmapping.Chat{}
err := c.Db.Select(&privateChats, "SELECT c.* FROM chats c, players p WHERE c.chat_type='private' AND p.telegram_id = c.telegram_id AND p.league_id = 1")
if err != nil {
c.Log.Error(err)
return privateChats, false
}
return privateChats, true
}
// GetAllGroupChats returns all group chats // GetAllGroupChats returns all group chats
func (ct *Chatter) GetAllGroupChats() ([]dbmapping.Chat, bool) { func (ct *Chatter) GetAllGroupChats() ([]dbmapping.Chat, bool) {
groupChats := []dbmapping.Chat{} groupChats := []dbmapping.Chat{}

View File

@ -22,8 +22,7 @@ func (f *Forwarder) ProcessForward(update *tgbotapi.Update, playerRaw *dbmapping
if playerRaw.LeagueID == 1 { if playerRaw.LeagueID == 1 {
return c.Pokedexer.ParsePokememe(update, playerRaw) return c.Pokedexer.ParsePokememe(update, playerRaw)
} else { } else {
c.Talkers.AnyMessageUnauthorized(update) return c.Talkers.AnyMessageUnauthorized(update)
return "fail"
} }
case profileMsg.MatchString(text): case profileMsg.MatchString(text):
c.Log.Debug("Profile posted!") c.Log.Debug("Profile posted!")

View File

@ -26,15 +26,14 @@ func (r *Router) routePrivateRequest(update *tgbotapi.Update, playerRaw *dbmappi
if playerRaw.ID != 0 { if playerRaw.ID != 0 {
c.Forwarder.ProcessForward(update, playerRaw) c.Forwarder.ProcessForward(update, playerRaw)
} else { } else {
c.Talkers.AnyMessageUnauthorized(update) return c.Talkers.AnyMessageUnauthorized(update)
return "fail"
} }
} }
} else { } else {
if update.Message.IsCommand() { if update.Message.IsCommand() {
switch { switch {
case update.Message.Command() == "start": case update.Message.Command() == "start":
if playerRaw.ID != 0 { if playerRaw.LeagueID != 0 {
c.Welcomer.PrivateWelcomeMessageAuthorized(update, playerRaw) c.Welcomer.PrivateWelcomeMessageAuthorized(update, playerRaw)
return "ok" return "ok"
} }
@ -56,8 +55,7 @@ func (r *Router) routePrivateRequest(update *tgbotapi.Update, playerRaw *dbmappi
return "ok" return "ok"
} }
c.Talkers.AnyMessageUnauthorized(update) return c.Talkers.AnyMessageUnauthorized(update)
return "fail"
case update.Message.Command() == "best": case update.Message.Command() == "best":
c.Pokedexer.BestPokememesList(update, playerRaw) c.Pokedexer.BestPokememesList(update, playerRaw)
return "ok" return "ok"
@ -67,24 +65,28 @@ func (r *Router) routePrivateRequest(update *tgbotapi.Update, playerRaw *dbmappi
return "ok" return "ok"
} }
c.Talkers.AnyMessageUnauthorized(update) return c.Talkers.AnyMessageUnauthorized(update)
return "fail" case update.Message.Command() == "send_league":
if c.Users.PlayerBetterThan(playerRaw, "admin") {
c.Broadcaster.AdminBroadcastMessageCompose(update, playerRaw)
return "ok"
}
return c.Talkers.AnyMessageUnauthorized(update)
case update.Message.Command() == "send_confirm": case update.Message.Command() == "send_confirm":
if c.Users.PlayerBetterThan(playerRaw, "admin") { if c.Users.PlayerBetterThan(playerRaw, "admin") {
c.Broadcaster.AdminBroadcastMessageSend(update, playerRaw) c.Broadcaster.AdminBroadcastMessageSend(update, playerRaw)
return "ok" return "ok"
} }
c.Talkers.AnyMessageUnauthorized(update) return c.Talkers.AnyMessageUnauthorized(update)
return "fail"
case update.Message.Command() == "group_chats": case update.Message.Command() == "group_chats":
if c.Users.PlayerBetterThan(playerRaw, "admin") { if c.Users.PlayerBetterThan(playerRaw, "admin") {
c.Chatter.GroupsList(update) c.Chatter.GroupsList(update)
return "ok" return "ok"
} }
c.Talkers.AnyMessageUnauthorized(update) return c.Talkers.AnyMessageUnauthorized(update)
return "fail"
case update.Message.Command() == "squads": case update.Message.Command() == "squads":
return c.Squader.SquadsList(update, playerRaw) return c.Squader.SquadsList(update, playerRaw)
case update.Message.Command() == "make_squad": case update.Message.Command() == "make_squad":
@ -92,23 +94,20 @@ func (r *Router) routePrivateRequest(update *tgbotapi.Update, playerRaw *dbmappi
return c.Squader.CreateSquad(update) return c.Squader.CreateSquad(update)
} }
c.Talkers.AnyMessageUnauthorized(update) return c.Talkers.AnyMessageUnauthorized(update)
return "fail"
case update.Message.Command() == "pin": case update.Message.Command() == "pin":
if c.Users.PlayerBetterThan(playerRaw, "admin") { if c.Users.PlayerBetterThan(playerRaw, "admin") {
return c.Pinner.PinMessageToAllChats(update) return c.Pinner.PinMessageToAllChats(update)
} }
c.Talkers.AnyMessageUnauthorized(update) return c.Talkers.AnyMessageUnauthorized(update)
return "fail"
case usersMsg.MatchString(text): case usersMsg.MatchString(text):
if c.Users.PlayerBetterThan(playerRaw, "admin") { if c.Users.PlayerBetterThan(playerRaw, "admin") {
return c.Users.UsersList(update) return c.Users.UsersList(update)
} }
c.Talkers.AnyMessageUnauthorized(update) return c.Talkers.AnyMessageUnauthorized(update)
return "fail"
case update.Message.Command() == "squad_add_user": case update.Message.Command() == "squad_add_user":
return c.Squader.AddUserToSquad(update, playerRaw) return c.Squader.AddUserToSquad(update, playerRaw)

View File

@ -14,8 +14,7 @@ import (
func (s *Squader) SquadsList(update *tgbotapi.Update, playerRaw *dbmapping.Player) string { func (s *Squader) SquadsList(update *tgbotapi.Update, playerRaw *dbmapping.Player) string {
if !c.Users.PlayerBetterThan(playerRaw, "admin") { if !c.Users.PlayerBetterThan(playerRaw, "admin") {
if s.isUserAnyCommander(playerRaw.ID) { if s.isUserAnyCommander(playerRaw.ID) {
c.Talkers.AnyMessageUnauthorized(update) return c.Talkers.AnyMessageUnauthorized(update)
return "fail"
} }
} }
squads, ok := s.getAllSquadsWithChats() squads, ok := s.getAllSquadsWithChats()
@ -53,15 +52,13 @@ func (s *Squader) SquadInfo(update *tgbotapi.Update, playerRaw *dbmapping.Player
if !c.Users.PlayerBetterThan(playerRaw, "admin") { if !c.Users.PlayerBetterThan(playerRaw, "admin") {
if s.getUserRoleForSquad(squadID, playerRaw.ID) != "commander" { if s.getUserRoleForSquad(squadID, playerRaw.ID) != "commander" {
c.Talkers.AnyMessageUnauthorized(update) return c.Talkers.AnyMessageUnauthorized(update)
return "fail"
} }
} }
squad, ok := s.GetSquadByID(squadID) squad, ok := s.GetSquadByID(squadID)
if !ok { if !ok {
c.Talkers.BotError(update) return c.Talkers.BotError(update)
return "fail"
} }
message := "*Информация об отряде* _" + squad.Chat.Name + "_*:*\n" message := "*Информация об отряде* _" + squad.Chat.Name + "_*:*\n"

View File

@ -292,13 +292,11 @@ func (s *Squader) AddUserToSquad(update *tgbotapi.Update, adderRaw *dbmapping.Pl
if !c.Users.PlayerBetterThan(adderRaw, "admin") { if !c.Users.PlayerBetterThan(adderRaw, "admin") {
if userType == "commander" { if userType == "commander" {
c.Talkers.AnyMessageUnauthorized(update) return c.Talkers.AnyMessageUnauthorized(update)
return "fail"
} }
if s.getUserRoleForSquad(squadRaw.ID, adderRaw.ID) != "commander" { if s.getUserRoleForSquad(squadRaw.ID, adderRaw.ID) != "commander" {
c.Talkers.AnyMessageUnauthorized(update) return c.Talkers.AnyMessageUnauthorized(update)
return "fail"
} }
} }

View File

@ -8,7 +8,7 @@ import (
) )
// AnyMessageUnauthorized throws when user can't do something // AnyMessageUnauthorized throws when user can't do something
func (t *Talkers) AnyMessageUnauthorized(update *tgbotapi.Update) { func (t *Talkers) AnyMessageUnauthorized(update *tgbotapi.Update) string {
message := "Извини, действие для тебя недоступно. Возможно, у меня нет твоего профиля или же твои права недостаточны для совершения данного действия\n\n" message := "Извини, действие для тебя недоступно. Возможно, у меня нет твоего профиля или же твои права недостаточны для совершения данного действия\n\n"
message += "Если тебе кажется, что это ошибка, пиши @fat0troll.\n" message += "Если тебе кажется, что это ошибка, пиши @fat0troll.\n"
@ -16,10 +16,12 @@ func (t *Talkers) AnyMessageUnauthorized(update *tgbotapi.Update) {
msg.ParseMode = "Markdown" msg.ParseMode = "Markdown"
c.Bot.Send(msg) c.Bot.Send(msg)
return "fail"
} }
// BotError throws when bot can't do something // BotError throws when bot can't do something
func (t *Talkers) BotError(update *tgbotapi.Update) { func (t *Talkers) BotError(update *tgbotapi.Update) string {
message := "Ой, внутренняя ошибка в боте :(\n\n" message := "Ой, внутренняя ошибка в боте :(\n\n"
message += "Напиши @fat0troll, приложив форвардом последние сообщения до этого.\n" message += "Напиши @fat0troll, приложив форвардом последние сообщения до этого.\n"
@ -27,4 +29,6 @@ func (t *Talkers) BotError(update *tgbotapi.Update) {
msg.ParseMode = "Markdown" msg.ParseMode = "Markdown"
c.Bot.Send(msg) c.Bot.Send(msg)
return "fail"
} }

View File

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

View File

@ -13,8 +13,8 @@ type TalkersInterface interface {
Init() Init()
HelpMessage(update *tgbotapi.Update, playerRaw *dbmapping.Player) HelpMessage(update *tgbotapi.Update, playerRaw *dbmapping.Player)
AnyMessageUnauthorized(update *tgbotapi.Update) AnyMessageUnauthorized(update *tgbotapi.Update) string
BotError(update *tgbotapi.Update) BotError(update *tgbotapi.Update) string
DurakMessage(update *tgbotapi.Update) DurakMessage(update *tgbotapi.Update)
MatMessage(update *tgbotapi.Update) MatMessage(update *tgbotapi.Update)

View File

@ -14,8 +14,7 @@ import (
func (u *Users) ProfileMessage(update *tgbotapi.Update, playerRaw *dbmapping.Player) string { func (u *Users) ProfileMessage(update *tgbotapi.Update, playerRaw *dbmapping.Player) string {
profileRaw, ok := u.GetProfile(playerRaw.ID) profileRaw, ok := u.GetProfile(playerRaw.ID)
if !ok { if !ok {
c.Talkers.AnyMessageUnauthorized(update) return c.Talkers.AnyMessageUnauthorized(update)
return "fail"
} }
league := dbmapping.League{} league := dbmapping.League{}
err := c.Db.Get(&league, c.Db.Rebind("SELECT * FROM leagues WHERE id=?"), playerRaw.LeagueID) err := c.Db.Get(&league, c.Db.Rebind("SELECT * FROM leagues WHERE id=?"), playerRaw.LeagueID)
@ -124,8 +123,7 @@ func (u *Users) UsersList(update *tgbotapi.Update) string {
} }
usersArray, ok := u.getUsersWithProfiles() usersArray, ok := u.getUsersWithProfiles()
if !ok { if !ok {
c.Talkers.BotError(update) return c.Talkers.BotError(update)
return "fail"
} else { } else {
u.usersList(update, page, usersArray) u.usersList(update, page, usersArray)
return "ok" return "ok"