romeotools/classes/api.py

53 lines
1.4 KiB
Python
Raw Permalink Normal View History

2022-09-08 12:32:31 +00:00
from .http import HTTPRequest, urlopen
from .message import Message
2022-09-08 12:32:31 +00:00
from urllib.error import HTTPError
from const import API_URL, X_API_KEY
import json
class RomeoAPI:
2022-09-08 12:32:31 +00:00
def __init__(self, login=True, username=None, password=None):
self.session = None
if login:
self.login(username, password)
2022-09-08 12:32:31 +00:00
def login(self, username, password):
2022-09-08 12:32:31 +00:00
payload = {"username": username,
"password": password,
"keep_login": True}
2022-09-08 12:32:31 +00:00
try:
response = urlopen(HTTPRequest(API_URL + "session?lang=en", headers=self.build_headers()),
json.dumps(payload).encode("utf-8"))
2022-09-08 12:32:31 +00:00
except HTTPError as e:
print(e.read())
raise
data = json.load(response)
self.session = data
def build_headers(self, additional={}):
headers = {
2022-09-08 12:32:31 +00:00
"X-Api-Key": X_API_KEY,
"X-Session-Id": self.session["session_id"] if self.session else ""
}
for key, value in additional:
headers[key] = value
return headers
def messages(self, count=16384):
headers = self.build_headers()
response = urlopen(
HTTPRequest(API_URL + "messages?lang=en&length=%i" % count, headers=headers))
data = json.load(response)
for message in data["items"]:
2022-09-08 12:32:31 +00:00
if messageobj := Message.from_dict(message):
yield messageobj