telegram-bot-api/bot.go

82 lines
1.3 KiB
Go
Raw Normal View History

package main
import (
"encoding/json"
"flag"
"io/ioutil"
"log"
"strings"
"time"
)
type Config struct {
2015-06-25 21:20:02 +02:00
Token string `json:"token"`
Plugins map[string]string `json:"plugins"`
}
type Plugin interface {
2015-06-25 21:20:02 +02:00
GetName() string
GetCommands() []string
GetHelpText() []string
GotCommand(string, Message, []string)
}
var bot *BotApi
2015-06-25 21:20:02 +02:00
var plugins []Plugin
var config Config
func main() {
configPath := flag.String("config", "config.json", "path to config.json")
flag.Parse()
data, err := ioutil.ReadFile(*configPath)
if err != nil {
log.Panic(err)
}
2015-06-25 21:20:02 +02:00
json.Unmarshal(data, &config)
bot = NewBotApi(BotConfig{
2015-06-25 21:20:02 +02:00
token: config.Token,
debug: true,
})
2015-06-25 21:20:02 +02:00
plugins = []Plugin{&HelpPlugin{}, &FAPlugin{}}
2015-06-25 21:20:02 +02:00
ticker := time.NewTicker(time.Second)
lastUpdate := 0
for range ticker.C {
2015-06-25 21:20:02 +02:00
update := NewUpdate(lastUpdate + 1)
update.Timeout = 30
updates, err := bot.getUpdates(update)
if err != nil {
log.Panic(err)
}
for _, update := range updates {
lastUpdate = update.UpdateId
if update.Message.Text == "" {
continue
}
for _, plugin := range plugins {
parts := strings.Split(update.Message.Text, " ")
2015-06-25 21:20:02 +02:00
for _, cmd := range plugin.GetCommands() {
if cmd == parts[0] {
args := append(parts[:0], parts[1:]...)
2015-06-25 21:20:02 +02:00
plugin.GotCommand(parts[0], update.Message, args)
}
}
}
}
}
}