diff --git a/Makefile b/Makefile index cd2abed..a507ec5 100644 --- a/Makefile +++ b/Makefile @@ -17,10 +17,10 @@ fmt: # Build localization files with separated untranslated strings translation: - goi18n merge -format yaml -sourceLanguage en-us -outdir ./i18n/ ./i18n/* + goi18n merge -format yaml -sourceLanguage en -outdir ./i18n/ ./i18n/*/* # Build localization files and merge untranslated strings localization: make translation - goi18n -format yaml -sourceLanguage en-us -outdir ./i18n/ ./i18n/*.all.yaml \ + goi18n -format yaml -sourceLanguage en -outdir ./i18n/ ./i18n/*.all.yaml \ ./i18n/*.untranslated.yaml \ No newline at end of file diff --git a/actions.go b/actions.go new file mode 100755 index 0000000..6dff3b7 --- /dev/null +++ b/actions.go @@ -0,0 +1,31 @@ +package main + +import ( + log "github.com/kirillDanshin/dlog" + tg "github.com/toby3d/telegram" +) + +// actions function check Message update on commands, sended stickers or other user stuff +func actions(msg *tg.Message) { + state, err := dbGetUserState(msg.From.ID) + errCheck(err) + + log.Ln("state:", state) + switch state { + case stateAddSticker: + actionAdd(msg, false) + case stateAddPack: + actionAdd(msg, true) + case stateDeleteSticker: + actionDelete(msg, false) + case stateDeletePack: + actionDelete(msg, true) + case stateReset: + actionReset(msg) + default: + err = dbChangeUserState(msg.From.ID, stateNone) + errCheck(err) + + actionError(msg) + } +} diff --git a/add.go b/add.go index d89bb13..6b964f9 100644 --- a/add.go +++ b/add.go @@ -1,18 +1,20 @@ package main import ( - log "github.com/kirillDanshin/dlog" // Insert logs only in debug builds - tg "github.com/toby3d/telegram" // My Telegram bindings + log "github.com/kirillDanshin/dlog" + tg "github.com/toby3d/telegram" ) func commandAdd(msg *tg.Message, pack bool) { - bot.SendChatAction(msg.Chat.ID, tg.ActionTyping) - T, err := switchLocale(msg.From.LanguageCode) errCheck(err) + _, err = bot.SendChatAction(msg.Chat.ID, tg.ActionTyping) + errCheck(err) + reply := tg.NewMessage(msg.Chat.ID, T("reply_add_sticker")) reply.ParseMode = tg.ModeMarkdown + reply.ReplyMarkup = getCancelButton(T) err = dbChangeUserState(msg.From.ID, stateAddSticker) errCheck(err) @@ -30,21 +32,44 @@ func commandAdd(msg *tg.Message, pack bool) { } func actionAdd(msg *tg.Message, pack bool) { - bot.SendChatAction(msg.Chat.ID, tg.ActionTyping) + if msg.Sticker == nil { + return + } T, err := switchLocale(msg.From.LanguageCode) errCheck(err) + _, err = bot.SendChatAction(msg.Chat.ID, tg.ActionTyping) + errCheck(err) + reply := tg.NewMessage(msg.Chat.ID, T("success_add_sticker")) reply.ParseMode = tg.ModeMarkdown - switch { - case pack && msg.Sticker.SetName == "": - reply.Text = T("error_empty_add_pack", map[string]interface{}{ - "AddStickerCommand": cmdAddSticker, - }) - case pack && msg.Sticker.SetName != "": - set, err := bot.GetStickerSet(msg.Sticker.SetName) + if !pack { + var exist bool + sticker := msg.Sticker + exist, err = dbAddSticker( + msg.From.ID, sticker.SetName, sticker.FileID, sticker.Emoji, + ) + errCheck(err) + + if exist { + reply.Text = T("error_already_add_sticker") + } + + reply.ReplyMarkup = getCancelButton(T) + _, err = bot.SendMessage(reply) + errCheck(err) + return + } + + reply.Text = T("error_empty_add_pack", map[string]interface{}{ + "AddStickerCommand": cmdAddSticker, + }) + + if msg.Sticker.SetName != "" { + var set *tg.StickerSet + set, err = bot.GetStickerSet(msg.Sticker.SetName) errCheck(err) log.Ln("SetTitle:", set.Title) @@ -54,64 +79,26 @@ func actionAdd(msg *tg.Message, pack bool) { allExists := true for _, sticker := range set.Stickers { - exists, err := dbAddSticker( - msg.From.ID, - sticker.SetName, - sticker.FileID, - sticker.Emoji, + var exist bool + exist, err = dbAddSticker( + msg.From.ID, sticker.SetName, sticker.FileID, sticker.Emoji, ) errCheck(err) - if !exists { + if !exist { allExists = false } } log.Ln("All exists?", allExists) - if allExists { reply.Text = T("error_already_add_pack", map[string]interface{}{ "SetTitle": set.Title, }) - } else { - markup := tg.NewInlineKeyboardMarkup( - tg.NewInlineKeyboardRow( - tg.NewInlineKeyboardButtonSwitch( - T("button_share"), - " ", - ), - ), - ) - reply.ReplyMarkup = &markup - } - default: - exists, err := dbAddSticker( - msg.From.ID, - msg.Sticker.SetName, - msg.Sticker.FileID, - msg.Sticker.Emoji, - ) - errCheck(err) - - if exists { - reply.Text = T("error_already_add_sticker") } - - if msg.Sticker.Emoji == "" { - msg.Sticker.Emoji = " " - } - - markup := tg.NewInlineKeyboardMarkup( - tg.NewInlineKeyboardRow( - tg.NewInlineKeyboardButtonSwitch( - T("button_share"), - msg.Sticker.Emoji, - ), - ), - ) - reply.ReplyMarkup = &markup } + reply.ReplyMarkup = getCancelButton(T) _, err = bot.SendMessage(reply) errCheck(err) } diff --git a/cancel.go b/cancel.go old mode 100644 new mode 100755 index f16f503..4d4150f --- a/cancel.go +++ b/cancel.go @@ -1,24 +1,27 @@ package main -import tg "github.com/toby3d/telegram" // My Telegram bindings +import tg "github.com/toby3d/telegram" func commandCancel(msg *tg.Message) { - bot.SendChatAction(msg.Chat.ID, tg.ActionTyping) - T, err := switchLocale(msg.From.LanguageCode) errCheck(err) state, err := dbGetUserState(msg.From.ID) errCheck(err) + _, err = bot.SendChatAction(msg.Chat.ID, tg.ActionTyping) + errCheck(err) + var text string switch state { case stateAddSticker: text = T("cancel_add_sticker") case stateAddPack: text = T("cancel_add_pack") - case stateDelete: - text = T("cancel_del") + case stateDeleteSticker: + text = T("cancel_del_sticker") + case stateDeletePack: + text = T("cancel_del_pack") case stateReset: text = T("cancel_reset") default: @@ -29,6 +32,8 @@ func commandCancel(msg *tg.Message) { errCheck(err) reply := tg.NewMessage(msg.Chat.ID, text) + reply.ReplyMarkup = getMenuKeyboard(T) + _, err = bot.SendMessage(reply) errCheck(err) } diff --git a/commands.go b/commands.go old mode 100644 new mode 100755 index 2aac03f..3eacf2c --- a/commands.go +++ b/commands.go @@ -3,22 +3,23 @@ package main import ( "strings" - log "github.com/kirillDanshin/dlog" // Insert logs only in debug builds - tg "github.com/toby3d/telegram" // My Telegram bindings + log "github.com/kirillDanshin/dlog" + tg "github.com/toby3d/telegram" ) const ( - cmdAddPack = "addPack" - cmdAddSticker = "addSticker" - cmdCancel = "cancel" - cmdHelp = "help" - cmdDelete = "del" - cmdReset = "reset" - cmdStart = "start" + cmdAddPack = "addPack" + cmdAddSticker = "addSticker" + cmdCancel = "cancel" + cmdHelp = "help" + cmdDeleteSticker = "delSticker" + cmdDeletePack = "delPack" + cmdReset = "reset" + cmdStart = "start" ) func commands(msg *tg.Message) { - log.Ln("Received a", msg.Command(), "command") + log.Ln("command:", msg.Command()) switch strings.ToLower(msg.Command()) { case strings.ToLower(cmdStart): commandStart(msg) @@ -28,8 +29,10 @@ func commands(msg *tg.Message) { commandAdd(msg, false) case strings.ToLower(cmdAddPack): commandAdd(msg, true) - case strings.ToLower(cmdDelete): - commandDelete(msg) + case strings.ToLower(cmdDeleteSticker): + commandDelete(msg, false) + case strings.ToLower(cmdDeletePack): + commandDelete(msg, true) case strings.ToLower(cmdReset): commandReset(msg) case strings.ToLower(cmdCancel): diff --git a/database.go b/database.go old mode 100644 new mode 100755 index a10e0aa..1d297f6 --- a/database.go +++ b/database.go @@ -5,21 +5,19 @@ import ( "strconv" "strings" - log "github.com/kirillDanshin/dlog" // Insert logs only in debug builds - "github.com/tidwall/buntdb" // Redis-like database + log "github.com/kirillDanshin/dlog" + "github.com/tidwall/buntdb" ) const ( - stateNone = "none" - stateAddSticker = "addSticker" - stateAddPack = "addPack" - stateDelete = "del" - stateReset = "reset" + stateNone = "none" + stateAddSticker = "addSticker" + stateAddPack = "addPack" + stateDeleteSticker = "delSticker" + stateDeletePack = "delPack" + stateReset = "reset" setUploaded = "?" - - patternUsers = "users" - patternUserSets = "user_sets" ) var db *buntdb.DB @@ -30,30 +28,6 @@ func dbInit() { db, err = buntdb.Open("stickers.db") errCheck(err) - log.Ln("Creating users index...") - err = db.CreateIndex( - patternUsers, // name - "user:*", // pattern - buntdb.IndexString, // options - ) - errCheck(err) - - log.Ln("Creating user_sets index...") - err = db.CreateIndex( - patternUserSets, // name - "user:*:set:*", // pattern - buntdb.IndexString, // options - ) - errCheck(err) - - err = db.Update(func(tx *buntdb.Tx) error { - return tx.AscendKeys("user:*:sticker:*", func(key, val string) bool { - tx.Delete(key) - return true - }) - }) - errCheck(err) - select {} } @@ -63,7 +37,6 @@ func dbGetUsers() ([]int, error) { return tx.AscendKeys( "user:*:state", func(key, val string) bool { - log.Ln(key, "=", val) subKeys := strings.Split(key, ":") id, err := strconv.Atoi(subKeys[1]) if err == nil { @@ -84,11 +57,7 @@ func dbGetUsers() ([]int, error) { func dbChangeUserState(userID int, state string) error { log.Ln("Trying to change", userID, "state to", state) return db.Update(func(tx *buntdb.Tx) error { - _, _, err := tx.Set( - fmt.Sprint("user:", userID, ":state"), // key - state, // val - nil, // options - ) + _, _, err := tx.Set(fmt.Sprint("user:", userID, ":state"), state, nil) return err }) } @@ -105,7 +74,7 @@ func dbGetUserState(userID int) (string, error) { switch err { case buntdb.ErrNotFound: log.Ln(userID, "not found, create new one") - if err := dbChangeUserState(userID, stateNone); err != nil { + if err = dbChangeUserState(userID, stateNone); err != nil { return state, err } } @@ -146,7 +115,9 @@ func dbDeleteSticker(userID int, setName, fileID string) (bool, error) { } err := db.Update(func(tx *buntdb.Tx) error { - _, err := tx.Delete(fmt.Sprint("user:", userID, ":set:", setName, ":sticker:", fileID)) + _, err := tx.Delete( + fmt.Sprint("user:", userID, ":set:", setName, ":sticker:", fileID), + ) return err }) @@ -159,13 +130,51 @@ func dbDeleteSticker(userID int, setName, fileID string) (bool, error) { return false, err } +func dbDeletePack(userID int, setName string) (bool, error) { + log.Ln("Trying to remove all", setName, "sticker from", userID, "user") + if setName == "" { + setName = setUploaded + } + + var fileIDs []string + err := db.View(func(tx *buntdb.Tx) error { + return tx.AscendKeys( + fmt.Sprint("user:", userID, ":set:", setName, ":*"), + func(key, val string) bool { + keys := strings.Split(key, ":") + fileIDs = append(fileIDs, keys[5]) + return true + }, + ) + }) + + if len(fileIDs) == 0 { + return true, nil + } + + for _, fileID := range fileIDs { + var notExist bool + notExist, err = dbDeleteSticker(userID, setName, fileID) + if err != nil { + return notExist, err + } + } + + switch err { + case buntdb.ErrNotFound: + log.Ln(userID, "not found") + return true, nil + } + + return false, err +} + func dbResetUserStickers(userID int) error { log.Ln("Trying reset all stickers of", userID, "user") return db.Update(func(tx *buntdb.Tx) error { var keys []string - - err := tx.AscendKeys( - patternUserSets, // index + if err := tx.AscendKeys( + fmt.Sprint("user:", userID, ":set:*"), // index func(key, val string) bool { // iterator subKeys := strings.Split(key, ":") if subKeys[1] == strconv.Itoa(userID) { @@ -173,19 +182,18 @@ func dbResetUserStickers(userID int) error { } return true }, - ) - if err != nil { + ); err != nil { return err } for i := range keys { - _, err = tx.Delete(keys[i]) + _, err := tx.Delete(keys[i]) if err != nil { break } } - return err + return nil }) } @@ -199,14 +207,12 @@ func dbGetUserStickers(userID, offset int, query string) ([]string, int, error) return tx.AscendKeys( fmt.Sprint("user:", userID, ":set:*"), // index func(key, val string) bool { // iterator - log.Ln(key, "=", val) subKeys := strings.Split(key, ":") if subKeys[1] != strconv.Itoa(userID) { return true } total++ - if count >= 51 { return true } @@ -215,8 +221,7 @@ func dbGetUserStickers(userID, offset int, query string) ([]string, int, error) return true } - if query != "" && - query != val { + if query != "" && !strings.Contains(query, val) { return true } diff --git a/delete.go b/delete.go old mode 100644 new mode 100755 index 3543815..a78abae --- a/delete.go +++ b/delete.go @@ -1,64 +1,91 @@ package main -import tg "github.com/toby3d/telegram" // My Telegram bindings - -func commandDelete(msg *tg.Message) { - bot.SendChatAction(msg.Chat.ID, tg.ActionTyping) +import ( + log "github.com/kirillDanshin/dlog" + tg "github.com/toby3d/telegram" +) +func commandDelete(msg *tg.Message, pack bool) { T, err := switchLocale(msg.From.LanguageCode) errCheck(err) _, total, err := dbGetUserStickers(msg.From.ID, 0, "") errCheck(err) + _, err = bot.SendChatAction(msg.Chat.ID, tg.ActionTyping) + errCheck(err) + if total <= 0 { err = dbChangeUserState(msg.From.ID, stateNone) errCheck(err) - reply := tg.NewMessage(msg.Chat.ID, T("error_empty_remove")) + reply := tg.NewMessage(msg.Chat.ID, T("error_empty_del")) + reply.ReplyMarkup = getMenuKeyboard(T) _, err = bot.SendMessage(reply) errCheck(err) return } - err = dbChangeUserState(msg.From.ID, stateDelete) + reply := tg.NewMessage(msg.Chat.ID, T("reply_del_sticker")) + reply.ParseMode = tg.ModeMarkdown + reply.ReplyMarkup = getCancelButton(T) + + err = dbChangeUserState(msg.From.ID, stateDeleteSticker) errCheck(err) - markup := tg.NewInlineKeyboardMarkup( - tg.NewInlineKeyboardRow( - tg.NewInlineKeyboardButtonSwitchSelf( - T("button_remove"), - " ", - ), - ), - ) + if pack { + err = dbChangeUserState(msg.From.ID, stateDeletePack) + errCheck(err) - reply := tg.NewMessage(msg.Chat.ID, T("reply_remove")) - reply.ParseMode = tg.ModeMarkdown - reply.ReplyMarkup = &markup + reply.Text = T("reply_del_pack") + } _, err = bot.SendMessage(reply) errCheck(err) + + _, err = bot.SendChatAction(msg.Chat.ID, tg.ActionTyping) + errCheck(err) + + reply = tg.NewMessage(msg.Chat.ID, T("reply_switch_button")) + reply.ReplyMarkup = getSwitchButton(T) + _, err = bot.SendMessage(reply) + errCheck(err) } -func actionDelete(msg *tg.Message) { - bot.SendChatAction(msg.Chat.ID, tg.ActionTyping) +func actionDelete(msg *tg.Message, pack bool) { + if msg.Sticker == nil { + return + } T, err := switchLocale(msg.From.LanguageCode) errCheck(err) - notExist, err := dbDeleteSticker( - msg.From.ID, - msg.Sticker.SetName, - msg.Sticker.FileID, - ) + _, err = bot.SendChatAction(msg.Chat.ID, tg.ActionTyping) errCheck(err) - reply := tg.NewMessage(msg.Chat.ID, T("success_remove")) + reply := tg.NewMessage(msg.Chat.ID, T("success_del_sticker")) reply.ParseMode = tg.ModeMarkdown + reply.ReplyMarkup = getCancelButton(T) + + var notExist bool + if pack { + var set *tg.StickerSet + set, err = bot.GetStickerSet(msg.Sticker.SetName) + errCheck(err) + + log.Ln("SetName:", set.Title) + reply.Text = T("success_del_pack", map[string]interface{}{ + "SetTitle": set.Title, + }) + + notExist, err = dbDeletePack(msg.From.ID, msg.Sticker.SetName) + } else { + notExist, err = dbDeleteSticker(msg.From.ID, msg.Sticker.SetName, msg.Sticker.FileID) + } + errCheck(err) if notExist { - reply.Text = T("error_already_remove") + reply.Text = T("error_already_del") } _, err = bot.SendMessage(reply) diff --git a/error.go b/error.go new file mode 100644 index 0000000..5f2052c --- /dev/null +++ b/error.go @@ -0,0 +1,25 @@ +package main + +import tg "github.com/toby3d/telegram" + +func actionError(msg *tg.Message) { + T, err := switchLocale(msg.From.LanguageCode) + errCheck(err) + + _, err = bot.SendChatAction(msg.Chat.ID, tg.ActionTyping) + errCheck(err) + + reply := tg.NewMessage( + msg.Chat.ID, T("error_unknown", map[string]interface{}{ + "AddStickerCommand": cmdAddSticker, + "AddPackCommand": cmdAddPack, + "DeleteStickerCommand": cmdDeleteSticker, + "DeletePackCommand": cmdDeletePack, + }), + ) + reply.ParseMode = tg.ModeMarkdown + reply.ReplyMarkup = getMenuKeyboard(T) + + _, err = bot.SendMessage(reply) + errCheck(err) +} diff --git a/get_updates_channel.go b/get_updates_channel.go index 428274c..76f51ab 100644 --- a/get_updates_channel.go +++ b/get_updates_channel.go @@ -3,8 +3,8 @@ package main import ( "fmt" - log "github.com/kirillDanshin/dlog" // Insert logs only in debug builds - tg "github.com/toby3d/telegram" // My Telegram bindings + log "github.com/kirillDanshin/dlog" + tg "github.com/toby3d/telegram" ) // allowedUpdates is a value for parameter of updates configuration diff --git a/help.go b/help.go old mode 100644 new mode 100755 index fcce82d..d6bf435 --- a/help.go +++ b/help.go @@ -1,37 +1,30 @@ package main -import tg "github.com/toby3d/telegram" // My Telegram bindings +import tg "github.com/toby3d/telegram" func commandHelp(msg *tg.Message) { - bot.SendChatAction(msg.Chat.ID, tg.ActionTyping) - - err := dbChangeUserState(msg.From.ID, stateNone) + T, err := switchLocale(msg.From.LanguageCode) errCheck(err) - T, err := switchLocale(msg.From.LanguageCode) + err = dbChangeUserState(msg.From.ID, stateNone) errCheck(err) - markup := tg.NewInlineKeyboardMarkup( - tg.NewInlineKeyboardRow( - tg.NewInlineKeyboardButtonSwitch( - T("button_share"), - " ", - ), - ), - ) + _, err = bot.SendChatAction(msg.Chat.ID, tg.ActionTyping) + errCheck(err) reply := tg.NewMessage( msg.Chat.ID, T("reply_help", map[string]interface{}{ - "AddStickerCommand": cmdAddSticker, - "AddPackCommand": cmdAddPack, - "DeleteCommand": cmdDelete, - "ResetCommand": cmdReset, - "CancelCommand": cmdCancel, - "Username": bot.Self.Username, + "AddStickerCommand": cmdAddSticker, + "AddPackCommand": cmdAddPack, + "DeleteStickerCommand": cmdDeleteSticker, + "DeletePackCommand": cmdDeletePack, + "ResetCommand": cmdReset, + "CancelCommand": cmdCancel, + "Username": bot.Self.Username, }), ) reply.ParseMode = tg.ModeMarkdown - reply.ReplyMarkup = &markup + reply.ReplyMarkup = getMenuKeyboard(T) _, err = bot.SendMessage(reply) errCheck(err) diff --git a/helpers.go b/helpers.go new file mode 100644 index 0000000..813c0a0 --- /dev/null +++ b/helpers.go @@ -0,0 +1,58 @@ +package main + +import ( + "github.com/nicksnyder/go-i18n/i18n" + tg "github.com/toby3d/telegram" + "golang.org/x/text/runes" + "golang.org/x/text/transform" +) + +var bannedSkins = []rune{127995, 127996, 127997, 127998, 127999} + +var skinRemover = runes.Remove(runes.Predicate( + func(r rune) bool { + for _, skin := range bannedSkins { + if r == skin { + return true + } + } + return false + }, +)) + +func getMenuKeyboard(T i18n.TranslateFunc) *tg.ReplyKeyboardMarkup { + return tg.NewReplyKeyboardMarkup( + tg.NewReplyKeyboardRow( + tg.NewReplyKeyboardButton(T("button_add_sticker")), + tg.NewReplyKeyboardButton(T("button_add_pack")), + ), + tg.NewReplyKeyboardRow( + tg.NewReplyKeyboardButton(T("button_del_sticker")), + tg.NewReplyKeyboardButton(T("button_del_pack")), + ), + tg.NewReplyKeyboardRow( + tg.NewReplyKeyboardButton(T("button_reset")), + ), + ) +} + +func getCancelButton(T i18n.TranslateFunc) *tg.ReplyKeyboardMarkup { + return tg.NewReplyKeyboardMarkup( + tg.NewReplyKeyboardRow( + tg.NewReplyKeyboardButton(T("button_cancel")), + ), + ) +} + +func getSwitchButton(T i18n.TranslateFunc) *tg.InlineKeyboardMarkup { + return tg.NewInlineKeyboardMarkup( + tg.NewInlineKeyboardRow( + tg.NewInlineKeyboardButtonSwitchSelf(T("button_inline_select"), " "), + ), + ) +} + +func fixEmoji(raw string) (string, error) { + result, _, err := transform.String(skinRemover, raw) + return result, err +} diff --git a/i18n/en-us.buttons.yaml b/i18n/en-us.buttons.yaml deleted file mode 100644 index f740b19..0000000 --- a/i18n/en-us.buttons.yaml +++ /dev/null @@ -1,11 +0,0 @@ -button_inline_empty: - other: Your pack is empty -button_inline_nothing: - other: Not found stickers for {{.Query}}, add one? -button_inline_add: - one: You have {{.Count}} sticker. Add one more? - other: You have {{.Count}} stickers. Add one more? -button_remove: - other: Select sticker for remove -button_share: - other: Use your stickers pack! \ No newline at end of file diff --git a/i18n/en-us.cancel.yaml b/i18n/en-us.cancel.yaml deleted file mode 100644 index d18a347..0000000 --- a/i18n/en-us.cancel.yaml +++ /dev/null @@ -1,10 +0,0 @@ -cancel_add_sticker: - other: You cancelled the process of adding a new sticker to your pack. -cancel_add_pack: - other: You cancelled the process of adding a new pack to yours. -cancel_del: - other: You cancelled the process of removing a sticker from your pack. -cancel_reset: - other: You cancelled the process of reseting your stickers pack. -cancel_error: - other: Nothing to cancel. \ No newline at end of file diff --git a/i18n/en-us.meta.yaml b/i18n/en-us.meta.yaml deleted file mode 100644 index 294be8f..0000000 --- a/i18n/en-us.meta.yaml +++ /dev/null @@ -1,6 +0,0 @@ -meta_reset_1: - other: Wait. Who are you? -meta_reset_2: - other: What are you doing here? -meta_reset_3: - other: What am I doing here? \ No newline at end of file diff --git a/i18n/en-us.all.yaml b/i18n/en.all.yaml old mode 100644 new mode 100755 similarity index 60% rename from i18n/en-us.all.yaml rename to i18n/en.all.yaml index e306635..700e1ac --- a/i18n/en-us.all.yaml +++ b/i18n/en.all.yaml @@ -1,37 +1,45 @@ -button_inline_add: - one: You have {{.Count}} sticker. Add one more? - other: You have {{.Count}} stickers. Add one more? +button_add_pack: + other: "\U0001F4E6 Add pack" +button_add_sticker: + other: ➕ Add sticker +button_cancel: + other: ❌ Cancel +button_del_pack: + other: "\U0001F5D1 Delete pack" +button_del_sticker: + other: "\U0001F5D1 Delete sticker" button_inline_empty: other: Your pack is empty button_inline_nothing: - other: Not found stickers for {{.Query}}, add one? -button_remove: - other: Select sticker for remove + other: Not found stickers for {{.Query}} +button_inline_search: + one: You have {{.Count}} sticker + other: You have {{.Count}} stickers +button_inline_select: + other: Select sticker +button_reset: + other: "\U0001F525 Reset pack" button_share: other: Use your stickers pack! -cancel_add: - other: You cancelled the process of adding a new sticker to your pack. cancel_add_pack: - other: You cancelled the process of adding a new pack to yours. + other: You cancelled the process of adding a new packs to yours. cancel_add_sticker: - other: You cancelled the process of adding a new sticker to your pack. -cancel_del: - other: You cancelled the process of removing a sticker from your pack. + other: You cancelled the process of adding a new stickers to your pack. +cancel_del_pack: + other: You cancelled the process of removing a sticker packs from yours. +cancel_del_sticker: + other: You cancelled the process of removing a stickers from your pack. cancel_error: other: Nothing to cancel. -cancel_remove: - other: You cancelled the process of removing a sticker from your pack. cancel_reset: other: You cancelled the process of reseting your stickers pack. -error_already_add: - other: This sticker is already in your pack. error_already_add_pack: other: All stickers from *{{.SetTitle}}* pack is already in yours. error_already_add_sticker: other: This sticker is already in your pack. -error_already_del: - other: Maybe this sticker is already removed from your pack. -error_already_remove: +error_already_del_pack: + other: Maybe this pack is already removed from yours. +error_already_del_sticker: other: Maybe this sticker is already removed from your pack. error_already_reset: other: There is nothing to reset, pack is already empty. @@ -40,40 +48,33 @@ error_empty_add_pack: instead. error_empty_del: other: There is nothing to remove, pack is empty. -error_empty_remove: - other: There is nothing to remove, pack is empty. error_reset_phrase: other: Invalid phrase of resetting. This action has been canceled. error_unknown: other: |- I do not know what to do with this sticker. - Please run /{{.AddStickerCommand}}, /{{.AddPackCommand}} or /{{.DeleteCommand}} command first. -meta_reset_1: - other: Wait. Who are you? -meta_reset_2: - other: What are you doing here? -meta_reset_3: - other: What am I doing here? -reply_add: - other: Send an existing sticker from any other pack to add it to yourself. + Please run /{{.AddStickerCommand}}, /{{.AddPackCommand}}, /{{.DeleteStickerCommand}} or /{{.DeletePackCommand}} command first. +key_phrase: + other: Yes, I am totally sure. reply_add_pack: other: Send an existing stickers from any other packs to add the entire packs to yourself. reply_add_sticker: other: Send an existing stickers from any other packs to add it to yourself. -reply_del: +reply_del_pack: + other: Send an existing stickers from your pack to delete its entire set. +reply_del_sticker: other: Send an existing stickers from your pack for removing it. reply_help: - other: |- + other: | /{{.AddStickerCommand}} - add a single sticker to your pack /{{.AddPackCommand}} - add a full other pack to your pack - /{{.DeleteCommand}} - remove a single sticker from your pack + /{{.DeleteStickerCommand}} - remove a single sticker from your pack + /{{.DeletePackCommand}} - remove a sticker set from your pack /{{.ResetCommand}} - remove all stickers from your pack /{{.CancelCommand}} - cancel the current operation To view and send stickers from your pack, just type `@{{.Username}}` (and space) in any chat. -reply_remove: - other: Send an existing sticker from your pack for removing it. reply_reset: other: | This operation will remove *all* stickers from your pack and *this can't be undone*. @@ -85,15 +86,16 @@ reply_start: Hello, I'm the [@{{.Username}}](tg://user?id={{.ID}})! I can create your personal pack with stickers from others packs. Without limits and installing. In any chat. For free. -success_add: - other: The sticker was successfully added to your pack! +reply_switch_button: + other: This button will help you quickly call your pack to select the sticker you + want. success_add_pack: other: The sticker pack *{{.SetTitle}}* was successfully added to yours! success_add_sticker: other: The sticker was successfully added to your pack! -success_del: - other: The sticker was successfully removed from your pack! -success_remove: +success_del_pack: + other: The sticker pack *{{.SetTitle}}* was successfully removed from yours! +success_del_sticker: other: The sticker was successfully removed from your pack! success_reset: other: The contents of your pack are completely reset!.. diff --git a/i18n/en-us.untranslated.yaml b/i18n/en.untranslated.yaml similarity index 100% rename from i18n/en-us.untranslated.yaml rename to i18n/en.untranslated.yaml diff --git a/i18n/en/en.buttons.yaml b/i18n/en/en.buttons.yaml new file mode 100644 index 0000000..8de869f --- /dev/null +++ b/i18n/en/en.buttons.yaml @@ -0,0 +1,23 @@ +button_inline_empty: + other: Your pack is empty +button_inline_nothing: + other: Not found stickers for {{.Query}} +button_inline_search: + one: You have {{.Count}} sticker + other: You have {{.Count}} stickers +button_inline_select: + other: Select sticker +button_share: + other: Use your stickers pack! +button_add_sticker: + other: ➕ Add sticker +button_add_pack: + other: 📦 Add pack +button_del_sticker: + other: 🗑 Delete sticker +button_del_pack: + other: 🗑 Delete pack +button_reset: + other: 🔥 Reset pack +button_cancel: + other: ❌ Cancel \ No newline at end of file diff --git a/i18n/en/en.cancel.yaml b/i18n/en/en.cancel.yaml new file mode 100755 index 0000000..8ef2eb3 --- /dev/null +++ b/i18n/en/en.cancel.yaml @@ -0,0 +1,12 @@ +cancel_add_sticker: + other: You cancelled the process of adding a new stickers to your pack. +cancel_add_pack: + other: You cancelled the process of adding a new packs to yours. +cancel_del_sticker: + other: You cancelled the process of removing a stickers from your pack. +cancel_del_pack: + other: You cancelled the process of removing a sticker packs from yours. +cancel_reset: + other: You cancelled the process of reseting your stickers pack. +cancel_error: + other: Nothing to cancel. \ No newline at end of file diff --git a/i18n/en-us.errors.yaml b/i18n/en/en.errors.yaml similarity index 73% rename from i18n/en-us.errors.yaml rename to i18n/en/en.errors.yaml index d6f3fa7..e7377c3 100644 --- a/i18n/en-us.errors.yaml +++ b/i18n/en/en.errors.yaml @@ -2,8 +2,10 @@ error_already_add_sticker: other: This sticker is already in your pack. error_already_add_pack: other: All stickers from *{{.SetTitle}}* pack is already in yours. -error_already_del: +error_already_del_sticker: other: Maybe this sticker is already removed from your pack. +error_already_del_pack: + other: Maybe this pack is already removed from yours. error_already_reset: other: There is nothing to reset, pack is already empty. error_reset_phrase: @@ -15,4 +17,4 @@ error_empty_add_pack: error_unknown: other: | I do not know what to do with this sticker. - Please run /{{.AddStickerCommand}}, /{{.AddPackCommand}} or /{{.DeleteCommand}} command first. \ No newline at end of file + Please run /{{.AddStickerCommand}}, /{{.AddPackCommand}}, /{{.DeleteStickerCommand}} or /{{.DeletePackCommand}} command first. \ No newline at end of file diff --git a/i18n/en-us.replies.yaml b/i18n/en/en.replies.yaml old mode 100644 new mode 100755 similarity index 73% rename from i18n/en-us.replies.yaml rename to i18n/en/en.replies.yaml index b7e9121..ea6677b --- a/i18n/en-us.replies.yaml +++ b/i18n/en/en.replies.yaml @@ -7,8 +7,10 @@ reply_add_sticker: other: Send an existing stickers from any other packs to add it to yourself. reply_add_pack: other: Send an existing stickers from any other packs to add the entire packs to yourself. -reply_del: +reply_del_sticker: other: Send an existing stickers from your pack for removing it. +reply_del_pack: + other: Send an existing stickers from your pack to delete its entire set. reply_reset: other: | This operation will remove *all* stickers from your pack and *this can't be undone*. @@ -19,8 +21,11 @@ reply_help: other: | /{{.AddStickerCommand}} - add a single sticker to your pack /{{.AddPackCommand}} - add a full other pack to your pack - /{{.DeleteCommand}} - remove a single sticker from your pack + /{{.DeleteStickerCommand}} - remove a single sticker from your pack + /{{.DeletePackCommand}} - remove a sticker set from your pack /{{.ResetCommand}} - remove all stickers from your pack /{{.CancelCommand}} - cancel the current operation - To view and send stickers from your pack, just type `@{{.Username}}` (and space) in any chat. \ No newline at end of file + To view and send stickers from your pack, just type `@{{.Username}}` (and space) in any chat. +reply_switch_button: + other: This button will help you quickly call your pack to select the sticker you want. \ No newline at end of file diff --git a/i18n/en-us.success.yaml b/i18n/en/en.success.yaml old mode 100644 new mode 100755 similarity index 72% rename from i18n/en-us.success.yaml rename to i18n/en/en.success.yaml index 76074fa..80a15fe --- a/i18n/en-us.success.yaml +++ b/i18n/en/en.success.yaml @@ -2,7 +2,9 @@ success_add_sticker: other: The sticker was successfully added to your pack! success_add_pack: other: The sticker pack *{{.SetTitle}}* was successfully added to yours! -success_del: +success_del_sticker: other: The sticker was successfully removed from your pack! +success_del_pack: + other: The sticker pack *{{.SetTitle}}* was successfully removed from yours! success_reset: other: The contents of your pack are completely reset!.. \ No newline at end of file diff --git a/i18n/en/en.yaml b/i18n/en/en.yaml new file mode 100644 index 0000000..530ead7 --- /dev/null +++ b/i18n/en/en.yaml @@ -0,0 +1,2 @@ +key_phrase: + other: Yes, I am totally sure. \ No newline at end of file diff --git a/i18n/ru.all.yaml b/i18n/ru.all.yaml new file mode 100755 index 0000000..6211331 --- /dev/null +++ b/i18n/ru.all.yaml @@ -0,0 +1,101 @@ +button_add_pack: + other: "\U0001F4E6 Добавить набор" +button_add_sticker: + other: ➕ Добавить стикер +button_cancel: + other: ❌ Отменить +button_del_pack: + other: "\U0001F5D1 Удалить набор" +button_del_sticker: + other: "\U0001F5D1 Удалить стикер" +button_inline_empty: + other: Твой набор пуст +button_inline_nothing: + other: Не найдены стикеры для {{.Query}} +button_inline_search: + few: У тебя {{.Count}} стикера + many: У тебя {{.Count}} стикеров + one: У тебя {{.Count}} стикер + other: У тебя {{.Count}} стикеров +button_inline_select: + other: Выбрать стикер +button_reset: + other: "\U0001F525 Сбросить набор" +button_share: + other: Воспользоваться твоим набором! +cancel_add_pack: + other: Ты отменил процесс добавления новых наборов в твой. +cancel_add_sticker: + other: Ты отменил процесс добавления новых стикеров в твой набор. +cancel_del_pack: + other: Ты отменил процесс удаления наборов из твоего набора. +cancel_del_sticker: + other: Ты отменил процесс удаления стикера из твоего набора. +cancel_error: + other: Нечего отменять. +cancel_reset: + other: Ты отменил процесс сброса твоего набора. +error_already_add_pack: + other: Все стикеры *{{.SetTitle}}* уже в твоём наборе. +error_already_add_sticker: + other: Этот стикер уже в твоём наборе. +error_already_del_pack: + other: Вероятно этот набор уже удалён из твоего. +error_already_del_sticker: + other: Вероятно этот стикер уже удалён из твоего набора. +error_already_reset: + other: Нечего сбрасывать, набор уже пуст. +error_empty_add_pack: + other: Кажется ты пытаешься добавить собственный стикер. Используй для этого /{{.AddStickerCommand}}. +error_empty_del: + other: Нечего удалять, набор уже пуст. +error_reset_phrase: + other: Неправильная фраза для сброса. Действие было отменено. +error_unknown: + other: |- + Я понятия не имею что делать с этим стикером. + Пожалуйста, сначала примени /{{.AddStickerCommand}}, /{{.AddPackCommand}}, /{{.DeleteStickerCommand}} или /{{.DeletePackCommand}}. +key_phrase: + other: Да, я абсолютно уверен. +reply_add_pack: + other: Пришли стикеры из любых других наборов чтобы целиком добавить их наборы в + свой. +reply_add_sticker: + other: Пришли стикеры из любых других наборов чтобы по-одному добавить их в свой. +reply_del_pack: + other: Пришли стикер из своего набора чтобы удалить весь его набор. +reply_del_sticker: + other: Пришли стикер из своего набора чтобы удалить его. +reply_help: + other: | + /{{.AddStickerCommand}} - по-одному добавляет стикеры в твой набор + /{{.AddPackCommand}} - добавляет сразу весь набор в твой + /{{.DeleteStickerCommand}} - по-одному удаляет стикер из твоего набора + /{{.DeletePackCommand}} - удаляет набор стикеров из твоего набора + /{{.ResetCommand}} - удаляет все стикеры из твоего набора + /{{.CancelCommand}} - отменяет текущую операцию + + Для просмотра и отправки стикеров из твоего набора просто набери `@{{.Username}}` (и пробел) в любом чате. +reply_reset: + other: | + Эта операция удалит *все* стикеры из твоего набора и *это не может быть отменено*. + + Напиши `{{.KeyPhrase}}` чтобы подтвердить своё намерение обнулить мои мозги (о боже зачем). + Или используй /{{.CancelCommand}} чтобы отменить текущую операцию. +reply_start: + other: | + Привет, я [@{{.Username}}](tg://user?id={{.ID}})! + Я могу создать твой персональный набор стикеров из других наборов. + Без ограничений и установки. В любых чатах. Бесплатно. +reply_switch_button: + other: Эта кнопка поможет тебе быстро вызвать твой набор для выбора нужного стикера. +success_add_pack: + other: Набор *{{.SetTitle}}* успешно добавлен в твой! +success_add_sticker: + other: Стикер успешно добавлен в твой набор! +success_del_pack: + other: Набор *{{.SetTitle}}* успешно удалён из твоего набора! +success_del_sticker: + other: Стикер успешно удалён из твоего набора! +success_reset: + other: Сброс твоего набора успешно произведён!.. diff --git a/i18n/ru.untranslated.yaml b/i18n/ru.untranslated.yaml new file mode 100644 index 0000000..0967ef4 --- /dev/null +++ b/i18n/ru.untranslated.yaml @@ -0,0 +1 @@ +{} diff --git a/i18n/ru/ru.buttons.yaml b/i18n/ru/ru.buttons.yaml new file mode 100644 index 0000000..4ca71ea --- /dev/null +++ b/i18n/ru/ru.buttons.yaml @@ -0,0 +1,25 @@ +button_inline_empty: + other: Твой набор пуст +button_inline_nothing: + other: Не найдены стикеры для {{.Query}} +button_inline_search: + few: У тебя {{.Count}} стикера + one: У тебя {{.Count}} стикер + many: У тебя {{.Count}} стикеров + other: У тебя {{.Count}} стикеров +button_inline_select: + other: Выбрать стикер +button_share: + other: Воспользоваться твоим набором! +button_add_sticker: + other: ➕ Добавить стикер +button_add_pack: + other: 📦 Добавить набор +button_del_sticker: + other: 🗑 Удалить стикер +button_del_pack: + other: 🗑 Удалить набор +button_reset: + other: 🔥 Сбросить набор +button_cancel: + other: ❌ Отменить \ No newline at end of file diff --git a/i18n/ru/ru.cancel.yaml b/i18n/ru/ru.cancel.yaml new file mode 100755 index 0000000..6ac9604 --- /dev/null +++ b/i18n/ru/ru.cancel.yaml @@ -0,0 +1,12 @@ +cancel_add_sticker: + other: Ты отменил процесс добавления новых стикеров в твой набор. +cancel_add_pack: + other: Ты отменил процесс добавления новых наборов в твой. +cancel_del_sticker: + other: Ты отменил процесс удаления стикера из твоего набора. +cancel_del_pack: + other: Ты отменил процесс удаления наборов из твоего набора. +cancel_reset: + other: Ты отменил процесс сброса твоего набора. +cancel_error: + other: Нечего отменять. \ No newline at end of file diff --git a/i18n/ru/ru.errors.yaml b/i18n/ru/ru.errors.yaml new file mode 100755 index 0000000..99a1bcb --- /dev/null +++ b/i18n/ru/ru.errors.yaml @@ -0,0 +1,20 @@ +error_already_add_sticker: + other: Этот стикер уже в твоём наборе. +error_already_add_pack: + other: Все стикеры *{{.SetTitle}}* уже в твоём наборе. +error_already_del_sticker: + other: Вероятно этот стикер уже удалён из твоего набора. +error_already_del_pack: + other: Вероятно этот набор уже удалён из твоего. +error_already_reset: + other: Нечего сбрасывать, набор уже пуст. +error_reset_phrase: + other: Неправильная фраза для сброса. Действие было отменено. +error_empty_del: + other: Нечего удалять, набор уже пуст. +error_empty_add_pack: + other: Кажется ты пытаешься добавить собственный стикер. Используй для этого /{{.AddStickerCommand}}. +error_unknown: + other: | + Я понятия не имею что делать с этим стикером. + Пожалуйста, сначала примени /{{.AddStickerCommand}}, /{{.AddPackCommand}}, /{{.DeleteStickerCommand}} или /{{.DeletePackCommand}}. \ No newline at end of file diff --git a/i18n/ru/ru.replies.yaml b/i18n/ru/ru.replies.yaml new file mode 100755 index 0000000..0530cd7 --- /dev/null +++ b/i18n/ru/ru.replies.yaml @@ -0,0 +1,31 @@ +reply_start: + other: | + Привет, я [@{{.Username}}](tg://user?id={{.ID}})! + Я могу создать твой персональный набор стикеров из других наборов. + Без ограничений и установки. В любых чатах. Бесплатно. +reply_add_sticker: + other: Пришли стикеры из любых других наборов чтобы по-одному добавить их в свой. +reply_add_pack: + other: Пришли стикеры из любых других наборов чтобы целиком добавить их наборы в свой. +reply_del_sticker: + other: Пришли стикер из своего набора чтобы удалить его. +reply_del_pack: + other: Пришли стикер из своего набора чтобы удалить весь его набор. +reply_reset: + other: | + Эта операция удалит *все* стикеры из твоего набора и *это не может быть отменено*. + + Напиши `{{.KeyPhrase}}` чтобы подтвердить своё намерение обнулить мои мозги (о боже зачем). + Или используй /{{.CancelCommand}} чтобы отменить текущую операцию. +reply_help: + other: | + /{{.AddStickerCommand}} - по-одному добавляет стикеры в твой набор + /{{.AddPackCommand}} - добавляет сразу весь набор в твой + /{{.DeleteStickerCommand}} - по-одному удаляет стикер из твоего набора + /{{.DeletePackCommand}} - удаляет набор стикеров из твоего набора + /{{.ResetCommand}} - удаляет все стикеры из твоего набора + /{{.CancelCommand}} - отменяет текущую операцию + + Для просмотра и отправки стикеров из твоего набора просто набери `@{{.Username}}` (и пробел) в любом чате. +reply_switch_button: + other: Эта кнопка поможет тебе быстро вызвать твой набор для выбора нужного стикера. \ No newline at end of file diff --git a/i18n/ru/ru.success.yaml b/i18n/ru/ru.success.yaml new file mode 100755 index 0000000..eac6284 --- /dev/null +++ b/i18n/ru/ru.success.yaml @@ -0,0 +1,10 @@ +success_add_sticker: + other: Стикер успешно добавлен в твой набор! +success_add_pack: + other: Набор *{{.SetTitle}}* успешно добавлен в твой! +success_del_sticker: + other: Стикер успешно удалён из твоего набора! +success_del_pack: + other: Набор *{{.SetTitle}}* успешно удалён из твоего набора! +success_reset: + other: Сброс твоего набора успешно произведён!.. \ No newline at end of file diff --git a/i18n/ru/ru.yaml b/i18n/ru/ru.yaml new file mode 100644 index 0000000..96fec39 --- /dev/null +++ b/i18n/ru/ru.yaml @@ -0,0 +1,2 @@ +key_phrase: + other: Да, я абсолютно уверен. \ No newline at end of file diff --git a/init.go b/init.go index baa8b20..181668b 100644 --- a/init.go +++ b/init.go @@ -6,9 +6,9 @@ import ( "path/filepath" "strings" - log "github.com/kirillDanshin/dlog" // Insert logs only in debug builds - "github.com/nicksnyder/go-i18n/i18n" // Internationalization and localization - "github.com/olebedev/config" // Easy configuration file parsing + log "github.com/kirillDanshin/dlog" + "github.com/nicksnyder/go-i18n/i18n" + "github.com/olebedev/config" ) var ( diff --git a/main.go b/main.go index a5550bc..ffcaa8b 100644 --- a/main.go +++ b/main.go @@ -1,8 +1,8 @@ package main import ( - log "github.com/kirillDanshin/dlog" // Insert logs only in debug builds - tg "github.com/toby3d/telegram" // My Telegram bindings + log "github.com/kirillDanshin/dlog" + tg "github.com/toby3d/telegram" ) // bot is general structure of the bot @@ -23,26 +23,16 @@ func main() { for update := range getUpdatesChannel() { switch { case update.InlineQuery != nil: - // Just don't check same updates - log.D(update.InlineQuery.Query) - if len(update.InlineQuery.Query) > 25 { - continue - } - - inlineQuery(update.InlineQuery) + log.D(update.InlineQuery) + updateInlineQuery(update.InlineQuery) case update.Message != nil: - if bot.IsMessageFromMe(update.Message) || - bot.IsForwardFromMe(update.Message) { - log.Ln("Ignore message update") - return - } - - messages(update.Message) + log.D(update.Message) + updateMessage(update.Message) case update.ChannelPost != nil: - channelPost(update.ChannelPost) + log.D(update.ChannelPost) + updateChannelPost(update.ChannelPost) default: - log.Ln("Get unsupported update") - continue + log.D(update) } } diff --git a/messages.go b/messages.go index 421b29c..74e11f3 100644 --- a/messages.go +++ b/messages.go @@ -1,77 +1,29 @@ package main import ( - log "github.com/kirillDanshin/dlog" // Insert logs only in debug builds - tg "github.com/toby3d/telegram" // My Telegram bindings + "strings" + + tg "github.com/toby3d/telegram" ) -// message function check Message update on commands, sended stickers or other -// user stuff func messages(msg *tg.Message) { - if msg.IsCommand() { - commands(msg) - return - } - - state, err := dbGetUserState(msg.From.ID) + T, err := switchLocale(msg.From.LanguageCode) errCheck(err) - switch state { - case stateNone: - bot.SendChatAction(msg.Chat.ID, tg.ActionTyping) - - T, err := switchLocale(msg.From.LanguageCode) - errCheck(err) - - reply := tg.NewMessage( - msg.Chat.ID, - T("error_unknown", map[string]interface{}{ - "AddStickerCommand": cmdAddSticker, - "AddPackCommand": cmdAddPack, - "DeleteCommand": cmdDelete, - })) - reply.ParseMode = tg.ModeMarkdown - - _, err = bot.SendMessage(reply) - errCheck(err) - return - case stateAddSticker: - if msg.Sticker == nil { - return - } - - log.D(msg.Sticker) - log.D(msg.Sticker.Emoji) - - actionAdd(msg, false) - return - case stateAddPack: - if msg.Sticker == nil { - return - } - - log.D(msg.Sticker) - log.D(msg.Sticker.Emoji) - - actionAdd(msg, true) - return - case stateDelete: - if msg.Sticker == nil { - return - } - - log.D(msg.Sticker) - log.D(msg.Sticker.Emoji) - - actionDelete(msg) - return - case stateReset: - actionReset(msg) - return + switch { + case strings.EqualFold(msg.Text, T("button_add_sticker")): + commandAdd(msg, false) + case strings.EqualFold(msg.Text, T("button_add_pack")): + commandAdd(msg, true) + case strings.EqualFold(msg.Text, T("button_del_sticker")): + commandDelete(msg, false) + case strings.EqualFold(msg.Text, T("button_del_pack")): + commandDelete(msg, true) + case strings.EqualFold(msg.Text, T("button_reset")): + commandReset(msg) + case strings.EqualFold(msg.Text, T("button_cancel")): + commandCancel(msg) + case strings.EqualFold(msg.Text, T("meta_key_phrase")): + actions(msg) } - - err = dbChangeUserState(msg.From.ID, stateNone) - errCheck(err) - - messages(msg) } diff --git a/reset.go b/reset.go index 7ec3328..8faa408 100644 --- a/reset.go +++ b/reset.go @@ -1,30 +1,28 @@ package main import ( - "fmt" - "time" + "strings" - tg "github.com/toby3d/telegram" // My Telegram bindings + tg "github.com/toby3d/telegram" ) -const keyPhrase = "Yes, I am totally sure." - func commandReset(msg *tg.Message) { - bot.SendChatAction(msg.Chat.ID, tg.ActionTyping) - T, err := switchLocale(msg.From.LanguageCode) errCheck(err) _, total, err := dbGetUserStickers(msg.From.ID, 0, "") errCheck(err) + _, err = bot.SendChatAction(msg.Chat.ID, tg.ActionTyping) + errCheck(err) + if total <= 0 { err = dbChangeUserState(msg.From.ID, stateNone) errCheck(err) reply := tg.NewMessage(msg.Chat.ID, T("error_already_reset")) reply.ParseMode = tg.ModeMarkdown - + reply.ReplyMarkup = getMenuKeyboard(T) _, err = bot.SendMessage(reply) errCheck(err) return @@ -33,31 +31,30 @@ func commandReset(msg *tg.Message) { err = dbChangeUserState(msg.From.ID, stateReset) errCheck(err) - reply := tg.NewMessage( - msg.Chat.ID, - T("reply_reset", map[string]interface{}{ - "KeyPhrase": keyPhrase, - "CancelCommand": cmdCancel, - })) + reply := tg.NewMessage(msg.Chat.ID, T("reply_reset", map[string]interface{}{ + "KeyPhrase": T("meta_key_phrase"), + "CancelCommand": cmdCancel, + })) reply.ParseMode = tg.ModeMarkdown - + reply.ReplyMarkup = getCancelButton(T) _, err = bot.SendMessage(reply) errCheck(err) } func actionReset(msg *tg.Message) { - bot.SendChatAction(msg.Chat.ID, tg.ActionTyping) + T, err := switchLocale(msg.From.LanguageCode) + errCheck(err) - err := dbChangeUserState(msg.From.ID, stateNone) + err = dbChangeUserState(msg.From.ID, stateNone) errCheck(err) - T, err := switchLocale(msg.From.LanguageCode) + _, err = bot.SendChatAction(msg.Chat.ID, tg.ActionTyping) errCheck(err) - if msg.Text != keyPhrase { + if !strings.EqualFold(msg.Text, T("meta_key_phrase")) { reply := tg.NewMessage(msg.Chat.ID, T("error_reset_phrase")) reply.ParseMode = tg.ModeMarkdown - + reply.ReplyMarkup = getMenuKeyboard(T) _, err = bot.SendMessage(reply) errCheck(err) return @@ -68,21 +65,7 @@ func actionReset(msg *tg.Message) { reply := tg.NewMessage(msg.Chat.ID, T("success_reset")) reply.ParseMode = tg.ModeMarkdown - + reply.ReplyMarkup = getMenuKeyboard(T) _, err = bot.SendMessage(reply) errCheck(err) - - for i := 1; i <= 3; i++ { - bot.SendChatAction(msg.Chat.ID, tg.ActionTyping) - - text := T(fmt.Sprint("meta_reset_", i)) - - time.Sleep(time.Minute * time.Duration(len(text)) / 1000) - - reply = tg.NewMessage(msg.Chat.ID, text) - reply.ParseMode = tg.ModeMarkdown - - _, err = bot.SendMessage(reply) - errCheck(err) - } } diff --git a/start.go b/start.go index 8685fd1..10ab47d 100644 --- a/start.go +++ b/start.go @@ -3,20 +3,21 @@ package main import ( "strings" - log "github.com/kirillDanshin/dlog" // Insert logs only in debug builds - tg "github.com/toby3d/telegram" // My Telegram bindings + log "github.com/kirillDanshin/dlog" + tg "github.com/toby3d/telegram" ) func commandStart(msg *tg.Message) { - bot.SendChatAction(msg.Chat.ID, tg.ActionTyping) - err := dbChangeUserState(msg.From.ID, stateNone) errCheck(err) + _, err = bot.SendChatAction(msg.Chat.ID, tg.ActionTyping) + errCheck(err) + if msg.HasArgument() { log.Ln("Received a", msg.Command(), "command with", msg.CommandArgument(), "argument") - if strings.ToLower(msg.CommandArgument()) == strings.ToLower(cmdAddSticker) { - commandAdd(msg, false) + if strings.ToLower(msg.CommandArgument()) == strings.ToLower(cmdHelp) { + commandHelp(msg) return } } @@ -24,13 +25,12 @@ func commandStart(msg *tg.Message) { T, err := switchLocale(msg.From.LanguageCode) errCheck(err) - reply := tg.NewMessage( - msg.Chat.ID, T("reply_start", map[string]interface{}{ - "Username": bot.Self.Username, - "ID": bot.Self.ID, - }), - ) + reply := tg.NewMessage(msg.Chat.ID, T("reply_start", map[string]interface{}{ + "Username": bot.Self.Username, + "ID": bot.Self.ID, + })) reply.ParseMode = tg.ModeMarkdown + reply.ReplyMarkup = getMenuKeyboard(T) _, err = bot.SendMessage(reply) errCheck(err) diff --git a/switch_locale.go b/switch_locale.go index b6011d5..6655ab5 100644 --- a/switch_locale.go +++ b/switch_locale.go @@ -1,18 +1,13 @@ package main import ( - log "github.com/kirillDanshin/dlog" // Insert logs only in debug builds - "github.com/nicksnyder/go-i18n/i18n" // Internationalization and localization + log "github.com/kirillDanshin/dlog" + "github.com/nicksnyder/go-i18n/i18n" ) -const langDefault = "en-us" +const langFallback = "en" -func switchLocale(langCode string) (T i18n.TranslateFunc, err error) { +func switchLocale(langCode string) (i18n.TranslateFunc, error) { log.Ln("Check", langCode, "localization") - T, err = i18n.Tfunc(langCode) - if err != nil { - log.Ln("Unsupported language, change to 'en-us' by default") - T, err = i18n.Tfunc(langDefault) - } - return + return i18n.Tfunc(langCode, langFallback) } diff --git a/channel_post.go b/update_channel_post.go similarity index 61% rename from channel_post.go rename to update_channel_post.go index e9a359d..b7e7424 100644 --- a/channel_post.go +++ b/update_channel_post.go @@ -3,11 +3,11 @@ package main import ( "time" - log "github.com/kirillDanshin/dlog" // Insert logs only in debug builds - tg "github.com/toby3d/telegram" // My Telegram bindings + log "github.com/kirillDanshin/dlog" + tg "github.com/toby3d/telegram" ) -func channelPost(post *tg.Message) { +func updateChannelPost(post *tg.Message) { if post.Chat.ID != channelID { log.Ln(post.Chat.ID, "!=", channelID) return @@ -17,9 +17,11 @@ func channelPost(post *tg.Message) { errCheck(err) for i := range users { - bot.ForwardMessage( + if _, err = bot.ForwardMessage( tg.NewForwardMessage(post.Chat.ID, int64(users[i]), post.ID), - ) + ); err != nil { + log.Ln(err.Error()) + } time.Sleep(time.Second / 10) // For avoid spamming } diff --git a/inline_query.go b/update_inline_query.go old mode 100644 new mode 100755 similarity index 53% rename from inline_query.go rename to update_inline_query.go index d1ffa18..63d733d --- a/inline_query.go +++ b/update_inline_query.go @@ -2,52 +2,54 @@ package main import ( "strconv" - "strings" - log "github.com/kirillDanshin/dlog" // Insert logs only in debug builds - tg "github.com/toby3d/telegram" // My Telegram bindings + log "github.com/kirillDanshin/dlog" + tg "github.com/toby3d/telegram" ) -var r = strings.NewReplacer( - "🏻", "", - "🏼", "", - "🏽", "", - "🏾", "", - "🏿", "", -) +func updateInlineQuery(inlineQuery *tg.InlineQuery) { + fixedQuery, err := fixEmoji(inlineQuery.Query) + if err == nil { + inlineQuery.Query = fixedQuery + } -func inlineQuery(inline *tg.InlineQuery) { - inline.Query = r.Replace(inline.Query) + answer := &tg.AnswerInlineQueryParameters{} + answer.InlineQueryID = inlineQuery.ID + answer.CacheTime = 1 + answer.IsPersonal = true + + if len([]rune(inlineQuery.Query)) >= 256 { + _, err = bot.AnswerInlineQuery(answer) + errCheck(err) + return + } log.Ln("Let's preparing answer...") - T, err := switchLocale(inline.From.LanguageCode) + T, err := switchLocale(inlineQuery.From.LanguageCode) errCheck(err) - log.Ln("INLINE OFFSET:", inline.Offset) - if inline.Offset == "" { - inline.Offset = "-1" + log.Ln("INLINE OFFSET:", inlineQuery.Offset) + if inlineQuery.Offset == "" { + inlineQuery.Offset = "-1" } - offset, err := strconv.Atoi(inline.Offset) + offset, err := strconv.Atoi(inlineQuery.Offset) errCheck(err) offset++ - log.Ln("CURRENT OFFSET:", inline.Offset) - answer := &tg.AnswerInlineQueryParameters{} - answer.InlineQueryID = inline.ID - answer.CacheTime = 1 - answer.IsPersonal = true - - stickers, packSize, err := dbGetUserStickers(inline.From.ID, offset, inline.Query) + stickers, packSize, err := dbGetUserStickers( + inlineQuery.From.ID, offset, inlineQuery.Query, + ) errCheck(err) totalStickers := len(stickers) if totalStickers == 0 { if offset == 0 { - if inline.Query != "" { + if inlineQuery.Query != "" { // If search stickers by emoji return 0 results answer.SwitchPrivateMessageText = T( - "button_inline_nothing", - map[string]interface{}{"Query": inline.Query}, + "button_inline_nothing", map[string]interface{}{ + "Query": inlineQuery.Query, + }, ) answer.SwitchPrivateMessageParameter = cmdAddSticker } else { @@ -55,10 +57,8 @@ func inlineQuery(inline *tg.InlineQuery) { answer.SwitchPrivateMessageText = T("button_inline_empty") answer.SwitchPrivateMessageParameter = cmdAddSticker } - } else { - return + answer.Results = nil } - answer.Results = nil } else { log.Ln("STICKERS FROM REQUEST:", totalStickers) if totalStickers > 50 { @@ -72,26 +72,20 @@ func inlineQuery(inline *tg.InlineQuery) { var results = make([]interface{}, len(stickers)) for i, sticker := range stickers { - results[i] = tg.NewInlineQueryResultCachedSticker( - sticker, sticker, - ) + results[i] = tg.NewInlineQueryResultCachedSticker(sticker, sticker) } answer.SwitchPrivateMessageText = T( - "button_inline_add", - packSize, - map[string]interface{}{ + "button_inline_search", packSize, map[string]interface{}{ "Count": packSize, }, ) - answer.SwitchPrivateMessageParameter = cmdAddSticker + answer.SwitchPrivateMessageParameter = cmdHelp answer.Results = results } log.Ln("CacheTime:", answer.CacheTime) _, err = bot.AnswerInlineQuery(answer) - if err != nil { - log.Ln(err.Error()) - } + errCheck(err) } diff --git a/update_message.go b/update_message.go new file mode 100644 index 0000000..f52d1c1 --- /dev/null +++ b/update_message.go @@ -0,0 +1,22 @@ +package main + +import ( + log "github.com/kirillDanshin/dlog" + tg "github.com/toby3d/telegram" +) + +func updateMessage(msg *tg.Message) { + if bot.IsMessageFromMe(msg) || bot.IsForwardFromMe(msg) { + log.Ln("Ignore message update") + return + } + + switch { + case bot.IsCommandToMe(msg): + commands(msg) + case msg.Text != "": + messages(msg) + default: + actions(msg) + } +}