Ishayahu
Ishayahu

Reputation: 355

How to use URL with InlineKeyboardButton for Telegram Bot

I saw that question, but it doesn't work for me. I don't understand why. I need button that opens an url link. Here is my startng point

from telegram import Update
from telegram.ext import Updater, CommandHandler, CallbackContext
from telegram import ReplyKeyboardMarkup, KeyboardButton


def start(update, context):
    context.bot.send_message(chat_id=update.effective_chat.id,
                             text="I'm a bot, please talk to me!",
                             reply_markup=ReplyKeyboardMarkup([
                                [KeyboardButton('rules', url='https://google.com'), ],
                                ])
                             )


updater = Updater('APIKEY', use_context=True)
dispatcher = updater.dispatcher

start_handler = CommandHandler('start', start)
dispatcher.add_handler(start_handler)

updater.start_polling()
updater.idle()

Upvotes: 0

Views: 1928

Answers (1)

Rafael Colombo
Rafael Colombo

Reputation: 435

You must use InlineKeyboardButton in order to be able to open an URL from a button.

from telegram import InlineKeyboardButton, InlineKeyboardMarkup
from telegram.ext import CallbackQueryHandler, CallbackContext

def start(update, context):
    
    query = update.callback_query
    chat_id = query.message.chat_id

    keyboard = [[InlineKeyboardButton('rules', url = 'https://google.com')]]
    reply_markup = InlineKeyboardMarkup(keyboard)
    context.bot.send_message(chat_id = chat_id,
                             text = "I'm a bot, please talk to me!",
                             reply_markup = reply_markup)

Additionally you must have a function for InlineKeyboardButton

def button (update, context):
    query = update.callback_context
    query.answer()

and a CallbackQueryHandler for the button and start:

dp.add_handler(CallbackQueryHandler(button))
dp.add_handler(CallbackQueryhandler(start))

Upvotes: 2

Related Questions