-
Notifications
You must be signed in to change notification settings - Fork 0
/
api.js
291 lines (284 loc) · 12 KB
/
api.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
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
var { APIAI_TOKEN } = process.env
const apiai = require('apiai')(APIAI_TOKEN)
const express = require('express')
const axios = require('axios')
const cheerio = require('cheerio')
const router = express.Router()
const bodyParser = require('body-parser')
router.use(bodyParser.urlencoded({ extended: false }))
router.use(bodyParser.json())
router.use((req, res, next) => {
console.log('A')
console.log(req.get('Origin'))
res.header("Access-Control-Allow-Origin", "https://yunisdev.github.io");
res.header("Access-Control-Allow-Credentials", "true");
res.header("Access-Control-Allow-Methods", "GET,HEAD,OPTIONS,POST,PUT");
res.header("Access-Control-Allow-Headers", "Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers");
next();
});
router.get('/api', (req, res) => {
res.status(200).json({
message: 'API v1',
author: 'Yunis Huseynzade'
})
})
router.post('/api/webhook', (req, Res) => {
try {
const functionList = {
currencyConvert({ parameters, queryText }) {
var resolvedQuery = queryText
var from = parameters['unit-currency']['currency']
if (from == 'XBT') {
from = 'BTC'
}
var q = resolvedQuery.toLowerCase()
if ((q.includes('try') || q.includes('turkish lira')) && !from) {
from = 'try'
}
var to = parameters['currency-name']
if (to == 'XBT') {
to = 'BTC'
}
var amount = parameters['unit-currency']['amount']
if (from && to && amount) {
var url = `https://exchangerate.guru/${from.toLowerCase()}/${to.toLowerCase()}/${amount}/`
axios.get(url).then((res) => {
var html = res.data
const $ = cheerio.load(html)
const value = $('div.conversion-content div.blockquote-classic p span.pretty-sum')
Res.send({
"fulfillmentMessages": [
{
"text": {
"text": [
value.eq(1).text() + ' ' + to
]
}
}
]
})
}).catch((e) => {
Res.send({
"fulfillmentMessages": [
{
"text": {
"text": [
"Can not do this operation"
]
}
}
]
})
})
} else {
Res.send({
"fulfillmentMessages": [
{
"text": {
"text": [
"Can not do this operation"
]
}
}
]
})
}
},
countryInfo: ({ parameters }) => {
axios.get(`https://restcountries.eu/rest/v2/alpha/${parameters['geo-country-code'][parameters['geo-country-code'].length - 1]['alpha-3'].toLowerCase()}`)
.then(response => {
var typeOfData = parameters['country-info-type']
if (typeOfData == 'currencies' || typeOfData == 'languages') {
var dataForReturn = []
response.data[typeOfData].forEach(i => {
dataForReturn.push(i.name)
})
Res.send({
"fulfillmentMessages": [
{
"text": {
"text": [
dataForReturn.join(',')
]
}
}
]
})
} else {
Res.send({
"fulfillmentMessages": [
{
"text": {
"text": [
response.data[typeOfData] || 'I don\'t know.'
]
}
}
]
})
}
})
.catch(error => {
console.log(error);
});
},
globalStats: ({ parameters }) => {
var type = parameters['global-stats-types']
if (type == 'covid19') {
axios.get(`https://www.worldometers.info/coronavirus/`).then((res) => {
var html = res.data
const $ = cheerio.load(html)
const value = $('.maincounter-number')
Res.send({
"fulfillmentMessages": [
{
"text": {
"text": [
`${value.eq(0).text()} total cases, ${value.eq(1).text()} deaths, ${value.eq(2).text()} recovered`
]
}
}
]
})
}).catch((e) => {
Res.send({
"fulfillmentMessages": [
{
"text": {
"text": [
'Can not do this operation'
]
}
}
]
})
})
} else if (type == 'worldPopulation') {
axios.get(`https://www.worldometers.info/world-population/`).then((res) => {
var html = res.data
const $ = cheerio.load(html)
const value = $('[rel="current_population"]')
Res.send({
"fulfillmentMessages": [
{
"text": {
"text": [
value.text()
]
}
}
]
})
}).catch((e) => {
Res.send({
"fulfillmentMessages": [
{
"text": {
"text": [
'Can not do this operation'
]
}
}
]
})
})
}
},
}
var key = req.body.queryResult.fulfillmentText
console.log(JSON.stringify(req.body))
if (functionList[key]) {
functionList[key](req.body.queryResult)
} else {
Res.send({
"fulfillmentMessages": [
{
"text": {
"text": [
req.body.queryResult.fulfillmentText
]
}
}
]
})
}
} catch (e) {
console.log(e.message)
}
})
router.post('/api/req', (req, Res) => {
try {
const dataResolver = {
searchQuery: ({ parameters }) => {
axios.get('https://en.wikipedia.org/w/api.php?action=query&format=json&list=search&srsearch=' + parameters['query'])
.then((res) => {
var data = res.data.query.search[0]
Res.send({
type: 'bot reply multi',
result: [`
<div style="width:100%;max-width:100%;">
<h4 style="display:block;font-weight:bold">${data.title}</h4>
<p>${data.snippet}...<a target="_blank" href="https://en.wikipedia.org/wiki/${data.title.split(' ').join('_')}">read more</a></p>
</div>
`, 'I have found something like this.']
})
})
.catch((err) => {
console.log(err.message)
})
},
youAreWrong: ({ }) => {
Res.send({
type: 'bot reply multi',
result: [
`I will be happy if you help me to be better. For this you can open issue by <a href="https://github.com/YunisDEV/JessieAI/issues">clicking here</a>`,
`I will be happy if you help me to be better. For this you can open issue by clicking here`
]
})
},
sleepTactics: ({ }) => {
Res.send({
type: 'bot reply multi',
result: [
`You can check <a target="_blank" href="https://www.healthline.com/nutrition/ways-to-fall-asleep">'20 Simple Tips That Help You Fall Asleep Quickly'</a> article`,
`You can check '20 Simple Tips That Help You Fall Asleep Quickly' article`
]
})
},
relaxTactics: ({ }) => {
Res.send({
type: 'bot reply multi',
result: [
`You can check <a target="_blank" href="https://www.healthline.com/health/stress/how-to-relax">'How to Relax: Tips for Chilling Out'</a> article`,
`You can check 'How to Relax: Tips for Chilling Out' article`
]
})
},
clearScreen: () => {
Res.send({ type: 'bot do', result: 'clearScreen' })
},
changeTheme: () => {
Res.send({ type: 'bot do', result: 'changeTheme' })
}
}
var { text } = req.body
let apiaiReq = apiai.textRequest(text, {
sessionId: Math.random() * 10000
})
apiaiReq.on('response', (response) => {
var aiText = response.result.fulfillment.messages[response.result.fulfillment.messages.length - 1].speech || response.result.fulfillment.speech
if (dataResolver[aiText]) {
dataResolver[aiText](response.result)
} else {
Res.send({ type: 'bot reply', result: aiText })
}
})
apiaiReq.on('error', (error) => {
console.log(error)
})
apiaiReq.end()
} catch (e) {
console.log(e.message)
}
})
module.exports = router