Base bot.

This commit is contained in:
Alex Root Junior 2017-05-19 21:20:59 +03:00
parent 3a2fafae2b
commit 23525fd364
7 changed files with 230 additions and 0 deletions

61
aiogram/types/__init__.py Normal file
View file

@ -0,0 +1,61 @@
import json
class Serializable:
def to_json(self):
"""
Returns a JSON string representation of this class.
This function must be overridden by subclasses.
:return: a JSON formatted string.
"""
raise NotImplementedError
class Deserializable:
"""
Subclasses of this class are guaranteed to be able to be created from a json-style dict or json formatted string.
All subclasses of this class must override de_json.
"""
@property
def bot(self):
if not hasattr(self, '_bot'):
raise AttributeError('object is not configured for bot.')
return getattr(self, '_bot')
@bot.setter
def bot(self, bot):
setattr(self, '_bot', bot)
def to_json(self):
return getattr(self, 'data', {})
@classmethod
def de_json(cls, data):
"""
Returns an instance of this class from the given json dict or string.
This function must be overridden by subclasses.
:return: an instance of this class created from the given json dict or string.
"""
raise NotImplementedError
@staticmethod
def check_json(data):
"""
Checks whether json_type is a dict or a string. If it is already a dict, it is returned as-is.
If it is not, it is converted to a dict by means of json.loads(json_type)
:param data:
:return:
"""
if isinstance(data, dict):
return data
elif isinstance(data, str):
return json.loads(data)
else:
raise ValueError("data should be a json dict or string.")
def __str__(self):
return json.dumps(self.to_json())

48
aiogram/types/user.py Normal file
View file

@ -0,0 +1,48 @@
from aiogram.types import Deserializable
class User(Deserializable):
__slots__ = ('data', 'id', 'first_name', 'last_name', 'username', 'language_code')
def __init__(self, data, id, first_name, last_name, username, language_code):
self.data: dict = data
self.id: int = id
self.first_name: str = first_name
self.last_name: str = last_name
self.username: str = username
self.language_code: str = language_code
@classmethod
def de_json(cls, data: str or dict) -> 'User':
"""
id Integer Unique identifier for this user or bot
first_name String Users or bots first name
last_name String Optional. Users or bots last name
username String Optional. Users or bots username
language_code String Optional. IETF language tag of the user's language
:param data:
:return:
"""
data = cls.check_json(data)
id = data.get('id')
first_name = data.get('first_name')
last_name = data.get('last_name')
username = data.get('username')
language_code = data.get('language_code')
return User(data, id, first_name, last_name, username, language_code)
@property
def full_name(self):
full_name = self.first_name
if self.last_name:
full_name += ' ' + self.last_name
return full_name
@property
def mention(self):
if self.username:
return '@' + self.username
return self.full_name