-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
251 lines (237 loc) · 9.61 KB
/
index.js
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
245
246
247
248
249
250
251
const dotenv = require('dotenv').config();
const TelegramBot = require('node-telegram-bot-api');
const AWS = require('aws-sdk');
const dateFormat = require('dateformat');
const token = process.env.TELEGRAM_BOT_TOKEN;
const groupId = process.env.GROUP_ID;
const bot = new TelegramBot(token, {polling: true});
AWS.config = new AWS.Config();
AWS.config.accessKeyId = process.env.SP_AWS_ACCESS_KEY_ID;
AWS.config.secretAccessKey = process.env.SP_AWS_SECRET_ACCESS_KEY;
const pricesTable = process.env.PRICES_TABLE;
const usersTable = process.env.USERS_TABLE;
const dynamodbService = require('./services/dynamodb.service');
const textService = require('./services/text.service');
const usersService = require('./services/user.service');
const template = require('./resources/template.resource');
bot.onText(template.commands.sellPrice, function(msg){
let chatId = msg.chat.id;
let userId = msg.from.id;
let amount;
//TODO: meter esto en una función
let hour = new Date().getHours() + Number(process.env.TIMEZONE);
let field = hour < 12 ? "morning" : "evening"
let date = dateFormat(new Date(), "dd/mm/yyyy");
return usersService.getUser(userId)
.then((userData) => {
if(new Date().getDay() == 0) {
throw {"errorTitle": "is_sunday", "errorMessage": template.errors.is_sunday};
}
amount = Number(textService.cleanCommand(msg.text));
if(!Number.isInteger(amount)){
throw {"errorTitle": "invalid data", "errorMessage": template.errors.invalid_data};
}
return dynamodbService.get({date, "chat_id":chatId}, pricesTable)
})
.then((exists) => {
if(Object.keys(exists).length) {
var params = {
TableName: pricesTable,
Key:{
date,
"chat_id": userId
},
UpdateExpression: `set ${field} = :a`,
ExpressionAttributeValues:{
":a":amount,
},
ReturnValues:"UPDATED_NEW"
};
return dynamodbService.update(params)
}else {
let params = {
date,
"timestamp": +new Date,
"chat_id": userId,
}
params[field] = amount
return dynamodbService.put(params, pricesTable)
}
})
.then((document) => {
return bot.sendMessage(userId, template.sellPriceResponse(amount, template.sellTurns[field]));
})
.catch((err) => {
if(err.errorTitle) {
let response = err.errorTitle == "access_denied" ? chatId : userId;
return bot.sendMessage(response, err.errorMessage);
}
return bot.sendMessage(userId, template.errors.sellPriceError);
})
});
bot.onText(template.commands.sellingList, function(msg){
var chatId = msg.chat.id;
let userId = msg.from.id
let hour = new Date().getHours() + Number(process.env.TIMEZONE);
let field = hour < 12 ? "morning" : "evening";
return usersService.getUser(userId)
.then((userData) => {
if(new Date().getDay() == 0) {
throw {"errorTitle": "is_sunday", "errorMessage": template.errors.is_sunday};
}
let date = dateFormat(new Date(), "dd/mm/yyyy");
let params = {
TableName: pricesTable,
KeyConditionExpression: "#dt = :dddd",
ExpressionAttributeNames: {
"#dt":"date",
"#f": field
},
FilterExpression:"attribute_exists(#f)",
ExpressionAttributeValues: {
":dddd": date
}
}
return dynamodbService.query(params)
})
.then(async(itemList) => {
if(itemList.length) {
let title = template.sellingList.title;
let composeMessage = await template.listPrices(itemList, field);
return bot.sendMessage(userId, title + composeMessage);
}
return bot.sendMessage(userId, template.sellingList.noPrices);
})
.catch((err) => {
if(err.errorTitle) {
let response = err.errorTitle == "access_denied" ? chatId : userId;
return bot.sendMessage(response, err.errorMessage);
}
return bot.sendMessage(userId, template.errors.sellingList);
})
});
bot.onText(template.commands.purchasePrice, function(msg){
let chatId = msg.chat.id;
let userId = msg.from.id;
let amount;
return usersService.getUser(userId)
.then((userData) => {
if(new Date().getDay() != 0) {
throw {"errorTitle": "not sunday", "errorMessage": template.errors.not_sunday};
}
amount = Number(textService.cleanCommand(msg.text));
if(!Number.isInteger(amount)){
throw {"errorTitle": "invalid data", "error_data": template.errors.invalid_data};
}
let today = new Date();
let params = {
"date": dateFormat(today, "dd/mm/yyyy"),
"timestamp": +new Date,
"chat_id": userId,
"purchase": amount
}
return dynamodbService.put(params, pricesTable)
})
.then(() => {
return bot.sendMessage(userId, template.purchasePriceResponse(amount));
})
.catch((err) => {
if(err.errorTitle) {
let response = err.errorTitle == "access_denied" ? chatId : userId;
return bot.sendMessage(response, err.errorMessage);
}
return bot.sendMessage(userId, template.errors.purchasePriceError);
})
});
bot.onText(template.commands.purchaseList, function(msg){
var chatId = msg.chat.id;
let userId = msg.from.id
return usersService.getUser(userId)
.then((userData) => {
if(new Date().getDay() != 0) {
throw {"errorTitle": "not sunday", "errorMessage": template.errors.not_sunday};
}
let date = dateFormat(new Date(), "dd/mm/yyyy");
let params = {
TableName: pricesTable,
KeyConditionExpression: "#dt = :dddd",
ExpressionAttributeNames: {
"#dt":"date",
"#p": "purchase"
},
FilterExpression:"attribute_exists(#p)",
ExpressionAttributeValues: {
":dddd": date
}
}
return dynamodbService.query(params)
})
.then(async(itemList) => {
if(itemList.length) {
let title = `Estos son los precios de compra:`;
let composeMessage = await template.listPrices(itemList, "purchase");
return bot.sendMessage(userId, title + composeMessage);
}
return bot.sendMessage(userId, template.purchaseList.noPrices);
})
.catch((err) => {
if(err.errorTitle) {
let response = err.errorTitle == "access_denied" ? chatId : userId;
return bot.sendMessage(response, err.errorMessage);
}
return bot.sendMessage(userId, template.errors.purchaseListError);
})
});
bot.onText(template.commands.start, function(msg){
var chatId = msg.chat.id;
bot.sendMessage(chatId, template.startBot);
});
bot.onText(template.commands.help, function(msg){
var chatId = msg.chat.id;
let userId = msg.from.id
return usersService.getUser(userId)
.then((userData) => {
//TODO: format
bot.sendMessage(chatId, template.helpMessage);
})
.catch((err) => {
console.log(err)
if(err.errorTitle) {
let response = err.errorTitle == "access_denied" ? chatId : userId;
return bot.sendMessage(response, err.errorMessage);
}
return bot.sendMessage(userId, template.errors.helpError);
})
});
bot.onText(template.commands.register, function(msg){
const chatId = msg.chat.id;
const userId = msg.from.id;
console.log(`Si has lanzado este comando desde el chat grupal, el groupId es: ${chatId}`)
if(chatId != userId) {
throw {"errorTitle": "register_private", "errorMessage": template.errors.register_private};
}
bot.getChatMember(groupId, chatId)
.then((chatMember) => {
if(chatMember.status != "creator" && chatMember.status != "member") {
throw {"errorTitle": "membership_required", "errorMessage": template.errors.membership_required};
}
let username = msg.from.username ? msg.from.username : "";
let params = {
"chat_id": chatId,
username,
"displayName": chatMember.user.first_name
}
return dynamodbService.put(params, usersTable)
})
.then((onInsert) => {
return bot.sendMessage(chatId, template.registerResponse(onInsert.displayName));
})
.catch((err) => {
console.log(err)
if(err.errorTitle) {
let response = err.errorTitle == "access_denied" ? chatId : userId;
return bot.sendMessage(response, err.errorMessage);
}
return bot.sendMessage(chatId, template.errors.registerError);
})
});