-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
244 lines (228 loc) · 5.68 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
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
package main
import (
"encoding/base64"
"fmt"
"log"
"os"
"strconv"
"strings"
"time"
"github.com/aws/aws-lambda-go/lambda"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/aws/external"
"github.com/aws/aws-sdk-go-v2/service/dynamodb"
"github.com/aws/aws-sdk-go-v2/service/kms"
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
"github.com/victpork/BeanCounter/beancount"
)
var (
apiKey string
cfg *aws.Config
bot *tgbotapi.BotAPI
db *dynamodb.DynamoDB
tz *time.Location
)
const ()
func init() {
apiKey = os.Getenv("TELEGRAM_API_KEY")
var err error
tz, err = time.LoadLocation("Asia/Hong_Kong")
if err != nil {
log.Println("Cannot load timezone information, revert to use local time")
tz = time.Local
}
}
func main() {
lambda.Start(handleTelegramMsg)
}
func handleTelegramMsg(update tgbotapi.Update) {
if cfg == nil {
var err error
cfgVal, err := external.LoadDefaultAWSConfig()
if err != nil {
log.Fatalf("failed to load config, %v", err)
}
cfg = &cfgVal
}
if bot == nil {
var err error
bot, err = tgbotapi.NewBotAPI(apiKey)
if err != nil {
log.Fatal(err)
}
}
if db == nil {
db = dynamodb.New(*cfg)
}
if update.CallbackQuery != nil {
cbQuery := update.CallbackQuery
data := strings.Split(cbQuery.Data, " ")
chatID, _ := strconv.ParseInt(data[0], 10, 64)
newBal, err := beancount.UpdateBalance(db, chatID, data[1])
if err != nil {
log.Fatal(err)
}
err = SendMsg(chatID, fmt.Sprintf("@%v reverted entry.\nBalance updated. New balance %v", cbQuery.From.UserName, newBal))
if err != nil {
log.Fatal(err)
}
return
}
chatID := update.Message.Chat.ID
if update.Message.ReplyToMessage != nil {
amt := update.Message.Text
if strings.ToLower(strings.TrimSpace(amt)) == "cancel" {
return
}
// Trim text after space if there's one
spaceIdx := strings.Index(amt, " ")
if spaceIdx >= 0 {
amt = amt[:spaceIdx]
}
if _, err := strconv.ParseFloat(amt, 32); len(amt) == 0 || err != nil {
msg := tgbotapi.NewMessage(chatID, "Don't know what you're talking. Try again, or say \"cancel\" to cancel.")
msg.ReplyToMessageID = update.Message.MessageID
msg.ReplyMarkup = tgbotapi.ForceReply{
ForceReply: true,
Selective: true,
}
bot.Send(msg)
return
}
newBal, err := beancount.UpdateBalance(db, chatID, amt)
if err != nil {
log.Fatal(err)
}
err = SendMsg(chatID, fmt.Sprintf("Balance updated. New balance %v", newBal))
if err != nil {
log.Fatal(err)
}
}
// Split command and argument
spaceIdx := strings.Index(update.Message.Text, " ")
var cmdText string
var args string
if spaceIdx >= 0 {
cmdText = update.Message.Text[:spaceIdx]
args = update.Message.Text[spaceIdx+1:]
} else {
cmdText = update.Message.Text
}
// Trim the @botName out
atIdx := strings.Index(cmdText, "@")
if atIdx >= 0 {
cmdText = cmdText[:atIdx]
}
switch cmdText {
case "/add":
if len(args) == 0 {
// Force reply from user if no argument detected
msg := tgbotapi.NewMessage(chatID, "How much?")
msg.ReplyToMessageID = update.Message.MessageID
msg.ReplyMarkup = tgbotapi.ForceReply{
ForceReply: true,
Selective: true,
}
bot.Send(msg)
return
}
// Trim everything after space
spaceIdx = strings.Index(args, " ")
if spaceIdx >= 0 {
args = args[:spaceIdx]
}
if _, err := strconv.ParseFloat(args, 32); err != nil {
err = SendMsg(chatID, "Don't understand, please try again.")
if err != nil {
log.Fatal(err)
}
}
newBal, err := beancount.UpdateBalance(db, chatID, args)
if err != nil {
log.Fatal(err)
}
err = SendMsg(chatID, fmt.Sprintf("Balance updated. New balance %v", newBal))
if err != nil {
log.Fatal(err)
}
case "/list":
cnt, _ := strconv.Atoi(args)
if cnt == 0 {
cnt = 10
}
hist, err := beancount.GetTxHist(db, chatID, cnt)
if err != nil {
log.Fatal(err)
}
PrintHist(chatID, hist)
case "/balance":
bal, err := beancount.GetBalance(db, chatID)
if err != nil {
log.Fatal(err)
}
err = SendMsg(chatID, fmt.Sprintf("Current balance: %v", bal))
if err != nil {
log.Fatal(err)
}
case "/reset":
newBal := "0"
if _, err := strconv.ParseFloat(args, 32); err == nil {
newBal = args
}
err := beancount.ResetBalance(db, chatID, newBal)
if err != nil {
log.Fatal(err)
}
err = SendMsg(chatID, "Balance reset")
if err != nil {
log.Fatal(err)
}
}
}
// SendMsg sends simple telegram message back to user
func SendMsg(chatID int64, text string) error {
msg := tgbotapi.NewMessage(chatID, text)
_, err := bot.Send(msg)
if err != nil {
return err
}
return nil
}
// PrintHist display transaction history in chat, along
// with the reverse entry button
func PrintHist(chatID int64, hist []beancount.Entry) {
for _, entry := range hist {
ts := time.Unix(entry.Timestamp, -1)
msg := tgbotapi.NewMessage(chatID, fmt.Sprintf("%v @ %v", entry.Amount, ts.In(tz).Format("02/01/2006 15:04:05")))
kbMarkup := tgbotapi.NewInlineKeyboardMarkup(
[]tgbotapi.InlineKeyboardButton{
tgbotapi.NewInlineKeyboardButtonData("⏪", fmt.Sprintf("%v %v", chatID, negate(entry.Amount))),
})
msg.ReplyMarkup = kbMarkup
bot.Send(msg)
}
}
// negate returns the
func negate(num string) string {
if num[0] == '-' {
return num[1:]
}
return "-" + num
}
func decrypt(cfg aws.Config, encrypted string) (string, error) {
kmsClient := kms.New(cfg)
decodedBytes, err := base64.StdEncoding.DecodeString(encrypted)
if err != nil {
return "", err
}
input := &kms.DecryptInput{
CiphertextBlob: decodedBytes,
}
req := kmsClient.DecryptRequest(input)
rsp, err := req.Send()
if err != nil {
return "", err
}
// Plaintext is a byte array, so convert to string
return string(rsp.Plaintext), nil
}