0

I'm creating my first Telegram bot. I want the bot to filter text looking only for URLs, and trigger when is found.

For example, if someone types in the chat "www.google.com", I want the bot to recognize it as a URL and later do X action. I tried filtering for words to get an exact URL, but I'm doing it wrong.

I'm trying with Filters.entity(URL) but I've not been able to make the full necessary code.

This is the actual bot code:

import logging
from telegram.ext import Updater, CommandHandler, ConversationHandler, MessageHandler, Filters
import os
import random
import requests

TOKEN = "XXXXX"
PORT = int(os.environ.get('PORT', '8443'))
updater = Updater(TOKEN)

# Enable logging
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
                   level=logging.INFO)

logger = logging.getLogger(__name__)

# Define a few command handlers. These usually take the two arguments update and
# context. Error handlers also receive the raised TelegramError object in error.
def start(update, context):
   """Send a message when the command /start is issued."""
   update.message.reply_text('Hi!')

def coin(update, context):
   ''' ⚪️/⚫️ Moneda 
   Genera un número elatorio entre 1 y 2.
   '''
   cid=update.message.chat_id
   msg="⚫️ Cara" if random.randint(1,2)==1 else "⚪️ Cruz"
   # Responde directametne en el canal donde se le ha hablado.
   update.message.reply_text(msg)

def help(update, context):
   """Send a message when the command /help is issued."""
   update.message.reply_text('Help!')

def links(update, context):
   """Echo the user message."""
   url = str(update.message.text)
   if url.lower() == '*morning*':
   update.message.reply_text(update.message.text)
   
def error(update, context):
   """Log Errors caused by Updates."""
   logger.warning('Update "%s" caused error "%s"', update, context.error)

def main():
   """Start the bot."""
   # Create the Updater and pass it your bot's token.
   # Make sure to set use_context=True to use the new context based callbacks
   # Post version 12 this will no longer be necessary
   updater = Updater(TOKEN, use_context=True)

   # Get the dispatcher to register handlers
   dp = updater.dispatcher

   # on different commands - answer in Telegram
   dp.add_handler(CommandHandler("start", start))
   dp.add_handler(CommandHandler("help", help))
   dp.add_handler(CommandHandler("coin", coin))          

   # on noncommand i.e message - echo the message on Telegram    
   dp.add_handler(MessageHandler(Filters.entity(URL), links))

   # log all errors
   dp.add_error_handler(error)

   # Start the Bot
   updater.start_webhook(listen="0.0.0.0",
                         port=PORT,
                         url_path=TOKEN,
webhook_url="XXXXX/" + TOKEN)

   # Run the bot until you press Ctrl-C or the process receives SIGINT,
   # SIGTERM or SIGABRT. This should be used most of the time, since
   # start_polling() is non-blocking and will stop the bot gracefully.
   updater.idle()

if __name__ == '__main__':
   main()
Alex Waygood
  • 6,304
  • 3
  • 24
  • 46
  • After reading the docs, it's not clear to me if messages with the URL entity are messages that *contain* URLs or the entire message is a URL. It's possible there is some confusion there. Secondly, in your `links` function, the message text can never be `*morning*` because that isn't a valid URL. That message would not trigger that handler. Try just spitting the message back unmodified, that will show you what is getting detected as a URL message. – TechnoSam Jul 26 '21 at 17:05
  • Thanks. I was trying to filter the URL to avoid the bot trigger with all the written URL. But was a mistake, because I need first to make it works reading all URL. – Sabrani Wodoo Jul 26 '21 at 17:14

1 Answers1

2
dp.add_handler(MessageHandler(Filters.entity(URL), links))

change this to this ->

dp.add_handler(MessageHandler(Filters.entity('url'), links))

disable your other replyto normal text handler .. because that function concider your links as a normal text

py coder
  • 21
  • 3
  • `Filters.entity('url')` — this comment saved my time! Everywhere is shown URL in examples — and what variable URL is equal to — no any explanations... – Constantine Kurbatov Jan 29 '22 at 03:58