0

I have the following telegram bot written in Python (3.x):

import telebot
import subprocess
from telebot import types
import os

bot = telebot.TeleBot(os.environ['BOT_API_TOKEN'])
@bot.message_handler(commands=['start'])

def save(messages):
    for m in messages:
        if "keyword" in m.text:
            f = open("channel", "a")
            f.write(m.text +  "\n")
            f.close()
            bot.send_message(m.chat.id, "Saved!")

bot.set_update_listener(save)
bot.polling()

The idea is to store in the file channel the messages that contain the word keyword. This bot works perfectly if I talk to him, but if I add the bot to a channel, it doesn't work. The bot has disable the privacy mode and enable the joingroups option.

I have another bot that do the same but with different code: import logging import os from telegram.ext import Updater, MessageHandler, Filters

updater = Updater(token=os.environ['BOT_API_TOKEN'])
dispatcher = updater.dispatcher
def save(bot, update):
    print(update.message.text)
    if "keyword" in update.message.text:
        f = open("channel", "a")
        f.write(update.message.text +  "\n")
        f.close()
        bot.sendMessage(chat_id=update.message.chat_id, text="Saved!")

save_handler = MessageHandler(Filters.text, save)
dispatcher.add_handler(save_handler)
updater.start_polling()

I don't mind in which version can you help me.

Néstor
  • 351
  • 1
  • 5
  • 20

1 Answers1

1

If you want to handle channel messages, you need to parse channel_post field instead of message field.

You can lockup Update section of official document for more details.

Sean Wei
  • 7,433
  • 1
  • 19
  • 39
  • This works, thanks! Do you know how to send a message to a channel? `bot.sendMessage(chat_id=update.message.update_id, text="Saved!")` doesn't work for me. (My bot is admin of the channel) – Néstor May 04 '17 at 14:40
  • @n23, don't abuse. This is not a comment, is a new question. Check this one as solution and post a new one. – dani herrera May 04 '17 at 15:13