This repository has been archived by the owner on Jan 26, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
main.go
216 lines (188 loc) · 4.84 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
// Copyright 2015 The tgbot Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"bufio"
"fmt"
"io"
"log"
"os"
"os/exec"
"os/signal"
"regexp"
"strings"
"github.com/BurntSushi/toml"
"github.com/jroimartin/tgbot/commands"
)
var (
// Message format: "[MSG] title from msg".
msgRegexp = regexp.MustCompile(`^\[MSG\] ([^ ]+) ([^ ]+) (.*)$`)
// Global configuration.
globalConfig config
// Enabled commands.
enabledCommands = []commands.Command{}
// Channel used to receive OS signals.
sig = make(chan os.Signal, 1)
// Communication pipes with the tg client
stdoutTg io.ReadCloser
stdinTg io.WriteCloser
)
// Configuration used for bot and commands.
type config struct {
TgBin string
TgPubKey string
MinOutput string
Chats []string
Echo commands.EchoConfig
Quotes commands.QuotesConfig
Ano commands.AnoConfig
Breakfast commands.BreakfastConfig
Voice commands.VoiceConfig
Bing commands.BingConfig
Fcdg commands.FcdgConfig
Hater commands.HaterConfig
Tweet commands.TweetConfig
}
func main() {
if len(os.Args) != 2 {
fmt.Fprintln(os.Stderr, "usage: tgbot config")
os.Exit(2)
}
configFile := os.Args[1]
if _, err := toml.DecodeFile(configFile, &globalConfig); err != nil {
log.Fatalln(err)
}
for i := range globalConfig.Chats {
globalConfig.Chats[i] = strings.Replace(globalConfig.Chats[i], " ", "_", -1)
}
// Clean shutdown with Ctrl-C
signal.Notify(sig, os.Interrupt, os.Kill)
if err := listenAndServe(); err != nil {
log.Fatalln(err)
}
log.Println("Bye!")
}
func listenAndServe() error {
// -R: disable readline, -C: disable color, -D: disable output,
// -W: send dialog_list on start, -s: lua script
cmd := exec.Command(globalConfig.TgBin, "-R", "-C", "-D", "-W",
"-s", globalConfig.MinOutput,
"-k", globalConfig.TgPubKey)
stdoutTg, err := cmd.StdoutPipe()
if err != nil {
return err
}
stdinTg, err = cmd.StdinPipe()
if err != nil {
return err
}
if err := cmd.Start(); err != nil {
return err
}
// initCommads must be caled after stdinTg and stdoutTg has bee initialized
initCommads()
defer shutdownCommands()
log.Println("Monitoring...")
s := bufio.NewScanner(stdoutTg)
readLoop:
for {
select {
case <-sig: // Ctrl-C
break readLoop
default:
if !s.Scan() {
break readLoop
}
handleMsg(s.Text())
}
}
if err := s.Err(); err != nil {
return err
}
if err := cmd.Wait(); err != nil {
return err
}
return nil
}
// initCommads enables plugins.
func initCommads() {
enabledCommands = append(enabledCommands,
commands.NewCmdEcho(stdinTg, globalConfig.Echo))
enabledCommands = append(enabledCommands,
commands.NewCmdQuotes(stdinTg, globalConfig.Quotes))
enabledCommands = append(enabledCommands,
commands.NewCmdAno(stdinTg, globalConfig.Ano))
enabledCommands = append(enabledCommands,
commands.NewCmdBreakfast(stdinTg, globalConfig.Breakfast))
enabledCommands = append(enabledCommands,
commands.NewCmdVoice(stdinTg, globalConfig.Voice))
enabledCommands = append(enabledCommands,
commands.NewCmdBing(stdinTg, globalConfig.Bing))
enabledCommands = append(enabledCommands,
commands.NewCmdFcdg(stdinTg, globalConfig.Fcdg))
enabledCommands = append(enabledCommands,
commands.NewCmdHater(stdinTg, globalConfig.Hater))
enabledCommands = append(enabledCommands,
commands.NewCmdTweet(stdinTg, globalConfig.Tweet))
}
// shutdownCommands gracefully shuts down all commands.
func shutdownCommands() {
for _, cmd := range enabledCommands {
if !cmd.Enabled() {
continue
}
if err := cmd.Shutdown(); err != nil {
log.Println(err)
}
}
}
// handleMsg parses the message and calls handleCommand
// with the title, from and text of the message.
func handleMsg(msg string) {
sm := msgRegexp.FindStringSubmatch(msg)
if len(sm) != 4 {
return
}
title := sm[1]
from := sm[2]
text := sm[3]
log.Printf("DEBUG: title=%v, from=%v, text=%v\n", title, from, text)
if !isMonitored(title) {
return
}
handleCommand(title, from, text)
}
// isMonitored returns true if "title" is monitored.
func isMonitored(title string) bool {
if len(globalConfig.Chats) == 0 {
return true
}
for _, c := range globalConfig.Chats {
if c == title {
return true
}
}
return false
}
// handleCommand selects the command and executes it.
func handleCommand(title, from, text string) {
if strings.HasPrefix(text, "!?") {
for _, cmd := range enabledCommands {
if cmd.Enabled() && cmd.Syntax() != "" {
fmt.Fprintf(stdinTg, "msg %v - %v: %v\n",
title, cmd.Syntax(), cmd.Description())
}
}
return
}
for _, cmd := range enabledCommands {
if cmd.Enabled() && cmd.Match(text) {
if err := cmd.Run(title, from, text); err != nil {
log.Println(err)
fmt.Fprintf(stdinTg, "msg %v error: command error\n", title)
}
return
}
}
}