Test working scripts. Automation of analysis of active community members. by alexmove

View this thread on steempeak.com
· @alexmove · (edited)
$23.81
Test working scripts. Automation of analysis of active community members.
![working scripts.png](https://cdn.steemitimages.com/DQmPA1U7sufD2crtv59kQd5F5XEEVVaj41mr7Nn4V8fdqt1/working%20scripts.png)

<h2> Скрипт, который считает комментарии (в пределах 100) за текущую неделю и сохраняет в файл </h2>

Внимание! Он забирает из файла spisok.txt по одному имени участника, удаляет и пересохраняет файл. Т.е. для того, чтобы посчитать для 56 человек, необходимо 56 раз запустить скрипт. Да, такие особенности :) Это тестовый скрипт.

В файле spisok.txt в строку через пробел имена участников 

>olesia sergeyk dmitrik slon21veka antikus369 strecoza alena-vladi olga.maslievich notannov may2015 milakz greatketty apnigrich veta-less qwerrie eternaldreamer yura77 thimalteb steemit-bank maxer27 nesmeliy yetaras strawberrry s

Сохраняет в файл: brustat.txt

```
const fs = require("fs");
const steem = require('steem');
let xc;

//for (xc = 0; xc < 3; xc++) {

						var y, err;
						
						let array = fs.readFileSync('spisok.txt').toString().split("\n");
						let test_a = array[0].split(' ');
						let popped = test_a.shift();
							console.log(test_a);

						function test_c(qu) {
						 steem.api.getDiscussionsByComments({
									"start_author": qu,
									"limit": 100
								}, function (err, result) {
								  //  console.log(err, result);
									
									if (err === null) {
										 var stat = 0;
											  console.log(stat);

										var i, len = result.length;
										for (i = 0; i < len; i++) {
											var discussion = result[i];
										//	console.log(discussion.created);
											const moment= require('moment');
											var now = moment();
											var input = moment(discussion.created);
											var isThisWeek = (now.isoWeek() == input.isoWeek())
										//	console.log(isThisWeek);
										
											if (isThisWeek === true) {
											  stat=stat+1;
												console.log(stat);
												console.log(qu);
												
						  
										}}
									//	console.log(array[y]);
										//console.log(stat);
									//	console.log(array[y]);
												
											
									}
									
										console.log(qu, stat);
										qu2 = qu+' '+stat+"\r\n";
										fs.appendFile("brustat.txt", qu2, (err) => { 
										  if (err) { 
											console.log(err); 
										  } 
										}); 
									}
									
									);



						}


						//for (y = 0; y < 6; y++) {

						//	console.log(array[y]);
							let stat, test;
							test = test_a[1].trim();
							//console.log(test);
							test_c(test);
						//}	

						fs.writeFile("spisok.txt", test_a.join(' '), (err) => { 
						  if (err) { 
							console.log(err); 
						  } 
						}); 
						
//}

```
<h2> Скрипт сортирует из файла brustat.txt по количеству комментариев и сохраняет в brustat_sort.txt </h2>


```

const fs = require("fs");

	let data = fs.readFileSync('brustat.txt').toString();
    let ar2= [];

        var first=data.split('\n');
        var second = new Array();
        for(i=1;i<first.length;i++)
        {
          second[i] = first[i].substring(first[i].indexOf(" ")+1);	

  ar2.push([ first[i], second[i] ]);



ar2.sort(function (a, b) {
    return a.price - b.price;
});

ar2.sort(function(a, b) {
  return (a[0] - b[0]) || (a[1] - b[1]);
});
ar2.reverse;
console.log(ar2);

	fs.writeFile("brustat_sort.txt", ar2.join(' '), (err) => { 
	  if (err) { 
		console.log(err); 
	  } 
	});

```

<h2> Скрипт телеграмм бота </h2>

```
const TelegramBot = require('node-telegram-bot-api');
const steem = require('steem');
const fs = require("fs");


	function test_c(qu) {
						 steem.api.getDiscussionsByComments({
									"start_author": qu,
									"limit": 100
								}, function (err, result) {
								   //console.log(err, result);


									if (err === null) {
										 var stat = 0;

										var i, len = result.length;
										for (i = 0; i < len; i++) {
											var discussion = result[i];
										//	console.log(discussion.created);
											const moment= require('moment');
											var now = moment();
											var input = moment(discussion.created);
											var isThisWeek = (now.isoWeek() == input.isoWeek())
										//	console.log(isThisWeek);
										
											if (isThisWeek === true) {
											  stat=stat+1;

												
						  
										}}
									//	console.log(array[y]);
										//console.log(stat);
									//	console.log(array[y]);
												
											
									}

					qu2 = qu+' '+stat+"\r\n";
					fs.appendFile("brustat.txt", qu2, (err) => { 
		    		  if (err) { 
											console.log(err); 
										  } 
										}); 
									}
							
									);
																							return stat;
						}

// replace the value below with the Telegram token you receive from @BotFather
const token = 'хххх';

// Create a bot that uses 'polling' to fetch new updates
const bot = new TelegramBot(token, {polling: true});

// Matches "/echo [whatever]"
bot.onText(/\/echo (.+)/, (msg, match) => {
  // 'msg' is the received Message from Telegram
  // 'match' is the result of executing the regexp above on the text content
  // of the messag


});


// Listen for any kind of message. There are different kinds of
// messages.
bot.on('message', (msg) => {
  const chatId = msg.chat.id;
const { id } = msg.chat;

//bot.sendMessage(chatId, msg.text);
  // send a message to the chat acknowledging receipt of their message

if (msg.text === "stat")
{
	let array = fs.readFileSync('brustat.txt').toString();
	//let test_a = array[0].split(' ');
		console.log(array);
	bot.sendMessage(chatId, array);
	
}
else if (msg.text === "help")
{
	bot.sendMessage(chatId, `Введите имя пользователя, количество комментариев которого вы хотите узнать. Количество комментариев на этой неделе. Внимание - считается с понедельника! 

	Пока работает только для активных участников bru и выдает всю табличку. Работа идет!:) Если хотите получить статистику - напишите stat 

	Внимание!!!! Это прототип! Т.е. показывает как будет работать, пока не подключено к скрипту напрямую! Подробности: https://steemit.com/hive-171319/@alexmove/sozdanie-interaktivnogo-reitinga-soobshestva-steem-bru-podschet-kommentariev-na-nodejs-dlya-steemit`);
						

}
else
{
	
						var err;
		console.log(chatId);
						bot.sendMessage(chatId, chatId);
						bot.sendMessage(chatId, msg.text);
						bot.sendMessage(chatId, 'Спасибо. Посчитано. Добавлено в статистику. Пока, чтобы просмотреть статистику. Отправьте боту слово stat. Спасибо');
	
	test_c(msg.text);
				

						fs.writeFile("spisok.txt", test_a.join(' '), (err) => { 
						  if (err) { 
							console.log(err); 
						  } 
						}); 
}
		
});

```

Ближайшие задачи - это:

Сменить недельный подсчет на ежедневный. Почему-то сегодня этого не удалось сделать, хотя я занимался этим более двух часов. 

Наладить телеграмм бот, чтобы он выдавал данные сразу же после запроса.
👍  , , , , , , , , , , , , , , , , , , , ,
properties (23)
post_id93,441,124
authoralexmove
permlinktest-working-scripts-automation-of-analysis-of-active-community-members
categoryhive-171319
json_metadata{"tags":["steemit","js","javascripts","programming"],"image":["https:\/\/cdn.steemitimages.com\/DQmPA1U7sufD2crtv59kQd5F5XEEVVaj41mr7Nn4V8fdqt1\/working%20scripts.png"],"app":"steemit\/0.2","format":"markdown"}
created2021-08-22 13:55:57
last_update2021-08-22 13:57:42
depth0
children8
net_rshares27,737,472,367,802
last_payout2021-08-29 13:55:57
cashout_time1969-12-31 23:59:59
total_payout_value11.909 SBD
curator_payout_value11.905 SBD
pending_payout_value0.000 SBD
promoted0.000 SBD
body_length6,850
author_reputation163,849,244,963,971
root_title"Test working scripts. Automation of analysis of active community members."
beneficiaries[]
max_accepted_payout1,000,000.000 SBD
percent_steem_dollars10,000
author_curate_reward""
vote details (21)
@vipnata ·
полезная вещь для статистики на Steemit  @alexmove
properties (22)
post_id93,443,370
authorvipnata
permlinkqy909w
categoryhive-171319
json_metadata{"users":["alexmove"],"app":"steemit\/0.2"}
created2021-08-22 15:56:21
last_update2021-08-22 15:56:21
depth1
children0
net_rshares0
last_payout2021-08-29 15:56:21
cashout_time1969-12-31 23:59:59
total_payout_value0.000 SBD
curator_payout_value0.000 SBD
pending_payout_value0.000 SBD
promoted0.000 SBD
body_length50
author_reputation283,284,114,896,802
root_title"Test working scripts. Automation of analysis of active community members."
beneficiaries[]
max_accepted_payout1,000,000.000 SBD
percent_steem_dollars10,000
@ir3k ·
Нужный скрипт, экономящий много времени!
properties (22)
post_id93,444,276
authorir3k
permlinkqy92ju
categoryhive-171319
json_metadata{"app":"steemit\/0.2"}
created2021-08-22 16:45:00
last_update2021-08-22 16:45:00
depth1
children0
net_rshares0
last_payout2021-08-29 16:45:00
cashout_time1969-12-31 23:59:59
total_payout_value0.000 SBD
curator_payout_value0.000 SBD
pending_payout_value0.000 SBD
promoted0.000 SBD
body_length40
author_reputation193,989,300,832,423
root_title"Test working scripts. Automation of analysis of active community members."
beneficiaries[]
max_accepted_payout1,000,000.000 SBD
percent_steem_dollars10,000
@greatketty ·
Все, что ты пишешь, я оперативно тестирую. Сегодня у меня нет результата( 


![image.png](https://cdn.steemitimages.com/DQmd7BphLfvLMpuJFFrWfBkRwqp9MHx5FwnWMNZVQbgemZY/image.png)

Или я что-то не то делаю? Успехов в разработке! Это по-настоящему ценный вклад!!!
properties (22)
post_id93,444,703
authorgreatketty
permlinkqy93kh
categoryhive-171319
json_metadata{"image":["https:\/\/cdn.steemitimages.com\/DQmd7BphLfvLMpuJFFrWfBkRwqp9MHx5FwnWMNZVQbgemZY\/image.png"],"app":"steemit\/0.2"}
created2021-08-22 17:07:33
last_update2021-08-22 17:07:33
depth1
children5
net_rshares0
last_payout2021-08-29 17:07:33
cashout_time1969-12-31 23:59:59
total_payout_value0.000 SBD
curator_payout_value0.000 SBD
pending_payout_value0.000 SBD
promoted0.000 SBD
body_length261
author_reputation179,198,072,237,533
root_title"Test working scripts. Automation of analysis of active community members."
beneficiaries[]
max_accepted_payout1,000,000.000 SBD
percent_steem_dollars10,000
@alexmove ·
Класс! 
Сейчас доделал скрипт, который по дням считает - за вчера :) 

Сейчас его запущу и опубликую результаты)
А затем займусь телеграмм ботов, пока он работает еще не очень.
properties (22)
post_id93,447,198
authoralexmove
permlinkqy9b4y
categoryhive-171319
json_metadata{"app":"steemit\/0.2"}
created2021-08-22 19:51:00
last_update2021-08-22 19:51:00
depth2
children4
net_rshares0
last_payout2021-08-29 19:51:00
cashout_time1969-12-31 23:59:59
total_payout_value0.000 SBD
curator_payout_value0.000 SBD
pending_payout_value0.000 SBD
promoted0.000 SBD
body_length176
author_reputation163,849,244,963,971
root_title"Test working scripts. Automation of analysis of active community members."
beneficiaries[]
max_accepted_payout1,000,000.000 SBD
percent_steem_dollars10,000
@greatketty ·
Супер!) Воспитываешь телеграмм-бота:)
properties (22)
post_id93,447,448
authorgreatketty
permlinkqy9c9s
categoryhive-171319
json_metadata{"app":"steemit\/0.2"}
created2021-08-22 20:15:30
last_update2021-08-22 20:15:30
depth3
children3
net_rshares0
last_payout2021-08-29 20:15:30
cashout_time1969-12-31 23:59:59
total_payout_value0.000 SBD
curator_payout_value0.000 SBD
pending_payout_value0.000 SBD
promoted0.000 SBD
body_length37
author_reputation179,198,072,237,533
root_title"Test working scripts. Automation of analysis of active community members."
beneficiaries[]
max_accepted_payout1,000,000.000 SBD
percent_steem_dollars10,000