Telegram Bot with Telegraf.js - Send messages to chat

22,461

Solution 1

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);
})

Solution 2

app.on('message', function (ctx, next) {
    ctx.telegram.sendMessage(ctx.message.chat.id,
      "File content at: " + new Date() + " is: \n" + file
    )
});
Share:
22,461
Nono
Author by

Nono

Updated on January 16, 2022

Comments

  • Nono
    Nono over 2 years

    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.

  • Nono
    Nono about 7 years
    Ok ty. But I have to add a chat ID as parameter. Do you know how I can get it?
  • Nono
    Nono about 7 years