-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathbot.js
298 lines (262 loc) · 11 KB
/
bot.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
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
require('dotenv').config()
const { Telegraf,session,Markup } = require('telegraf')
const bot = new Telegraf(process.env.BOT_TOKEN, { handlerTimeout: 1000_000 });
const cron = require('node-cron')
const fs = require('fs');
const path = require('path');
bot.use(session({ ttl: 10 }))
const queryTypes = require('./src/util/queryTypes');
const networkPubs = require('./src/modules/networkPubs.js')
const autoTweet = require ('./src/modules/autoTweet.js')
const { isAdmin, adminCommand, adminCommandList } = require('./src/modules/adminCommands.js')
const generalCommandList = require('./src/modules/generalCommandList.js');
const networkStats = require('./src/modules/networkStats.js')
const nodeStats = require('./src/modules/nodeStats.js')
const eventMonitor = require('./src/modules/eventMonitor.js')
//const publishCommand = require('./src/modules/publishCommand.js');
const createCommand = require('./src/modules/createCommand.js');
const glossary = require ('./glossary.js');
const sendInvoice = require('./src/modules/sendInvoice');
const balanceOperations = require('./src/modules/balanceOperations');
const schedule = require('node-schedule');
//const fetchTransactions = require('./src/modules/transactionSync');
const checkReceipt = require('./src/modules/checkReceipt');
const recordAlerts = require('./src/modules/recordAlerts.js');
const handleCommand = async (ctx, command, actionFunction) => {
try {
const telegramId = ctx.message.from.id;
const { permission } = await queryTypes.spamCheck().getData(command, telegramId);
if (permission !== 'allow') {
await ctx.deleteMessage();
return;
}
const userInput = ctx.message.text.split(' ')[1]?.toLowerCase();
// if (!userInput || typeof userInput !== 'string' || userInput.trim() === '') {
// await ctx.reply('Please provide a valid token symbol.');
// return;
// }
if (Array.isArray(actionFunction)) {
for (const action of actionFunction) {
await action(ctx, userInput);
}
} else {
await actionFunction(ctx, userInput);
}
} catch (error) {
console.error(`Error handling command: ${error.message}`);
await ctx.reply(`Error handling command: ${error.message}`);
} finally {
await ctx.deleteMessage();
}
};
async function postTelegramMessage(message, chatId, threadId) {
try {
await bot.telegram.sendMessage(chatId, message, {
message_thread_id: threadId
});
console.log('Message sent to Telegram');
} catch (error) {
console.error('Error sending message to Telegram:', error);
}
}
const createNodeStatsCommand = (commandName, nodeStatsFunction) => {
bot.command(commandName, ctx => handleCommand(ctx, commandName, async (ctx, tokenSymbol) => {
try {
const stats = await nodeStatsFunction(tokenSymbol);
if (stats) {
await ctx.reply(stats);
} else {
await ctx.reply('No data found for the given token symbol.');
}
} catch (error) {
console.error(`Error retrieving node stats: ${error.message}`);
await ctx.reply(`Error retrieving node stats: ${error.message}`);
}
}));
};
bot.command('networkstats', ctx => handleCommand(ctx, 'networkstats', networkStats.fetchNetworkStatistics));
autoTweet.getRecordStats().then(initialRecords => {
recordAlerts.initializeLastKnownRecords(initialRecords);
});
cron.schedule(process.env.HOURLY, async () => {
const currentRecords = await autoTweet.getRecordStats();
recordAlerts.checkAndBroadcastNewRecords(bot, currentRecords);
});
cron.schedule(process.env.DAILY, async () => {
console.log('Running daily publication stats...');
const message = await autoTweet.gatherAndDisplayChainStatsWithImage();
if (message) {
await postTelegramMessage(message, process.env.OTC_ID, process.env.OTC_THREAD_ID);
await postTelegramMessage(message, process.env.OTHUB_ID);
} else {
console.error('Failed to generate daily statistics message.');
}
}, {
timezone: 'America/New_York'
});
// (async () => {
// console.log('Manually testing the daily publication stats...');
// try {
// const message = await autoTweet.gatherAndDisplayChainStatsWithImage();
// if (message) {
// console.log('Tweet posted:', message);
// await postTelegramMessage(message, process.env.OTHUB_ADMIN_ID);
// } else {
// console.error('Failed to generate daily statistics message.');
// }
// } catch (error) {
// console.error('Error in manual tweet posting:', error);
// }
// })();
cron.schedule(process.env.WEEKLY, async () => {
console.log('Running weekly publication stats...');
const message = await autoTweet.postStatistics('weekly');
if (message) {
await autoTweet.postTweet(message);
await postTelegramMessage(message, process.env.OTC_ID, process.env.OTC_THREAD_ID);
} else {
console.error('Failed to generate weekly statistics message.');
}
}, {
timezone: 'America/New_York'
});
cron.schedule(process.env.MONTHLY, async () => {
console.log('Running monthly publication stats...');
const message = await autoTweet.postStatistics('monthly');
if (message) {
await autoTweet.postTweet(message);
await postTelegramMessage(message, process.env.OTC_ID, process.env.OTC_THREAD_ID);
} else {
console.error('Failed to generate monthly statistics message.');
}
}, {
timezone: 'America/New_York'
});
// (async () => {
// try {
// console.log('Running daily publication stats test...');
// const message = await autoTweet.postStatistics('monthly');
// if (message) {
// await autoTweet.postTweet(message);
// await postTelegramMessage(message, process.env.OTC_ID, process.env.OTC_THREAD_ID);
// console.log('Messages posted successfully.');
// } else {
// console.error('Failed to generate daily statistics message.');
// }
// } catch (error) {
// console.error('Error during test execution:', error);
// }
// })();
adminCommand(bot);
bot.command('admincommands', ctx => handleCommand(ctx, 'admincommands', async (ctx) => {
if (!isAdmin(ctx)) {
const botmessage = await ctx.reply('You are not authorized to execute this command.');
if (botmessage) {
setTimeout(async () => {
try {
await ctx.telegram.deleteMessage(ctx.chat.id, botmessage.message_id);
} catch (error) {
console.error('Error deleting message:', error);
}
}, process.env.DELETE_TIMER);
}
return;
}
const message = adminCommandList();
await ctx.reply(message);
}));
bot.command('commands', ctx => handleCommand(ctx, 'commands', async (ctx) => {
const message = generalCommandList.generateCommandList();
await ctx.reply(message);
}));
bot.command('glossary', async (ctx) => {
const command = 'glossary'
const telegramId = ctx.message.from.id
const { permission } = await spamCheck(command, telegramId);
if (permission !== 'allow') {
await ctx.deleteMessage();
return;
}
let message = "📃Here's a list of OriginTrail terms:\n";
for (let term in glossary) {
message += `/${term.replace(" ", "_")}\n`;
}
const lines = message.split('\n');
lines.splice(-4, 4); // This removes the last two elements of the array
message = lines.join('\n');
});
for (let term in glossary) {
const commandName = term.replace(" ", "_");
bot.command(commandName, async (ctx) => {
const command = commandName
const telegramId = ctx.message.from.id
const { permission } = await spamCheck(command, telegramId);
if (permission != `allow`) {
await ctx.deleteMessage()
return
}
const botmessage = await ctx.reply(glossary[term]);
const gifPath = path.join(__dirname, 'glossary', `${term}.gif`);
const imagePath = path.join(__dirname, 'glossary', `${term}`);
if (fs.existsSync(gifPath)) {
await ctx.replyWithAnimation({ source: gifPath });
} else if (fs.existsSync(imagePath)) {
await ctx.replyWithPhoto({ source: imagePath });
}
});
}
cron.schedule(process.env.DAILY, function() {
eventMonitor.otpContractsChange(eventMonitor.notifyTelegramOtpContractsChange);
eventMonitor.gnosisContractsChange(eventMonitor.notifyTelegramGnosisContractsChange);
});
cron.schedule(process.env.HOURLY, function(){
eventMonitor.gnosisStagingUpdateStatus(eventMonitor.notifyTelegramGnosisStagingUpdateStatus);
eventMonitor.otpStagingUpdateStatus(eventMonitor.notifyTelegramOtpStagingUpdateStatus);
});
bot.command('pubsgraph', ctx => handleCommand(ctx, 'pubsgraph', [
async ctx => {
const data = await networkStats.fetchDateTotalPubs();
const dates = data.map(row => row.date);
const totalPubsValues = data.map(row => row.totalPubs);
const imageBuffer = await networkStats.KnowledgeAssetsOverTime(dates, totalPubsValues);
const imageStream = networkStats.bufferToStream(imageBuffer);
await ctx.replyWithPhoto({ source: imageStream });
},
]));
bot.command('networkgraph', ctx => handleCommand(ctx, 'networkgraph', [
async ctx => {
const cumulativeTracSpentData = await networkStats.fetchDateCumulativeTracSpent();
const cumulativePubsData = await networkStats.fetchDateCumulativePubs();
const cumulativePayoutsData = await networkStats.fetchDateCumulativePayouts();
const dates = cumulativeTracSpentData.map(row => row.date);
const cumulativePubsValues = cumulativePubsData.map(row => row.cumulativePubs);
const cumulativePayoutsValues = cumulativePayoutsData.map(row => row.cumulativePayout);
const cumulativeTotalTracSpentValues = cumulativeTracSpentData.map(row => row.cumulativeTotalTracSpent);
const imageBuffer = await networkStats.cumulativeGraph(dates, cumulativeTotalTracSpentValues, cumulativePubsValues, cumulativePayoutsValues);
const imageStream = networkStats.bufferToStream(imageBuffer);
await ctx.replyWithPhoto({ source: imageStream });
}
]));
bot.command('record', ctx => handleCommand(ctx, 'record', autoTweet.fetchAndSendRecordStats));
bot.command('hourlypubs', ctx => handleCommand(ctx, 'hourlypubs', networkPubs.fetchAndSendHourlyPubs));
bot.command('dailypubs', ctx => handleCommand(ctx, 'dailypubs', networkPubs.fetchAndSendDailyPubs));
bot.command('weeklypubs', ctx => handleCommand(ctx, 'weeklypubs', networkPubs.fetchAndSendWeeklyPubs));
bot.command('monthlypubs', ctx => handleCommand(ctx, 'monthlypubs', networkPubs.fetchAndSendMonthlyPubs));
bot.command('totalpubs', ctx => handleCommand(ctx, 'totalpubs', networkPubs.fetchAndSendTotalPubs));
createNodeStatsCommand('nodestatslasthour', nodeStats.lastHourNodeStats);
createNodeStatsCommand('nodestatslastday', nodeStats.lastDayNodeStats);
createNodeStatsCommand('nodestatslastweek', nodeStats.lastWeekNodeStats);
createNodeStatsCommand('nodestatslastmonth', nodeStats.lastMonthNodeStats);
createNodeStatsCommand('nodestats', nodeStats.NodeStats);
createCommand(bot);
sendInvoice(bot);
balanceOperations(bot);
//publishCommand(bot);
schedule.scheduleJob('*/1 * * * *', () => {
checkReceipt(bot);
});
//schedule.scheduleJob('*/1 * * * *', fetchTransactions);
//-----------------------END---------------------------
bot.launch()
process.once('SIGINT', () => bot.stop('SIGINT'))
process.once('SIGTERM', () => bot.stop('SIGTERM'))