Search code examples
python-3.xbotstelegram-botpython-telegram-bot

How can I use web scraping codes correctly for telegram bot and send messages?


When I call the /exchange command, the result comes out in the terminal. But It didn't show the result when I call by telegram. I looked through the documents in the Telegram bot library but still haven't found a solution.

    def exchange(update, context):
      my_url = 'https://finance.yahoo.com/quote/USDTRY=X/'
      uClient = uReq(my_url)
      page_html = uClient.read()
      uClient.close()
      page_soup = soup(page_html,"html.parser")
      containers = page_soup.findAll("div", {"class":"My(6px) Pos(r) smartphone_Mt(6px)"})
    
      USDTORTY = containers[0].div.span.string
      USDTORTYPERCENTAGE = containers[0].div.div.span.string
      exchange_msg = print("TRY TO USD: "+ USDTORTY, "PERCANTAGE: " +  USDTORTYPERCENTAGE)
      update.message_reply_text(exchange_msg)

Returns on Terminal

TRY TO USD: 5.70, PERCANTAGE: 0.12%

Solution

  • You should construct the response first (print it if you need it for debugging) and use the method reply_text

    exchange_msg = "TRY TO USD: " + USDTORTY, "PERCANTAGE: " + USDTORTYPERCENTAGE
    print(exchange_msg)
    # send reply
    update.message.reply_text(exchange_msg)