Skip to content

Commit

Permalink
Try except on opuslib/nacl imports
Browse files Browse the repository at this point in the history
  • Loading branch information
Shell1010 committed Feb 10, 2024
1 parent 2d0aa90 commit ab499d3
Show file tree
Hide file tree
Showing 7 changed files with 67 additions and 42 deletions.
33 changes: 24 additions & 9 deletions selfcord/api/gateway.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down Expand Up @@ -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)
Expand Down
18 changes: 5 additions & 13 deletions selfcord/api/http.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
from ..utils import logging

lib, _, _ = __name__.partition(".")
log = logging.getLogger(__name__)



class HttpClient:
Expand Down Expand Up @@ -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

Expand All @@ -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:
Expand Down
10 changes: 7 additions & 3 deletions selfcord/api/voice.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
26 changes: 16 additions & 10 deletions selfcord/bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,6 @@
winloop.install()


log = logging.getLogger(__name__)


class Bot:
Expand Down Expand Up @@ -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))
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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()
Expand All @@ -432,15 +431,15 @@ 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:
path = f"{dir}/{os.path.basename(urlparse(url).path)}"

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)
Expand All @@ -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


Expand All @@ -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")
Expand Down Expand Up @@ -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]:
Expand Down
9 changes: 8 additions & 1 deletion selfcord/models/channels.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"]
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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:
Expand Down
7 changes: 4 additions & 3 deletions selfcord/models/users.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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):
Expand Down
6 changes: 3 additions & 3 deletions selfcord/utils/command.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
from ..models import *


log = logging.getLogger(__name__)



class Extension:
Expand Down Expand Up @@ -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

Expand Down

0 comments on commit ab499d3

Please sign in to comment.