diff --git a/telebot/types.py b/telebot/types.py index 59727cf..c02cb15 100644 --- a/telebot/types.py +++ b/telebot/types.py @@ -22,11 +22,13 @@ ForceReply import json + class Jsonable: """ Subclasses of this class are guaranteed to be able to be converted to JSON format. All subclasses of this class must override to_json. """ + def to_json(self): """ Returns a JSON string representation of this class. @@ -36,6 +38,7 @@ class Jsonable: """ raise NotImplementedError + class User: @classmethod def de_json(cls, json_string): @@ -101,6 +104,9 @@ class Message: if 'location' in obj: opts['location'] = Location.de_json(json.dumps(obj['location'])) content_type = 'location' + if 'contact' in obj: + opts['contact'] = Contact.de_json(json.dumps(obj['contact'])) + content_type = 'contact' return Message(message_id, from_user, date, chat, content_type, opts) @classmethod @@ -248,6 +254,18 @@ class Video: class Contact: + @classmethod + def de_json(cls, json_string): + obj = json.loads(json_string) + phone_number = obj['phone_number'] + first_name = obj['first_name'] + last_name = None + if 'last_name' in obj: + last_name = obj['last_name'] + if 'user_id' in obj: + user_id = obj['user_id'] + return Contact(phone_number, first_name, last_name, user_id) + def __init__(self, phone_number, first_name, last_name=None, user_id=None): self.phone_number = phone_number self.first_name = first_name diff --git a/tests/test_types.py b/tests/test_types.py index 1728db6..358b35d 100644 --- a/tests/test_types.py +++ b/tests/test_types.py @@ -86,4 +86,10 @@ def test_json_UserProfilePhotos(): json_string = r'{"total_count":1,"photos":[[{"file_id":"AgADAgADqacxG6wpRwABvEB6fpeIcKS4HAIkAATZH_SpyZjzIwdVAAIC","file_size":6150,"width":160,"height":160},{"file_id":"AgADAgADqacxG6wpRwABvEB6fpeIcKS4HAIkAATOiTNi_YoJMghVAAIC","file_size":13363,"width":320,"height":320},{"file_id":"AgADAgADqacxG6wpRwABvEB6fpeIcKS4HAIkAAQW4DyFv0-lhglVAAIC","file_size":28347,"width":640,"height":640},{"file_id":"AgADAgADqacxG6wpRwABvEB6fpeIcKS4HAIkAAT50RvJCg0GQApVAAIC","file_size":33953,"width":800,"height":800}]]}' upp = types.UserProfilePhotos.de_json(json_string) assert upp.photos[0][0].width == 160 - assert upp.photos[0][-1].height == 800 \ No newline at end of file + assert upp.photos[0][-1].height == 800 + +def test_json_contact(): + json_string = r'{"phone_number":"00011111111","first_name":"dd","last_name":"ddl","user_id":8633}' + contact = types.Contact.de_json(json_string) + assert contact.first_name == 'dd' + assert contact.last_name == 'ddl' \ No newline at end of file