-
Notifications
You must be signed in to change notification settings - Fork 0
/
bot.go
114 lines (100 loc) · 2.53 KB
/
bot.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
package main
import (
_ "embed"
"fmt"
"path"
"strconv"
"strings"
"github.com/simba-fs/telegrary/bot"
"github.com/simba-fs/telegrary/config"
"github.com/simba-fs/telegrary/git"
"github.com/simba-fs/telegrary/note"
"github.com/simba-fs/telegrary/util"
log "github.com/sirupsen/logrus"
)
//go:embed help/bot.txt
var help string
var loginedUsers = make(map[string]bool, 0)
func auth(ctx *bot.Context) bool {
if _, ok := loginedUsers[ctx.Update.Message.From.UserName]; !ok {
ctx.Send("please login first")
return false
}
return true
}
func init() {
bot.AddCmd("start", func(ctx *bot.Context) bool {
if len(ctx.Args) == 1 {
ctx.Send("please enter secret key")
return true
}
if util.Hash(ctx.Args[1]) != config.Config.Secret {
ctx.Send("wrong secret key")
return true
}
username := ctx.Update.Message.From.UserName
loginedUsers[username] = true
ctx.Send("Welcome to Telegrary! " + username)
return true
})
bot.AddCmd("help", auth, func(ctx *bot.Context) bool {
ctx.Send(help)
return true
})
bot.AddCmd("read", auth, func(ctx *bot.Context) bool {
git.Pull()
year, month, day := util.GetDate(strings.Split(ctx.Update.Message.Text, " ")[1:])
diary, err := note.Read(util.Path(year, month, day))
if err != nil {
ctx.Send("No diary found")
return true
}
ctx.Send(fmt.Sprintf("===== %s/%s/%s.md =====\n%s", year, month, day, diary))
return true
})
bot.AddCmd("write", auth, func(ctx *bot.Context) bool {
git.Pull()
year, month, day := util.GetDate(strings.Split(ctx.Update.Message.Text, " ")[1:])
log.Debugln(ctx.Update.Message.Text)
// get content
a := strings.Split(ctx.Update.Message.Text, " ")
for k, v := range a {
_, err := strconv.Atoi(v)
if k == 0 || err == nil && k <= 3 {
a = a[1:]
} else {
break
}
}
content := "\n" + strings.Trim(strings.Join(a, " "), " ")
// write
err := note.Write(util.Path(year, month, day), content, false)
if err != nil {
ctx.Send("Write failed")
log.Fatal(err)
return true
}
ctx.Send("write successfully, use /read to read it")
git.Push()
return true
})
bot.AddCmd("tree", auth, func(ctx *bot.Context) bool {
git.Pull()
prefix := ""
if len(strings.Split(ctx.Update.Message.Text, " ")) > 1 {
prefix = strings.Split(ctx.Update.Message.Text, " ")[1]
}
tree, err := note.Tree(path.Join(config.Config.Root, prefix))
if err != nil {
ctx.Send("Tree failed")
log.Error(err)
return true
}
ctx.Send(tree)
return true
})
}
// startBot starts the bot
func startBot() {
bot.Run(config.Config.Token)
}