Advertisement
Guest User

Untitled

a guest
Feb 7th, 2016
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. 'use strict';
  2.  
  3. let request = require('request'),
  4.     fs = require('fs');
  5.  
  6. class dialogBotVK {
  7.   constructor(login, password) {
  8.     this.login      = login,
  9.       this.password = password,
  10.       this.safe     = true,
  11.       this.temp     = false,
  12.       this.apiVer   = '5.44',
  13.       this.botName  = 'бот',
  14.       this.modDialg = 0,
  15.       this.tempPoll = {},
  16.       this.tempMsg  = {},
  17.       this.bodyMsg  = {},
  18.       this.typeMsg  = 0,
  19.       this.token    = 0,
  20.       this.botID    = 0;
  21.      
  22.     this.commandBot = [];
  23.     this.wordBot = {};
  24.     this.usersChat = {};
  25.   }
  26.  
  27.   authBot() {
  28.     try {
  29.       request(this.getObject('auth'), (error, response, body) => {
  30.         if (!error && response.statusCode == 200) {
  31.           this.temp = this.parseJSON(body);
  32.           this.token = this.temp['access_token'];
  33.           this.botID = this.temp['user_id'];
  34.          
  35.           this.getLongPollServer();
  36.         } else {
  37.           throw new Error(`Ошибка отправки запроса авторизации, подробнее: ${body}`);
  38.         }
  39.       });
  40.     } catch(e) {
  41.       console.log(e);
  42.     }
  43.   }
  44.  
  45.   setName(name) {
  46.     this.botName = name.toLowerCase();
  47.   }
  48.  
  49.   setWord(word) {
  50.     this.wordBot = word;
  51.   }
  52.  
  53.   getLongPollServer() {
  54.     request(this.getObject('longpollServer'), (error, response, body) => {
  55.       try {
  56.         if (!error && response.statusCode == 200) {
  57.           this.tempPoll = this.parseJSON(body)['response'];
  58.           this.getLongPollMessage();
  59.         } else {
  60.           throw new Error(`Ошибка получения данных longpoll сервера, подробнее: ${body}`);
  61.         }
  62.       } catch(e) {
  63.         console.log(e);
  64.       }
  65.     });
  66.   }
  67.  
  68.   getLongPollMessage() {
  69.     request(this.getObject('longpollMessage'), (error, response, body) => {
  70.       try {
  71.         this.tempPoll['ts'] = this.parseJSON(body)['ts'];
  72.         this.getLongPollMessage().getMessage(this.parseJSON(body)['updates']);
  73.       } catch(e) {
  74.         this.getLongPollMessage();
  75.       }
  76.     });
  77.     return this;
  78.   }
  79.  
  80.   getMessage(message) {
  81.     try {
  82.       let block = message[0];
  83.       if(6 in block) {
  84.         this.tempMsgID = block[1];
  85.         request(this.getObject('getMessage'), (error, response, body) => {
  86.           if (!error && response.statusCode == 200) {
  87.             this.tempMsg = this.parseJSON(body);
  88.             this.filterMessage();
  89.           } else {
  90.             console.log(`Невозможно получить json данные сообщения ${this.tempMsgID}, подробнее: ${body}`);
  91.           }
  92.         });
  93.       }
  94.     } catch(e) {
  95.       //console.log(e);
  96.     }
  97.   }
  98.  
  99.   filterMessage() {
  100.     try {
  101.       this.bodyMsg = this.tempMsg['response'][1];
  102.      
  103.       if('chat_id' in this.bodyMsg) {
  104.         this.typeMsg = 0;
  105.         this.getUsersChat(this.bodyMsg['chat_active']);
  106.       } else {
  107.         this.typeMsg = 1;
  108.       }
  109.        
  110.       let commandStatus = 0;
  111.       if(this.bodyMsg.body.toLowerCase().match(this.botName, 'g')) {
  112.         for(let i = 0; i < this.commandBot.length; i+=2) {
  113.           commandStatus = 0;
  114.           this.commandBot[i].split(' ').forEach((item) => {
  115.             if(this.bodyMsg.body.toLowerCase().match(item, 'g')) {
  116.               if(commandStatus === 0) {
  117.                 this.commandBot[i+1]();
  118.                 commandStatus = 1;
  119.               }
  120.             }
  121.           });
  122.         }
  123.       }
  124.      
  125.       if(this.modDialg === 1) {
  126.         if(this.bodyMsg['body'].toLowerCase() in this.wordBot) {
  127.           let sizeObject = Object.keys(this.wordBot[this.bodyMsg['body']]).length;
  128.           this.sendMessage(this.wordBot[this.bodyMsg['body']][parseInt(Math.random() * sizeObject)], {
  129.             attachMessage: false,
  130.             limitWord: 1
  131.           });
  132.         }
  133.       }
  134.      
  135.       if(this.bodyMsg.body.toLowerCase().match(/.*?\).*(\?\)|\))/g)) {
  136.         let text = this.bodyMsg.body.toLowerCase().match(/.*?\).*(\?\)|\))/g)[0];
  137.        
  138.         fs.readFile('lavash.txt', {encoding: 'utf8'}, function (err, data) {
  139.           if (err) {
  140.             fs.writeFile("lavash.txt", '{}');
  141.           }
  142.           try {
  143.             let test = JSON.parse(data);
  144.             test[Object.keys(test).length] = text;
  145.            
  146.             fs.writeFile("lavash.txt", JSON.stringify(test));
  147.           } catch(e) {
  148.             fs.writeFile("lavash.txt", '{}');
  149.           }
  150.         });
  151.       }
  152.  
  153.       console.log(this.typeMsg, this.tempMsg);
  154.     } catch(e) {
  155.       console.log(e);
  156.     }
  157.   }
  158.  
  159.   getUsersChat(ids) {
  160.     if(this.bodyMsg['chat_id'] in this.usersChat)
  161.       return false;
  162.    
  163.     request({
  164.       url:                  'http://api.vk.com/method/users.get',
  165.       qs: {
  166.         user_ids:           ids
  167.       }
  168.     }, (error, response, body) => {
  169.       if (!error && response.statusCode == 200) {
  170.         try {
  171.           this.usersChat[this.bodyMsg['chat_id']] = this.parseJSON(body)['response'];
  172.         } catch(e) {
  173.           console.log(e);
  174.         }
  175.       }
  176.     });
  177.   }
  178.  
  179.   sendMessage(messageText, options) {
  180.     /*if(this.botID == this.bodyMsg['uid'])
  181.       return true;*/
  182.      
  183.     let optionsDefault = {
  184.       attachMessage: true,
  185.       limitWord: 10
  186.     };
  187.    
  188.     optionsDefault['attachMessage'] = options['attachMessage'];
  189.     optionsDefault['limitWord'] = options['limitWord'];
  190.    
  191.     if(this.bodyMsg.body.split(' ').length > optionsDefault['limitWord'])
  192.       return false;
  193.    
  194.     let object = {
  195.       url:                  'https://api.vk.com/method/messages.send',
  196.       method:               'GET',
  197.       qs: {
  198.         access_token:       this.token,
  199.         guid:               parseInt(Math.random() * 500010),
  200.         message:            messageText
  201.       }
  202.     };
  203.    
  204.     if(this.typeMsg == 0)
  205.       object['qs']['chat_id'] = this.bodyMsg['chat_id'];
  206.     else
  207.       object['qs']['user_id'] = this.bodyMsg['uid'];
  208.      
  209.     if(optionsDefault['attachMessage'] == true)
  210.       object['qs']['forward_messages'] = this.bodyMsg['mid'];
  211.    
  212.    
  213.     request(object, (error, response, body) => {
  214.       if (!error && response.statusCode == 200) {
  215.         //console.log(body);
  216.       }
  217.     });
  218.   }
  219.  
  220.   addCommand(text, callback) {
  221.     this.commandBot.push(text.toLowerCase(), callback);
  222.   }
  223.  
  224.   parseJSON(json) {
  225.     try {
  226.       return JSON.parse(json);
  227.     } catch(e) {
  228.       console.log('Невозможно преобразовать в JSON формат');
  229.     }
  230.   }
  231.  
  232.   getObject(name) {
  233.     switch(name) {
  234.       case 'auth':
  235.         return {
  236.           url:              'https://oauth.vk.com/token',
  237.           method:           'GET',
  238.           qs: {
  239.             grant_type:     'password',
  240.             client_id:      2274003,
  241.             client_secret:  'hHbZxrka2uZ6jB1inYsH',
  242.             username:       this.login,
  243.             password:       this.password
  244.           }
  245.         };
  246.       break;
  247.       case 'longpollServer':
  248.         return {
  249.           url:              'https://api.vk.com/method/messages.getLongPollServer',
  250.           method:           'GET',
  251.           qs: {
  252.             access_token:   this.token,
  253.           }
  254.         };
  255.       break;
  256.       case 'longpollMessage':
  257.         return {
  258.           url:              'http://'+this.tempPoll.server,
  259.           method:           'GET',
  260.           qs: {
  261.             act:            'a_check',
  262.             key:            this.tempPoll.key.substr(0, (this.tempPoll.key.length - 10)),
  263.             ts:             this.tempPoll.ts,
  264.             wait:           25,
  265.             mode:           2
  266.           }
  267.         };
  268.       break;
  269.       case 'getMessage':
  270.         return {
  271.           url:              'https://api.vk.com/method/messages.getById',
  272.           method:           'GET',
  273.           qs: {
  274.             access_token:   this.token,
  275.             message_ids:    this.tempMsgID
  276.           }
  277.         };
  278.       break;
  279.     }
  280.   }
  281. }
  282.  
  283. module.exports = dialogBotVK;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement