Advertisement
Guest User

Untitled

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