all repos — telegram-bot-api @ a7b8af6adbdae556dab8deca6d6560961eb41f24

Golang bindings for the Telegram Bot API

bot.go (view raw)

  1package main
  2
  3import (
  4	"encoding/json"
  5	"flag"
  6	"io/ioutil"
  7	"log"
  8	"strconv"
  9	"strings"
 10	"time"
 11)
 12
 13type Config struct {
 14	Token string `json:"token"`
 15}
 16
 17type Plugin interface {
 18	GetCommand() string
 19	GotCommand(Message, []string)
 20}
 21
 22type ColonThree struct {
 23}
 24
 25func (plugin *ColonThree) GetCommand() string {
 26	return "/three"
 27}
 28
 29func (plugin *ColonThree) GotCommand(message Message, args []string) {
 30	if len(args) > 0 {
 31		n, err := strconv.Atoi(args[0])
 32		if err != nil {
 33			msg := NewMessage(message.Chat.Id, "Bad number!")
 34			msg.ReplyToMessageId = message.MessageId
 35
 36			bot.sendMessage(msg)
 37
 38			return
 39		}
 40
 41		if n > 5 {
 42			msg := NewMessage(message.Chat.Id, "That's a bit much, no?")
 43			msg.ReplyToMessageId = message.MessageId
 44
 45			bot.sendMessage(msg)
 46
 47			return
 48		}
 49
 50		for i := 0; i < n; i++ {
 51			bot.sendMessage(NewMessage(message.Chat.Id, ":3"))
 52		}
 53	} else {
 54		bot.sendMessage(NewMessage(message.Chat.Id, ":3"))
 55
 56		bot.sendPhoto(NewPhotoUpload(message.Chat.Id, "fox.png"))
 57	}
 58}
 59
 60var bot *BotApi
 61
 62func main() {
 63	configPath := flag.String("config", "config.json", "path to config.json")
 64
 65	flag.Parse()
 66
 67	data, err := ioutil.ReadFile(*configPath)
 68	if err != nil {
 69		log.Panic(err)
 70	}
 71
 72	var cfg Config
 73	json.Unmarshal(data, &cfg)
 74
 75	bot = NewBotApi(BotConfig{
 76		token: cfg.Token,
 77		debug: true,
 78	})
 79
 80	plugins := []Plugin{&ColonThree{}}
 81
 82	ticker := time.NewTicker(5 * time.Second)
 83
 84	lastUpdate := 0
 85
 86	for range ticker.C {
 87		updates, err := bot.getUpdates(NewUpdate(lastUpdate + 1))
 88
 89		if err != nil {
 90			log.Panic(err)
 91		}
 92
 93		for _, update := range updates {
 94			lastUpdate = update.UpdateId
 95
 96			if update.Message.Text == "" {
 97				continue
 98			}
 99
100			for _, plugin := range plugins {
101				parts := strings.Split(update.Message.Text, " ")
102
103				if plugin.GetCommand() == parts[0] {
104					parts = append(parts[:0], parts[1:]...)
105
106					plugin.GotCommand(update.Message, parts)
107				}
108			}
109		}
110	}
111}