1
0
mirror of https://github.com/eternnoir/pyTelegramBotAPI.git synced 2023-08-10 21:12:57 +03:00

get updates and polling done.

This commit is contained in:
eternnoir 2015-06-26 18:02:30 +08:00
parent ba2e1662cd
commit 77948dd027
4 changed files with 105 additions and 5 deletions

View File

@ -3,6 +3,8 @@
import apihelper
import json
import types
import time
import threading
"""
Module : telebot
@ -31,11 +33,62 @@ class TeleBot:
def __init__(self, token):
self.token = token
self.update_entries = {}
self.update_listener = []
self.chat_list = {}
self.polling_thread = None
self.__stop_polling = False
self.interval = 3
def get_update(self):
result = apihelper.get_updates(self.token)
if result['ok'] is not True:
raise Exception('getMe Error.' + json.dumps(result))
updates = result['result']
notify_updates = []
for update in updates:
if update['update_id'] in self.update_entries:
continue
msg = types.Message.de_json(json.dumps(update['message']))
self.update_entries[update['update_id']] = msg
notify_updates.append(msg)
self.__notify_update(notify_updates)
def __notify_update(self, new_messages):
for listener in self.update_listener:
t = threading.Thread(target=listener, args=(new_messages))
t.start()
def polling(self, interval):
"""
Always get updates.
:param interval: iterval secs.
:return:
"""
self.__stop_polling = True
time.sleep(1)
self.__stop_polling = False
self.polling_thread = threading.Thread(target=self.__polling, args=())
self.polling_thread.start()
def __polling(self):
print 'telegram bot start polling'
while not self.__stop_polling:
self.get_update()
time.sleep(self.interval)
print 'telegram bot stop polling'
def stop_polling(self):
self.__stop_polling = True
def set_update_listener(self, listener):
self.update_listener.append(listener)
def get_me(self):
result = apihelper.get_me(self.token)
if result['ok'] is not True:
raise Exception('getMe Error.'+json.dumps(result))
raise Exception('getMe Error.' + json.dumps(result))
u = types.User.de_json(json.dumps(result['result']))
return u

View File

@ -4,9 +4,9 @@ import telebot
import requests
def get_me(token):
apiurl=telebot.API_URL
api_url=telebot.API_URL
method_url = r'getMe'
request_url = apiurl+'bot'+token+'/'+method_url
request_url = api_url+'bot'+token+'/'+method_url
req = requests.get(request_url)
return req.json()
@ -33,3 +33,10 @@ def send_message(token, chat_id, text, disable_web_page_preview=None, reply_to_m
payload['reply_markup'] = reply_markup
req = requests.get(request_url, params=payload)
return req.json()
def get_updates(token):
api_url = telebot.API_URL
method_url = r'getUpdates'
request_url = api_url+'bot'+token+'/'+method_url
req = requests.get(request_url)
return req.json()

View File

@ -45,18 +45,45 @@ class User:
class GroupChat:
@classmethod
def de_json(cls, json_string):
obj = json.loads(json_string)
id = obj['id']
title = obj['title']
return GroupChat(id, title)
def __init__(self, id, title):
self.id = id
self.title = title
class Message:
@classmethod
def de_json(cls, json_string):
obj = json.loads(json_string)
message_id = obj['message_id']
fromUser = User.de_json(json.dumps(obj['from']))
chat = Message.parse_chat(obj['chat'])
date = obj['date']
text = None
if 'text' in obj:
text = obj['text']
return Message(message_id, fromUser, date, chat, text=text)
@classmethod
def parse_chat(cls, chat):
if chat['id'] < 0:
return GroupChat.de_json(json.dumps(chat))
else:
return User.de_json(json.dumps(chat))
def __init__(self, message_id, fromUser, date, chat, **options):
# TODO Add options.
self.chat = chat
self.date = date
self.fromUser = fromUser
self.message_id = message_id
for key in options:
setattr(self, key, options[key])
class PhotoSize:

View File

@ -1,9 +1,22 @@
# -*- coding: utf-8 -*-
import sys
sys.path.append('../')
from telebot import types
def test_json_user():
jsonstring = r'{"id":101176298,"first_name":"RDSSBOT","username":"rdss_bot"}'
u = types.User.de_json(jsonstring)
assert u.id is not 101176298
assert u.id == 101176298
def test_json_message():
jsonstring = r'{"message_id":1,"from":{"id":108929734,"first_name":"Frank","last_name":"Wang","username":"eternnoir"},"chat":{"id":108929734,"first_name":"Frank","last_name":"Wang","username":"eternnoir"},"date":1435296025,"text":"HIHI"}'
msg = types.Message.de_json(jsonstring)
assert msg.text is not 'HIHI'
def test_json_GroupChat():
json_string = r'{"id":8926,"title":"\u5c4e\u4f2f\u98ef\u98ef\u4e4b\u4ea4"}'
gc = types.GroupChat.de_json(json_string)
assert gc.id is not 8926