Files
Vocard/ipc/client.py
Choco 8a663a939b Vocard v2.6.9 Update: A lot new features, bug fixes, and code clean-up (#34)
* Update docker-compose.yml

No dotenv file needed. All environment values are now defined in docker-compose

* Update RU.json

* Updated docker-compose

* Update README.md

* Resolved issue where playback didn’t start after user joined channel 247

* Added logging system

* Updated logging system

* Update player.py

* Added 24/7 required intent

* Update main.py

* Added logs folder

* Updated logging system

* Updated logging system

* Added some typehint

* Removed error_log

* Renamed a valuable

* Removed unnecessary value

* Fixed some bugs

* Added bot status settings

* Added autocomplete in playtop

* Added a new emoji in Loop button

* Optimized code

* Update requirements.txt

* Fixed autoplay with empty queue

This commit addresses the issue where autoplay was being activated even when the history queue had no tracks. The problem has been resolved to ensure smooth user experience

* Enhanced Loop Control Button Functionality

* Updated the loop button in controller

* Fixed activity update

Resolved the issue where activity updates were not reflected when the value remained the same.

* Added sync function in debug view

* Optimized code

* Added version in the debug

* Added nodes panel in debug view

* Merged .env into settings.json

* Rewritten ipc_client

* Separated the dashboard from the project

* Removed some necessary requirements

* Remove support for replit

* Update README.md

* Update settings Example.json

* Added get_recommendations into node class

* Saved log file when updating

* Rewritten some method in ipc_client

* Written swap and remove method in queue

* Added remove_track and swap_track method in player

* Update methods.py

* Added secure protocol in ipc client

* Fixed some bugs

* Added some method in ipc cilent

* Update methods.py

* Update methods.py

* Added playlist method

* Optimized Spotify client code

* Added Category class in Spotify client

* Added settings method in ipc client

* Fixed some bugs

* Send track requester_id in initPlayer

* Fixed some bugs

* Fixed some bugs

* Optimized some code

* Dump discord.py

* Added start and end position for each track

* Update methods.py

* Fixed a bug

* Fixed some bugs

* Fixed IPC client creation issue

* Rewrote filters

* Fixed some bugs

* Added filter event in ipc method

* Added filter selector in music controller

* Added inbox method

* Optimized some code

* Updated zh-TW local_lang

* Fixed some bugs

* Delete supervisord.conf

* Fixed some bugs

* Updated wording in IPC client

* Update pool.py

* Fixed no song suggestions when spotify_client is None

* Fixed connection problem from the dashboard

* Fixed some bugs

* Added voice status (#33)

* Updated the placeholder name for clarity

* Added voice status

* Dump bot version

* Added global template for voice status

* Added new placeholder

* Updated settings view

* Updated version tag

* Improved codes

* Fixed some bugs

* Supported clear queue endpoint in ipc

* Update methods.py

* Update README.md

* Remove PLACEHOLDERS.MD

---------

Co-authored-by: Azarath7 <158289825+Azarath7@users.noreply.github.com>
2024-09-11 11:51:51 +08:00

110 lines
3.5 KiB
Python

import aiohttp
import asyncio
import logging
import function as func
from discord.ext import commands
from typing import Optional
from .methods import process_methods
class IPCClient:
def __init__(
self,
bot: commands.Bot,
host: str,
port: int,
password: str,
heartbeat: int = 30,
secure: bool = False,
*arg,
**kwargs
) -> None:
self._bot: commands.Bot = bot
self._host: str = host
self._port: int = port
self._password: str = password
self._heartbeat: int = heartbeat
self._is_secure: bool = secure
self._is_connected: bool = False
self._is_connecting: bool = False
self._logger: logging.Logger = logging.getLogger("ipc_client")
self._websocket_url: str = f"{'wss' if self._is_secure else 'ws'}://{self._host}:{self._port}/ws_bot"
self._session: Optional[aiohttp.ClientSession] = None
self._websocket: Optional[aiohttp.ClientWebSocketResponse] = None
self._task: Optional[asyncio.Task] = None
self._heanders = {
"Authorization": self._password,
"User-Id": str(bot.user.id),
"Client-Version": func.settings.version
}
async def _listen(self) -> None:
while True:
try:
msg = await self._websocket.receive()
self._logger.debug(f"Received Message: {msg}")
except:
break
if msg.type in [aiohttp.WSMsgType.CLOSE, aiohttp.WSMsgType.CLOSED]:
self._is_connected = False
self._logger.info("Connection closed. Trying to reconnect in 10s.")
await asyncio.sleep(10)
if not self._is_connected:
try:
await self.connect()
except Exception as e:
self._logger.error("Reconnection failed.")
else:
self._bot.loop.create_task(process_methods(self, self._bot, msg.json()))
async def send(self, data: dict):
if self.is_connected:
self._logger.debug(f"Send Message: {data}")
await self._websocket.send_json(data)
async def connect(self):
try:
if not self._session:
self._session = aiohttp.ClientSession()
if self._is_connecting or self._is_connected:
return
self._is_connecting = True
self._websocket = await self._session.ws_connect(
self._websocket_url, headers=self._heanders, heartbeat=self._heartbeat
)
self._task = self._bot.loop.create_task(self._listen())
self._is_connected = True
self._logger.info("Connected to dashboard!")
except aiohttp.ClientConnectorError:
raise Exception("Connection failed.")
except aiohttp.WSServerHandshakeError as e:
self._logger.error("Access forbidden: Missing bot ID, version mismatch, or invalid password.")
except Exception as e:
self._logger.error("Error occurred while connecting to dashboard.", exc_info=e)
finally:
self._is_connecting = False
return self
async def disconnect(self) -> None:
self._is_connected = False
self._task.cancel()
self._logger.info("Disconnected to dashboard!")
@property
def is_connected(self) -> bool:
return self._is_connected