Skip to content
This repository was archived by the owner on Aug 9, 2023. It is now read-only.

Add some models classes #6

Open
wants to merge 26 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 14 commits
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
35a51bd
chore: Update gitignore
Gugu7264 Dec 27, 2021
13f91cd
feat: Added User and ClientUser models
Gugu7264 Dec 28, 2021
adffec1
chore: Rename folders and added snowflake type
Gugu7264 Dec 28, 2021
60ee0df
refactor: moved BaseUser in protocols
Gugu7264 Dec 28, 2021
9d9c2cf
Merge branch 'nextcord:master' into master
Gugu7264 Dec 28, 2021
36a0f4b
fix: fixed relative imports
Gugu7264 Dec 28, 2021
d6baf9c
feat: adding Messageable and Embed models
Gugu7264 Dec 28, 2021
d5f7404
refactor: renamed embed functions
Gugu7264 Dec 28, 2021
1c0f1eb
feat: added InvalidArgument exception
Gugu7264 Dec 28, 2021
a3663cc
feat: Added Embed class and Embed* classes
Gugu7264 Dec 28, 2021
9a1d3ab
feat: switched video and provider to properties, added [from/to]_dict…
Gugu7264 Dec 29, 2021
1accd2a
feat: added allowed_mentions, modified embed, started work on channel…
Gugu7264 Jan 3, 2022
24f737e
Merge branch 'nextcord:master' into master
Gugu7264 Jan 3, 2022
31e0af9
refactor: linted
Gugu7264 Jan 3, 2022
91c5386
style: switched to comments for license
Gugu7264 Jan 4, 2022
9b2b62e
revert: remove abc.py ; early WIP
Gugu7264 Jan 8, 2022
8c1cd9e
fix: pull upstream and resolve conflicts
Gugu7264 Jan 9, 2022
53484c4
refactor/fix: moves code around and fixes typehinting
Gugu7264 Jan 9, 2022
6d711aa
Delete abc.py
Gugu7264 Jan 9, 2022
1cd594d
chore: subclass Protocol and use cls()
Gugu7264 Jan 19, 2022
3e08309
Merge branch 'master' of https://github.com/nextcord/nextcord-v3
Gugu7264 Jan 19, 2022
da41a2c
chore: fix mypy errors
Gugu7264 Jan 22, 2022
40b3721
Merge branch 'master' of https://github.com/nextcord/nextcord-v3
Gugu7264 Jan 22, 2022
3bb752b
fix: from_dict and to_dict now working almost entirely
Gugu7264 Jan 25, 2022
f66da5f
chore: change test
Gugu7264 Jan 25, 2022
cf51ca2
refactor: rename SnowflakeArray to SnowflakeList
Gugu7264 Jan 25, 2022
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -140,3 +140,4 @@ cython_debug/
# Editors
.vscode/
.idea/
.nova/
2 changes: 1 addition & 1 deletion nextcord/core/gateway/gateway.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,9 +36,9 @@
from typing import Any, Optional

from nextcord.exceptions import NextcordException
from .protocols.shard import ShardProtocol

from ...client.state import State
from .protocols.shard import ShardProtocol

logger = getLogger(__name__)

Expand Down
8 changes: 6 additions & 2 deletions nextcord/core/gateway/protocols/gateway.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,8 +51,12 @@ def should_reconnect(self, shard: ShardProtocol) -> bool:
async def close(self) -> None:
...

def _shard_dispatch(self, event_name: str, shard: ShardProtocol, *args: Any) -> None:
def _shard_dispatch(
self, event_name: str, shard: ShardProtocol, *args: Any
) -> None:
...

def _shard_raw_dispatch(self, opcode: int, shard: ShardProtocol, *args: Any) -> None:
def _shard_raw_dispatch(
self, opcode: int, shard: ShardProtocol, *args: Any
) -> None:
...
4 changes: 4 additions & 0 deletions nextcord/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,3 +25,7 @@ def __init__(self) -> None:
"You have been banned by Cloudflare. "
"See https://discord.dev/topics/rate-limits#invalid-request-limit-aka-cloudflare-bans"
)


class InvalidArgument(NextcordException):
...
7 changes: 5 additions & 2 deletions nextcord/type_sheet.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,8 @@
T = TypeVar("T")

from .core.gateway.gateway import GatewayProtocol
from .core.protocols.http import BucketProtocol, HTTPClientProtocol
from .core.gateway.protocols.shard import ShardProtocol
from .core.protocols.http import BucketProtocol, HTTPClientProtocol


@dataclass
Expand All @@ -49,5 +49,8 @@ def default(cls: Type[T]) -> T:
from .core.http import HTTPClient as DefaultHTTPClient

return cls(
http_client=DefaultHTTPClient, http_bucket=DefaultBucket, gateway=Gateway, shard=Shard
http_client=DefaultHTTPClient,
http_bucket=DefaultBucket,
gateway=Gateway,
shard=Shard,
)
78 changes: 78 additions & 0 deletions nextcord/types/allowed_mentions.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
"""
The MIT License (MIT)
Copyright (c) 2021-present vcokltfre & tag-epic
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
"""
from __future__ import annotations

from logging import getLogger
from typing import TYPE_CHECKING, Union

if TYPE_CHECKING:
...


Role, User = None # TODO: DEFINE and import

logger = getLogger(__name__)


class AllowedMentions:
def __init__(
self,
*,
everyone: bool = False,
roles: Union[bool, list[Role], Role] = False,
users: Union[bool, User, list[User]] = True,
replied_user: bool = None,
):
self.everyone = everyone
self.roles = roles
self.users = users
self.replied_user = replied_user

def to_dict(self):
allowed = {"parse": []}
if self.everyone:
allowed["parse"].append("everyone")

if isinstance(self.roles, bool) and self.roles:
allowed["parse"].append("roles")
elif isinstance(self.roles, list):
allowed["roles"] = [r.id for r in self.roles]
elif isinstance(self.roles, Role):
allowed["roles"] = [self.roles.id]

if isinstance(self.users, bool) and self.roles:
allowed["parse"].append("users")
elif isinstance(self.users, list):
allowed["users"] = [u.id for u in self.roles]
elif isinstance(self.users, User):
allowed["users"] = [self.users.id]

if self.replied_user:
allowed["replied_user"] = bool(self.replied_user)

@classmethod
def none(cls):
return cls.__init__(
everyone=False, roles=False, users=False, replied_user=False
)

@classmethod
def all(cls):
return cls.__init__(everyone=True, roles=True, users=True, replied_user=True)
33 changes: 33 additions & 0 deletions nextcord/types/channel.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
"""
The MIT License (MIT)
Copyright (c) 2021-present vcokltfre & tag-epic
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
"""
from __future__ import annotations

from logging import getLogger
from typing import TYPE_CHECKING

if TYPE_CHECKING:
from ..client.state import State

logger = getLogger(__name__)


class Channel:
def __init__(self, *, state: State, data: dict):
pass
179 changes: 179 additions & 0 deletions nextcord/types/embed.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,179 @@
"""
The MIT License (MIT)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I honestly dislike the embed api, it looks super messy imo

Copy link
Author

@Gugu7264 Gugu7264 Jan 3, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I honestly dislike the embed api, it looks super messy imo

Oh? Why that? Because of a class per Proxy?

Or maybe I should add some set_* functions to the Embed class?

Copyright (c) 2021-present vcokltfre & tag-epic
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
"""
from __future__ import annotations

from dataclasses import dataclass
from logging import getLogger
from typing import TYPE_CHECKING, Optional

if TYPE_CHECKING:
from datetime import datetime


logger = getLogger(__name__)


@dataclass(frozen=True)
class EmbedFile:
url: str
proxy_url: Optional[str] = None
height: Optional[int] = None
width: Optional[int] = None


@dataclass(frozen=True)
class EmbedThumbnail(EmbedFile):
...


@dataclass(frozen=True)
class EmbedVideo(EmbedFile):
url: Optional[str] = None


@dataclass(frozen=True)
class EmbedImage(EmbedFile):
...


@dataclass(frozen=True)
class EmbedProvider:
name: Optional[str] = None
url: Optional[str] = None


@dataclass(frozen=True)
class EmbedAuthor:
name: str
url: Optional[str] = None
icon_url: Optional[str] = None
proxy_icon_url: Optional[str] = None


@dataclass(frozen=True)
class EmbedFooter:
text: str
icon_url: Optional[str] = None
proxy_icon_url: Optional[str] = None


class EmbedField:
def __init__(self, name: str, value: str, *, inline: bool = None):
self.name = str(name)
self.value = str(value)
self.inline = bool(inline)


class Embed:
__slots__ = (
"title",
"description",
"url",
"timestamp",
"color",
"footer",
"image",
"thumbnail",
"author",
"fields",
"provider",
"video",
)

def __init__(
self,
*,
title: Optional[str] = None,
description: Optional[str] = None,
url: Optional[str] = None,
timestamp: Optional[datetime] = None,
color: Optional[int] = None,
footer: Optional[EmbedFooter] = None,
image: Optional[EmbedImage] = None,
thumbnail: Optional[EmbedThumbnail] = None,
author: Optional[EmbedAuthor] = None,
fields: Optional[list[EmbedField]] = [],
):
self.title = str(title) if title is not None else None
self.description = str(description) if description is not None else None
self.url = str(url) if url is not None else None
self.color = int(color) if color is not None else None
self.timestamp = timestamp

self.footer = footer if isinstance(footer, EmbedFooter) else None
self.image = image if isinstance(image, EmbedImage) else None
self.thumbnail = thumbnail if isinstance(thumbnail, EmbedThumbnail) else None
self.author = author if isinstance(author, EmbedAuthor) else None
self.fields = fields if isinstance(fields, list) else []

def add_field(
self, name: str, value: str, *, inline: bool = None, position: int = None
) -> None:
if position is not None:
self.fields.insert(position, EmbedField(name, value, inline=inline))
else:
self.fields.append(EmbedField(name, value, inline=inline))

def edit_field(
self, index: int, name: str = None, value: str = None, *, inline: bool = None
) -> None:
if name is not None:
self.fields[index].name = name
if value is not None:
self.fields[index].value = value
if inline is not None:
self.fields[index].inline = inline

def remove_field(self, *, index: int) -> None:
try:
del self.fields[index]
except IndexError:
pass

@property
def video(self):
return self._video

@property
def provider(self):
return self._provider

@classmethod
def from_dict(cls, data: dict):
embed = cls.__init__()
for key, value in data.items():
if key in ["video", "provider"]:
setattr(embed, "_" + key, value)
elif key in embed.__slots__:
setattr(embed, key, value)
else:
continue # TODO: Unknown key, should it raise an error?

return embed

def to_dict(self):
data = {}
for key in self.__slots__:
if key in ["video", "provider"]:
data[key] = getattr(self, "_" + key)
else:
data[key] = getattr(self, key)

return data
Loading