-
Notifications
You must be signed in to change notification settings - Fork 0
Home
cua-cua edited this page Jul 21, 2015
·
3 revisions
Importing module to send HTTP/1.1 requests and access the response data. http://docs.python-requests.org/en/latest/user/quickstart
import requests
Writting the url of our bot.
- Opening and reading .token file. The rstrip method is included to remove right whitespace characters(line break for UNIX files, carriage return and line break for Windows files) to keep only token value.
- The format method is used to do complex variable substitutions and value formatting, it substitutes replacement field ({}) with the string token.
with open('.token', 'r') as f:
token = f.read().rstrip()
url = 'https://api.telegram.org/bot{}/'.format(token)
Getting data from the server
- Making a get request to bot url using requests module.The url parameters are passed as a dictionary with params keyword argument.The 'getUpdates' string is part together with params of Telegram Bot API. https://core.telegram.org/bots/api. Update_id param is updated with each new message.
params = {'offset': update_id + 1, 'timeout': LONG_POLLING}
response = requests.get(url + 'getUpdates', params)
Managing data from the server
- Requests module includes a JSON decoder that transforms data in JSON format from server to python dictionary.
data = response.json()
{'result': [{'message': {'message_id': 16,
'from': {'first_name': 'Juan', 'last_name': 'Distinto', 'id': 48518059},
'chat': {'first_name': 'Juan', 'last_name': 'Distinto', 'id': 48518059},
'text': 'hello world',
'date': 1437424266},
'update_id': 186452562}],
'ok': True}
- Updating last response id and checking if last response is a message.
update_id = update['update_id']
if 'message' not in update:
continue
Bot functionality
- Bot repeats received message. Simple action, empty section. Last message is direct included in the send request argument.
Sending data to the server.
- Making a get request to bot url using requests module. To send data the telegram API needs'sendMessage' string together with params arguments. Pay attention on how it is accessing dictionaries data with consecutive branches. The chat_id is unique by chat, it must be included to sendMessage request to identify the chat where bot is acting.
params = {'chat_id': update['message']['chat']['id'],
'text': update['message']['text']}
requests.get(url + 'sendMessage', params)