Telegram Bot with Telegraf.js - Send messages to chat
Asked Answered
M

2

16

I want to create a Telegram Bot with Node.js and I am using Telegraf for it. I know I can answer to messages like this:

app.hears('hi', (ctx) => ctx.reply('Hey there!'))

But how can I send a message without getting a message before? I want to read a file and always when the file got changed I want to send a message.

const Telegraf = require('telegraf');
var fs = require('fs');

const app = new Telegraf(process.env.BOT_TOKEN);

var filePath = "C:\\path\\to\\my\\file.txt";

fs.watchFile(filePath, function() {
    file = fs.readFileSync(filePath);

    // Send message to chat or group with the file content here

    console.log("File content at: " + new Date() + " is: \n" + file);
})

Would be nice if someone can help me with it.

Marnamarne answered 4/5, 2017 at 21:51 Comment(1)
Having a similar situation xD funny how that usecase is not as straightforward as it is thought to be... So as far as I got it - I need to have the chatID of course if the chat is initially startet just when the bot is running I may get the chatId from the ctx object. But what if the bot just later connects from the service? Do I have to manually find out that specific chatId and provide it to the Bot hardcodedly?Shennashensi
B
16

You can use app.telegram.sendMessage for that, see following snippet.

const Telegraf = require('telegraf');
var fs = require('fs');

const app = new Telegraf(process.env.BOT_TOKEN);

var filePath = "C:\\path\\to\\my\\file.txt";

fs.watchFile(filePath, function() {
  file = fs.readFileSync(filePath);
  app.telegram.sendMessage(chatId, "File content at: " + new Date() + " is: \n" + file);
})
Bithia answered 5/5, 2017 at 19:5 Comment(3)
Ok ty. But I have to add a chat ID as parameter. Do you know how I can get it?Marnamarne
Found it: api.telegram.org/bot[BOT-TOKEN]/getUpdates -> chat -> idMarnamarne
I get a 400 Bad Request: chat not found when trying to send a messagePanslavism
S
3
app.on('message', function (ctx, next) {
    ctx.telegram.sendMessage(ctx.message.chat.id,
      "File content at: " + new Date() + " is: \n" + file
    )
});
Stichomythia answered 23/8, 2017 at 7:39 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.