0

I'm writing a simple telegram bot to accept a word as input and return a message inlcuding a Youtube link based on that word. The bot should look for the word after the '/search' command is invoked but here it's using every word sent to the chat. Please can you help me to fix it?

import logging
from telegram import Update
from telegram.ext import ApplicationBuilder, ContextTypes, CommandHandler, MessageHandler, filters
import random
import re
import urllib.request



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


async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
    await context.bot.send_message(chat_id=update.effective_chat.id, text="I'm a bot, please talk to me!")



async def search(update: Update, context: ContextTypes.DEFAULT_TYPE):
    """Search a single word"""
    await update.message.reply_text("Type a single word")  
    return short_reply


async def short_reply(update: Update, context: ContextTypes.DEFAULT_TYPE):
    word = update.message.text
    html = urllib.request.urlopen("https://www.youtube.com/results?search_query=" + word)
    video_ids = re.findall(r"watch\?v=(\S{11})", html.read().decode())
    await context.bot.send_message(chat_id=update.effective_chat.id, text=f"https://www.youtube.com/watch?v=" + video_ids[random.randrange(1,20)])
    return start



if __name__ == '__main__':
    application = ApplicationBuilder().token('TOKEN').build()
    
    start_handler = CommandHandler('start', start)
    application.add_handler(start_handler)

    search_handler = CommandHandler('search', search)
    application.add_handler(search_handler)
   
    short_reply_handler = MessageHandler(filters.TEXT, short_reply)
    application.add_handler(short_reply_handler)

    
    application.run_polling()

I even tried to add other functions as a sort of 'keywords menu' but i encountered the same problem: the bot will immediately reply with "I didn't undestand your command" because it's always reading the message sent right before the function invocation (the function/command invocation itself).

async def edit_tags(update: Update, context: ContextTypes.DEFAULT_TYPE):
    await context.bot.send_message(chat_id=update.effective_chat.id, text="ADD/REMOVE?")
    msg = update.message.text
    if msg == 'ADD':
        await context.bot.send_message(chat_id=update.effective_chat.id, text="Write a keyword")
        keyword = update.message.text
        print(keyword)
    elif msg == 'REMOVE':
        await context.bot.send_message(chat_id=update.effective_chat.id, text="Remove")
        pass
    else:
        await context.bot.send_message(chat_id=update.effective_chat.id, text="I didn't undestand your command")




    tags_handler = MessageHandler(filters.TEXT, edit_tags)
    application.add_handler(tags_handler)


Mira
  • 25
  • 4

0 Answers0