diff --git a/src/nanobot.py b/src/nanobot.py index 9edf852..194ab75 100644 --- a/src/nanobot.py +++ b/src/nanobot.py @@ -24,19 +24,26 @@ 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): - await self._ws.send(json.dumps({"content": message})) + async def chat(self, message: str, timeout: float = 60): + 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")