♻️ Refactoring codewith adding some small features

Remove linter warnings, changed inline-feed-button command, added message with switch-button. Also, fixed #1
This commit is contained in:
Maxim Lebedev 2018-01-20 01:41:16 +05:00
parent 1f53b751f8
commit 6ade04cfc9
No known key found for this signature in database
GPG Key ID: F8978F46FF0FFA4F
16 changed files with 111 additions and 78 deletions

50
add.go
View File

@ -1,8 +1,8 @@
package main package main
import ( import (
log "github.com/kirillDanshin/dlog" // Insert logs only in debug builds log "github.com/kirillDanshin/dlog"
tg "github.com/toby3d/telegram" // My Telegram bindings tg "github.com/toby3d/telegram"
) )
func commandAdd(msg *tg.Message, pack bool) { func commandAdd(msg *tg.Message, pack bool) {
@ -45,14 +45,31 @@ func actionAdd(msg *tg.Message, pack bool) {
reply := tg.NewMessage(msg.Chat.ID, T("success_add_sticker")) reply := tg.NewMessage(msg.Chat.ID, T("success_add_sticker"))
reply.ParseMode = tg.ModeMarkdown reply.ParseMode = tg.ModeMarkdown
switch { if !pack {
case pack && var exist bool
msg.Sticker.SetName == "": exist, err = dbAddSticker(
reply.Text = T("error_empty_add_pack", map[string]interface{}{ msg.From.ID,
"AddStickerCommand": cmdAddSticker, msg.Sticker.SetName,
}) msg.Sticker.FileID,
case pack && msg.Sticker.Emoji,
msg.Sticker.SetName != "": )
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 var set *tg.StickerSet
set, err = bot.GetStickerSet(msg.Sticker.SetName) set, err = bot.GetStickerSet(msg.Sticker.SetName)
errCheck(err) errCheck(err)
@ -85,19 +102,6 @@ func actionAdd(msg *tg.Message, pack bool) {
"SetTitle": set.Title, "SetTitle": set.Title,
}) })
} }
default:
var exist bool
exist, err = dbAddSticker(
msg.From.ID,
msg.Sticker.SetName,
msg.Sticker.FileID,
msg.Sticker.Emoji,
)
errCheck(err)
if exist {
reply.Text = T("error_already_add_sticker")
}
} }
reply.ReplyMarkup = getCancelButton(T) reply.ReplyMarkup = getCancelButton(T)

View File

@ -1,6 +1,6 @@
package main package main
import tg "github.com/toby3d/telegram" // My Telegram bindings import tg "github.com/toby3d/telegram"
func commandCancel(msg *tg.Message) { func commandCancel(msg *tg.Message) {
T, err := switchLocale(msg.From.LanguageCode) T, err := switchLocale(msg.From.LanguageCode)

View File

@ -3,8 +3,8 @@ package main
import ( import (
"strings" "strings"
// log "github.com/kirillDanshin/dlog" // Insert logs only in debug builds // log "github.com/kirillDanshin/dlog"
tg "github.com/toby3d/telegram" // My Telegram bindings tg "github.com/toby3d/telegram"
) )
const ( const (

View File

@ -1,8 +1,8 @@
package main package main
import ( import (
log "github.com/kirillDanshin/dlog" // Insert logs only in debug builds log "github.com/kirillDanshin/dlog"
tg "github.com/toby3d/telegram" // My Telegram bindings tg "github.com/toby3d/telegram"
) )
func commandDelete(msg *tg.Message, pack bool) { func commandDelete(msg *tg.Message, pack bool) {
@ -42,6 +42,14 @@ func commandDelete(msg *tg.Message, pack bool) {
_, err = bot.SendMessage(reply) _, err = bot.SendMessage(reply)
errCheck(err) 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, pack bool) { func actionDelete(msg *tg.Message, pack bool) {

View File

@ -1,6 +1,6 @@
package main package main
import tg "github.com/toby3d/telegram" // My Telegram bindings import tg "github.com/toby3d/telegram"
func commandHelp(msg *tg.Message) { func commandHelp(msg *tg.Message) {
T, err := switchLocale(msg.From.LanguageCode) T, err := switchLocale(msg.From.LanguageCode)

View File

@ -44,6 +44,14 @@ func getCancelButton(T i18n.TranslateFunc) *tg.ReplyKeyboardMarkup {
) )
} }
func getSwitchButton(T i18n.TranslateFunc) *tg.InlineKeyboardMarkup {
return tg.NewInlineKeyboardMarkup(
tg.NewInlineKeyboardRow(
tg.NewInlineKeyboardButtonSwitchSelf(T("button_inline_select"), " "),
),
)
}
func fixEmoji(raw string) (string, error) { func fixEmoji(raw string) (string, error) {
result, _, err := transform.String(skinRemover, raw) result, _, err := transform.String(skinRemover, raw)
return result, err return result, err

View File

@ -4,19 +4,19 @@ button_add_sticker:
other: Add sticker other: Add sticker
button_cancel: button_cancel:
other: ❌ Cancel other: ❌ Cancel
button_del:
other: Select sticker for remove
button_del_pack: button_del_pack:
other: "\U0001F5D1 Delete pack" other: "\U0001F5D1 Delete pack"
button_del_sticker: button_del_sticker:
other: "\U0001F5D1 Delete sticker" other: "\U0001F5D1 Delete sticker"
button_inline_add:
one: You have {{.Count}} sticker. Add one more?
other: You have {{.Count}} stickers. Add one more?
button_inline_empty: button_inline_empty:
other: Your pack is empty other: Your pack is empty
button_inline_nothing: button_inline_nothing:
other: Not found stickers for {{.Query}}, add one? 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: button_reset:
other: "\U0001F525 Reset pack" other: "\U0001F525 Reset pack"
button_share: button_share:
@ -37,7 +37,9 @@ error_already_add_pack:
other: All stickers from *{{.SetTitle}}* pack is already in yours. other: All stickers from *{{.SetTitle}}* pack is already in yours.
error_already_add_sticker: error_already_add_sticker:
other: This sticker is already in your pack. other: This sticker is already in your pack.
error_already_del: 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. other: Maybe this sticker is already removed from your pack.
error_already_reset: error_already_reset:
other: There is nothing to reset, pack is already empty. other: There is nothing to reset, pack is already empty.
@ -70,7 +72,7 @@ reply_del_pack:
reply_del_sticker: reply_del_sticker:
other: Send an existing stickers from your pack for removing it. other: Send an existing stickers from your pack for removing it.
reply_help: reply_help:
other: |- other: |
/{{.AddStickerCommand}} - add a single sticker to your pack /{{.AddStickerCommand}} - add a single sticker to your pack
/{{.AddPackCommand}} - add a full other pack to your pack /{{.AddPackCommand}} - add a full other pack to your pack
/{{.DeleteStickerCommand}} - remove a single sticker from your pack /{{.DeleteStickerCommand}} - remove a single sticker from your pack
@ -90,6 +92,9 @@ reply_start:
Hello, I'm the [@{{.Username}}](tg://user?id={{.ID}})! Hello, I'm the [@{{.Username}}](tg://user?id={{.ID}})!
I can create your personal pack with stickers from others packs. I can create your personal pack with stickers from others packs.
Without limits and installing. In any chat. For free. Without limits and installing. In any chat. For free.
reply_switch_button:
other: This button will help you quickly call your pack to select the sticker you
want.
success_add_pack: success_add_pack:
other: The sticker pack *{{.SetTitle}}* was successfully added to yours! other: The sticker pack *{{.SetTitle}}* was successfully added to yours!
success_add_sticker: success_add_sticker:

View File

@ -1,12 +1,12 @@
button_inline_empty: button_inline_empty:
other: Your pack is empty other: Your pack is empty
button_inline_nothing: button_inline_nothing:
other: Not found stickers for {{.Query}}, add one? other: Not found stickers for {{.Query}}
button_inline_add: button_inline_search:
one: You have {{.Count}} sticker. Add one more? one: You have {{.Count}} sticker
other: You have {{.Count}} stickers. Add one more? other: You have {{.Count}} stickers
button_del: button_inline_select:
other: Select sticker for remove other: Select sticker
button_share: button_share:
other: Use your stickers pack! other: Use your stickers pack!
button_add_sticker: button_add_sticker:

View File

@ -2,8 +2,10 @@ error_already_add_sticker:
other: This sticker is already in your pack. other: This sticker is already in your pack.
error_already_add_pack: error_already_add_pack:
other: All stickers from *{{.SetTitle}}* pack is already in yours. 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. 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: error_already_reset:
other: There is nothing to reset, pack is already empty. other: There is nothing to reset, pack is already empty.
error_reset_phrase: error_reset_phrase:

View File

@ -26,4 +26,6 @@ reply_help:
/{{.ResetCommand}} - remove all stickers from your pack /{{.ResetCommand}} - remove all stickers from your pack
/{{.CancelCommand}} - cancel the current operation /{{.CancelCommand}} - cancel the current operation
To view and send stickers from your pack, just type `@{{.Username}}` (and space) in any chat. 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.

View File

@ -4,21 +4,21 @@ button_add_sticker:
other: Добавить стикер other: Добавить стикер
button_cancel: button_cancel:
other: ❌ Отменить other: ❌ Отменить
button_del:
other: Выбрать стикер для удаления
button_del_pack: button_del_pack:
other: "\U0001F5D1 Удалить набор" other: "\U0001F5D1 Удалить набор"
button_del_sticker: button_del_sticker:
other: "\U0001F5D1 Удалить стикер" other: "\U0001F5D1 Удалить стикер"
button_inline_add:
few: У тебя {{.Count}} стикеров. Добавить ещё один?
many: У тебя {{.Count}} стикеров. Добавить ещё один?
one: У тебя {{.Count}} стикер. Добавить ещё один?
other: У тебя {{.Count}} стикеров. Добавить ещё один?
button_inline_empty: button_inline_empty:
other: Твой набор пуст other: Твой набор пуст
button_inline_nothing: button_inline_nothing:
other: Нет стикеров с {{.Query}}, добавить один? other: Не найдены стикеры для {{.Query}}
button_inline_search:
few: У тебя {{.Count}} стикера
many: У тебя {{.Count}} стикеров
one: У тебя {{.Count}} стикер
other: У тебя {{.Count}} стикеров
button_inline_select:
other: Выбрать стикер
button_reset: button_reset:
other: "\U0001F525 Сбросить набор" other: "\U0001F525 Сбросить набор"
button_share: button_share:
@ -39,7 +39,9 @@ error_already_add_pack:
other: Все стикеры *{{.SetTitle}}* уже в твоём наборе. other: Все стикеры *{{.SetTitle}}* уже в твоём наборе.
error_already_add_sticker: error_already_add_sticker:
other: Этот стикер уже в твоём наборе. other: Этот стикер уже в твоём наборе.
error_already_del: error_already_del_pack:
other: Вероятно этот набор уже удалён из твоего.
error_already_del_sticker:
other: Вероятно этот стикер уже удалён из твоего набора. other: Вероятно этот стикер уже удалён из твоего набора.
error_already_reset: error_already_reset:
other: Нечего сбрасывать, набор уже пуст. other: Нечего сбрасывать, набор уже пуст.
@ -71,7 +73,7 @@ reply_del_pack:
reply_del_sticker: reply_del_sticker:
other: Пришли стикер из своего набора чтобы удалить его. other: Пришли стикер из своего набора чтобы удалить его.
reply_help: reply_help:
other: |- other: |
/{{.AddStickerCommand}} - по-одному добавляет стикеры в твой набор /{{.AddStickerCommand}} - по-одному добавляет стикеры в твой набор
/{{.AddPackCommand}} - добавляет сразу весь набор в твой /{{.AddPackCommand}} - добавляет сразу весь набор в твой
/{{.DeleteStickerCommand}} - по-одному удаляет стикер из твоего набора /{{.DeleteStickerCommand}} - по-одному удаляет стикер из твоего набора
@ -91,6 +93,8 @@ reply_start:
Привет, я [@{{.Username}}](tg://user?id={{.ID}})! Привет, я [@{{.Username}}](tg://user?id={{.ID}})!
Я могу создать твой персональный набор стикеров из других наборов. Я могу создать твой персональный набор стикеров из других наборов.
Без ограничений и установки. В любых чатах. Бесплатно. Без ограничений и установки. В любых чатах. Бесплатно.
reply_switch_button:
other: Эта кнопка поможет тебе быстро вызвать твой набор для выбора нужного стикера.
success_add_pack: success_add_pack:
other: Набор *{{.SetTitle}}* успешно добавлен в твой! other: Набор *{{.SetTitle}}* успешно добавлен в твой!
success_add_sticker: success_add_sticker:

View File

@ -1,14 +1,14 @@
button_inline_empty: button_inline_empty:
other: Твой набор пуст other: Твой набор пуст
button_inline_nothing: button_inline_nothing:
other: Нет стикеров с {{.Query}}, добавить один? other: Не найдены стикеры для {{.Query}}
button_inline_add: button_inline_search:
few: У тебя {{.Count}} стикеров. Добавить ещё один? few: У тебя {{.Count}} стикера
one: У тебя {{.Count}} стикер. Добавить ещё один? one: У тебя {{.Count}} стикер
many: У тебя {{.Count}} стикеров. Добавить ещё один? many: У тебя {{.Count}} стикеров
other: У тебя {{.Count}} стикеров. Добавить ещё один? other: У тебя {{.Count}} стикеров
button_del: button_inline_select:
other: Выбрать стикер для удаления other: Выбрать стикер
button_share: button_share:
other: Воспользоваться твоим набором! other: Воспользоваться твоим набором!
button_add_sticker: button_add_sticker:

View File

@ -2,8 +2,10 @@ error_already_add_sticker:
other: Этот стикер уже в твоём наборе. other: Этот стикер уже в твоём наборе.
error_already_add_pack: error_already_add_pack:
other: Все стикеры *{{.SetTitle}}* уже в твоём наборе. other: Все стикеры *{{.SetTitle}}* уже в твоём наборе.
error_already_del: error_already_del_sticker:
other: Вероятно этот стикер уже удалён из твоего набора. other: Вероятно этот стикер уже удалён из твоего набора.
error_already_del_pack:
other: Вероятно этот набор уже удалён из твоего.
error_already_reset: error_already_reset:
other: Нечего сбрасывать, набор уже пуст. other: Нечего сбрасывать, набор уже пуст.
error_reset_phrase: error_reset_phrase:

View File

@ -26,4 +26,6 @@ reply_help:
/{{.ResetCommand}} - удаляет все стикеры из твоего набора /{{.ResetCommand}} - удаляет все стикеры из твоего набора
/{{.CancelCommand}} - отменяет текущую операцию /{{.CancelCommand}} - отменяет текущую операцию
Для просмотра и отправки стикеров из твоего набора просто набери `@{{.Username}}` (и пробел) в любом чате. Для просмотра и отправки стикеров из твоего набора просто набери `@{{.Username}}` (и пробел) в любом чате.
reply_switch_button:
other: Эта кнопка поможет тебе быстро вызвать твой набор для выбора нужного стикера.

View File

@ -16,8 +16,8 @@ func commandStart(msg *tg.Message) {
if msg.HasArgument() { if msg.HasArgument() {
log.Ln("Received a", msg.Command(), "command with", msg.CommandArgument(), "argument") log.Ln("Received a", msg.Command(), "command with", msg.CommandArgument(), "argument")
if strings.ToLower(msg.CommandArgument()) == strings.ToLower(cmdAddSticker) { if strings.ToLower(msg.CommandArgument()) == strings.ToLower(cmdHelp) {
commandAdd(msg, false) commandHelp(msg)
return return
} }
} }

View File

@ -19,9 +19,8 @@ func updateInlineQuery(inlineQuery *tg.InlineQuery) {
answer.IsPersonal = true answer.IsPersonal = true
if len([]rune(inlineQuery.Query)) >= 256 { if len([]rune(inlineQuery.Query)) >= 256 {
if _, err := bot.AnswerInlineQuery(answer); err != nil { _, err = bot.AnswerInlineQuery(answer)
log.Ln(err.Error()) errCheck(err)
}
return return
} }
@ -58,10 +57,8 @@ func updateInlineQuery(inlineQuery *tg.InlineQuery) {
answer.SwitchPrivateMessageText = T("button_inline_empty") answer.SwitchPrivateMessageText = T("button_inline_empty")
answer.SwitchPrivateMessageParameter = cmdAddSticker answer.SwitchPrivateMessageParameter = cmdAddSticker
} }
} else { answer.Results = nil
return
} }
answer.Results = nil
} else { } else {
log.Ln("STICKERS FROM REQUEST:", totalStickers) log.Ln("STICKERS FROM REQUEST:", totalStickers)
if totalStickers > 50 { if totalStickers > 50 {
@ -79,17 +76,16 @@ func updateInlineQuery(inlineQuery *tg.InlineQuery) {
} }
answer.SwitchPrivateMessageText = T( answer.SwitchPrivateMessageText = T(
"button_inline_add", packSize, map[string]interface{}{ "button_inline_search", packSize, map[string]interface{}{
"Count": packSize, "Count": packSize,
}, },
) )
answer.SwitchPrivateMessageParameter = cmdAddSticker answer.SwitchPrivateMessageParameter = cmdHelp
answer.Results = results answer.Results = results
} }
log.Ln("CacheTime:", answer.CacheTime) log.Ln("CacheTime:", answer.CacheTime)
if _, err = bot.AnswerInlineQuery(answer); err != nil { _, err = bot.AnswerInlineQuery(answer)
log.Ln(err.Error()) errCheck(err)
}
} }