Advertisement
djimirji

golos bot v2

Mar 22nd, 2018
289
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // У вас должен быть установлен nodejs
  2. // Установите зависимости для скрипта командой npm install golos-js
  3. // =====================================================================
  4. // Автор https://golos.io/@djimirji/
  5. // =====================================================================
  6. // Логин и пароль(постинг ключ) аккаунта который будет делать реблоги в свой блог
  7. const votersSemiBot = [
  8. {user:"djimirji", userpwd:"555555555555555555555555555555"}
  9.  
  10. ];
  11.  
  12. // Логин аккаунта на который должены подписываться пользователи, что бы их имена попали в белый список!
  13. const mainBot = 'djimirji';
  14.  
  15. //Вызов бота
  16. const UpVoteCall = '@djimirji up!';
  17.  
  18. // ======================= Коннект ==========================
  19. //const GOLOSNODE = "ws://localhost:9090"
  20. const GOLOSNODE = "wss://api.golos.cf"; //нода @vik
  21. // Подключение JavaScript библиотеки для работы c API голоса
  22. const golos = require('golos-js');
  23.  
  24. // Указываем ноду, к которой будет подключен скрипт
  25. golos.config.set('websocket', GOLOSNODE);
  26. // =====================================================================
  27.  
  28. //#######################################################################
  29. // =================== Удаление дублей =========================
  30. function removeDuplicates(arr){
  31.     let unique_array = []
  32.     for(let i = 0;i < arr.length; i++){
  33.         if(unique_array.indexOf(arr[i]) == -1){
  34.             unique_array.push(arr[i])
  35.         }
  36.     }
  37.     return unique_array
  38. }
  39. // =================== Конец удаления дублей ========================
  40. //##########################################################################
  41. // =================== Получение блогов =========================
  42. function getEachBlog(follower) {
  43.     let d = new Date();
  44.     let dt = d.toISOString().split('.')[0];
  45.     let author = follower;
  46.     let startPermlink = '';
  47.     let beforeDate = dt;
  48.     let limit = 3;
  49.    
  50.     return golos.api.getDiscussionsByAuthorBeforeDate(author, startPermlink, beforeDate, limit, async function(err, result) {  
  51.     });
  52. };
  53.  
  54. // =================== Конец получения постов из блогов =========================
  55. //##########################################################################
  56.  
  57. //##########################################################################
  58. // =================== Получения подписчиков =========================
  59. var startFollower = '';
  60. var followType = 'blog';
  61. var limit = 100;
  62. let i_followers = [];
  63. let lastFollower = '';
  64.  
  65. let getfollowers = (startFollower) => {    
  66.         golos.api.getFollowers(mainBot, startFollower, followType, limit, function(err, result) {
  67.             if ( ! err) {
  68.                
  69.                 for (let f of result){
  70.                     i_followers.push(f.follower);                  
  71.                 };                 
  72.                 lastFollower = i_followers[i_followers.length - 1];
  73.             };
  74.             if (startFollower === i_followers[i_followers.length - 1]) {
  75.                 //console.log("Всех выбрали");
  76.                 i_followers = removeDuplicates(i_followers);                       
  77.                                                                        
  78.                 setTimeout(() => {
  79.                     getblogs(i_followers);
  80.                 },1000);
  81.             }
  82.             else {
  83.                 getfollowers(lastFollower);
  84.             };         
  85.         });
  86.        
  87.     };
  88.        
  89. // =================== Конец функции получения подписчиков =========================
  90. //##########################################################################
  91. // =================== Получение коментариев =========================
  92. all_Comments_From_Blog = [];
  93. function CallCommFromBlog (CommCheckAuthor, CommCheckLink) {   
  94.    
  95.     async function GetComments (CommCheckAuthor, CommCheckLink, commchildren) {    
  96.         function i_GetComments (Author, Link) {
  97.             return golos.api.getContentReplies(Author, Link,function(err, result) { });            
  98.         };
  99.         let FirstLevel = await i_GetComments (CommCheckAuthor, CommCheckLink);
  100.        
  101.         if (FirstLevel != null) {
  102.        
  103.             for (let i of FirstLevel){
  104.                 //console.log(i); //
  105.                 if (i.children > 0){
  106.                     await GetComments (i.author, i.permlink, commchildren);
  107.                     //console.log("дочерних каментов", i.children);
  108.                 }
  109.                 else {};
  110.            
  111.                 if (i.body.toLowerCase().search(UpVoteCall) != '-1'){                  
  112.                     //console.log("Найден запрос", i.url, commchildren);
  113.                     let findedcall = '';
  114.                     let comented = '';
  115.                     findedcall = await i_GetComments (i.author, i.permlink);
  116.                
  117.                     if ( findedcall != '' ) {
  118.                         let checkanswer = [];
  119.                         let str = "";
  120.                         for (let f of findedcall ){                          
  121.                             str = f.json_metadata.split(',"app":')[1];
  122.                             if (str != null){
  123.                                 str = str.substring(0, str.length - 2);
  124.                                 str = str.substring(1);
  125.                                 checkanswer.push(str);
  126.                             };                         
  127.                         }
  128.                        
  129.                         if (checkanswer.includes("djimirji upvote bot")){
  130.                             comented = 1;
  131.                             //console.log("Прокоментировано");
  132.                         }
  133.                         else {
  134.                             comented = 0;
  135.                             //console.log("Коментарий не оставлен");
  136.                         };                     
  137.                     }              
  138.                     else {
  139.                         comented = 0;
  140.                         //console.log("Коментарий не оставлен");
  141.                     }                      
  142.                         add_comm_to_array = {
  143.                             url: i.url,
  144.                             author: i.author,
  145.                             permlink: i.permlink,
  146.                             body: i.body,
  147.                             created: i.created,
  148.                             comented: comented
  149.                         }
  150.                        
  151.                     all_Comments_From_Blog.push(add_comm_to_array);
  152.                 }
  153.             }      
  154.         }
  155.         else {
  156.             return;
  157.         };
  158.     }
  159.    
  160. GetComments (CommCheckAuthor, CommCheckLink, 0);
  161.  
  162. }; 
  163.    
  164. // =================== Конец получения коментариев =========================
  165. // =================== Проверка на апвоут ================================
  166.  
  167. function UpVoteCheck (url) {
  168.    
  169.     let str = url.split('#')[0];
  170.     str = str.split('@')[1];
  171.     let pauthor = str.split('/')[0];
  172.     let plink = str.split('/')[1];
  173.    
  174.     return golos.api.getActiveVotes(pauthor, plink, function(err, result) {
  175.     });
  176. };
  177.  
  178. // =================== Конец проверки на апвоут =========================
  179.  
  180. //##########################################################################
  181.  
  182. // =================== Коментарий ================================
  183.  
  184. function CommentAdd (parentAuthor, parentPermlink,body,p) {
  185.     let postingkey = votersSemiBot[0].userpwd;
  186. //  let permlink = 're-' + parentAuthor + '-' + parentPermlink + '-' + Date.now();
  187.     let permlink = 're-' + parentPermlink + '-' + Date.now();
  188.     let title = '';
  189.     let jsonMetadata = {
  190.                     "tags": ["djimirji"],
  191.                     "app": "djimirji upvote bot"
  192.                     }
  193.     setTimeout(() => {
  194.         console.log("Коментирую",parentAuthor,body);
  195.         return golos.broadcast.comment(postingkey, parentAuthor, parentPermlink, mainBot, permlink, title, body, jsonMetadata, function(err, result) {
  196.         //  console.log(err, result);  
  197.         });
  198.     },p);
  199. };
  200.  
  201. // =================== Конец кометария =============================
  202. // =================== Голосование =========================
  203.  
  204. function Vote (parent_author,parent_permlink,VOTEPOWER,postingkey,author,p) {
  205.     setTimeout(() => {
  206.     console.log("ГОЛОСУЮ",author, parent_author);
  207.     return golos.broadcast.vote(postingkey, author, parent_author, parent_permlink, VOTEPOWER * 100, function(err, result) {
  208.     });
  209.     },p);
  210.  
  211. };
  212.  
  213. // =================== Конец голосования =========================
  214. //################################################################################
  215. //##########################################################################
  216. var end_of_check_all_comments = '';
  217. async function getblogs (i_followers) {
  218.     let allblogs = [];
  219.     for (i=0;i<i_followers.length;i++){
  220.         let carentBlog = await getEachBlog(i_followers[i]);
  221.             if (carentBlog != null) {              
  222.                 carentBlog.forEach(function(item){
  223.                     //console.log(item.author);
  224.                     blg = {
  225.                         author: item.author,
  226.                         permlink: item.permlink                    
  227.                     }
  228.                     allblogs.push(blg);
  229.                 });
  230.                
  231.             }
  232.         if (i == i_followers.length -1 ){          
  233.             i_followers = []; //Чистим массив подписчиков
  234.             //console.log("Всего блогов",allblogs.length);          
  235.            
  236.             for (k=0;k < allblogs.length;k++){
  237.                 CallCommFromBlog(allblogs[k].author, allblogs[k].permlink);
  238.                
  239.                 if (k == allblogs.length - 1){
  240.                     //console.log(allblogs);
  241.                     allblogs = []; //Чистим массив блогов
  242.                     end_of_check_all_comments = 'end';
  243.                 };
  244.             };
  245.                        
  246.         };
  247.     }; 
  248. }
  249.  
  250.  
  251. function runBot() {
  252.     getfollowers();
  253.    
  254.     async function BroadcastCommentAndVote () {
  255.         let pause_comments = [];
  256.         let p = 0;
  257.        
  258.         for (z=0;z < all_Comments_From_Blog.length;z++){           
  259.             let upvoted = '';
  260.             let body = '';
  261.             let VOTEPOWER = '';
  262.             let str = all_Comments_From_Blog[z].url.split('#')[0];
  263.             str = str.split('@')[1];
  264.             let pauthor = str.split('/')[0];
  265.             let plink = str.split('/')[1];             
  266.            
  267.             let votecheck = await UpVoteCheck (all_Comments_From_Blog[z].url);
  268.             let voters = [];
  269.                 votecheck.forEach(function(item) {                                 
  270.                 voters.push(item.voter);               
  271.                 })             
  272.                 if (voters.includes(mainBot)) {
  273.                     upvoted = 1;               
  274.                 }
  275.                 else {
  276.                     upvoted = 0;
  277.                 }
  278.            
  279.             let commentFromAuthorByDay = [];
  280.             all_Comments_From_Blog.forEach( function (item) {
  281.                 if ((item.author == pauthor) && (new Date(item.created) > new Date(new Date().getTime() - 60 * 60 * 24 * 1000))) {
  282.                     //console.log(pauthor, item.created);                  
  283.                     commentFromAuthorByDay.push(item);
  284.                 }
  285.             });
  286.            
  287.             if (commentFromAuthorByDay.length != 0) {
  288.                 VOTEPOWER = (Math.floor((Math.random() * 20) + 79)) - (commentFromAuthorByDay.length * 15);
  289.                 if (VOTEPOWER < 30) {
  290.                     VOTEPOWER = 33;
  291.                 };             
  292.             }
  293.             else {
  294.                 VOTEPOWER = (Math.floor((Math.random() * 35) + 64));
  295.             }
  296. //          console.log(pauthor,commentFromAuthorByDay.length );
  297.             commentFromAuthorByDay = [];
  298. //          console.log(pauthor, plink, all_Comments_From_Blog[z].created,VOTEPOWER);          
  299.            
  300.             if (all_Comments_From_Blog[z].comented == 0){              
  301.             pause_comments.push(all_Comments_From_Blog[z].url);
  302.             p = (pause_comments.length -1 ) * 23000;
  303.             votersSemiBot.forEach(function (v) {
  304.                 //console.log(p);              
  305.                 if ((upvoted == 1) && (v.user == mainBot)){
  306.                     body = "💡 Этот пост уже получал upvote ранее :)";                    
  307.                     CommentAdd (all_Comments_From_Blog[z].author, all_Comments_From_Blog[z].permlink,body,p);                                                      
  308.                     return console.log(`\x1b[31m☹️ ${body} - ${all_Comments_From_Blog[z].author} - ${all_Comments_From_Blog[z].permlink} \x1b[0m`);
  309.                 }
  310.                 else {
  311.                     if (v.user == mainBot){
  312.                         //VOTEPOWER = (Math.floor((Math.random() * 50) + 50));
  313.                         body = "💡 @" + pauthor + " получил апвоут на " + VOTEPOWER +"% :)"+ `<br>` + `<pre><code class="language-sh">` + " Что бы вызывать бота подпишись на меня! " + `</code></pre>` + "";
  314.                         CommentAdd (all_Comments_From_Blog[z].author, all_Comments_From_Blog[z].permlink,body,p);                                                      
  315.                         Vote(pauthor,plink,VOTEPOWER,v.userpwd,v.user,p);                          
  316.                         return console.log(`\x1b[96m💬 ${v.user} коментирует и голосует за ${pauthor}, по ссылке - ${plink} \x1b[0m`);
  317.                     }
  318.                     else {
  319.                         VOTEPOWER = 100;   
  320.                         Vote(pauthor,plink,VOTEPOWER,v.userpwd,v.user,p);
  321.                         return console.log(`\x1b[32m🔗 Голосует доп.аккаунт: ${v.user} силой ${VOTEPOWER}, за ${pauthor}, статья: ${plink} \x1b[0m`);
  322.                     }
  323.                 };
  324.             });
  325.             }
  326.         }; 
  327.    
  328.     pause = ( pause_comments.length * 23000 ) + 120000;
  329.     console.log(new Date(), " Пауза", pause/1000," сек.");
  330.     setTimeout(() => {
  331.         all_Comments_From_Blog = [];
  332.         end_of_check_all_comments = '';
  333.         pause_comments = [];               
  334.         runBot();      
  335.     }, pause );
  336.            
  337.     }
  338.    
  339.     function checkArrayEmptines (){
  340.         if (end_of_check_all_comments == 'end') {
  341.             //console.log("Коментарии обработаны");                    
  342.             setTimeout(() => {
  343.                 BroadcastCommentAndVote();     
  344.             }, 10000);         
  345.         }
  346.         else {
  347.             setTimeout(checkArrayEmptines, 1000);
  348.             //console.log("Не все проверено, ждем");         
  349.         }
  350.     }
  351.     checkArrayEmptines();
  352. }
  353.  
  354. runBot();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement