Reputation: 103
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
Reputation: 4473
Some thoughts and improvements:
POST
to send bot messages json()
to iterate over data in response. \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