trashbin-scheduler-bot-tg 1.1.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.env.example +18 -0
- package/LICENSE +373 -0
- package/README.md +157 -0
- package/db/2025-11.json +134 -0
- package/db/2025-12.json +29 -0
- package/db/2026-01.json +29 -0
- package/db/2026-02.json +26 -0
- package/db/2026-03.json +28 -0
- package/db/2026-04.json +26 -0
- package/db/2026-05.json +27 -0
- package/db/2026-06.json +27 -0
- package/ecosystem.config.js +26 -0
- package/lib/constants.js +12 -0
- package/lib/utils.js +130 -0
- package/package.json +51 -0
- package/trashbin-day-handler.js +264 -0
|
@@ -0,0 +1,264 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// load environment variables from .env (BOT_TOKEN, TARGET_CHAT_ID, ...)
|
|
3
|
+
require('dotenv').config();
|
|
4
|
+
// import shared constants and utils
|
|
5
|
+
const { EMOJI_MAP } = require('./lib/constants');
|
|
6
|
+
const { parseTargetChats, getEntryForDate, loadScheduleForDate, ensureLogsDir, logRequest, getSubscribers, subscribeChat, unsubscribeChat } = require('./lib/utils');
|
|
7
|
+
const TelegramBot = require('node-telegram-bot-api');
|
|
8
|
+
// read the Telegram token from environment variable BOT_TOKEN
|
|
9
|
+
const token = process.env.BOT_TOKEN;
|
|
10
|
+
// Create a bot that uses 'polling' to fetch new updates
|
|
11
|
+
if (!token) {
|
|
12
|
+
console.error('Error: BOT_TOKEN is not set. Copy .env.example to .env and set BOT_TOKEN (see README / INSTALL.md).');
|
|
13
|
+
process.exit(1);
|
|
14
|
+
}
|
|
15
|
+
const bot = new TelegramBot(token, {polling: true});
|
|
16
|
+
// store last active chat id as fallback for scheduled messages
|
|
17
|
+
let lastActiveChatId = null;
|
|
18
|
+
|
|
19
|
+
// Listen for any kind of message. There are different kinds of messages.
|
|
20
|
+
// NOTE: logs are written to stdout so pm2 can capture them. To also persist logs to file,
|
|
21
|
+
// set WRITE_REQUESTS_LOG=true in .env and the logger will append to logs/requests.log.
|
|
22
|
+
bot.on('message', (msg) => {
|
|
23
|
+
// Always log the request and auto-subscribe, but don't auto-send the detailed 'today...' message here.
|
|
24
|
+
logRequest(msg, null, __dirname);
|
|
25
|
+
const chatId = msg.chat.id;
|
|
26
|
+
lastActiveChatId = chatId;
|
|
27
|
+
// add to subscribers list (saved into ecosystem.config.js TARGET_CHAT_ID)
|
|
28
|
+
try {
|
|
29
|
+
subscribeChat(String(chatId), __dirname);
|
|
30
|
+
} catch (e) {
|
|
31
|
+
console.error('Failed to subscribe chat:', e.message);
|
|
32
|
+
}
|
|
33
|
+
// any other simple auto-replies can be added here, but the main info message is now sent only on /info
|
|
34
|
+
});
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
// Matches "/echo [whatever]". Logs message, info about the user and echoes back the same message.
|
|
38
|
+
bot.onText(/\/echo (.+)/, (msg, match) => {
|
|
39
|
+
// 'msg' is the received Message from Telegram
|
|
40
|
+
// 'match' is the result of executing the regexp above on the text content
|
|
41
|
+
// of the message
|
|
42
|
+
|
|
43
|
+
const chatId = msg.chat.id;
|
|
44
|
+
const resp = match[1]; // the captured "whatever"
|
|
45
|
+
|
|
46
|
+
// send back the matched "whatever" to the chat
|
|
47
|
+
bot.sendMessage(chatId, resp);
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
// Admin command: /subscribers -> list subscriber chat IDs (restricted for admin) TODO: test with account having different id than admin.
|
|
51
|
+
bot.onText(/\/subscribers/, async (msg) => {
|
|
52
|
+
const fromId = msg.from && (msg.from.id || msg.from.username);
|
|
53
|
+
const adminEnv = process.env.ADMIN_CHAT_ID || '';
|
|
54
|
+
const admins = adminEnv.split(',').map(s => s.trim()).filter(Boolean);
|
|
55
|
+
const isAdmin = admins.length === 0 ? false : admins.includes(String(fromId)) || admins.includes(String(msg.chat.id));
|
|
56
|
+
if (!isAdmin) {
|
|
57
|
+
return bot.sendMessage(msg.chat.id, 'Not authorized');
|
|
58
|
+
}
|
|
59
|
+
try {
|
|
60
|
+
const { getSubscribers } = require('./lib/utils');
|
|
61
|
+
const subs = getSubscribers(__dirname);
|
|
62
|
+
if (!subs || subs.length === 0) {
|
|
63
|
+
return bot.sendMessage(msg.chat.id, 'No subscribers yet');
|
|
64
|
+
}
|
|
65
|
+
const body = subs.join('\n');
|
|
66
|
+
bot.sendMessage(msg.chat.id, `Subscribers:\n${body}`);
|
|
67
|
+
} catch (e) {
|
|
68
|
+
console.error('Failed to list subscribers:', e.message);
|
|
69
|
+
bot.sendMessage(msg.chat.id, 'Error reading subscribers');
|
|
70
|
+
}
|
|
71
|
+
});
|
|
72
|
+
|
|
73
|
+
// Command for users to unsubscribe themselves TODO: is not working yet.
|
|
74
|
+
bot.onText(/\/unsubscribe/, (msg) => {
|
|
75
|
+
const chatId = msg.chat && msg.chat.id;
|
|
76
|
+
if (!chatId) return;
|
|
77
|
+
try {
|
|
78
|
+
unsubscribeChat(String(chatId), __dirname);
|
|
79
|
+
bot.sendMessage(chatId, 'You have been unsubscribed.');
|
|
80
|
+
} catch (e) {
|
|
81
|
+
console.error('Failed to unsubscribe:', e.message);
|
|
82
|
+
bot.sendMessage(chatId, 'Unable to unsubscribe right now.');
|
|
83
|
+
}
|
|
84
|
+
});
|
|
85
|
+
|
|
86
|
+
// New command: /info -> reply with today's and tomorrow's schedule (same message used by scheduler)
|
|
87
|
+
bot.onText(/\/info/, (msg) => {
|
|
88
|
+
const chatId = msg.chat && msg.chat.id;
|
|
89
|
+
if (!chatId) return;
|
|
90
|
+
|
|
91
|
+
const now = new Date();
|
|
92
|
+
const today = getEntryForDate(now, __dirname);
|
|
93
|
+
const tomorrowDate = new Date(now);
|
|
94
|
+
tomorrowDate.setDate(tomorrowDate.getDate() + 1);
|
|
95
|
+
const tomorrow = getEntryForDate(tomorrowDate, __dirname);
|
|
96
|
+
|
|
97
|
+
const emojiToday = EMOJI_MAP[today.type] || EMOJI_MAP.UNKNOWN;
|
|
98
|
+
const emojiTomorrow = EMOJI_MAP[tomorrow.type] || EMOJI_MAP.UNKNOWN;
|
|
99
|
+
const outMsg = `Today is ${today.dateStr} ${emojiToday} (${today.type}). Tonight, after 20:00 you must put outside ${emojiTomorrow} ${tomorrow.type}`;
|
|
100
|
+
bot.sendMessage(chatId, outMsg).catch((err) => console.error('Send /info error:', err.message));
|
|
101
|
+
console.log(`Sent /info to ${chatId}: ${outMsg}`);
|
|
102
|
+
});
|
|
103
|
+
|
|
104
|
+
// /week -> reply with the collection type for each of the next 7 days
|
|
105
|
+
bot.onText(/\/week/, (msg) => {
|
|
106
|
+
const chatId = msg.chat && msg.chat.id;
|
|
107
|
+
if (!chatId) return;
|
|
108
|
+
|
|
109
|
+
const now = new Date();
|
|
110
|
+
const lines = [];
|
|
111
|
+
for (let i = 0; i < 7; i++) {
|
|
112
|
+
const d = new Date(now);
|
|
113
|
+
d.setDate(d.getDate() + i);
|
|
114
|
+
const entry = getEntryForDate(d, __dirname);
|
|
115
|
+
const emoji = EMOJI_MAP[entry.type] || EMOJI_MAP.UNKNOWN;
|
|
116
|
+
lines.push(`${entry.dateStr} ${emoji} ${entry.type}`);
|
|
117
|
+
}
|
|
118
|
+
const outMsg = `📆 Next 7 days\n\n${lines.join('\n')}`;
|
|
119
|
+
bot.sendMessage(chatId, outMsg).catch((err) => console.error('Send /week error:', err.message));
|
|
120
|
+
console.log(`Sent /week to ${chatId}`);
|
|
121
|
+
});
|
|
122
|
+
|
|
123
|
+
// /month -> reply with the full schedule for the current month
|
|
124
|
+
bot.onText(/\/month/, (msg) => {
|
|
125
|
+
const chatId = msg.chat && msg.chat.id;
|
|
126
|
+
if (!chatId) return;
|
|
127
|
+
|
|
128
|
+
const now = new Date();
|
|
129
|
+
const monthStr = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}`;
|
|
130
|
+
const schedule = loadScheduleForDate(now, __dirname);
|
|
131
|
+
if (!schedule.length) {
|
|
132
|
+
return bot.sendMessage(chatId, `No schedule available for ${monthStr}.`);
|
|
133
|
+
}
|
|
134
|
+
const lines = schedule
|
|
135
|
+
.slice()
|
|
136
|
+
.sort((a, b) => a.date.localeCompare(b.date))
|
|
137
|
+
.map((e) => {
|
|
138
|
+
const emoji = EMOJI_MAP[e.type] || EMOJI_MAP.UNKNOWN;
|
|
139
|
+
return `${e.date.slice(8, 10)} ${emoji} ${e.type}`;
|
|
140
|
+
});
|
|
141
|
+
const outMsg = `🗓️ Calendar for ${monthStr}\n\n${lines.join('\n')}`;
|
|
142
|
+
bot.sendMessage(chatId, outMsg).catch((err) => console.error('Send /month error:', err.message));
|
|
143
|
+
console.log(`Sent /month to ${chatId} (${lines.length} days)`);
|
|
144
|
+
});
|
|
145
|
+
|
|
146
|
+
// /help (and /start) -> list available commands
|
|
147
|
+
bot.onText(/\/(help|start)/, (msg) => {
|
|
148
|
+
const chatId = msg.chat && msg.chat.id;
|
|
149
|
+
if (!chatId) return;
|
|
150
|
+
|
|
151
|
+
const outMsg = [
|
|
152
|
+
'🤖 Trashbin Scheduler Bot — available commands:',
|
|
153
|
+
'',
|
|
154
|
+
'/info — today\'s collection + what to put out tonight',
|
|
155
|
+
'/week — schedule for the next 7 days',
|
|
156
|
+
'/month — full calendar for the current month',
|
|
157
|
+
'/unsubscribe — stop receiving the daily message',
|
|
158
|
+
'/echo <text> — echo the text back (debug)'
|
|
159
|
+
].join('\n');
|
|
160
|
+
bot.sendMessage(chatId, outMsg).catch((err) => console.error('Send /help error:', err.message));
|
|
161
|
+
console.log(`Sent /help to ${chatId}`);
|
|
162
|
+
});
|
|
163
|
+
|
|
164
|
+
// --- scheduling logic: send daily at 20:30 local time ---
|
|
165
|
+
|
|
166
|
+
const sendDailyMessage = () => {
|
|
167
|
+
const now = new Date();
|
|
168
|
+
const today = getEntryForDate(now, __dirname);
|
|
169
|
+
const tomorrowDate = new Date(now);
|
|
170
|
+
tomorrowDate.setDate(tomorrowDate.getDate() + 1);
|
|
171
|
+
const tomorrow = getEntryForDate(tomorrowDate, __dirname);
|
|
172
|
+
|
|
173
|
+
const emojiToday = EMOJI_MAP[today.type] || EMOJI_MAP.UNKNOWN;
|
|
174
|
+
const emojiTomorrow = EMOJI_MAP[tomorrow.type] || EMOJI_MAP.UNKNOWN;
|
|
175
|
+
const outMsg = `Today is ${today.dateStr} ${emojiToday} (${today.type}). Tonight, after 20:00 pm you must put outside ${emojiTomorrow} ${tomorrow.type}`;
|
|
176
|
+
|
|
177
|
+
// decide targets: env TARGET_CHAT_ID has precedence; if SEND_TO_SUBSCRIBERS=true, use saved subscribers instead
|
|
178
|
+
let targets = parseTargetChats();
|
|
179
|
+
if (process.env.SEND_TO_SUBSCRIBERS === 'true') {
|
|
180
|
+
try {
|
|
181
|
+
const subs = getSubscribers(__dirname);
|
|
182
|
+
targets = subs.map(String);
|
|
183
|
+
} catch (e) {
|
|
184
|
+
console.error('Failed to load subscribers:', e.message);
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
if (targets.length === 0) {
|
|
189
|
+
if (lastActiveChatId) {
|
|
190
|
+
bot.sendMessage(lastActiveChatId, outMsg).catch((err) => console.error('Scheduled send error:', err.message));
|
|
191
|
+
console.log(`Scheduled message sent to last active chat ${lastActiveChatId}: ${outMsg}`);
|
|
192
|
+
} else {
|
|
193
|
+
console.warn('No TARGET_CHAT_ID configured and no last active chat available. Skipping scheduled send.');
|
|
194
|
+
}
|
|
195
|
+
return;
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
targets.forEach(t => {
|
|
199
|
+
bot.sendMessage(t, outMsg).catch((err) => console.error('Scheduled send error to', t, err.message));
|
|
200
|
+
console.log(`Scheduled message sent to ${t}: ${outMsg}`);
|
|
201
|
+
});
|
|
202
|
+
};
|
|
203
|
+
|
|
204
|
+
const scheduleNextRun = () => {
|
|
205
|
+
const now = new Date();
|
|
206
|
+
const next = new Date(now);
|
|
207
|
+
next.setHours(20, 30, 0, 0); // 20:30:00.000 local
|
|
208
|
+
if (next <= now) {
|
|
209
|
+
// if already past today 20:30, schedule for tomorrow
|
|
210
|
+
next.setDate(next.getDate() + 1);
|
|
211
|
+
}
|
|
212
|
+
const msUntilNext = next - now;
|
|
213
|
+
console.log('Scheduling next daily send at', next.toString());
|
|
214
|
+
setTimeout(() => {
|
|
215
|
+
try {
|
|
216
|
+
sendDailyMessage();
|
|
217
|
+
} catch (e) {
|
|
218
|
+
console.error('Error during scheduled send:', e.message);
|
|
219
|
+
}
|
|
220
|
+
// after running, schedule subsequent runs every 24h using scheduleNextRun
|
|
221
|
+
scheduleNextRun();
|
|
222
|
+
}, msUntilNext);
|
|
223
|
+
};
|
|
224
|
+
|
|
225
|
+
// send startup notification to configured TARGET_CHAT_ID(s)
|
|
226
|
+
const sendStartupNotification = () => {
|
|
227
|
+
const targets = parseTargetChats();
|
|
228
|
+
if (targets.length === 0) {
|
|
229
|
+
console.log('No TARGET_CHAT_ID configured; skipping startup notification.');
|
|
230
|
+
return;
|
|
231
|
+
}
|
|
232
|
+
try {
|
|
233
|
+
const now = new Date();
|
|
234
|
+
const today = getEntryForDate(now, __dirname);
|
|
235
|
+
const tomorrowDate = new Date(now);
|
|
236
|
+
tomorrowDate.setDate(tomorrowDate.getDate() + 1);
|
|
237
|
+
const tomorrow = getEntryForDate(tomorrowDate, __dirname);
|
|
238
|
+
const rocket = '🚀';
|
|
239
|
+
const welcome = `${rocket} Bot is up`;
|
|
240
|
+
const emojiToday = EMOJI_MAP[today.type] || EMOJI_MAP.UNKNOWN;
|
|
241
|
+
const emojiTomorrow = EMOJI_MAP[tomorrow.type] || EMOJI_MAP.UNKNOWN;
|
|
242
|
+
const outMsg = `(startup) Today is ${today.dateStr} ${emojiToday} (${today.type}). Tomorrow you must put outside ${emojiTomorrow} ${tomorrow.type}`;
|
|
243
|
+
targets.forEach(t => {
|
|
244
|
+
bot.sendMessage(t, welcome).catch((err) => console.error('Startup welcome send error to', t, err.message));
|
|
245
|
+
bot.sendMessage(t, outMsg).catch((err) => console.error('Startup send error to', t, err.message));
|
|
246
|
+
console.log(`Startup notification sent to ${t}: ${welcome}; ${outMsg}`);
|
|
247
|
+
});
|
|
248
|
+
} catch (e) {
|
|
249
|
+
console.error('Error sending startup notification:', e.message);
|
|
250
|
+
}
|
|
251
|
+
};
|
|
252
|
+
|
|
253
|
+
// register the command list so it shows in Telegram's UI menu
|
|
254
|
+
bot.setMyCommands([
|
|
255
|
+
{ command: 'info', description: "Today's collection + what to put out tonight" },
|
|
256
|
+
{ command: 'week', description: 'Schedule for the next 7 days' },
|
|
257
|
+
{ command: 'month', description: 'Full calendar for the current month' },
|
|
258
|
+
{ command: 'help', description: 'List available commands' },
|
|
259
|
+
{ command: 'unsubscribe', description: 'Stop receiving the daily message' }
|
|
260
|
+
]).catch((err) => console.error('setMyCommands error:', err.message));
|
|
261
|
+
|
|
262
|
+
// start scheduler
|
|
263
|
+
scheduleNextRun();
|
|
264
|
+
sendStartupNotification();
|