sanghmitra
sanghmitra

Reputation: 103

passing text/string in url of telegram bot by python

I want to pick a data from a website and need to send on telegram bot as message i'm able to send a text message "Hello" on telegram bot by pyhton code:

r = requests.get('https://api.telegram.org/botXXXXtokenXXXX/sendMessage?chat_id=XXXXXXXX&text=hello)

but I want to pass a variable string(str1 in the code) instead of static text message. Hence what is the change I need to do?

My code is:

import requests
response1 = requests.get('https://coindelta.com/api/v1/public/getticker/')
lines = []
for line in response1.text:
    lines.append(line)
str1 = ''.join(lines)
r = requests.get('https://api.telegram.org/botXXXXtokenXXXX/sendMessage?chat_id=XXXXXXXX&text=hello)

Upvotes: 1

Views: 2739

Answers (1)

Ivan Vinogradov
Ivan Vinogradov

Reputation: 4473

Some thoughts and improvements:

  1. It's more clear and readable to use POST to send bot messages
  2. Since you receive a JSON from https://coindelta.com, you can use json() to iterate over data in response.
  3. You can use list comprehension to format data from response.
  4. I've put a \n delimiter to str1. I think it's more readable.

Working example:

import requests

USER_ID = 12345678900000  # this is your chat_id: int
BOT_TOKEN = 'botXXXXtokenXXXX'  # your bot token: str 

# getting data from coindelta.com
r = requests.get('https://coindelta.com/api/v1/public/getticker/')
str1 = '\n'.join([str(line) for line in r.json()])  # desired formatted string

# sending message to user
url = 'https://api.telegram.org/{}/sendMessage'.format(BOT_TOKEN)
post_data = {"chat_id": USER_ID, "text": str1}
tg_req = requests.post(url, data=post_data)

Upvotes: 2

Related Questions