node.jsbotstelegramtelegram-botnode-telegram-bot-api

Telegram message relay bot


Good afternoon. I am writing a telegram bot using node-telegram-bot-api and sequelize. One of the tasks that the bot faces is to automatically forward or copy messages from one channel to another. In both channels, the bot is assigned as an administrator. Unfortunately, none of the solutions used worked. I made the channels both private and public, I also tried changing the id to "@channelusername" of the channel, none of the options worked. Examples that I used:

What could be the problem?

Ex 1:

const TelegramBot = require('node-telegram-bot-api');
const token = 'YOUR_TELEGRAM_BOT_TOKEN';
const bot = new TelegramBot(token, { polling: true });

const sourceChannelId = -1001234567890; 
const targetChannelId = -1009876543210; 

bot.on('message', (msg) => {
  if (msg.chat.id === sourceChannelId) {
    
    bot.forwardMessage(targetChannelId, sourceChannelId, msg.message_id);
  }
});

Ex 2:

const TelegramBot = require('node-telegram-bot-api');

const sourceChannelId = -1001234567890;
const targetChannelId = -1009876543210;

const bot = new TelegramBot('YOUR_TELEGRAM_BOT_TOKEN', { polling: true });

bot.on('message', (message) => {
  
  if (message.chat.id === sourceChannelId) {
    
    const notification = `Новое сообщение в канале ${message.chat.title}:\n\n${message.text}`;

    
    bot.sendMessage(targetChannelId, notification);
  }
});

Solution

  • thanks for reaching out. It seems oblivious that you're listening to message updates. The messages that arrive in channels are not considered messages, instead, they're treated as channel_post updates.

    So, simply the same code with listening to channel posts would work perfectly fine:

    bot.on('channel_post', (msg) => {
      if (msg.chat.id === sourceChannelId) {
        bot.forwardMessage(targetChannelId, sourceChannelId, msg.message_id);
      }
    });
    

    Regards :)