-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbot15.js
270 lines (229 loc) · 8.15 KB
/
bot15.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
require('dotenv').config();
// const moment = require('moment'); Using moment-timezone to select preferred timezone
const moment = require('moment-timezone');
const preferredTimezone = 'America/Sao_Paulo';
const Mastodon = require('mastodon-api');
const readline = require('readline');
const M = new Mastodon({
client_key: process.env.CLIENT_KEY,
client_secret: process.env.CLIENT_SECRET,
access_token: process.env.ACCESS_TOKEN,
timeout_ms: 60 * 1000,
api_url: process.env.MASTODON_URL,
});
const hashtags = [
'almocodedomingo',
'segundaficha',
'tercinema',
'quartacapa',
'musiquinta',
'sextaserie',
'caturday',
];
const ignoredAccounts = ['TagsBR','TrendsBR','trending'];
const todayTimestamp = moment().startOf('day').unix();
console.log(moment.unix(todayTimestamp).tz(preferredTimezone).format('YYYY-MM-DD'));
// Function to calculate the relevance score based on favorites, boosts, and followers
async function calculateRelevance(toot) {
if (!toot || !toot.account || !toot.account.id) {
console.warn('Ignorando toot sem informações sobre conta:', toot);
return null;
}
try {
const w_F = 0.4; // Weight for favorites
const w_B = 0.3; // Weight for boosts
const w_N = 0.3; // Weight for followers
const relevanceScore = Math.round((w_F * toot.favourites_count + w_B * toot.reblogs_count + w_N * (toot.account.followers_count || 0)) * 10) / 10;
const result = {
...toot,
relevanceScore,
};
return result;
} catch (error) {
console.error(`Erro ao calcular a pontuação de relevância para o toot ${toot.id || 'unknown'}:`, error);
return null;
}
}
// Function to sort toots by relevance
async function sortTootsByRelevance(toots) {
const relevanceScores = await Promise.all(toots.map(calculateRelevance));
return relevanceScores.sort((a, b) => b.relevanceScore - a.relevanceScore);
}
// Function to fetch toots for the current day and log progress
async function fetchToots(hashtag) {
try {
let toots = [];
let maxId = null;
let progress = 0;
console.log(`Obtendo posts para ${hashtag} ...`);
while (true) {
const params = {
tag: hashtag,
limit: 40,
};
if (maxId) {
params.max_id = maxId;
}
const response = await fetchTootsFromAPI(hashtag, params);
if (!Array.isArray(response.data)) {
console.error('Erro ao obeter posts:', response);
break;
}
const newToots = response.data.filter(toot => toot && moment(toot.created_at).unix() >= todayTimestamp);
toots.push(...newToots);
maxId = newToots[newToots.length - 1]?.id;
progress += newToots.length;
if (newToots.length < 40) {
break;
}
}
console.log(`Posts obtidos: ${toots.length}`);
console.log(`Progresso: ${progress} / ${toots.length}`);
return toots;
} catch (error) {
console.error('Erro ao obter posts:', error);
throw error;
}
}
async function fetchTootsFromAPI(hashtag, params) {
const url = `timelines/tag/${hashtag}`;
console.log(`Buscando ${url}...`);
const response = await M.get(url, params);
return response;
}
// Filter only toots from the current day
function filterTootsByDate(toots, date) {
return toots.filter(toot => moment(toot.created_at).isSame(date, 'day'));
}
// Function to get hashtag usasge for the current day
async function getHashtagUse(hashtag) {
try {
const response = await M.get(`tags/${hashtag}`);
return response.data.history;
} catch (error) {
console.error(`Erro ao obter dados de uso da hashtag para ${hashtag}:`, error);
return [];
}
}
const generateTootLink = (tootId) => `https://ursal.zone/web/statuses/${tootId}`;
const generateTootText = async (hashtag, toots) => {
if (!hashtag || !toots || toots.length === 0) return null;
const topToots = toots.slice(0, 5);
const [history, topTootDetails] = await Promise.all([
getHashtagUse(hashtag).then(result => result?.[0]),
Promise.all(topToots.map(({
account = { username: '(unknown username)', followers_count: 0 },
favourites_count = 0,
reblogs_count = 0,
relevanceScore = 0,
id,
}) => [
account.username,
account.followers_count,
favourites_count,
reblogs_count,
relevanceScore,
generateTootLink(id),
]))
]);
const hist = await getHashtagUse(hashtag);
const historicUses = await calculateSumOfUses(hist);
const tootText = [
`Tag do dia: #${hashtag}\n\n`,
`Uso da tag na semana: ${historicUses}\n`,
`Participantes: ${history?.accounts || 'unknown'}\n`,
`Posts hoje: ${history?.uses || 'unknown'}\n\n`,
`Principais posts de hoje:\n\n`,
...topTootDetails.map(([
account, followers_count, favourites_count, reblogs_count, relevanceScore, link
], i) => [
`Publicado por ${account}\n`,
`Seguidores: ${followers_count}\n`,
`⭐ ${favourites_count} `,
`🔄 ${reblogs_count} `,
`📈 ${relevanceScore}\n`,
`🔗 ${link}\n\n`,
].join('')),
].join('');
console.log(tootText);
return tootText;
}
// Function to calculate sum of uses in history object
async function calculateSumOfUses(hist) {
if (!hist) {
return 0;
}
let totalUses = 0;
for (const entry of hist) {
if (entry && entry.uses) {
totalUses += parseInt(entry.uses);
}
}
return totalUses;
}
// Function to sort toots by relevance
async function sortTootsByRelevance(toots) {
return Promise.all(toots.map(calculateRelevance))
.then(relevanceScores => relevanceScores.sort((a, b) => b.relevanceScore - a.relevanceScore));
}
// Function to remove toots from ignored accounts
async function removeIgnoredToots(toots) {
return toots.filter(toot => !ignoredAccounts.includes(toot.account.username));
}
// Function to create toot
async function createToot(tootText) {
console.log('Entering createToot function');
console.log('tootText:', tootText, tootText.length);
if (typeof tootText !== 'string') {
throw new Error('Toot text must be a string');
}
if (tootText.trim() === '') {
throw new Error('Toot text cannot be empty');
}
try {
console.log('Attempting to create toot');
const response = await M.post('statuses', {
status: tootText,
sensitive: false,
visibility: 'public',
language: 'pt',
}, {
headers: {
'Authorization': `Bearer ${process.env.ACCESS_TOKEN}`,
},
});
if (!response || !response.data) {
throw new Error('Invalid response data from Mastodon API');
}
} catch (error) {
console.error('Error creating toot:', error);
throw error;
}
console.log('Exiting createToot function');
}
// Main function to fetch, process, and print toots
async function main() {
const hashtag = hashtags[new Date().getDay()];
const currentDate = new Date().toISOString().split('T')[0];
const toots = await fetchToots(hashtag);
const sortedToots = await sortTootsByRelevance(toots);
console.log(`Retrieved ${toots.length} toots`);
const allowedToots = await removeIgnoredToots(sortedToots);
const todaysToots = await filterTootsByDate(allowedToots, currentDate);
const tootText = await generateTootText(hashtag, todaysToots);
const answer = await new Promise(resolve => {
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.question('Do you want to toot? (y/n) ', answer => {
rl.close();
resolve(answer);
});
});
if (answer.toLowerCase() === 'y') {
console.log(tootText);
await createToot(tootText);
}
}
main();