all repos — telegram-bot-api @ 567a37868d87cbd50149f484f26cefd2859ecbfd

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	"strings"
 9	"time"
10)
11
12type Config struct {
13	Token   string            `json:"token"`
14	Plugins map[string]string `json:"plugins"`
15}
16
17type Plugin interface {
18	GetName() string
19	GetCommands() []string
20	GetHelpText() []string
21	GotCommand(string, Message, []string)
22}
23
24var bot *BotApi
25var plugins []Plugin
26var config Config
27
28func main() {
29	configPath := flag.String("config", "config.json", "path to config.json")
30
31	flag.Parse()
32
33	data, err := ioutil.ReadFile(*configPath)
34	if err != nil {
35		log.Panic(err)
36	}
37
38	json.Unmarshal(data, &config)
39
40	bot = NewBotApi(BotConfig{
41		token: config.Token,
42		debug: true,
43	})
44
45	plugins = []Plugin{&HelpPlugin{}, &FAPlugin{}}
46
47	ticker := time.NewTicker(time.Second)
48
49	lastUpdate := 0
50
51	for range ticker.C {
52		update := NewUpdate(lastUpdate + 1)
53		update.Timeout = 30
54
55		updates, err := bot.getUpdates(update)
56
57		if err != nil {
58			log.Panic(err)
59		}
60
61		for _, update := range updates {
62			lastUpdate = update.UpdateId
63
64			if update.Message.Text == "" {
65				continue
66			}
67
68			for _, plugin := range plugins {
69				parts := strings.Split(update.Message.Text, " ")
70
71				for _, cmd := range plugin.GetCommands() {
72					if cmd == parts[0] {
73						args := append(parts[:0], parts[1:]...)
74
75						plugin.GotCommand(parts[0], update.Message, args)
76					}
77				}
78			}
79		}
80	}
81}