bot.go (view raw)
1package main
2
3import (
4 "encoding/json"
5 "flag"
6 "fmt"
7 "io/ioutil"
8 "log"
9 "strings"
10 "time"
11)
12
13type Config struct {
14 Token string `json:"token"`
15 Plugins map[string]string `json:"plugins"`
16 EnabledPlugins map[string]bool `json:"enabled"`
17}
18
19type Plugin interface {
20 GetName() string
21 GetCommands() []string
22 GetHelpText() []string
23 GotCommand(string, Message, []string)
24 Setup()
25}
26
27var bot *BotApi
28var plugins []Plugin
29var config Config
30var configPath *string
31
32func main() {
33 configPath = flag.String("config", "config.json", "path to config.json")
34
35 flag.Parse()
36
37 data, err := ioutil.ReadFile(*configPath)
38 if err != nil {
39 log.Panic(err)
40 }
41
42 json.Unmarshal(data, &config)
43
44 bot = NewBotApi(BotConfig{
45 token: config.Token,
46 debug: true,
47 })
48
49 plugins = []Plugin{&HelpPlugin{}, &FAPlugin{}, &ManagePlugin{}}
50
51 for _, plugin := range plugins {
52 val, ok := config.EnabledPlugins[plugin.GetName()]
53
54 if !ok {
55 fmt.Printf("Enable '%s'? [y/N] ", plugin.GetName())
56
57 var enabled string
58 fmt.Scanln(&enabled)
59
60 if strings.ToLower(enabled) == "y" {
61 plugin.Setup()
62 log.Printf("Plugin '%s' started!\n", plugin.GetName())
63
64 config.EnabledPlugins[plugin.GetName()] = true
65 } else {
66 config.EnabledPlugins[plugin.GetName()] = false
67 }
68 }
69
70 if val {
71 plugin.Setup()
72 log.Printf("Plugin '%s' started!\n", plugin.GetName())
73 }
74
75 saveConfig()
76 }
77
78 ticker := time.NewTicker(time.Second)
79
80 lastUpdate := 0
81
82 for range ticker.C {
83 update := NewUpdate(lastUpdate + 1)
84 update.Timeout = 30
85
86 updates, err := bot.getUpdates(update)
87
88 if err != nil {
89 log.Panic(err)
90 }
91
92 for _, update := range updates {
93 lastUpdate = update.UpdateId
94
95 if update.Message.Text == "" {
96 continue
97 }
98
99 for _, plugin := range plugins {
100 val, _ := config.EnabledPlugins[plugin.GetName()]
101 if !val {
102 continue
103 }
104
105 parts := strings.Split(update.Message.Text, " ")
106 command := parts[0]
107
108 for _, cmd := range plugin.GetCommands() {
109 if cmd == command {
110 if bot.config.debug {
111 log.Printf("'%s' matched plugin '%s'", update.Message.Text, plugin.GetName())
112 }
113
114 args := append(parts[:0], parts[1:]...)
115
116 plugin.GotCommand(command, update.Message, args)
117 }
118 }
119 }
120 }
121 }
122}
123
124func saveConfig() {
125 data, _ := json.MarshalIndent(config, "", " ")
126
127 ioutil.WriteFile(*configPath, data, 0600)
128}