Compare commits

...

2 Commits
dev ... main

Author SHA1 Message Date
Adib Pratama 7175cc5ef3
Add locking for multiple reciever 2 months ago
Adib Pratama 6a4dabf28f
Change timeout to 60 and add reconnect when timeout 2 months ago
  1. 15
      src/nanobot.py

@ -14,6 +14,7 @@ class Nanobot:
def __init__(self):
self._ws = None
self._chat_id = None
self._lock = asyncio.Lock()
async def __aenter__(self):
await self.connect()
@ -24,19 +25,27 @@ class Nanobot:
async def connect(self):
uri = f"{NANOBOT_WS_ENDPOINT}/?token={NANOBOT_WS_TOKEN}"
self._ws = await websockets.connect(uri)
self._ws = await websockets.connect(uri, ping_interval=None)
ready = json.loads(await self._ws.recv())
self._chat_id = ready["chat_id"]
main_logger.info("connected chat_id=%s", self._chat_id)
async def chat(self, message: str, timeout: float = 10):
async def chat(self, message: str, timeout: float = 60):
async with self._lock:
try:
await self._ws.send(json.dumps({"content": message}))
except websockets.ConnectionClosed:
main_logger.info("ws: reconnecting...")
await self.connect()
await self._ws.send(json.dumps({"content": message}))
parts = []
while True:
try:
raw = await asyncio.wait_for(self._ws.recv(), timeout=timeout)
except asyncio.TimeoutError:
main_logger.info("ws: timeout (no data for %.1fs), generator done", timeout)
main_logger.info("ws: timeout (no data for %.1fs), reconnecting", timeout)
await self.close()
await self.connect()
return
frame = json.loads(raw)
event = frame.get("event")

Loading…
Cancel
Save