From ea154163564ddd7bed4bf48a06b1e31668f35c22 Mon Sep 17 00:00:00 2001 From: Stefano Pigozzi Date: Sat, 25 Feb 2017 21:49:06 +0100 Subject: [PATCH] First commit --- .gitignore | 94 +++++++++++++++++++++++++++++++++++++++++++++++++++++ telegram.py | 57 ++++++++++++++++++++++++++++++++ 2 files changed, 151 insertions(+) create mode 100644 .gitignore create mode 100644 telegram.py diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..8d31baee --- /dev/null +++ b/.gitignore @@ -0,0 +1,94 @@ +# Created by .ignore support plugin (hsz.mobi) +### Python template +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +env/ +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +*.egg-info/ +.installed.cfg +*.egg + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*,cover +.hypothesis/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +target/ + +# IPython Notebook +.ipynb_checkpoints + +# pyenv +.python-version + +# celery beat schedule file +celerybeat-schedule + +# dotenv +.env + +# virtualenv +venv/ +ENV/ + +# Spyder project settings +.spyderproject + +# Rope project settings +.ropeproject + +.gitignore +.idea/ diff --git a/telegram.py b/telegram.py new file mode 100644 index 00000000..34b242d5 --- /dev/null +++ b/telegram.py @@ -0,0 +1,57 @@ +import asyncio +loop = asyncio.get_event_loop() +import aiohttp +import async_timeout + +class TelegramError(Exception): + pass + + +class Bot: + def __init__(self, token): + self.token = token + self.user_data = None + self.updates = list() + self.users = list() + self.chats = list() + # Update user_data + loop.run_until_complete(self.update_bot_data()) + + async def update_bot_data(self): + """Update self.user_data with the latest information from /getMe.""" + data = await self.api_request("getMe") + self.user_data = User(data) + + async def api_request(self, endpoint, **params): + """Send a request to the Telegram API at the specified endpoint.""" + # Request timeout is 10 seconds. + with async_timeout.timeout(10): + # Create a new session for each request. + async with aiohttp.ClientSession() as session: + # Send the request to the Telegram API + token = self.token + async with session.request("GET", f"https://api.telegram.org/bot{token}/{endpoint}", params=params) as response: + # Check for errors in the request + if response.status != 200: + raise TelegramError(f"Request returned {response.status} {response.reason}") + # Parse the json data as soon it's ready + data = await response.json() + # Check for errors in the response + if not data["ok"]: + error = data["description"] + raise TelegramError(f"Response returned an error: {error}") + # Return a dictionary containing the data + return data["result"] + +class User: + def __init__(self, user_dict): + self.user_id = user_dict["id"] + self.first_name = user_dict["first_name"] + if "last_name" in user_dict: + self.last_name = user_dict["last_name"] + else: + self.last_name = None + if "username" in user_dict: + self.username = user_dict["username"] + else: + self.username = None