-
Notifications
You must be signed in to change notification settings - Fork 0
/
bot.go
59 lines (51 loc) · 1.14 KB
/
bot.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
package main
import (
"context"
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
"github.com/phuslu/log"
)
type Bot struct {
tgbot *tgbotapi.BotAPI
updates tgbotapi.UpdatesChannel
}
func NewBot(tgbot *tgbotapi.BotAPI, updates tgbotapi.UpdatesChannel) *Bot {
return &Bot{
updates: updates,
tgbot: tgbot,
}
}
func (b *Bot) processUpdates(ctx context.Context) {
for {
select {
case update := <-b.updates:
if update.Message == nil || update.Message.Text == "" {
log.Debug().Msg("received non-text message")
continue
}
log.Info().
Str("username", update.Message.From.UserName).
Str("text", update.Message.Text).
Msg("received update")
msg := tgbotapi.NewMessage(
update.Message.Chat.ID,
reverse(update.Message.Text),
)
if _, err := b.tgbot.Send(msg); err != nil {
log.Error().Err(err).Msg("send message failed")
}
case <-ctx.Done():
return
}
}
}
// Reverse reverse string
func reverse(in string) string {
runes := []rune(in)
low, high := 0, len(runes)-1
for low < high {
runes[low], runes[high] = runes[high], runes[low]
low++
high--
}
return string(runes)
}