1
bot/examples/commands/main.go

48 lines
1.1 KiB
Go
Raw Permalink Normal View History

2022-04-26 00:02:51 +08:00
package main
import (
"context"
2022-04-29 17:21:42 +08:00
"os"
"os/signal"
2022-04-26 00:02:51 +08:00
"github.com/go-telegram/bot"
"github.com/go-telegram/bot/models"
)
// Send any text message to the bot after the bot has been started
func main() {
ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt)
defer cancel()
2022-04-26 00:02:51 +08:00
opts := []bot.Option{
bot.WithDefaultHandler(defaultHandler),
}
b, err := bot.New(os.Getenv("EXAMPLE_TELEGRAM_BOT_TOKEN"), opts...)
if nil != err {
// panics for the sake of simplicity.
// you should handle this error properly in your code.
panic(err)
}
2022-04-26 00:02:51 +08:00
b.RegisterHandler(bot.HandlerTypeMessageText, "/hello", bot.MatchTypeExact, helloHandler)
b.Start(ctx)
2022-04-26 00:02:51 +08:00
}
func helloHandler(ctx context.Context, b *bot.Bot, update *models.Update) {
b.SendMessage(ctx, &bot.SendMessageParams{
2022-04-29 17:21:42 +08:00
ChatID: update.Message.Chat.ID,
2022-04-26 00:02:51 +08:00
Text: "Hello, *" + bot.EscapeMarkdown(update.Message.From.FirstName) + "*",
ParseMode: models.ParseModeMarkdown,
})
}
func defaultHandler(ctx context.Context, b *bot.Bot, update *models.Update) {
b.SendMessage(ctx, &bot.SendMessageParams{
2022-04-29 17:21:42 +08:00
ChatID: update.Message.Chat.ID,
2022-04-26 00:02:51 +08:00
Text: "Say /hello",
})
}