all repos — telegram-bot-api @ 5be25266b56e4097ab270fd83ccbec87f80d4eb8

Golang bindings for the Telegram Bot API

docs/examples/command-handling.md (view raw)

 1# Command Handling
 2
 3This is a simple example of changing behavior based on a provided command.
 4
 5```go
 6package main
 7
 8import (
 9    "log"
10    "os"
11
12    "github.com/go-telegram-bot-api/telegram-bot-api"
13)
14
15func main() {
16    bot, err := tgbotapi.NewBotAPI(os.Getenv("TELEGRAM_APITOKEN"))
17    if err != nil {
18        log.Panic(err)
19    }
20
21    bot.Debug = true
22
23    log.Printf("Authorized on account %s", bot.Self.UserName)
24
25    u := tgbotapi.NewUpdate(0)
26    u.Timeout = 60
27
28    updates := bot.GetUpdatesChan(u)
29
30    for update := range updates {
31        if update.Message == nil { // ignore any non-Message updates
32            continue
33        }
34
35        if !update.Message.IsCommand() { // ignore any non-command Messages
36            continue
37        }
38
39        // Create a new MessageConfig. We don't have text yet,
40        // so we leave it empty.
41        msg := tgbotapi.NewMessage(update.Message.Chat.ID, "")
42
43        // Extract the command from the Message.
44        switch update.Message.Command() {
45        case "help":
46            msg.Text = "I understand /sayhi and /status."
47        case "sayhi":
48            msg.Text = "Hi :)"
49        case "status":
50            msg.Text = "I'm ok."
51        default:
52            msg.Text = "I don't know that command"
53        }
54
55        if _, err := bot.Send(msg); err != nil {
56            log.Panic(err)
57        }
58    }
59}
60```