all repos — telegram-bot-api @ 434756c165a9b43d750eb56e6a4eaff067f1bcbb

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}
 57
 58var bot *BotApi
 59
 60func main() {
 61	configPath := flag.String("config", "config.json", "path to config.json")
 62
 63	flag.Parse()
 64
 65	data, err := ioutil.ReadFile(*configPath)
 66	if err != nil {
 67		log.Panic(err)
 68	}
 69
 70	var cfg Config
 71	json.Unmarshal(data, &cfg)
 72
 73	bot = NewBotApi(BotConfig{
 74		token: cfg.Token,
 75		debug: true,
 76	})
 77
 78	plugins := []Plugin{&ColonThree{}}
 79
 80	ticker := time.NewTicker(5 * time.Second)
 81
 82	lastUpdate := 0
 83
 84	for range ticker.C {
 85		updates, err := bot.getUpdates(NewUpdate(lastUpdate + 1))
 86
 87		if err != nil {
 88			log.Panic(err)
 89		}
 90
 91		for _, update := range updates {
 92			lastUpdate = update.UpdateId
 93
 94			if update.Message.Text == "" {
 95				continue
 96			}
 97
 98			for _, plugin := range plugins {
 99				parts := strings.Split(update.Message.Text, " ")
100
101				if plugin.GetCommand() == parts[0] {
102					parts = append(parts[:0], parts[1:]...)
103
104					plugin.GotCommand(update.Message, parts)
105				}
106			}
107		}
108	}
109}