From ab499d3e9fb450a3284768723eddbbbc87542b8b Mon Sep 17 00:00:00 2001 From: Shell1010 Date: Sat, 10 Feb 2024 21:30:07 +0000 Subject: [PATCH] Try except on opuslib/nacl imports --- selfcord/api/gateway.py | 33 ++++++++++++++++++++++++--------- selfcord/api/http.py | 18 +++++------------- selfcord/api/voice.py | 10 +++++++--- selfcord/bot.py | 26 ++++++++++++++++---------- selfcord/models/channels.py | 9 ++++++++- selfcord/models/users.py | 7 ++++--- selfcord/utils/command.py | 6 +++--- 7 files changed, 67 insertions(+), 42 deletions(-) diff --git a/selfcord/api/gateway.py b/selfcord/api/gateway.py index 7ce32c8..f2e29b2 100644 --- a/selfcord/api/gateway.py +++ b/selfcord/api/gateway.py @@ -52,6 +52,7 @@ def __init__(self, bot: Bot, decompress: bool = True) -> None: "wss://gateway.discord.gg/?encoding=json&v=9" ) self.voice: Optional[Voice] = None + self.subscriptions_data = {} async def linux_run(self, cmd): proc = await asyncio.create_subprocess_shell( @@ -320,17 +321,31 @@ def correct_channels(self, guild: Guild): return list(set(channels)) - async def subscriptions(self, guild: Guild): + def get_ranges(self, amount: int): + ranges = [] + for i in range(0, amount, 100): + ranges.append( + [i, self.roundup(i + (amount - i)) - 1] + ) if i + 99 > amount else ranges.append([i, i + 99]) + return ranges + + async def subscriptions(self, guild: Guild, channels: Optional[list[Messageable]] = None): # In Progres... # Basically discord no longer uses op 14, uses this now - payload = { - "op": 37, - "d": { - "subscriptions": { - "guild_id":{"channels": {"channel_id": []}} - } - } - } + if guild.member_count is not None: + ranges = self.get_ranges(guild.member_count) + if channels is None: + channels = self.correct_channels(guild) + + for channel in channels: + self.subscriptions_data[guild.id]["channels"].update({channel.id: [0, 99]}) + print("subscriptions", self.subscriptions_data) + payload = { + "op": 37, + "d": { + "subscriptions": self.subscriptions_data + } + } async def chunk_members(self, guild: Guild): channels = self.correct_channels(guild) diff --git a/selfcord/api/http.py b/selfcord/api/http.py index 409447c..010e658 100644 --- a/selfcord/api/http.py +++ b/selfcord/api/http.py @@ -15,7 +15,7 @@ from ..utils import logging lib, _, _ = __name__.partition(".") -log = logging.getLogger(__name__) + class HttpClient: @@ -133,32 +133,24 @@ async def request(self, method: str, endpoint: str, *args, **kwargs) -> Optional try: json = await resp.json() await asyncio.sleep(json["retry_after"]) - log.error(f"429 Ratelimited: {json}") continue except Exception as e: error = "".join(format_exception(e, e, e.__traceback__)) text = await resp.text() - log.error(f"Error upon parsing json : {text}") - log.error(f"Error upon parsing json : \n{error}") - log.info( - f"Attempted to send request to URL: {url} PAYLOAD: {kwargs}" - ) + await aprint(error) return None elif resp.status == 401: json = await resp.json() - log.error(f"{json} -- {resp.status}") + await aprint(json) return None elif resp.status == 403: json = await resp.json() - log.error(f"403 Unauthorized: {json}") - log.info( - f"Attempted to send request to URL: {url} PAYLOAD: {args} {kwargs}" - ) + await aprint(json) return None @@ -182,7 +174,7 @@ async def request(self, method: str, endpoint: str, *args, **kwargs) -> Optional return None except Exception as e: error = "".join(format_exception(e, e, e.__traceback__)) - log.error(f"Unable to log response: \n{error}") + await aprint(error) return None try: diff --git a/selfcord/api/voice.py b/selfcord/api/voice.py index 0bac467..82ba6f2 100644 --- a/selfcord/api/voice.py +++ b/selfcord/api/voice.py @@ -6,13 +6,17 @@ import asyncio import socket import io -import nacl.secret -import nacl.utils import struct import ctypes -import opuslib import array +try: + import opuslib + import nacl.secret + import nacl.utils +except ImportError: + pass + SAMPLING_RATE = 48000 diff --git a/selfcord/bot.py b/selfcord/bot.py index 3c0540d..d3b46e7 100644 --- a/selfcord/bot.py +++ b/selfcord/bot.py @@ -51,7 +51,6 @@ winloop.install() -log = logging.getLogger(__name__) class Bot: @@ -263,7 +262,7 @@ def on(self, event: str, mass_token: bool = False): def decorator(coro): if not inspect.iscoroutinefunction(coro): - log.error("Not a coroutine") + raise Exception("Not a coroutine") else: self._events[event].append(Event(name=event, coro=coro, ext=None, mass_token=mass_token)) @@ -318,7 +317,7 @@ def cmd(self, description="", aliases=[], mass_token: bool = False): def decorator(coro): name = coro.__name__ if not inspect.iscoroutinefunction(coro): - log.error("Not a coroutine") + raise Exception("Not a coroutine") return else: @@ -389,7 +388,7 @@ def add_cmd(self, coro, description="", aliases=[]): aliases = [aliases] name = coro.__name__ if not inspect.iscoroutinefunction(coro): - log.error("Not a coroutine") + raise Exception("Not a coroutine") else: cmd = Command( @@ -421,7 +420,7 @@ async def load_extension(self, name: Optional[str] = None, url: Optional[str] = if path.endswith(".py"): if os.path.exists(path): - log.error(f"Path already exists. {path}") + return lines = text.splitlines() @@ -432,7 +431,7 @@ async def load_extension(self, name: Optional[str] = None, url: Optional[str] = name = f"{os.path.basename(urlparse(url).path)[:-3]}" else: - log.error(f"{path} is not a python file") + return else: @@ -440,7 +439,7 @@ async def load_extension(self, name: Optional[str] = None, url: Optional[str] = if path.endswith(".py"): if os.path.exists(path): - log.error(f"Path already exists. {path}") + return if not os.path.exists(dir): os.makedirs(dir) @@ -452,7 +451,7 @@ async def load_extension(self, name: Optional[str] = None, url: Optional[str] = name = f"{dir}.{os.path.basename(urlparse(url).path)[:-3]}" else: - log.error(f"{path} is not a python file") + return @@ -469,8 +468,7 @@ async def load_extension(self, name: Optional[str] = None, url: Optional[str] = try: spec.loader.exec_module(lib) except Exception as e: - error = "".join(format_exception(e, e, e.__traceback__)) - log.error(f"Spec could not be loaded\n{error}") + return try: ext = getattr(lib, "Ext") @@ -528,6 +526,14 @@ def get_channel(self, channel_id: str) -> Optional[Messageable|Callable]: if channel_id is None: return return self.cached_channels.get(channel_id) + + def get_dm(self, user_id: str) -> Optional[DMChannel]: + for channel in self.cached_channels.values(): + if isinstance(channel, DMChannel): + + if channel.recipient.id == user_id: + return channel + # Cry it's O(N) - max 100 guilds so it's cool def fetch_guild(self, guild_id: str) -> Optional[Guild]: diff --git a/selfcord/models/channels.py b/selfcord/models/channels.py index 8cb75c5..2ce0e5b 100644 --- a/selfcord/models/channels.py +++ b/selfcord/models/channels.py @@ -183,7 +183,7 @@ def __str__(self): if hasattr(self, "name"): return self.name else: - return self.recipient + return self.recipient.username def update(self, payload): self.id: str = payload["id"] @@ -430,12 +430,17 @@ async def purge(self, amount: int): class DMChannel(Messageable, Callable): def __init__(self, payload: dict, bot: Bot): + super().__init__(payload, bot) + super().update(payload) + self.bot = bot self.http = bot.http + self.update(payload) + @property def recipient(self): return self.bot.fetch_user(self.recipient_id) @@ -698,7 +703,9 @@ def update(self, payload): class Convert(Messageable): def __new__(cls, payload: dict, bot: Bot) -> Messageable: + tpe = payload["type"] + if tpe == 0: return TextChannel(payload, bot) if tpe == 1: diff --git a/selfcord/models/users.py b/selfcord/models/users.py index 738ae98..6e01da0 100644 --- a/selfcord/models/users.py +++ b/selfcord/models/users.py @@ -6,7 +6,7 @@ if TYPE_CHECKING: from ..bot import Bot from .guild import Guild, Role - from .channels import DMChannel, Messageable + from .channels import Convert, Messageable # Realise this might be fucked because my subclassism didn't work with channels @@ -165,10 +165,11 @@ async def reset_relationship(self): async def create_dm(self) -> Optional[DMChannel]: json = await self.http.request( - "post", "/channels", json={"recipients": [self.id if self.id is not None else ""]} + "post", "/users/@me/channels", json={"recipients": [self.id if self.id is not None else ""]} ) + print(json) - return DMChannel(json, self.bot) or None + return Convert(json, self.bot) class Client(User): diff --git a/selfcord/utils/command.py b/selfcord/utils/command.py index ffa1d14..c071282 100644 --- a/selfcord/utils/command.py +++ b/selfcord/utils/command.py @@ -15,7 +15,7 @@ from ..models import * -log = logging.getLogger(__name__) + class Extension: @@ -75,9 +75,9 @@ def add(self, ext: Extension): ValueError: A name or alias is already registered """ if not isinstance(ext, Extension): - log.error("ext is not an Extension or subclass of Extension") + raise ValueError("Extension must be subclass of Extension") if self._is_already_registered(ext): - log.error("Name or Alias is already registered") + raise ValueError("A name or alias is already registered") # Add extension to the collection self.extensions[ext.name] = ext