PageRenderTime 10ms CodeModel.GetById 1ms app.highlight 6ms RepoModel.GetById 1ms app.codeStats 0ms

/modules/services/duckduckgo.js

https://bitbucket.org/slimdll/botphp
JavaScript | 58 lines | 56 code | 2 blank | 0 comment | 4 complexity | e2d9f334e51424827235e004880bbfe1 MD5 | raw file
 1'use strict'
 2
 3const s = require('../settings')
 4
 5const url = require('url')
 6const http = require('http')
 7const parse = { 'parse_mode': 'HTML' }
 8const stickers = [
 9  'BQADBAADMgEAAl6A9AWiXNcdh4N2fgI',
10  'BQADBAADzQADXoD0BfaPN-SRlpBYAg',
11  'BQADBAADxQADXoD0Be6MWaqIBanrAg',
12  'BQADBAADAQEAAl6A9AVrEFjvEfTbRwI',
13  'BQADBAADOQEAAl6A9AWLW7oQoiHXdAI',
14  'BQADBAADBwEAAl6A9AXuD8xAc5avLwI',
15  'BQADBAADxwADXoD0BaTJK9_y3lrtAg',
16  'BQADBAADyQADXoD0BYyFKrC9hFpcAg',
17  'BQADBAADywADXoD0BaJ-5YWTuZxTAg',
18  'BQADBAADzwADXoD0BactihrL_9LKAg',
19  'BQADBAAD6wADXoD0Bbi4Fg2kp0fUAg'
20]
21const execute = (bot, msg, match) => {
22  const query = match.query
23  const _base = 'http://api.duckduckgo.com/?format=json&q='
24  const _url = url.parse(_base + encodeURIComponent(query))
25  _url.headers = {
26    'User-Agent': 'Telegram Bot',
27    'Accept-Language': 'pt-BR;q=1, pt;q=0.8, en;q=0.5'
28  }
29  const req = http.request(_url, (res) => {
30    let data = ''
31    res.on('data', (chunk) => data += chunk)
32    res.on('end', (err) => {
33      try {
34        data = JSON.parse(data)
35        if (data.AbstractText !== '') {
36          const _return = 'Achei isso no DuckDuckGo: <i>' + data.AbstractText + '</i> Saiba mais em ' + data.AbstractURL
37          bot.sendMessage(msg.chat.id, _return, parse).catch(console.log)
38          console.log('data): ' + data)
39        } else {
40          const sticker = stickers[Math.floor(Math.random() * stickers.length)]
41          const _return = '<b>Não achei nada jovem!</b> Sorry mesmo, mas você pode fumar um pra relaxar.'
42          bot.sendMessage(msg.chat.id, _return, parse).catch(console.log)
43          s.get(msg.chat.id, 'stickers', (err, data) => {
44            if (data == 'true') bot.sendSticker(msg.chat.id, sticker).catch(console.log)
45          })
46        }
47      } catch (e) {
48        bot.sendMessage(msg.chat.id, 'DEU MERDA: ' + e).catch(console.log)
49        console.log('Erro end: ' + err)
50      }
51    })
52  })
53  req.end()
54  req.on('error', (e) => console.error(e))
55}
56module.exports = {
57  execute
58}