Skip to content

Commit

Permalink
perf: 优化telegram Button封装
Browse files Browse the repository at this point in the history
  • Loading branch information
TBXark committed Nov 6, 2024
1 parent 044159d commit cd4b297
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 8 deletions.
4 changes: 4 additions & 0 deletions internal/server/bot/bot.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,10 @@ func (b *Bot) Close(ctx context.Context) error {
return b.Bot.Close(ctx)
}

func NewButton[T any](text, query string, data T) telegram.Button {
return telegram.NewButton(text, query, data)
}

func UnmarshalUpdateDataWithDefault[T any](update *models.Update, defaultValue T) T {
if update != nil && update.CallbackQuery != nil {
_, data, err := telegram.UnmarshalData[T](update.CallbackQuery.Data)
Expand Down
8 changes: 4 additions & 4 deletions internal/server/bot/codec.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,12 +32,12 @@ func (b *Bot) EncodeCounterResponse(ctx context.Context, reply *botv1.CounterRes
Text: fmt.Sprintf("Counter: %d", reply.Count),
Button: [][]telegram.Button{
{
telegram.Button{Text: "+", Type: QueryCounter, Data: reply.Count + 1},
telegram.Button{Text: "-", Type: QueryCounter, Data: reply.Count - 1},
NewButton("Increment", QueryCounter, reply.Count+1),
NewButton("Decrement", QueryCounter, reply.Count-1),
},
{
telegram.Button{Text: "Reset", Type: QueryCounter, Data: 0},
telegram.Button{Text: "Random", Type: QueryCounter, Data: rand.Int() % 100},
NewButton("Reset", QueryCounter, 0),
NewButton("Random", QueryCounter, rand.Int()%100),
},
},
}, nil
Expand Down
16 changes: 12 additions & 4 deletions pkg/telegram/message.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,17 @@ import (
)

type Button struct {
Text string
Type string
Data any
Text string
Type string
CallbackData string
}

func NewButton[T any](text, dType string, data T) Button {
return Button{
Text: text,
Type: dType,
CallbackData: MarshalData(dType, data),
}
}

type Message struct {
Expand All @@ -24,7 +32,7 @@ func (m *Message) toInlineKeyboardMarkup() *models.InlineKeyboardMarkup {
for _, btn := range row {
buttons = append(buttons, models.InlineKeyboardButton{
Text: btn.Text,
CallbackData: MarshalData(btn.Type, btn.Data),
CallbackData: btn.CallbackData,
})
}
keyboard = append(keyboard, buttons)
Expand Down

0 comments on commit cd4b297

Please sign in to comment.