Created
February 16, 2016 05:39
-
-
Save sigsergv/f9b986c00b3607c6ac2a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python3 | |
import http.client | |
import urllib.parse | |
import json | |
import time | |
API_TOKEN = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' | |
BASE_URL = '/bot{token}/'.format(token=API_TOKEN) | |
HEADERS = {'Content-Type': 'application/x-www-form-urlencoded'} | |
UPDATE_ID = int(open('last_id.txt').read()) | |
conn = http.client.HTTPSConnection('api.telegram.org') | |
def method_call(method, params=None): | |
url = BASE_URL + method | |
if type(params) is not dict: | |
params = {} | |
conn.request('POST', url, urllib.parse.urlencode(params), HEADERS) | |
response = conn.getresponse() | |
# response.status, response.reason | |
data = response.read() | |
return json.loads(data.decode('utf8')) | |
def update_last_id(v): | |
global UPDATE_ID | |
if v > UPDATE_ID: | |
UPDATE_ID = v | |
open('last_id.txt', 'w').write(str(v)) | |
#method_call('getMe') | |
# polling | |
while True: | |
response = method_call('getUpdates', {'offset': UPDATE_ID+1}) | |
if response['ok'] == True and len(response['result']) > 0: | |
results = response['result'] | |
#print('processing', result) | |
for r in results: | |
update_last_id(r['update_id']) | |
m = r['message'] | |
sender = m['from'] | |
print(sender, m['text']) | |
if m['text'] == '/start': | |
method_call('sendMessage', { | |
'chat_id': sender['id'], | |
'text': 'Hello, ' + json.dumps(sender) + '\nThere is no commands here yet, just numbers.' | |
}) | |
else: | |
method_call('sendMessage', { | |
'chat_id': sender['id'], | |
'text': '→ {0}'.format(len(m['text'])) | |
}) | |
time.sleep(2) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment