Answer the question
In order to leave comments, you need to log in
How to get chat_id from database - Telegram bot?
Hi
I'm making a bot on Telegraf
, I use cron
it to send alerts and mongodb
store user data.
I'm trying to run a script like this:
const CronJob = require('cron').CronJob;
const job = new CronJob('*/5 * * * * *', async function() {
const user = await db.User.findOne({chat_id: ctx.chat.id});
await bot.telegram.sendMessage(user.chat_id, 'Hello World');
})
bot.command('launch', async (ctx) => {
job.start()
})
bot.command('stop', async (ctx) => {
job.stop();
})
db.User.findOne()
, it turns out to take only the first user from the database. chat_id
in the event when I access the ctx
. bot.command('launch', async (ctx) => {
const user = await db.User.findOne({chat_id: ctx.chat.id});
console.log(user.chat_id)
})
Answer the question
In order to leave comments, you need to log in
const job = new CronJob('*/5 * * * * *', async function() {
const user = await db.User.findOne({chat_id: ctx.chat.id});
await bot.telegram.sendMessage(user.chat_id, 'Hello World');
})
Dmitry Gololobov , I tried your version, it works.
I'm trying to make the bot send a certain number of messages from the database:
// беру сообщения из бд
const messages = data.get('messages')
.map('message')
.value();
let i=0;
const CronJob = require('cron').CronJob;
const createJob = async function(chatid) {
return new CronJob('*/15 * * * * *', async function() {
const user = await db.User.findOne({chat_id: chatid});
await bot.telegram.sendMessage(user.chat_id, messages[i]);
console.log('Job running');
i++;
});
}
bot.command('launch', async (ctx) => {
const myNewJob = await createJob(ctx.chat.id)
await bot.telegram.sendMessage(ctx.chat.id, `Let's start`);
myNewJob.start()
})
const messages = data.get('messages')
.map('message')
.value();
const CronJob = require('cron').CronJob;
const usersToNotify = []
let i=0;
const job = new CronJob('*/15 * * * * *', async function() {
for await (const user of usersToNotify) {
await bot.telegram.sendMessage(user, messages[i]);
i++;
if (messages.length == i) {
job.stop();
}
}
})
job.start()
bot.command('launch', async (ctx) => {
const User = await db.User.findOne({chat_id: ctx.chat.id});
usersToNotify.push(User.chat_id)
})
bot.command('stop', async (ctx) => {
const User = await db.User.findOne({chat_id: ctx.chat.id});
const index = usersToNotify.findIndex(value => value === User.chat_id)
usersToNotify.splice(index,1)
})
cron
works for all users globally. chat_id
? Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question