Advertisement
Guest User

Untitled

a guest
Feb 10th, 2016
152
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.botName  = 'бот',
  13.       this.modDialg = 1,
  14.       this.tempPoll = {},
  15.       this.tempMsg  = {},
  16.       this.bodyMsg  = {},
  17.       this.fullMsg  = false,
  18.       this.typeMsg  = 0,
  19.       this.changeS  = false,
  20.       this.limitMsg = {},
  21.       this.token    = 0,
  22.       this.botID    = 0,
  23.       this.reqBot   = 0;
  24.      
  25.     this.commandBot = [];
  26.     this.wordBot = {};
  27.     this.usersChat = {};
  28.   }
  29.  
  30.   authBot() {
  31.     try {
  32.       request(this.getObject('auth'), (error, response, body) => {
  33.         if (!error && response.statusCode === 200) {
  34.           this.temp = this.parseJSON(body);
  35.           this.token = this.temp['access_token'];
  36.           this.botID = this.temp['user_id'];
  37.          
  38.           this.getLongPollServer();
  39.          
  40.           console.log(`Авторизация прошла успешно, ID: ${this.botID}`);
  41.         } else {
  42.           throw new Error(`Авторизация провалилась, подробнее: ${body}`);
  43.         }
  44.       });
  45.     } catch(e) {
  46.       console.log(e);
  47.     }
  48.   }
  49.  
  50.   setName(name) {
  51.     this.botName = name.toLowerCase();
  52.   }
  53.  
  54.   setWord(word) {
  55.     this.wordBot = word;
  56.   }
  57.  
  58.   setChangeStatus(bool, callback) {
  59.     this.changeS = bool;
  60.     callback();
  61.   }
  62.  
  63.   getLongPollServer() {
  64.     try {
  65.       request(this.getObject('longpollServer'), (error, response, body) => {
  66.         if (!error && response.statusCode === 200) {
  67.           this.tempPoll = this.parseJSON(body)['response'];
  68.           this.getLongPollMessage();
  69.            
  70.           console.log(`Бот успешно получил данные с лонгполлинг сервера`);
  71.         } else {
  72.           throw new Error(`Получение данных с лонгполлинг сервера не удалось, подробнее: ${body}`);
  73.         }
  74.       });
  75.     } catch(e) {
  76.       console.log(e);
  77.     }
  78.   }
  79.  
  80.   getLongPollMessage() {
  81.       request(this.getObject('longpollMessage'), (error, response, body) => {
  82.         try {
  83.           let data = this.parseJSON(body);
  84.           if('failed' in data) {
  85.             this.longpollServer();
  86.           } else {
  87.             this.tempPoll['ts'] = this.parseJSON(body)['ts'];
  88.             this.getMessage(this.parseJSON(body)['updates']);
  89.             this.getLongPollMessage();
  90.              
  91.             console.log(`Обновление сообщения с лонгполлинг сервера полученно`, this.parseJSON(body));
  92.           }
  93.         } catch(e) {
  94.           this.getLongPollMessage();
  95.      
  96.           console.log(`Сообщения не появлялись, попробуем снова`);
  97.         }
  98.       });
  99.     return this;
  100.   }
  101.  
  102.   getMessage(message) {
  103.     try {
  104.       let block = message[0];
  105.       if(6 in block) {
  106.         this.tempMsgID = block[1];
  107.         request(this.getObject('getMessage'), (error, response, body) => {
  108.           if (!error && response.statusCode === 200) {
  109.             this.tempMsg = this.parseJSON(body);
  110.             this.filterMessage();
  111.            
  112.             console.log(`Полученны json данные о сообщении`);
  113.           } else {
  114.             console.log(`Невозможно получить json данные сообщения ${this.tempMsg}, подробнее: ${error}`);
  115.           }
  116.         });
  117.       }
  118.     } catch(e) {
  119.       //console.log(e);
  120.     }
  121.   }
  122.  
  123.   filterMessage() {
  124.     try {
  125.       this.bodyMsg = this.tempMsg['response'][1];
  126.      
  127.       if('chat_id' in this.bodyMsg) {
  128.         this.typeMsg = 0;
  129.         this.getUsersChat(this.bodyMsg['chat_active']);
  130.       } else {
  131.         this.typeMsg = 1;
  132.       }
  133.        
  134.       let commandStatus = 0;
  135.      
  136.       if(this.bodyMsg['body'].toLowerCase().match(this.botName)) {
  137.         this.fullMsg = false;
  138.        
  139.         for(let i = 0; i < this.commandBot.length; i+=2) {
  140.          
  141.           this.commandBot[i].split(' ').forEach((item) => {
  142.             if(this.bodyMsg['body'].toLowerCase().match(item)) {
  143.               if(commandStatus === 0) {
  144.                
  145.                 if(this.checkLimit(10) === false)
  146.                   return false;
  147.                
  148.                 this.fullMsg = this.bodyMsg['body'].toLowerCase().replace(this.botName, '').replace(item, '').replace(',', '').trim();
  149.                 this.commandBot[i+1]();
  150.                 this.reqBot++;
  151.                
  152.                 commandStatus = 1;
  153.               }
  154.             }
  155.           });
  156.         }
  157.       }
  158.      
  159.       if(this.modDialg === 1) {
  160.         let text = this.bodyMsg['body'].toLowerCase();
  161.        
  162.         if(text in this.wordBot) {
  163.           let sizeObject = Object.keys(this.wordBot[text]).length;
  164.          
  165.           this.sendMessage(this.wordBot[text][parseInt(Math.random() * sizeObject)+1], {
  166.             attachMessage: false,
  167.             limitWord: 1
  168.           });
  169.         }
  170.       }
  171.  
  172.       console.log(`${this.bodyMsg['uid']}: ${this.bodyMsg['body']}`);
  173.     } catch(e) {
  174.       console.log(`${e} непредвиденная ошибка ${this.bodyMsg}`);
  175.     }
  176.   }
  177.  
  178.   checkLimit(num) {
  179.     let sender = this.bodyMsg['uid'], status = true;
  180.    
  181.     if(sender in this.limitMsg) {
  182.       if(this.limitMsg[sender]['msg'] === num) {
  183.         status = false;
  184.        
  185.         if(this.limitMsg[sender]['timeout'] === false) {
  186.           setTimeout(() => {
  187.             this.limitMsg[sender]['msg'] = 0;
  188.             this.limitMsg[sender]['timeout'] = false;
  189.           }, 60000);
  190.           this.limitMsg[sender]['timeout'] = true;
  191.         }
  192.       } else {
  193.         if(this.bodyMsg['uid'] != this.botID)
  194.           this.limitMsg[sender]['msg']++;
  195.       }
  196.     } else {
  197.       this.limitMsg[sender] = {};
  198.       this.limitMsg[sender]['msg'] = 0;
  199.       this.limitMsg[sender]['timeout'] = false;
  200.     }
  201.    
  202.     console.log(this.limitMsg, sender);
  203.    
  204.     return status;
  205.   }
  206.  
  207.   getUsersChat(ids) {
  208.     if(this.bodyMsg['chat_id'] in this.usersChat)
  209.       return false;
  210.    
  211.     request({
  212.       url:                  'http://api.vk.com/method/users.get',
  213.       qs: {
  214.         user_ids:           ids
  215.       }
  216.     }, (error, response, body) => {
  217.       if (!error && response.statusCode === 200) {
  218.         try {
  219.           this.usersChat[this.bodyMsg['chat_id']] = this.parseJSON(body)['response'];
  220.         } catch(e) {
  221.           console.log(e);
  222.         }
  223.       }
  224.     });
  225.   }
  226.  
  227.   sendMessage(messageText, options) {
  228.     let optionsDefault = {
  229.       attachMessage: true,
  230.       limitWord: 10,
  231.       attach: false
  232.     };
  233.    
  234.     if('attachMessage' in options)
  235.       optionsDefault['attachMessage'] = options['attachMessage'];
  236.     if('limitWord' in options)
  237.       optionsDefault['limitWord'] = options['limitWord'];
  238.     if('attach' in options)
  239.       optionsDefault['attach'] = options['attach'];
  240.    
  241.     if(this.bodyMsg.body.split(' ').length > optionsDefault['limitWord'])
  242.       return false;
  243.    
  244.     let object = {
  245.       url:                  'https://api.vk.com/method/messages.send',
  246.       method:               'GET',
  247.       qs: {
  248.         access_token:       this.token,
  249.         guid:               parseInt(Math.random() * 500010),
  250.         message:            messageText
  251.       }
  252.     };
  253.    
  254.     if(this.typeMsg === 0)
  255.       object['qs']['chat_id'] = this.bodyMsg['chat_id'];
  256.     else
  257.       object['qs']['user_id'] = this.bodyMsg['uid'];
  258.      
  259.     if(optionsDefault['attachMessage'] === true)
  260.       object['qs']['forward_messages'] = this.bodyMsg['mid'];
  261.      
  262.     if(optionsDefault['attach'] !== false) {
  263.       let attach = '', index = 0;
  264.       for(let key in optionsDefault['attach']) {
  265.         attach += optionsDefault['attach'][key];
  266.         if(index > 0) attach += ',';
  267.         index++;
  268.       }
  269.       object['qs']['attachment'] = attach;
  270.     }
  271.    
  272.    
  273.     request(object, (error, response, body) => {
  274.       if (!error && response.statusCode === 200) {
  275.         //console.log(body);
  276.       }
  277.     });
  278.   }
  279.  
  280.   changeStatus(text) {
  281.     if(this.changeS === true) {
  282.       request({
  283.         url: 'https://api.vk.com/method/status.set',
  284.         qs: {
  285.           access_token:   this.token,
  286.           text: text
  287.         }
  288.       }, (error, response, body) => {
  289.         console.log('Смена статуса произведена');
  290.       });
  291.     }
  292.   }
  293.  
  294.   addCommand(text, callback) {
  295.     this.commandBot.push(text.toLowerCase(), callback);
  296.   }
  297.  
  298.   parseJSON(json) {
  299.     try {
  300.       return JSON.parse(json);
  301.     } catch(e) {
  302.       console.log('Невозможно преобразовать в JSON формат');
  303.     }
  304.   }
  305.  
  306.   getObject(name) {
  307.     switch(name) {
  308.       case 'auth':
  309.         return {
  310.           url:              'https://oauth.vk.com/token',
  311.           method:           'GET',
  312.           qs: {
  313.             grant_type:     'password',
  314.             client_id:      2274003,
  315.             client_secret:  'hHbZxrka2uZ6jB1inYsH',
  316.             username:       this.login,
  317.             password:       this.password
  318.           }
  319.         };
  320.       case 'longpollServer':
  321.         return {
  322.           url:              'https://api.vk.com/method/messages.getLongPollServer',
  323.           method:           'GET',
  324.           qs: {
  325.             access_token:   this.token,
  326.           }
  327.         };
  328.       case 'longpollMessage':
  329.         return {
  330.           url:              'http://'+this.tempPoll.server,
  331.           method:           'GET',
  332.           qs: {
  333.             act:            'a_check',
  334.             key:            this.tempPoll.key.substr(0, (this.tempPoll.key.length - 10)),
  335.             ts:             this.tempPoll.ts,
  336.             wait:           25,
  337.             mode:           2
  338.           }
  339.         };
  340.       case 'getMessage':
  341.         return {
  342.           url:              'https://api.vk.com/method/messages.getById',
  343.           method:           'GET',
  344.           qs: {
  345.             access_token:   this.token,
  346.             message_ids:    this.tempMsgID
  347.           }
  348.         };
  349.     }
  350.   }
  351. }
  352.  
  353. module.exports = dialogBotVK;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement