59 lines
2.1 KiB
Python
Executable File
59 lines
2.1 KiB
Python
Executable File
"""Минимальный клиент Matrix (только то, что нужно рабочему секретарю).
|
|
|
|
Автономный: не зависит от домашних ботов, чтобы рабочий стек был изолирован.
|
|
"""
|
|
import json
|
|
import time
|
|
import urllib.parse
|
|
|
|
import requests
|
|
|
|
|
|
class Matrix:
|
|
def __init__(self, base, token, user_id):
|
|
self.base = base.rstrip("/")
|
|
self.token = token
|
|
self.user_id = user_id
|
|
self.s = requests.Session()
|
|
self._txn = 0
|
|
|
|
def _req(self, method, path, body=None, timeout=60):
|
|
url = self.base + path
|
|
headers = {"Authorization": "Bearer " + self.token}
|
|
if body is not None:
|
|
headers["Content-Type"] = "application/json"
|
|
r = self.s.request(method, url, headers=headers,
|
|
data=json.dumps(body) if body is not None else None,
|
|
timeout=timeout)
|
|
try:
|
|
return r.json()
|
|
except Exception:
|
|
return {"raw": r.text[:300]}
|
|
|
|
def whoami(self):
|
|
return self._req("GET", "/_matrix/client/v3/account/whoami", timeout=15)
|
|
|
|
def join(self, room_id):
|
|
return self._req("POST", "/_matrix/client/v3/join/" + urllib.parse.quote(room_id, safe=""), {})
|
|
|
|
def send(self, room_id, text):
|
|
self._txn += 1
|
|
txn = "w%d_%d" % (int(time.time() * 1000), self._txn)
|
|
body = {"msgtype": "m.text", "body": text}
|
|
path = "/_matrix/client/v3/rooms/%s/send/m.room.message/%s" % (
|
|
urllib.parse.quote(room_id, safe=""), txn)
|
|
return self._req("PUT", path, body, timeout=30)
|
|
|
|
def send_chunked(self, room_id, text, limit=12000):
|
|
if len(text) <= limit:
|
|
return self.send(room_id, text)
|
|
for i in range(0, len(text), limit):
|
|
self.send(room_id, text[i:i + limit])
|
|
time.sleep(0.3)
|
|
|
|
def sync(self, since=None, timeout_ms=30000):
|
|
q = "?timeout=%d" % timeout_ms
|
|
if since:
|
|
q += "&since=" + urllib.parse.quote(since, safe="")
|
|
return self._req("GET", "/_matrix/client/v3/sync" + q, timeout=timeout_ms // 1000 + 25)
|