Search code examples
pythonpython-3.xtelegramtelegram-botpython-telegram-bot

Is there a Way that a telegram Bot could respond to a command in a Channel?


i need a bot coded in python that can Reply to a Command like /start in a telegram channel. It needs to reply a InlineKeyboardMarkup.

from telegram import InlineKeyboardButton, InlineKeyboardMarkup
from telegram.ext.updater import Updater
from telegram.ext.commandhandler import CommandHandler
from telegram.ext.callbackqueryhandler import CallbackQueryHandler
from telegram.callbackquery import CallbackQuery
from telegram.ext.callbackcontext import CallbackContext
from telegram.update import Update
import telegram

updater: Updater = Updater("xxxxxxxxxx", use_context=True)

def start(update: Update, context: CallbackContext):
    keyboard = [[InlineKeyboardButton("xxxxx", url='xxxx'),
                        InlineKeyboardButton("xxxxx", url='xxxxx')],
                        [InlineKeyboardButton("xxxxx", url='xxxxx')]]
    reply_markup = InlineKeyboardMarkup(keyboard)

    update.effective_message.reply_text("Gruppen zum Beitreten: ", reply_markup=reply_markup)
    pass


def button(update, context):
    query: CallbackQuery = update.callback_query
    query.answer()
    query.edit_message_text(format(query.data))

updater.dispatcher.add_handler(telegram.ext.PrefixHandler("/", "button", start))
updater.dispatcher.add_handler(CallbackQueryHandler(button))
updater.start_polling()

So this code is working in Private Chat with bot and in a Group. But i need it in a Channel. Please someone help find a solution :/


Solution

  • Because PrefixHandler uses Filters.updates.messages internally, which excludes channel posts, PrefixHandler can't work. You can to use e.g. MessageHandler(Filters.regex("^/button"), start) instead. Ofc depending on your use case you might want to enhance the regex, e.g. '^/button\b'.