Уважаемые пользователи Голос!
Сайт доступен в режиме «чтение» до сентября 2020 года. Операции с токенами Golos, Cyber можно проводить, используя альтернативные клиенты или через эксплорер Cyberway. Подробности здесь: https://golos.io/@goloscore/operacii-s-tokenami-golos-cyber-1594822432061
С уважением, команда “Голос”
GOLOS
RU
EN
UA
djimirji
6 лет назад

Бот по вызову голосующий за Ваш пост

Вы можете получить безвоздмездно UpVote. Для этого достаточно подписаться на меня @djimirji (и не только) и в коментарии к своему посту указать @djimirji up!

Ух и много же времени у меня заняло написание такого бота. 

Первая версия ( https://golos.io/ru--golos/@djimirji/kak-ya-pytalsya-napisat-bot ) оказалась работоспособной, но "глючной". Бот нормально отрабатывал только тогда, когда в промежуток поиска вызова попадал только один запрос. В случае же с попаданием более одного запроса асинхронность вступала в действие ((( Побороть ее к сожалению у меня пока не хватает умения и знаний.  Понимание как работает async await пришло, а вот как работать с Promise так до меня и не дошло... Возможно из этого апи https://github.com/GolosChain/golos-js/ заюзать Promise и нельзя.. Но опять же я не смог разобраться. 

Логика мне подсказывает, что node.js на асинхнронность и заточен, и выходить из асинхронно кода в синхронный не особо правильно. Но моих навыков пока не хватает оставаться в асинхронном коде до конца. Ну что же пока так. 

В итоге куча костылей и пауз и сумашедший код готов!


// У вас должен быть установлен nodejs // Установите зависимости для скрипта командой npm install golos-js // ===================================================================== // Автор https://golos.io/@djimirji/ // ===================================================================== // Логин и пароль(постинг ключ) аккаунта который будет делать реблоги в свой блог const votersSemiBot = [ {user:"1", userpwd:"5.........................."}, {user:"2", userpwd:"5.........................."}, {user:"3", userpwd:"5.........................."} ]; // Логин аккаунта на который должены подписываться пользователи, что бы их имена попали в белый список! const mainBot = 'djimirji'; //Вызов бота const UpVoteCall = '@djimirji up!'; // ======================= Коннект ========================== //const GOLOSNODE = "ws://localhost:9090" const GOLOSNODE = "wss://api.golos.cf"; //нода @vik // Подключение JavaScript библиотеки для работы c API голоса const golos = require('golos-js'); // Указываем ноду, к которой будет подключен скрипт golos.config.set('websocket', GOLOSNODE); // ===================================================================== //####################################################################### // =================== Удаление дублей ========================= function removeDuplicates(arr){ let unique_array = [] for(let i = 0;i < arr.length; i++){ if(unique_array.indexOf(arr[i]) == -1){ unique_array.push(arr[i]) } } return unique_array } // =================== Конец удаления дублей ======================== //########################################################################## // =================== Получение блогов ========================= function getEachBlog(follower) { let d = new Date(); let dt = d.toISOString().split('.')[0]; let author = follower; let startPermlink = ''; let beforeDate = dt; let limit = 3; return golos.api.getDiscussionsByAuthorBeforeDate(author, startPermlink, beforeDate, limit, async function(err, result) { }); }; // =================== Конец получения постов из блогов ========================= //########################################################################## //########################################################################## // =================== Получения подписчиков ========================= var startFollower = ''; var followType = 'blog'; var limit = 100; let i_followers = []; let lastFollower = ''; const getfollowers = (startFollower) => { golos.api.getFollowers(mainBot, startFollower, followType, limit, function(err, result) { if ( ! err) { for (let f of result){ i_followers.push(f.follower); }; lastFollower = i_followers[i_followers.length - 1]; }; if (startFollower === i_followers[i_followers.length - 1]) { //console.log("Всех выбрали"); i_followers = removeDuplicates(i_followers); setTimeout(() => { getblogs(i_followers); },1000); } else { getfollowers(lastFollower); }; }); }; // =================== Конец функции получения подписчиков ========================= //########################################################################## // =================== Получение коментариев ========================= function CallCommFromBlog (CommCheckAuthor, CommCheckLink) { async function GetComments (CommCheckAuthor, CommCheckLink, commchildren) { function i_GetComments (Author, Link) { return golos.api.getContentReplies(Author, Link,function(err, result) { }); }; let FirstLevel = await i_GetComments (CommCheckAuthor, CommCheckLink); if (FirstLevel != null) { for (let i of FirstLevel){ //console.log(i.author, i.body); if (i.children == 5){ await GetComments (i.author, i.permlink, i.children + 10); //console.log("5 дочерних каментов"); } else if (i.children > 0){ await GetComments (i.author, i.permlink, commchildren); //console.log("дочерних каментов", i.children); } else {}; if (i.body.toLowerCase().search(UpVoteCall) != '-1'){ //console.log("Найден запрос", i.url, commchildren); let findedcall = ''; if (commchildren > 10){ findedcall = await i_GetComments (i.parent_author, i.parent_permlink); add_comm_to_array = { url: i.url, author: i.parent_author, permlink: i.parent_permlink, body: i.body } } else { findedcall = await i_GetComments (i.author, i.permlink); add_comm_to_array = { url: i.url, author: i.author, permlink: i.permlink, body: i.body } } if ( findedcall != '' ) { let checkanswer = []; let str = ""; for (let f of findedcall ){ str = f.json_metadata.split(',"app":')[1]; str = str.substring(0, str.length - 2); str = str.substring(1) checkanswer.push(str); } if (checkanswer.includes("djimirji upvote bot")){ //console.log("Прокоментировано"); } else { all_Comments_From_Blog.push(add_comm_to_array); //console.log("Коментарий не оставлен"); }; } else { all_Comments_From_Blog.push(add_comm_to_array); //console.log("Коментарий не оставлен"); }; } } } else { return; }; } GetComments (CommCheckAuthor, CommCheckLink, 0); }; //CallCommFromBlog('lilia', 'start-kotofoto-estafeta'); //CallCommFromBlog('first1by', 'streamity-obzor'); //https://golos.io/ico/@first1by/streamity-obzor#comments let all_Comments_From_Blog = []; function fill_call_bot (fill) { all_Comments_From_Blog.push(fill); }; // =================== Конец получения коментариев ========================= // =================== Проверка на апвоут ================================ function UpVoteCheck (url) { let str = url.split('#')[0]; str = str.split('@')[1]; let pauthor = str.split('/')[0]; let plink = str.split('/')[1]; return golos.api.getActiveVotes(pauthor, plink, function(err, result) { }); }; // =================== Конец проверки на апвоут ========================= //########################################################################## // =================== Коментарий ================================ function CommentAdd (parentAuthor, parentPermlink,body,p) { let postingkey = votersSemiBot[0].userpwd; let permlink = 're-' + parentAuthor + '-' + parentPermlink + '-' + Date.now(); let title = ''; let jsonMetadata = { "tags": ["djimirji"], "app": "djimirji upvote bot" } setTimeout(() => { console.log("Коментирую",parentAuthor,body); return golos.broadcast.comment(postingkey, parentAuthor, parentPermlink, mainBot, permlink, title, body, jsonMetadata, function(err, result) { }); },p); }; // =================== Конец кометария ============================= // =================== Голосование ========================= function Vote (parent_author,parent_permlink,VOTEPOWER,postingkey,author,p) { setTimeout(() => { console.log("ГОЛОСУЮ",author, parent_author); return golos.broadcast.vote(postingkey, author, parent_author, parent_permlink, VOTEPOWER * 100, function(err, result) { }); },p); }; // =================== Конец голосования ========================= //################################################################################ //########################################################################## //########################################################################## //########################################################################## var end_of_check_all_comments = ''; async function getblogs (i_followers) { let allblogs = []; for (i=0;i<i_followers.length;i++){ let carentBlog = await getEachBlog(i_followers[i]); if (carentBlog != null) { carentBlog.forEach(function(item){ //console.log(item.author); blg = { author: item.author, permlink: item.permlink } allblogs.push(blg); }); } if (i == i_followers.length -1 ){ i_followers = []; //Чистим массив подписчиков //console.log("Всего блогов",allblogs.length); for (k=0;k < allblogs.length;k++){ CallCommFromBlog(allblogs[k].author, allblogs[k].permlink); if (k == allblogs.length - 1){ //console.log(allblogs); allblogs = []; //Чистим массив блогов end_of_check_all_comments = 'end'; }; }; }; }; } //getblogs(['faalex']); function runBot() { getfollowers(); async function BroadcastCommentAndVote () { let p = 0; for (z=0;z < all_Comments_From_Blog.length;z++){ p = z * 21000; let upvoted = ''; let body = ''; let VOTEPOWER = ''; let str = all_Comments_From_Blog[z].url.split('#')[0]; str = str.split('@')[1]; let pauthor = str.split('/')[0]; let plink = str.split('/')[1]; let votecheck = await UpVoteCheck (all_Comments_From_Blog[z].url); let voters = []; votecheck.forEach(function(item) { voters.push(item.voter); }) if (voters.includes(mainBot)) { upvoted = 1; } else { upvoted = 0; } votersSemiBot.forEach(function (v) { console.log(p); if ((upvoted != 0) && (v.user == mainBot)){ body = "💡 Этот пост уже получал upvote ранее :)"; CommentAdd (all_Comments_From_Blog[z].author, all_Comments_From_Blog[z].permlink,body,p); return console.log(`\x1b[31m☹️ ${body} - ${all_Comments_From_Blog[z].author} - ${all_Comments_From_Blog[z].permlink} \x1b[0m`); } else { if (v.user == mainBot){ VOTEPOWER = (Math.floor((Math.random() * 50) + 50)); body = "💡 @" + pauthor + " получил апвоут на " + VOTEPOWER +"% :)"; CommentAdd (all_Comments_From_Blog[z].author, all_Comments_From_Blog[z].permlink,body,p); Vote(pauthor,plink,VOTEPOWER,v.userpwd,v.user,p); return console.log(`\x1b[96m💬 ${v.user} коментирует и голосует за ${pauthor}, по ссылке - ${plink} \x1b[0m`); } else { VOTEPOWER = 100; Vote(pauthor,plink,VOTEPOWER,v.userpwd,v.user,p); return console.log(`\x1b[32m🔗 Голосует доп.аккаунт: ${v.user} силой ${VOTEPOWER}, за ${pauthor}, статья: ${plink} \x1b[0m`); } }; }); }; pause = all_Comments_From_Blog.length * 21000; setTimeout(() => { all_Comments_From_Blog = []; end_of_check_all_comments = ''; console.log("Пауза", pause); runBot(); }, pause + 70000); } function checkArrayEmptines (){ if (end_of_check_all_comments == 'end') { //console.log("Коментарии обработаны"); setTimeout(() => { BroadcastCommentAndVote(); }, 5000); } else { setTimeout(checkArrayEmptines, 1000); //console.log("Не все проверено, ждем"); } } checkArrayEmptines(); } runBot();
3
0.000 GOLOS
На Golos с January 2018
Комментарии (41)
Сортировать по:
Сначала старые