stuppid_bot

Бот для контакта

Mar 26th, 2013
267
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // Пишите ваши предложения и пожелания на [email protected]
  2. // this - Window
  3.  
  4.  
  5. function Bot() {
  6.     var hello = this.hello = ['Здравствуй', 'Привет', 'Ку', 'Салют'];
  7.    
  8.     var labels = {
  9.         add_friends: 'Добавить друзей',
  10.         invite: 'Пригласить в группу',      
  11.         im2list: 'Рассылка по списку',
  12.         im2friends: 'Рассылка друзьям'
  13.     };
  14.    
  15.     var shuffle = function(arr) {
  16.         var i = 0, j, k, l = arr.length;
  17.  
  18.         while (i < l) {
  19.             j = Math.floor(Math.random() * l);
  20.             k = arr[i];
  21.             arr[i++] = arr[j];
  22.             arr[j] = k;
  23.         }
  24.     }
  25.    
  26.     var greeting = function() {
  27.         var hour = new Date().getHours();
  28.         return hour >= 22 || hour < 6 ? 'Доброй ночи' : ( hour >= 18 ? 'Добрый вечер' : (hour >= 12 ? 'Добрый день' : 'Доброе утро') );
  29.     }
  30.    
  31.     var parseMessage = this.parseMessage = function(input, extra) {
  32.         var ret = {
  33.                 title: '',
  34.                 media: ''
  35.             },
  36.            
  37.             reps = {
  38.                 hello: hello[ Math.floor( Math.random() * hello.length ) ],
  39.                 greeting: greeting()
  40.             };
  41.            
  42.         for (var prop in extra) {
  43.             reps[prop] = extra[prop];
  44.         }
  45.    
  46.         // {Вариант 1|Вариант 2|Вариант 3}
  47.         ret.body = input.replace(/\{(.+?)\}/g, function(str, match) {
  48.             match = match.split('|');
  49.             return match[ Math.floor( Math.random() * match.length ) ];
  50.         // %hello%, %id%, %name%, %surname%, %fullname%
  51.         }).replace(/%(.+?)%/g, function(str, match) {
  52.             return reps[match] ? reps[match] : str;
  53.         // <title>Заголовок</title>
  54.         // <media>photo:1_2,audio:3_4,video:5_6</media>
  55.         // <snippet>new Date()</snippet>
  56.         }).replace(/<(\w+)>(.*?)<\/\1>/g, function(str, tag, content) {
  57.             switch (tag) {
  58.                 case 'title':
  59.                     ret.title = content;
  60.                     return '';
  61.            
  62.                 case 'media':
  63.                     ret.media = content;
  64.                     return '';
  65.                    
  66.                 case 'snippet':
  67.                     eval('content=(function(){return ' + content + '})()');
  68.                     return content;
  69.             }
  70.            
  71.             return str;
  72.         });
  73.  
  74.         return ret;
  75.     }
  76.    
  77.     var selDialog = function(peer, cb) {
  78.         ajax.post('al_im.php', {
  79.             act: 'a_start',
  80.             peer: peer
  81.         }, {
  82.             onDone: function (response) {
  83.                 cb(response);
  84.             }
  85.         });
  86.     }
  87.    
  88.     // Функция для вычисления хэша при отправке личного сообщения.
  89.     //
  90.     // im.js:2069
  91.     // decHash: function(hash) {
  92.     //   (function(_){cur.decodedHashes[_]=(function(__){var ___=ge?'':'___';for(____=0;____<__.length;++____)___+=__.charAt(__.length-____-1);return geByClass?___:'___';})(_.substr(_.length-5)+_.substr(4,_.length-12));})(hash);
  93.     // },  
  94.     var hashIM = function(hash) {
  95.         return ( hash.slice(-5) + hash.substr(4, hash.length - 12) ).split('').reverse().join('');
  96.     }
  97.    
  98.     var _sendIM = function(user_id, hash, title, body, media, done) {
  99.         ajax.post('al_im.php', {
  100.             act: 'a_send',
  101.             al: 1,
  102.             to: user_id,
  103.             hash: hash,
  104.             title: title,
  105.             msg: body,
  106.             media: media                
  107.         }, { onDone: done });
  108.     }
  109.    
  110.     var notifyIM = function(user_id, fullname, sex, message, photo) {
  111.         Notifier.showEvent({
  112.             title: 'Сообщение доставлено',
  113.             text: '<a href="im?sel=' + user_id + '" target="_blank" class="mem_link">' + fullname + '</a> получил' + (sex == 1 ? 'а' : '') + ' сообщение:<p>' + message + '</p>',                            
  114.             author_photo: photo,
  115.             author_link: '',
  116.             add_photo: ''                                  
  117.         });
  118.     }
  119.  
  120.     var sendIM = this.sendIM = function(user_id, message) {
  121.         selDialog(user_id, function(dialog) {
  122.             message = parseMessage(message, {
  123.                id: user_id,
  124.                name: dialog.name,
  125.                fullname: dialog.tab,
  126.                surname: dialog.tab.split(' ')[1]
  127.             });
  128.            
  129.             console.log(dialog);
  130.            
  131.             _sendIM(user_id, hashIM(dialog.hash), message.title, message.body, message.media, function(response) {
  132.                 console.log(response);
  133.                 notifyIM(user_id, dialog.tab, response.sex, message.body, dialog.photo);
  134.             });
  135.         });
  136.     }
  137.    
  138.     var sendIM2List = this.sendIM2List = function(opts) {
  139.         var i = 0, loop = setInterval(function() {
  140.             if (!opts.to_ids[i]) {
  141.                 console.log('Рассылка личных сообщений завершена.');
  142.                 return clearInterval(loop);
  143.             }
  144.            
  145.             if ( !geByClass('captcha')[0] ) {              
  146.                 setTimeout(function() {
  147.                     console.log('#' + (i + 1) + '\t' + new Date().getTime());
  148.                     sendIM(opts.to_ids[i++], opts.message);
  149.                 }, Math.floor(Math.random() * opts.variance));
  150.             }
  151.         }, opts.interval);
  152.     }
  153.          
  154.     // получить список друзей
  155.     var getFriends = this.getFriends = function(cb, opts) {
  156.         opts = opts || {};
  157.         opts.id = opts.id || vk.id;
  158.         opts.city = opts.city ? opts.city.trim().toLowerCase() : '';
  159.        
  160.         ajax.post('al_friends.php', {
  161.             act: 'load_friends_silent',
  162.             al: 1,
  163.             id: opts.id,
  164.             gid: opts.gid || 0        
  165.         }, {
  166.             onDone: function(a, b, c) {
  167.                 // a - друзья, b - учебные заведения, c - города  
  168.                 eval('a=' + a);
  169.                 var friends = a.all;
  170.                 // return console.log(friends);
  171.                
  172.                 if (opts.gid) {
  173.                     friends = friends.filter(function(el) {
  174.                         return el;
  175.                     });
  176.                 }
  177.                
  178.                 if (opts.excludes) {
  179.                     friends = friends.filter(function(el) {
  180.                         return opts.excludes.indexOf( el[0] ) == -1;
  181.                     });
  182.                 }                          
  183.                
  184.                 if (opts.online) {
  185.                     friends = friends.filter(function(el) {
  186.                         return parseInt( el[4] );
  187.                     });
  188.                 }
  189.                
  190.                 if (opts.city || opts.sex || opts.age_from || opts.age_to) {  
  191.                     opts.city = (function() {                        
  192.                         if (opts.city) {                          
  193.                             for (var i = 0, l = c.cities.length; i < l; ++i) {
  194.                                 if (opts.city == c.cities[i][1].toLowerCase()) {
  195.                                     return c.cities[i][0];
  196.                                 }
  197.                             }
  198.                         }
  199.  
  200.                         return 0;
  201.                     })(),                
  202.                
  203.                     ajax.post('friends', {
  204.                         act: 'filter_friends',
  205.                         ads_section: 'friends',
  206.                         age_from: opts.age_from || 0,
  207.                         age_to: opts.age_to || 0,
  208.                         al: 1,
  209.                         al_ad: 1,
  210.                         city: opts.city,
  211.                         sex: opts.sex,
  212.                         uid: opts.id
  213.                     }, {
  214.                         onDone: function(arr) {
  215.                             friends = friends.filter(function(el) {
  216.                                 return arr.indexOf(el[0]) > -1;
  217.                             });
  218.                            
  219.                             cb(friends);
  220.                         }
  221.                     });
  222.                    
  223.                     return;
  224.                 }
  225.                
  226.                 cb(friends);
  227.             }
  228.         });
  229.     }
  230.    
  231.     var sendIM2Friends = this.sendIM2Friends = function(opts) {
  232.         getFriends(function(arr) {
  233.             opts.to_ids = arr.map(function(el) {
  234.                 return el[0];
  235.             });
  236.  
  237.             shuffle(opts.to_ids);            
  238.             sendIM2List(opts);
  239.         }, opts);
  240.     }
  241.    
  242.     var inviteTo = this.inviteTo = function(opts) {  
  243.         // список друзей получаем
  244.         getFriends(function(arr) {
  245.             shuffle(arr);
  246.             console.log(arr);
  247.             // return;
  248.  
  249.             if (arr.length) {
  250.                 var i = 0, loop = setInterval(function() {
  251.                     // проверяем есть ли капча
  252.                     if ( !geByClass('captcha')[0] ) {
  253.                         setTimeout(function() {
  254.                             ajax.post('al_page.php', {
  255.                                 act: 'a_invite',
  256.                                 gid: opts.gid,
  257.                                 mid: arr[i][0],
  258.                                 hash: arr[i][11]
  259.                             }, {
  260.                                 onDone: function(flg, msg) {
  261.                                     console.log('#' + (i + 1) + '\t' + new Date().getTime() + '\n' + msg);
  262.  
  263.                                     if (msg == 'Вы можете пригласить только 40 человек в день.') {                                                                            
  264.                                         i = -2;
  265.                                     }
  266.                                     else {
  267.                                         Notifier.showEvent({
  268.                                             title: labels.invite,
  269.                                             text: '<a href="' + arr[i][2] + '" target="_blank" class="mem_link">' + arr[i][5] + '</a><p>' + msg + '</p>',                            
  270.                                             author_photo: arr[i][1],
  271.                                             author_link: '',
  272.                                             add_photo: ''                                  
  273.                                         });  
  274.                                     }
  275.  
  276.                                     if (!arr[++i]) {
  277.                                         console.log('Рассылка приглашений в группу закончена.');
  278.                                         return clearInterval(loop);
  279.                                     }
  280.                                 },
  281.  
  282.                                 onFail: function(msg) {
  283.                                     console.log(msg);
  284.                                     clearInterval(loop);
  285.                                 }
  286.                             });
  287.                         }, Math.floor(Math.random() * opts.variance));
  288.                     }
  289.                 }, opts.interval);          
  290.             }        
  291.         }, opts);
  292.     }
  293.    
  294.     this.addFriends = function() {
  295.         var offset = 0;
  296.  
  297.         function doStuff() {
  298.             ajax.post('friends', {
  299.                 al: 1,
  300.                 act: 'get_section_friends',
  301.                 section: 'suggestions',
  302.                 offset: offset
  303.             }, {
  304.                 onDone: function(data) {
  305.                     eval('data=(' + data + ').suggestions');
  306.  
  307.                     if (data.length) {
  308.                         var i = 0, loop = setInterval(function() {  
  309.                             if ( !geByClass('captcha')[0] ) {
  310.                                 var arr = data[i++];
  311.                                 console.log(arr);
  312.  
  313.                                 if (!data[i]) {
  314.                                     clearInterval(loop);
  315.                                     doStuff();
  316.                                 }
  317.  
  318.                                 setTimeout(function() {
  319.                                     ajax.post('al_friends.php', {
  320.                                         act: 'add',
  321.                                         mid: arr[0],
  322.                                         hash: arr[8][0],
  323.                                         request: 1,
  324.                                         select_list: 1
  325.                                     }, {
  326.                                         onDone: function(msg) {
  327.                                             console.log('#' + (i + 1) + '\t' + new Date().getTime() + '\n' + msg);
  328.  
  329.                                             if ( /в друзьях/.test(msg) ) {
  330.                                                 msg = 'Заявка принята.';
  331.                                             }
  332.                                             else {                                              
  333.                                                 msg =  'Заявка' + (/уже/.test(msg) ? ' уже' : '') + ' отправлена.';
  334.  
  335.                                                 // убираем из списка возможных друзей
  336.                                                 setTimeout(function() {
  337.                                                     ajax.post('al_friends.php', { act: 'hide_possible', al: 1, mid: arr[0], hash: arr[8][1] });
  338.                                                 }, irand(1000, 3000));
  339.                                             }                                                                                                                            
  340.  
  341.                                             Notifier.showEvent({
  342.                                                 title: labels.add_friends,
  343.                                                 text: '<a href="id' + arr[0] + '" target="_blank" class="mem_link">' + arr[5] + '</a><p>' + msg + '</p>',                            
  344.                                                 author_photo: arr[1],
  345.                                                 author_link: '',
  346.                                                 add_photo: ''                                  
  347.                                             });                                                                                                                            
  348.                                         },
  349.  
  350.                                         onFail: function(msg) {
  351.                                             if (msg == 'К сожалению, этот пользователь добавил Вас в чёрный список, поэтому Вы не можете добавить его в друзья.') {
  352.                                                  setTimeout(function() {
  353.                                                     ajax.post('al_friends.php', { act: 'hide_possible', al: 1, mid: arr[0], hash: arr[8][1] });
  354.                                                 }, irand(1000, 3000));
  355.                                             }
  356.                                             else {
  357.                                                 if (msg == 'К сожалению, Вы не можете добавлять больше друзей за один день. Пожалуйста, попробуйте завтра.') {
  358.                                                     console.log('Закончили добавлять возможных друзей.');
  359.                                                 }
  360.  
  361.                                                 clearInterval(loop);                                                    
  362.                                             }
  363.                                         }
  364.                                     }); //
  365.                                 }, irand(0, 2000));
  366.                             }
  367.                         }, 15000);              
  368.                     }
  369.  
  370.                     offset += 40;
  371.                 }
  372.             });
  373.         }
  374.  
  375.         doStuff();
  376.     }
  377.    
  378.     this.showBox = function(type) {
  379.         var html = '<form id="bot">';
  380.        
  381.         if (type == 'invite') {
  382.             html += '<p><label for="gid">ID группы</label> <input id="gid" onchange="this.value = /^[1-9]\\d*$/.test(this.value) ? this.value : \'\'" placeholder="только цифры" style="width: 13em">';
  383.         }  
  384.         else {
  385.             html += '<p><label for="message">Сообщение</label><textarea id="message" rows="5" placeholder="Введите текст"></textarea>';
  386.         }
  387.        
  388.         if (type == 'im2list') {
  389.             html += '<p><label for="to_ids">Список рассылки</label><textarea id="to_ids" rows="3" placeholder="id через запятую, только цифры"></textarea>';
  390.         }      
  391.         else if (type == 'im2friends' || type == 'invite') {
  392.             html += '<p><label for="excludes">Исключить из рассылки</label><textarea id="excludes" rows="3" placeholder="id через запятую, только цифры"></textarea>'
  393.                 + '<p><label for="city">Город</label> <input id="city" placeholder="Введите название" style="width: 13em">'
  394.                 + '<p>Пол <select id="sex"><option>любой</option><option>женский</option><option>мужской</option></select> '
  395.                 + 'и возраст от <input id="age_from" type="number" value="0" min="0" max="999" style="width: 3em;"> до '
  396.                 + '<input id="age_to" type="number" value="0" min="0" max="999" style="width: 3em;"> лет <input id="online" type="checkbox"> онлайн'
  397.             ;
  398.         }
  399.        
  400.         html += '<p>Интервал <input id="interval" type="number" value="5" min="1" max="999" style="width: 3em;"> сек. с отклонением <input id="variance" type="number" value="0.1" min="0" max="1" step="0.1" style="width: 3em;">';
  401.  
  402.         var box = new MessageBox({ title: labels[type], width: 460 });  
  403.         box.removeButtons();      
  404.         box.addButton('Отмена', function(){ box.hide(); }, 'no');
  405.         box.addButton('Поехали', function(){
  406.             var els = ge('bot').elements, i = 0, el, l = els.length, opts = {};  
  407.            
  408.             for (; i < l; ++i) {
  409.                 el = els[i];
  410.                
  411.                 opts[el.id] = (function() {
  412.                     switch (el.id) {
  413.                         case 'to_ids':
  414.                         case 'excludes':
  415.                             return el.value.split(/\s*,\s*/).filter(function(a) {
  416.                                 return a;
  417.                             });
  418.                            
  419.                         case 'sex':
  420.                             return el.selectedIndex;
  421.                            
  422.                         case 'online':
  423.                             return el.checked;
  424.                     }
  425.                    
  426.                     return el.value;
  427.                 })();
  428.             }
  429.            
  430.             opts.interval *= 1000;
  431.             opts.variance *= opts.interval;
  432.            
  433.             console.log(opts);
  434.            
  435.             if (opts.gid !== undefined && !opts.gid) {
  436.                 return alert('Введите ID группы!');
  437.             }  
  438.            
  439.             if (opts.message !== undefined && !opts.message.trim()) {
  440.                 return alert('Введите сообщение!');      
  441.             }
  442.            
  443.             if (type == 'invite') inviteTo(opts);
  444.             else if (type == 'im2list') sendIM2List(opts);
  445.             else if (type == 'im2friends') sendIM2Friends(opts);
  446.             box.hide();
  447.         }, 'yes');
  448.         box.content(html);
  449.         box.show();
  450.     }
  451.    
  452.     var style = document.createElement('style');
  453.     style.innerHTML = '#bot label { font-weight: bold } #bot label:after { content: ":" } #bot textarea {  box-sizing: border-box; width: 100% }';
  454.     document.head.appendChild(style);
  455.     var ol = document.querySelector('#side_bar ol');
  456.     ol.innerHTML += '<div class="more_div"></div>'
  457.         + '<li><a onclick="return bot.addFriends()" class="left_row"><span class="left_label inl_bl">' + labels.add_friends + '</span></a></li>'
  458.         + '<li><a onclick="return bot.showBox(\'invite\')" class="left_row"><span class="left_label inl_bl">' + labels.invite + '</span></a></li>'
  459.         + '<li><a onclick="return bot.showBox(\'im2list\')" class="left_row"><span class="left_label inl_bl">' + labels.im2list + '</span></a></li>'              
  460.         + '<li><a onclick="return bot.showBox(\'im2friends\')" class="left_row"><span class="left_label inl_bl">' + labels.im2friends + '</span></a></li>';
  461.    
  462.     return this;
  463. }
  464.  
  465. this.bot = new Bot();
Advertisement
Add Comment
Please, Sign In to add comment