52 lines
1.4 KiB
Python
52 lines
1.4 KiB
Python
from .http import HTTPRequest, urlopen
|
|
from .message import Message
|
|
|
|
from urllib.error import HTTPError
|
|
|
|
from const import API_URL, X_API_KEY
|
|
|
|
import json
|
|
|
|
class RomeoAPI:
|
|
def __init__(self, login=True, username=None, password=None):
|
|
self.session = None
|
|
|
|
if login:
|
|
self.login(username, password)
|
|
|
|
|
|
def login(self, username, password):
|
|
payload = {"username": username,
|
|
"password": password,
|
|
"keep_login": True}
|
|
|
|
try:
|
|
response = urlopen(HTTPRequest(API_URL + "session?lang=en", headers=self.build_headers()),
|
|
json.dumps(payload).encode("utf-8"))
|
|
except HTTPError as e:
|
|
print(e.read())
|
|
raise
|
|
|
|
data = json.load(response)
|
|
self.session = data
|
|
|
|
def build_headers(self, additional={}):
|
|
headers = {
|
|
"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"]:
|
|
if messageobj := Message.from_dict(message):
|
|
yield messageobj
|