![](/img/trans.png)
[英]Telegram Bot Chain of Multiple Messages Sending NodeJS - Crashing
[英]Telegram bot - Sending messages to user every day
我想創建一個基於 Telegraf 的 Telegram 機器人。 我希望機器人通過啟動命令來安排並向用戶發送消息。
例如,我希望它作為一門課程工作:一旦你 select 一門課程,你每天都會得到教訓。
我嘗試使用 node-cron(參見下面的示例),但它通過啟動機器人開始發送消息。
const cron = require('node-cron');
const schedule = cron.schedule('*/5 * * * * *', async () => {
bot.telegram.sendMessage(chatId, 'Hello World');
});
bot.command('/launch', ctx => {
schedule.launch();
});
bot.command('/stop', ctx => {
schedule.stop();
});
請提出實現這樣的機器人的方法。 如果您知道現有的帶有源代碼的 Telegraf 機器人,請告訴我。
如果這是我的項目,我會編寫一個獨立的程序(用 nodejs 或其他語言)來運行操作系統的cron 子系統而不是 nodejs 經常調用的程序。 該程序不會作為 web 服務器運行,而只是獨立運行。
獨立程序將連接到您的用戶數據庫,檢索它需要發送的消息列表,然后使用電報發送它們。
完成發送后它會退出,因為知道操作系統的 cron 將在時間到來時再次啟動它。
有兩個選項可以做到這一點。
let timer = null;
bot.onText(/\/start/, message => {
timer = setInterval(() => {
if(new Date().getSeconds() === 1) {
bot.sendMessage(message.chat.id, "responce");
}
}, 1000)
});
bot.onText(/\/stop/, message => {
clearInterval(timer);
})
import schedule from "node-schedule";
let job;
bot.onText(/\/start/, message => {
job = schedule.scheduleJob('1 * * * * *', () => {
bot.sendMessage(message.chat.id, "responce");
});
});
bot.onText(/\/stop/, message => {
if (job) {
job.cancel()
}
});
我更喜歡第二種選擇,因為它更靈活。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.