94 Commits

Author SHA1 Message Date
Zomatree 7aa72d6e58 bump version to 0.1.7 2022-04-25 13:33:19 +01:00
HigherOrderLogic 94ba404912 Add cog_load and cog_unload method (#34)
* Add `cog_load` and `cog_unload` method

* Move `cog_load` to end

* Resolve conflict
2022-04-25 13:31:08 +01:00
Lewis L. Foster 4002be8d39 Implemented a servers property into revolt.Client (#36)
* Implement mention for users, members and channels

* Add servers property to revolt.Client

* Forgot to add the docstring for revolt.servers

* fix typo in revolt.Client.servers docstring
2022-04-25 13:30:30 +01:00
Achxy 8d1ee4609b Fix typo in the docstring of FeatureDisabled (#37) 2022-04-25 13:30:00 +01:00
Lewis L. Foster 8b7d850741 Implement mention for users, members and channels (#35) 2022-04-06 15:58:42 +01:00
Zomatree 2c25f2f05b fix ci issue 2022-04-05 06:21:13 +01:00
Zomatree e491ba0f6e rework converter internals to handle edgecases 2022-04-05 06:15:51 +01:00
Zomatree 7229b75c17 fix cog binding 2022-04-03 16:11:49 +01:00
Zomatree aea5c98dbb update justfile 2022-04-02 21:02:49 +01:00
Zomatree c61e58964c add missing docs to functions 2022-04-02 21:02:25 +01:00
Zomatree d5fb40690d switch to using NotRequired 2022-04-02 21:02:12 +01:00
Zomatree a539d8d8c1 fix help command to allow changing attrs 2022-04-02 20:36:05 +01:00
Zomatree 41eddffc1b make context generic over client 2022-03-30 19:03:03 +01:00
Zomatree 7f3253a3b5 add case_insenitive 2022-03-30 19:02:41 +01:00
Zomatree bbb3f18f42 add edit self 2022-03-30 19:00:02 +01:00
Zomatree a0717b180d remove manifest 2022-03-28 04:19:43 +01:00
Zomatree 85b6309192 fix workflow 2022-03-28 01:54:39 +01:00
Zomatree 16aa5308a9 dont cache pip 2022-03-28 01:03:15 +01:00
Zomatree d0263b5f8f switch to pyproject.toml 2022-03-28 01:02:04 +01:00
Zomatree 40ea19951f add basic help command framework 2022-03-26 18:03:13 +00:00
Zomatree f539590005 add group.commands 2022-03-26 18:02:12 +00:00
Zomatree 7b05466090 make add_command take one param and add remove_command 2022-03-26 18:01:44 +00:00
Zomatree 8ba3e047b9 add cog.qualified_name and cog.commands 2022-03-26 18:01:01 +00:00
Zomatree 2279f86446 fix codeblock in documentation 2022-03-23 23:49:28 +00:00
Zomatree 5b39fb1b74 fix voice channel permissions error 2022-03-23 23:39:39 +00:00
Zomatree c19003f2be initial user support 2022-03-23 23:31:45 +00:00
Zomatree c360bbda84 fix small issues 2022-03-23 23:29:16 +00:00
Zomatree b03ac0c9d2 add ClientSession helper function 2022-03-23 22:44:19 +00:00
Zomatree 21c9c78b6d fix up docs 2022-03-23 22:43:57 +00:00
Zomatree 452f1f45bc satisfy the type checker 2022-03-23 22:00:03 +00:00
Omkaar 8641f45400 Fix spelling errors (#30)
* Fix spelling errors in `websocket.py`

* Fix some errors in `utils.py`

* Fix spelling error in `asset.py`

* Fix spelling error in `enums.py`

* Fix some more errors
2022-03-11 10:37:54 +00:00
Zomatree 19d3d5ea4b fix 3.9 compat 2022-03-07 03:00:07 +00:00
Zomatree d7eb5cfe46 display errors from event handlers 2022-03-07 02:56:22 +00:00
Zomatree 07d8c9dd1b handle invalid json responses 2022-03-07 02:55:56 +00:00
Zomatree 0dc5e5510a fix message editing 2022-03-07 02:55:05 +00:00
Zomatree c83897a1f7 make channel.server_id optional 2022-03-07 02:54:25 +00:00
Zomatree be2af590af add cogs and extensions 2022-02-14 05:56:18 +00:00
Zomatree 16177e6698 fix missing inconsistancies 2022-02-14 05:51:46 +00:00
Zomatree 40e9e3a26e import * 2022-02-14 05:50:50 +00:00
Zomatree c29a763576 add embed support 2022-02-14 05:50:35 +00:00
Zomatree 5e757d129f fix parameters with no annotation 2022-02-08 22:15:45 +00:00
Zomatree b17b7fc171 inital implementation of group commands 2022-01-28 19:32:00 +00:00
Zomatree 9dfcf69e52 bump version to v0.1.6 2022-01-28 19:15:11 +00:00
Zomatree b1a91cecb1 fix typing fix error 2022-01-28 19:14:15 +00:00
Zomatree 7cf3fa3e01 bump version to 0.1.5 2022-01-27 23:41:56 +00:00
Zomatree bff242c3f6 fix deps not being auto installed from pypi 2022-01-27 23:41:21 +00:00
Zomatree 0fbb90f65e fix typing issues 2022-01-22 00:30:09 +00:00
Zomatree c7963f02e9 cover most api routes 2022-01-21 22:04:30 +00:00
Bye 5641390d5b Add pip install instructions (#25)
Co-authored-by: Zomatree <39768508+Zomatree@users.noreply.github.com>
2022-01-21 20:24:29 +00:00
Zomatree 7a37da571f bump version to 0.1.4 2022-01-05 18:45:23 +00:00
Zomatree 8aafa8b7f2 fix for 3.9 2022-01-05 18:36:32 +00:00
Zomatree 3754357812 bump version to 0.1.3 2022-01-05 18:33:44 +00:00
Zomatree 5b757bd5df fix union converters 2022-01-05 18:31:58 +00:00
Zomatree e938136b2e fix bug with channels 2022-01-05 18:24:06 +00:00
Zomatree 18e8366651 bump sphinx 2022-01-03 21:07:55 +00:00
Zomatree 85fbe30c32 Merge branch 'master' of github.com:Zomatree/revolt.py 2022-01-03 20:55:50 +00:00
Zomatree 02a839a903 bump version 2022-01-03 20:55:39 +00:00
LightSage 9fc5ee1c84 Fix user update (#23) 2022-01-03 20:54:05 +00:00
Zomatree 3200b06019 Merge branch 'master' of github.com:Zomatree/revolt.py 2022-01-03 20:51:22 +00:00
Zomatree df8815e68a add more converters 2022-01-03 20:51:19 +00:00
Ed L ccd379b24b update repo links, grammar (#24)
* chore: update repo links, grammar

* Update revolt/http.py

Co-authored-by: Zomatree <39768508+Zomatree@users.noreply.github.com>
2022-01-03 20:50:16 +00:00
Zomatree 1c5ceffc58 fix categories docs 2022-01-03 20:39:17 +00:00
Zomatree fd6ef5fc30 add utils.get 2022-01-03 20:37:21 +00:00
Zomatree 7ccd651e4b add server.categories and get_category 2022-01-03 20:00:50 +00:00
Zomatree 35566fff42 add client.users 2022-01-03 19:58:34 +00:00
Zomatree abbbc8c1eb fix client.get_* typehints 2022-01-03 19:58:02 +00:00
Zomatree 67af8b5bf0 update justfile 2022-01-03 19:57:23 +00:00
Zomatree 39098692bc add flags 2021-11-20 22:33:10 +00:00
Zomatree a16bac6207 isort 2021-11-13 23:59:25 +00:00
Zomatree 23d8ced599 Merge branch 'master' of github.com:Zomatree/revolt.py 2021-11-13 23:53:24 +00:00
Zomatree e5d65b9400 add Literal converter and rejig command client 2021-11-13 23:53:21 +00:00
Zomatree c874017a6b add more checks 2021-11-13 23:52:23 +00:00
LightSage 21d27bd44a Fix command repr (#22) 2021-11-13 10:35:57 +00:00
Zomatree 91fde98739 add more advance converters 2021-11-10 16:55:24 +00:00
Zomatree 34a80ea5e2 fix linter 2021-11-10 16:55:14 +00:00
Zomatree 7d6f33f95c auto install deps 2021-11-10 16:37:08 +00:00
Zomatree 1310f3a31a add the rest of the events 2021-11-08 13:59:16 +00:00
Zomatree 611939ed6f change check typings 2021-11-07 11:08:24 +00:00
Zomatree 5514d03b63 change example orefix 2021-11-07 10:39:19 +00:00
Zomatree bd984090c7 add basic check system 2021-11-07 10:33:41 +00:00
Zomatree b2558c1d37 fix deleting message outside cache 2021-11-07 10:26:39 +00:00
Zomatree 0c7cc738fc add masquerade 2021-11-07 10:26:12 +00:00
Zomatree d7175d0079 make context subclass messageable 2021-11-06 05:07:47 +00:00
rockboy987 b5727c818e Add replies parameter to messageable.send (#19)
* Add replies parameter to messageable.send

* Apply requested changes
2021-11-04 22:18:55 +00:00
rockboy987 89986731c1 Fix server to be optional in Channel (#21) 2021-11-03 04:37:10 +00:00
Zomatree 2a3071712e add proper argument parsing - converters and keyword arguments 2021-10-30 15:57:03 +01:00
Zomatree 77fa908ad5 add justfile 2021-10-29 09:16:43 +01:00
Zomatree b94c8cd58e fix argument splitter 2021-10-29 03:48:54 +01:00
Zomatree c5a67335d2 add more attributes to context 2021-10-29 03:48:38 +01:00
Zomatree 287b2d42ea add repr to command 2021-10-29 03:45:39 +01:00
Zomatree a2168e35e9 add server_update event + missing server attrs 2021-10-28 03:43:20 +01:00
Zomatree 497d666311 Closes #18 2021-10-28 03:42:06 +01:00
Zomatree c648eda8e5 fix slots issue 2021-10-23 19:58:12 +01:00
Zomatree 34a6a9cdbc bump dev status 2021-10-23 17:22:40 +01:00
61 changed files with 4988 additions and 928 deletions
+2 -4
View File
@@ -8,11 +8,9 @@ jobs:
- uses: actions/setup-python@v2
with:
python-version: '3.9'
- uses: BSFishy/pip-action@v1
with:
requirements: pyright_requirements.txt
- run: pip install .[speedups]
- uses: jakebailey/pyright-action@v1
with:
lib: true
python-version: 3.9.7
python-version: 3.9
working-directory: revolt
+3
View File
@@ -5,3 +5,6 @@ dist
*.egg-info
docs/_build
.vscode
.env
.mypy_cache
build
+8 -5
View File
@@ -1,12 +1,15 @@
version: 2
sphinx:
configuration: docs/conf.py
configuration: docs/conf.py
python:
version: "3.9"
install:
- requirements: docs_requirements.txt
version: "3.9"
install:
- method: pip
path: .
extra_requirements:
- docs
build:
image: testing
image: testing
Executable
+20
View File
@@ -0,0 +1,20 @@
set dotenv-load := true
test:
python test.py
build:
rm -rf dist/*
python -m build
upload:
python -m twine upload dist/* -u $PYPI_USERNAME -p $PYPI_PASSWORD
lint:
pyright . --venv-path .venv
coverage:
pyright --lib --ignoreexternal --verifytypes revolt
docs:
cd docs && make html
+15 -5
View File
@@ -1,16 +1,26 @@
# Revolt.py
An async library to interact with the https://revolt.chat api.
An async library to interact with the https://revolt.chat API.
This library will be focused on making bots and i will not implement anything only for user accounts.
You can join the support server [here](https://rvlt.gg/FDXER6hr) and find the library's documentation [here](https://revoltpy.readthedocs.io/en/latest/).
Support server: https://app.revolt.chat/invite/FDXER6hr
## Installing
Documentation is [here](https://revoltpy.readthedocs.io/en/latest/)
You can use `pip` to install revolt.py. It differs slightly depending on what OS/Distro you use.
On Windows
```
py -m pip install -U revolt.py # -U to update
```
On macOS and Linux
```
python3 -m pip install -U revolt.py
```
## Example
More examples in the [examples folder](https://github.com/zomatree/revolt.py/blob/master/examples)
More examples can be found in the [examples folder](https://github.com/revoltchat/revolt.py/blob/master/examples).
```py
import revolt
+160 -9
View File
@@ -16,6 +16,13 @@ Asset
.. autoclass:: Asset
:members:
PartialAsset
~~~~~~~~~~~~~
.. autoclass:: PartialAsset
:members:
Channel
~~~~~~~~
@@ -47,7 +54,7 @@ TextChannel
:members:
VoiceChannel
~~~~~~~~~~~~
~~~~~~~~~~~~~
.. autoclass:: VoiceChannel
:members:
@@ -59,6 +66,35 @@ Embed
.. autoclass:: Embed
:members:
WebsiteEmbed
~~~~~~~~~~~~~
.. autoclass:: WebsiteEmbed
:members:
ImageEmbed
~~~~~~~~~~~
.. autoclass:: ImageEmbed
:members:
TextEmbed
~~~~~~~~~~
.. autoclass:: TextEmbed
:members:
NoneEmbed
~~~~~~~~~~
.. autoclass:: NoneEmbed
:members:
SendableEmbed
~~~~~~~~~~~~~~
.. autoclass:: SendableEmbed
:members:
File
~~~~~
@@ -73,23 +109,35 @@ Member
:members:
Message
~~~~~~~
~~~~~~~~
.. autoclass:: Message
:members:
MessageReply
~~~~~~~~~~~~~
.. autoclass:: MessageReply
:members:
Masquerade
~~~~~~~~~~~~~
.. autoclass:: Masquerade
:members:
Messageable
~~~~~~~~~~~~
.. autoclass:: Messageable
:members:
Permissions
~~~~~~~~~~~~
ChannelPermissions
~~~~~~~~~~~~~~~~~~~
.. autoclass:: ChannelPermissions
:members:
ServerPermissions
~~~~~~~~~~~~~~~~~~
.. autoclass:: ServerPermissions
:members:
@@ -105,6 +153,26 @@ Server
.. autoclass:: Server
:members:
ServerBan
~~~~~~~~~~
.. autoclass:: ServerBan
:members:
Category
~~~~~~~~~
.. autoclass:: Category
:members:
SystemMessages
~~~~~~~~~~~~~~~
.. autoclass:: SystemMessages
:members:
User
~~~~~
@@ -122,11 +190,29 @@ Status
.. autonamedtuple:: Status
UserBadges
~~~~~~~~~~~
.. autoclass:: UserBadges
:members:
UserProfile
~~~~~~~~~~~~
.. autoclass:: UserProfile
:members:
Invite
~~~~~~~
.. autoclass:: Invite
:members:
Enums
======
The api uses enums to say what variant of something is, these represent those enums
The api uses enums to say what variant of something is,
these represent those enums
All enums subclass `aenum.Enum`.
@@ -138,10 +224,10 @@ All enums subclass `aenum.Enum`.
A private channel only you can access.
.. attribute:: direct_message
A private direct message channel between you and another user
.. attribute:: group
A private group channel for messages between a group of users
.. attribute:: text_channel
@@ -188,12 +274,77 @@ All enums subclass `aenum.Enum`.
They are sending you a friend request
.. attribute:: none
You have no relationship with them
.. attribute:: outgoing_friend_request
You are sending them a friend request
.. attribute:: user
That user is yourself
.. class:: AssetType
Specifies the type of asset
.. attribute:: image
The asset is an image
.. attribute:: video
The asset is a video
.. attribute:: text
The asset is a text file
.. attribute:: audio
The asset is an audio file
.. attribute:: file
The asset is a generic file
.. class:: SortType
The sort type for a message search
.. attribute:: latest
Sort by the latest message
.. attribute:: oldest
Sort by the oldest message
.. attribute:: relevance
Sort by the relevance of the message
.. class:: EmbedType
The type of embed
.. attribute:: website
The embed is a website
.. attribute:: image
The embed is an image
.. attribute:: text
The embed is text
.. attribute:: video
The embed is a video
.. attribute:: unknown
The embed is unknown
Utils
======
.. currentmodule:: revolt.utils
A collection a utility functions and classes to aid in making your bot
.. autofunction:: get
.. autodecorator:: client_session
+85 -4
View File
@@ -4,9 +4,9 @@ API Reference
===============
CommandsMixin
~~~~~~~~~~~~~
.. autoclass:: revolt.ext.commands.CommandsMixin
CommandsClient
~~~~~~~~~~~~~~~
.. autoclass:: revolt.ext.commands.CommandsClient
:members:
Context
@@ -19,11 +19,92 @@ Command
.. autoclass:: revolt.ext.commands.Command
:members:
Cog
~~~~
.. autoclass:: revolt.ext.commands.Cog
:members:
command
~~~~~~~~
.. autodecorator:: revolt.ext.commands.command
check
~~~~~~
.. autodecorator:: revolt.ext.commands.check
is_bot_owner
~~~~~~~~~~~~~
.. autodecorator:: revolt.ext.commands.is_bot_owner
is_server_owner
~~~~~~~~~~~~~~~~
.. autodecorator:: revolt.ext.commands.is_server_owner
Exceptions
===========
CommandError
~~~~~~~~~~~~~
.. autoexception:: revolt.ext.commands.CommandError
:members:
CommandNotFound
~~~~~~~~~~~~~~~~
.. autoclass:: revolt.ext.commands.CommandNotFound
.. autoexception:: revolt.ext.commands.CommandNotFound
:members:
NoClosingQuote
~~~~~~~~~~~~~~~
.. autoexception:: revolt.ext.commands.NoClosingQuote
:members:
CheckError
~~~~~~~~~~~
.. autoexception:: revolt.ext.commands.CheckError
:members:
NotBotOwner
~~~~~~~~~~~~
.. autoexception:: revolt.ext.commands.NotBotOwner
:members:
NotServerOwner
~~~~~~~~~~~~~~~
.. autoexception:: revolt.ext.commands.NotServerOwner
:members:
ServerOnly
~~~~~~~~~~~
.. autoexception:: revolt.ext.commands.ServerOnly
:members:
ConverterError
~~~~~~~~~~~~~~~
.. autoexception:: revolt.ext.commands.ConverterError
:members:
InvalidLiteralArgument
~~~~~~~~~~~~~~~~~~~~~~~
.. autoexception:: revolt.ext.commands.InvalidLiteralArgument
:members:
BadBoolArgument
~~~~~~~~~~~~~~~~
.. autoexception:: revolt.ext.commands.BadBoolArgument
:members:
CategoryConverterError
~~~~~~~~~~~~~~~~~~~~~~~
.. autoexception:: revolt.ext.commands.CategoryConverterError
:members:
UserConverterError
~~~~~~~~~~~~~~~~~~~
.. autoexception:: revolt.ext.commands.UserConverterError
:members:
MemberConverterError
~~~~~~~~~~~~~~~~~~~~~
.. autoexception:: revolt.ext.commands.MemberConverterError
:members:
-6
View File
@@ -1,6 +0,0 @@
Sphinx==3.5.4
sphinx-nameko-theme==0.0.3
aiohttp==3.7.4.post0
ulid-py==1.1.0
sphinx-toolbox==2.13.0
aenum==3.1.0
+2 -2
View File
@@ -6,9 +6,9 @@ import revolt
from revolt.ext import commands
class Client(commands.CommandsMixin, revolt.Client):
class Client(commands.CommandsClient):
async def get_prefix(self, message: revolt.Message):
return ">>>"
return "!"
@commands.command()
async def ping(self, ctx: commands.Context):
Generated Executable
+1298
View File
File diff suppressed because it is too large Load Diff
Executable
+46
View File
@@ -0,0 +1,46 @@
[tool.poetry]
name = "revolt.py"
version = "0.1.7"
description = "Python wrapper for the revolt.chat API"
authors = ["Zomatee <me@zomatree.live>"]
license = "MIT"
readme = "README.md"
homepage = "https://github.com/revoltchat/revolt.py"
documentation = "https://revoltpy.readthedocs.io/en/latest/"
classifiers = [
"Development Status :: 4 - Beta",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.9",
"Programming Language :: Python :: 3.10",
"Programming Language :: Python :: 3 :: Only",
]
keywords = ["wrapper", "async", "api", "websockets", "http"]
packages = [
{ include = "revolt" }
]
[tool.poetry.dependencies]
python = "^3.9"
aiohttp = "3.7.4"
ulid-py = "1.1.0"
aenum = "3.1.8"
typing-extensions = "4.1.1"
ujson = { version = "5.1.0", optional = true }
msgpack = { version = "", optional = true }
Sphinx = { version = "4.3.2", optional = true }
sphinx-nameko-theme = { version = "0.0.3", optional = true }
sphinx-toolbox = { version = "2.15.2", optional = true }
[tool.poetry.extras]
speedups = ["ujson", "aiohttp[speedups]", "msgpack"]
docs = ["Sphinx", "sphinx-nameko-theme", "sphinx-toolbox"]
[build-system]
requires = ["poetry-core>=1.0.0"]
build-backend = "poetry.core.masonry.api"
[tool.poetry.urls]
"Bug Tracker" = "https://github.com/revoltchat/revolt.py/issues"
Source = "https://github.com/revoltchat/revolt.py/"
-6
View File
@@ -1,6 +0,0 @@
aiohttp==3.7.4.post0
ulid-py==1.1.0
aenum==3.1.0
ujson
msgpack==1.0.2
.
-3
View File
@@ -1,3 +0,0 @@
aiohttp==3.7.4.post0
ulid-py==1.1.0
aenum==3.1.0
+19 -17
View File
@@ -1,18 +1,20 @@
from .asset import Asset
from .channel import (Channel, DMChannel, GroupDMChannel, SavedMessageChannel,
TextChannel, VoiceChannel)
from .client import Client
from .embed import Embed
from .enums import (AssetType, ChannelType, PresenceType, RelationshipType,
SortType)
from .errors import HTTPError, RevoltError, ServerError
from .file import File
from .member import Member
from .message import Message
from .messageable import Messageable
from .permissions import ChannelPermissions, ServerPermissions
from .role import Role
from .server import Server
from .user import Relation, Status, User
from . import utils
from .asset import *
from .category import *
from .channel import *
from .client import *
from .embed import *
from .enums import *
from .errors import *
from .file import *
from .flags import *
from .invite import *
from .member import *
from .message import *
from .messageable import *
from .permissions import *
from .role import *
from .server import *
from .user import *
__version__ = (0, 1, 0)
__version__ = (0, 1, 7)
+41 -26
View File
@@ -1,5 +1,6 @@
from __future__ import annotations
import mimetypes
from typing import TYPE_CHECKING
from .enums import AssetType
@@ -12,7 +13,7 @@ if TYPE_CHECKING:
from .types import File as FilePayload
__all__ = ("Asset",)
__all__ = ("Asset", "PartialAsset")
class Asset:
"""Represents a file on revolt
@@ -35,8 +36,10 @@ class Asset:
The content type of the file
type: :class:`AssetType`
The type of asset it is
url: :class:`str`
The assets url
"""
__slots__ = ("state", "id", "tag", "size", "filename", "content_type", "width", "height", "type")
__slots__ = ("state", "id", "tag", "size", "filename", "content_type", "width", "height", "type", "url")
def __init__(self, data: FilePayload, state: State):
self.state = state
@@ -48,7 +51,7 @@ class Asset:
metadata = data['metadata']
if metadata["type"] == "Image" or metadata["type"] == "Video": # cant use `in` because type narrowing wont happen
if metadata["type"] == "Image" or metadata["type"] == "Video": # cannot use `in` because type narrowing will not happen
self.height = metadata["height"]
self.width = metadata["width"]
else:
@@ -58,6 +61,9 @@ class Asset:
self.content_type = data["content_type"]
self.type = AssetType(metadata["type"])
base_url = self.state.api_info["features"]["autumn"]["url"]
self.url = f"{base_url}/{self.tag}/{self.id}"
async def read(self) -> bytes:
"""Reads the files content into bytes"""
return await self.state.http.request_file(self.url)
@@ -72,28 +78,37 @@ class Asset:
"""
fp.write(await self.read())
@property
def url(self) -> str:
"""Returns the url for the asset
.. note:: This can error if autumn is disabled on the instance of revolt
Returns
--------
:class:`str`
The url
class PartialAsset(Asset):
"""Partial asset for when we get limited data about the asset
Raises
-------
:class:`AutumnDisabled`
Raises if autumn is disabled
"""
enabled = self.state.api_info["features"]["autumn"]["enabled"]
if not enabled:
raise AutumnDisabled
Attributes
-----------
id: :class:`str`
The id of the asset, this will always be ``"0"``
tag: Optional[:class:`str`]
The tag of the asset, this corrasponds to where the asset is used, this will always be ``None``
size: :class:`int`
Amount of bytes in the file, this will always be ``0``
filename: :class:`str`
The name of the file, this be always be ``""``
height: Optional[:class:`int`]
The height of the file if it is an image or video, this will always be ``None``
width: Optional[:class:`int`]
The width of the file if it is an image or video, this will always be ``None``
content_type: Optional[:class:`str`]
The content type of the file, this is guessed from the url's file extension if it has one
type: :class:`AssetType`
The type of asset it is, this always be ``AssetType.file``
"""
base_url = self.state.api_info["features"]["autumn"]["url"]
return f"{base_url}/{self.tag}/{self.id}"
def __init__(self, url: str, state: State):
self.state = state
self.id = "0"
self.tag = None
self.size = 0
self.filename = ""
self.height = None
self.width = None
self.content_type = mimetypes.guess_extension(url)
self.type = AssetType.file
self.url = url
+34
View File
@@ -0,0 +1,34 @@
from __future__ import annotations
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from .channel import Channel
from .state import State
from .types import Category as CategoryPayload
__all__ = ("Category",)
class Category:
"""Represents a category in a server that stores channels.
Attributes
-----------
name: :class:`str`
The name of the category
id: :class:`str`
The id of the category
channel_ids: list[:class:`str`]
The ids of channels that are inside the category
"""
def __init__(self, data: CategoryPayload, state: State):
self.state = state
self.name = data["title"]
self.id = data["id"]
self.channel_ids = data["channels"]
@property
def channels(self) -> list[Channel]:
"""Returns a list of channels that the category contains"""
return [self.state.get_channel(channel_id) for channel_id in self.channel_ids]
+155 -35
View File
@@ -1,10 +1,14 @@
from __future__ import annotations
from typing import TYPE_CHECKING, Optional, cast
from typing import TYPE_CHECKING, Literal, Optional, Union
from revolt.utils import Missing
from .asset import Asset
from .enums import ChannelType
from .messageable import Messageable
from .permissions import ChannelPermissions
from .utils import Missing
if TYPE_CHECKING:
from .message import Message
@@ -13,13 +17,29 @@ if TYPE_CHECKING:
from .state import State
from .types import Channel as ChannelPayload
from .types import DMChannel as DMChannelPayload
from .types import Group as GroupDMChannelPayload
from .types import GroupDMChannel as GroupDMChannelPayload
from .types import SavedMessages as SavedMessagesPayload
from .types import TextChannel as TextChannelPayload
from .types import VoiceChannel as VoiceChannelPayload
from .user import User
__all__ = ("Channel",)
__all__ = ("DMChannel", "GroupDMChannel", "SavedMessageChannel", "TextChannel", "VoiceChannel", "Channel")
class EditableChannel:
__slots__ = ()
state: State
id: str
async def edit(self, **kwargs):
if kwargs.get("icon", Missing) == None:
remove = "Icon"
elif kwargs.get("description", Missing) == None:
remove = "Description"
else:
remove = None
await self.state.http.edit_channel(self.id, remove, kwargs)
class Channel:
"""Base class for all channels
@@ -30,8 +50,8 @@ class Channel:
The id of the channel
channel_type: ChannelType
The type of the channel
server: Optional[:class:`Server`]
The server the channel is part of
server_id: Optional[:class:`str`]
The server id of the chanel, if any
"""
__slots__ = ("state", "id", "channel_type", "server_id")
@@ -39,15 +59,32 @@ class Channel:
self.state = state
self.id = data["_id"]
self.channel_type = ChannelType(data["channel_type"])
self.server_id = ""
self.server_id: Optional[str] = None
@property
def server(self) -> Server:
return self.state.get_server(self.server_id)
async def _get_channel_id(self) -> str:
return self.id
def _update(self):
pass
async def delete(self):
"""Deletes or closes the channel"""
await self.state.http.close_channel(self.id)
@property
def server(self) -> Server:
""":class:`Server` The server this voice channel belongs too"""
if not self.server_id:
raise IndexError
return self.state.get_server(self.server_id)
@property
def mention(self) -> str:
""":class:`str`: Returns a string that allows you to mention the given channel."""
return f"<#{self.id}>"
class SavedMessageChannel(Channel, Messageable):
"""The Saved Message Channel"""
def __init__(self, data: SavedMessagesPayload, state: State):
@@ -58,26 +95,52 @@ class DMChannel(Channel, Messageable):
def __init__(self, data: DMChannelPayload, state: State):
super().__init__(data, state)
class GroupDMChannel(Channel, Messageable):
__slots__ = ("recipients", "name", "owner", "permissions")
class GroupDMChannel(Channel, Messageable, EditableChannel):
"""A group DM channel
Attributes
-----------
recipients: list[:class:`User`]
The recipients of the group dm channel
name: :class:`str`
The name of the group dm channel
owner: :class:`User`
The user who created the group dm channel
icon: Optional[:class:`Asset`]
The icon of the group dm channel
permissions: :class:`ChannelPermissions`
The permissions of the users inside the group dm channel
description: Optional[:class:`str`]
The description of the channel, if any
"""
__slots__ = ("recipients", "name", "owner", "permissions", "icon", "description")
"""A group DM channel"""
def __init__(self, data: GroupDMChannelPayload, state: State):
super().__init__(data, state)
self.recipients = [state.get_user(user_id) for user_id in data["recipients"]]
self.name = data["name"]
self.owner = state.get_user(data["owner"])
self.description: Optional[str] = data.get("description")
if perms := data.get("permissions"):
self.permissions = ChannelPermissions(perms)
if icon := data.get("icon"):
self.icon = Asset(icon, state)
else:
self.icon = None
def _update(self, *, name: Optional[str] = None, recipients: Optional[list[str]] = None):
perms = data.get("permissions", 0)
self.permissions = ChannelPermissions._from_value(perms)
def _update(self, *, name: Optional[str] = None, recipients: Optional[list[str]] = None, description: Optional[str] = None):
if name:
self.name = name
if recipients:
self.recipients = [self.state.get_user(user_id) for user_id in recipients]
if description:
self.description = description
async def set_default_permissions(self, permissions: ChannelPermissions) -> None:
"""Sets the default permissions for a group.
Parameters
@@ -87,28 +150,61 @@ class GroupDMChannel(Channel, Messageable):
"""
await self.state.http.set_channel_default_permissions(self.id, permissions.value)
class TextChannel(Channel, Messageable):
__slots__ = ("name", "description", "last_message_id", "server_id", "default_permissions", "role_permissions")
class TextChannel(Channel, Messageable, EditableChannel):
__slots__ = ("name", "description", "last_message_id", "server_id", "default_permissions", "role_permissions", "icon")
"""A text channel"""
"""A text channel
Attributes
-----------
name: :class:`str`
The name of the text channel
server_id: :class:`str`
The id of the server this text channel belongs to
last_message_id: Optional[:class:`str`]
The id of the last message in this channel, if any
default_permissions: :class:`ChannelPermissions`
The default permissions for all users in the text channel
role_permissions: dict[:class:`str`, :class:`ChannelPermissions`]
A dictionary of role id's to the permissions of that role in the text channel
icon: Optional[:class:`Asset`]
The icon of the text channel, if any
description: Optional[:class:`str`]
The description of the channel, if any
"""
def __init__(self, data: TextChannelPayload, state: State):
super().__init__(data, state)
self.server_id = data["server"]
self.name = data["name"]
self.description = data.get("description")
self.description: Optional[str] = data.get("description")
last_message_id = data.get("last_message")
self.last_message_id = last_message_id
if perms := data.get("default_permissions"):
self.default_permissions = ChannelPermissions(perms)
self.default_permissions = ChannelPermissions._from_value(data.get("default_permissions", 0))
self.role_permissions = {role_id: ChannelPermissions._from_value(perms) for role_id, perms in data.get("role_permissions", {}).items()}
if role_perms := data.get("role_permissions"):
self.role_permissions = {role_id: ChannelPermissions(perms) for role_id, perms in role_perms.items()}
if icon := data.get("icon"):
self.icon = Asset(icon, state)
else:
self.icon = None
async def _get_channel_id(self) -> str:
return self.id
@property
def last_message(self) -> Message:
def last_message(self) -> Optional[Message]:
"""Gets the last message from the channel, shorthand for `client.get_message(channel.last_message_id)`
Returns
--------
:class:`Message` the last message in the channel
"""
if not self.last_message_id:
return
return self.state.get_message(self.last_message_id)
def _update(self, *, name: Optional[str] = None, description: Optional[str] = None):
@@ -136,20 +232,44 @@ class TextChannel(Channel, Messageable):
"""
await self.state.http.set_channel_role_permissions(self.id, role.id, permissions.value)
class VoiceChannel(Channel):
"""A voice channel"""
class VoiceChannel(Channel, EditableChannel):
"""A voice channel
Attributes
-----------
name: :class:`str`
The name of the voice channel
server_id: :class:`str`
The id of the server this voice channel belongs to
last_message_id: Optional[:class:`str`]
The id of the last message in this channel, if any
default_permissions: :class:`ChannelPermissions`
The default permissions for all users in the voice channel
role_permissions: dict[:class:`str`, :class:`ChannelPermissions`]
A dictionary of role id's to the permissions of that role in the voice channel
icon: Optional[:class:`Asset`]
The icon of the voice channel, if any
description: Optional[:class:`str`]
The description of the channel, if any
"""
def __init__(self, data: VoiceChannelPayload, state: State):
super().__init__(data, state)
self.server_id = data["server"]
self.name = data["name"]
self.description = data.get("description")
self.description: Optional[str] = data.get("description")
if perms := data.get("default_permissions"):
self.default_permissions = ChannelPermissions(perms)
self.default_permissions = ChannelPermissions._from_value(perms)
else:
self.default_permissions = ChannelPermissions._from_value(0)
if role_perms := data.get("role_permissions"):
self.role_permissions = {role_id: ChannelPermissions(perms) for role_id, perms in role_perms.items()}
self.role_permissions = {role_id: ChannelPermissions._from_value(perms) for role_id, perms in data.get("role_permissions", {}).items()}
if icon := data.get("icon"):
self.icon = Asset(icon, state)
else:
self.icon = None
def _update(self, *, name: Optional[str] = None, description: Optional[str] = None):
if name:
@@ -176,8 +296,8 @@ class VoiceChannel(Channel):
"""
await self.state.http.set_channel_role_permissions(self.id, role.id, permissions.value)
def channel_factory(data: ChannelPayload, state: State) -> Channel:
if data["channel_type"] == "SavedMessage":
def channel_factory(data: ChannelPayload, state: State) -> Union[DMChannel, GroupDMChannel, SavedMessageChannel, TextChannel, VoiceChannel]:
if data["channel_type"] == "SavedMessages":
return SavedMessageChannel(data, state)
elif data["channel_type"] == "DirectMessage":
return DMChannel(data, state)
+200 -17
View File
@@ -2,13 +2,18 @@ from __future__ import annotations
import asyncio
import logging
from typing import TYPE_CHECKING, Any, Callable, Coroutine, Optional, TypeVar
from typing import TYPE_CHECKING, Any, Callable, Optional, Union, cast
import aiohttp
from .channel import (DMChannel, GroupDMChannel, SavedMessageChannel,
TextChannel, VoiceChannel, channel_factory)
from .http import HttpClient
from .invite import Invite
from .message import Message
from .state import State
from .websocket import WebsocketHandler
from .utils import Missing
try:
import ujson as json
@@ -28,7 +33,7 @@ logger = logging.getLogger("revolt")
class Client:
"""The client for interacting with revolt
Parameters
-----------
session: :class:`aiohttp.ClientSession`
@@ -40,14 +45,14 @@ class Client:
max_messages: :class:`int`
The max amount of messages stored in the cache, by default this is 5k
"""
__slots__ = ("session", "token", "api_url", "max_messages", "api_info", "http", "state", "websocket", "listeners")
def __init__(self, session: aiohttp.ClientSession, token: str, api_url: str = "https://api.revolt.chat", max_messages: int = 5000):
def __init__(self, session: aiohttp.ClientSession, token: str, *, api_url: str = "https://api.revolt.chat", max_messages: int = 5000, bot: bool = True):
self.session = session
self.token = token
self.api_url = api_url
self.max_messages = max_messages
self.bot = bot
self.api_info: ApiInfo
self.http: HttpClient
self.state: State
@@ -59,7 +64,7 @@ class Client:
def dispatch(self, event: str, *args: Any):
"""Dispatch an event, this is typically used for testing and internals.
Parameters
----------
event: class:`str`
@@ -87,12 +92,12 @@ class Client:
api_info = await self.get_api_info()
self.api_info = api_info
self.http = HttpClient(self.session, self.token, self.api_url, self.api_info)
self.http = HttpClient(self.session, self.token, self.api_url, self.api_info, self.bot)
self.state = State(self.http, api_info, self.max_messages)
self.websocket = WebsocketHandler(self.session, self.token, api_info["ws"], self.dispatch, self.state)
await self.websocket.start()
def get_user(self, id: str) -> Optional[User]:
def get_user(self, id: str) -> User:
"""Gets a user from the cache
Parameters
@@ -102,12 +107,12 @@ class Client:
Returns
--------
Optional[:class:`User`]
The user if found
:class:`User`
The user
"""
return self.state.get_user(id)
def get_channel(self, id: str) -> Optional[Channel]:
def get_channel(self, id: str) -> Channel:
"""Gets a channel from the cache
Parameters
@@ -117,12 +122,12 @@ class Client:
Returns
--------
Optional[:class:`Channel`]
The channel if found
:class:`Channel`
The channel
"""
return self.state.get_channel(id)
def get_server(self, id: str) -> Optional[Server]:
def get_server(self, id: str) -> Server:
"""Gets a server from the cache
Parameters
@@ -132,8 +137,8 @@ class Client:
Returns
--------
Optional[:class:`Server`]
The server if found
:class:`Server`
The server
"""
return self.state.get_server(id)
@@ -166,3 +171,181 @@ class Client:
self.listeners.setdefault(event, []).append((check, future))
return await asyncio.wait_for(future, timeout)
@property
def user(self) -> User:
""":class:`User` the user corrasponding to the client"""
user = self.websocket.user
assert user
return user
@property
def users(self) -> list[User]:
"""list[:class:`User`] All users the client can see"""
return list(self.state.users.values())
@property
def servers(self) -> list[Server]:
"""list[:class:'Server'] All servers the client can see"""
return list(self.state.servers.values())
async def fetch_user(self, user_id: str) -> User:
"""Fetchs a user
Parameters
-----------
user_id: :class:`str`
The id of the user you are fetching
Returns
--------
:class:`User`
The user with the matching id
"""
payload = await self.http.fetch_user(user_id)
return User(payload, self.state)
async def fetch_dm_channels(self) -> list[Union[DMChannel, GroupDMChannel]]:
"""Fetchs all dm channels the client has made
Returns
--------
list[Union[:class:`DMChanel`, :class:`GroupDMChannel`]]
A list of :class:`DMChannel` or :class`GroupDMChannel`
"""
channel_payloads = await self.http.fetch_dm_channels()
return cast(list[Union[DMChannel, GroupDMChannel]], [channel_factory(payload, self.state) for payload in channel_payloads])
async def fetch_channel(self, channel_id: str) -> Union[DMChannel, GroupDMChannel, SavedMessageChannel, TextChannel, VoiceChannel]:
"""Fetches a channel
Parameters
-----------
channel_id: :class:`str`
The id of the channel
Returns
--------
Union[:class:`DMChannel`, :class:`GroupDMChannel`, :class:`SavedMessageChannel`, :class:`TextChannel`, :class:`VoiceChannel`]
The channel with the matching id
"""
payload = await self.http.fetch_channel(channel_id)
return channel_factory(payload, self.state)
async def fetch_server(self, server_id: str) -> Server:
"""Fetchs a server
Parameters
-----------
server_id: :class:`str`
The id of the server you are fetching
Returns
--------
:class:`Server`
The server with the matching id
"""
payload = await self.http.fetch_server(server_id)
return Server(payload, self.state)
async def fetch_invite(self, code: str) -> Invite:
"""Fetchs an invite
Parameters
-----------
code: :class:`str`
The code of the invite you are fetching
Returns
--------
:class:`Invite`
The invite with the matching code
"""
payload = await self.http.fetch_invite(code)
return Invite(payload, code, self.state)
def get_message(self, message_id: str) -> Message:
"""Gets a message from the cache
Parameters
-----------
message_id: :class:`str`
The id of the message you are getting
Returns
--------
:class:`Message`
The message with the matching id
Raises
-------
LookupError
This raises if the message is not found in the cache
"""
for message in self.state.messages:
if message.id == message_id:
return message
raise LookupError
async def edit_self(self, **kwargs):
"""Edits the client's own user
Parameters
-----------
avatar: Optional[:class:`File`]
The avatar to change to, passing in ``None`` will remove the avatar
"""
if kwargs.get("avatar", Missing) == None:
del kwargs["avatar"]
remove = "Avatar"
else:
remove = None
await self.state.http.edit_self(remove, kwargs)
async def edit_status(self, **kwargs):
"""Edits the client's own status
Parameters
-----------
presence: :class:`PresenceType`
The presence to change to
text: Optional[:class:`str`]
The text to change the status to, passing in ``None`` will remove the status
"""
if kwargs.get("text", Missing) == None:
del kwargs["text"]
remove = "StatusText"
else:
remove = None
if presence := kwargs.get("presence"):
kwargs["presence"] = presence.value
await self.state.http.edit_self(remove, {"status": kwargs})
async def edit_profile(self, **kwargs):
"""Edits the client's own profile
Parameters
-----------
content: Optional[:class:`str`]
The new content for the profile, passing in ``None`` will remove the profile content
background: Optional[:class:`File`]
The new background for the profile, passing in ``None`` will remove the profile background
"""
if kwargs.get("content", Missing) == None:
del kwargs["content"]
remove = "ProfileContent"
elif kwargs.get("background", Missing) == None:
del kwargs["background"]
remove = "ProfileBackground"
else:
remove = None
await self.state.http.edit_self(remove, {"profile": kwargs})
+97 -8
View File
@@ -1,17 +1,106 @@
from __future__ import annotations
from typing import TYPE_CHECKING
from typing import TYPE_CHECKING, Optional, Union
from .enums import EmbedType
from .asset import Asset
if TYPE_CHECKING:
from .state import State
from .types import Embed as EmbedPayload
from .types import SendableEmbed as SendableEmbedPayload
from .types import WebsiteEmbed as WebsiteEmbedPayload
from .types import ImageEmbed as ImageEmbedPayload
from .types import TextEmbed as TextEmbedPayload
from .types import NoneEmbed as NoneEmbedPayload
__all__ = ("Embed", "WebsiteEmbed", "ImageEmbed", "TextEmbed", "NoneEmbed", "to_embed", "SendableEmbed")
__all__ = ("Embed",)
class WebsiteEmbed:
type = EmbedType.website
class Embed:
@classmethod
def from_dict(cls, data: EmbedPayload):
...
def __init__(self, embed: WebsiteEmbedPayload):
self.url = embed.get("url")
self.special = embed.get("special")
self.title = embed.get("title")
self.description = embed.get("description")
self.image = embed.get("image")
self.video = embed.get("video")
self.site_name = embed.get("site_name")
self.icon_url = embed.get("icon_url")
self.colour = embed.get("colour")
def to_dict(self) -> EmbedPayload:
...
class ImageEmbed:
type = EmbedType.image
def __init__(self, image: ImageEmbedPayload):
self.url = image.get("url")
self.width = image.get("width")
self.height = image.get("height")
self.size = image.get("size")
class TextEmbed:
type = EmbedType.text
def __init__(self, embed: TextEmbedPayload, state: State):
self.icon_url = embed.get("icon_url")
self.url = embed.get("url")
self.title = embed.get("title")
self.description = embed.get("description")
if media := embed.get("media"):
self.media = Asset(media, state)
else:
self.media = None
self.colour = embed.get("colour")
class NoneEmbed:
type = EmbedType.none
Embed = Union[WebsiteEmbed, ImageEmbed, TextEmbed, NoneEmbed]
def to_embed(payload: EmbedPayload, state: State) -> Embed:
if payload["type"] == "Website":
return WebsiteEmbed(payload)
elif payload["type"] == "Image":
return ImageEmbed(payload)
elif payload["type"] == "Text":
return TextEmbed(payload, state)
else:
return NoneEmbed()
class SendableEmbed:
def __init__(self, **attrs):
self.title: Optional[str] = None
self.description: Optional[str] = None
self.media: Optional[str] = None
self.icon_url: Optional[str] = None
self.colour: Optional[str] = None
self.url: Optional[str] = None
for key, value in attrs.items():
setattr(self, key, value)
def to_dict(self) -> SendableEmbedPayload:
output: SendableEmbedPayload = {"type": "Text"}
if title := self.title:
output["title"] = title
if description := self.description:
output["description"] = description
if media := self.media:
output["media"] = media
if icon_url := self.icon_url:
output["icon_url"] = icon_url
if colour := self.colour:
output["colour"] = colour
if url := self.url:
output["url"] = url
return output
+9 -2
View File
@@ -1,6 +1,6 @@
from typing import TYPE_CHECKING
# typing doesnt understand aenum so im pretending its stdlib enum while type checking
# typing does not understand aenum so I am pretending its stdlib enum while type checking
if TYPE_CHECKING:
import enum
@@ -14,10 +14,11 @@ __all__ = (
"RelationshipType",
"AssetType",
"SortType",
"EmbedType"
)
class ChannelType(enum.Enum):
saved_message = "SavedMessage"
saved_messages = "SavedMessages"
direct_message = "DirectMessage"
group = "Group"
text_channel = "TextChannel"
@@ -49,3 +50,9 @@ class SortType(enum.Enum):
latest = "Latest"
oldest = "Oldest"
relevance = "Relevance"
class EmbedType(enum.Enum):
website = "Website"
image = "Image"
text = "Text"
none = "None"
+1 -1
View File
@@ -16,7 +16,7 @@ class ServerError(RevoltError):
"Internal server error"
class FeatureDisabled(RevoltError):
"""Base class for any any feature disabled"""
"""Base class for any feature disabled errors"""
class AutumnDisabled(FeatureDisabled):
"""The autumn feature is disabled"""
+6 -1
View File
@@ -1,4 +1,9 @@
from .checks import *
from .client import *
from .command import *
from .context import *
from .converters import *
from .errors import *
from .mixin import *
from .group import *
from .help import *
from .cog import *
+61
View File
@@ -0,0 +1,61 @@
from typing import Any, Callable, Coroutine, TypeVar, Union
from .command import Command
from .context import Context
from .errors import NotBotOwner, NotServerOwner, ServerOnly
__all__ = ("check", "Check", "is_bot_owner", "is_server_owner")
Check = Callable[[Context], Union[Any, Coroutine[Any, Any, Any]]]
T = TypeVar("T", Callable[..., Any], Command)
def check(check: Check):
"""A decorator for adding command checks
Parameters
-----------
check: Callable[[Context], Union[Any, Coroutine[Any, Any, Any]]]
The function to be called, must take one parameter, context and optionally be a coroutine
Returns
--------
Any
The value denoating whether the check should pass or fail
"""
def inner(func: T) -> T:
if isinstance(func, Command):
func.checks.append(check)
else:
checks = getattr(func, "_checks", [])
checks.append(check)
func._checks = checks # type: ignore
return func
return inner
def is_bot_owner():
"""A command check for limiting the command to only the bot's owner"""
@check
def inner(context: Context):
if context.author.id == context.client.user.owner_id:
return True
raise NotBotOwner
return inner
def is_server_owner():
"""A command check for limiting the command to only a server's owner"""
@check
def inner(context: Context):
if not context.server:
raise ServerOnly
if context.author.id == context.server.owner_id:
return True
raise NotServerOwner
return inner
+351
View File
@@ -0,0 +1,351 @@
from __future__ import annotations
import traceback
import sys
from typing import Any, Union, Protocol, runtime_checkable, Optional, TYPE_CHECKING
from typing_extensions import Self
from importlib import import_module
import revolt
if TYPE_CHECKING:
from .help import HelpCommand
from .command import Command
from .context import Context
from .errors import CheckError, CommandNotFound, MissingSetup
from .view import StringView
from .cog import Cog
__all__ = (
"CommandsMeta",
"CommandsClient"
)
@runtime_checkable
class ExtensionProtocol(Protocol):
@staticmethod
def setup(client: CommandsClient) -> None:
raise NotImplementedError
class CommandsMeta(type):
_commands: list[Command]
def __new__(cls, name: str, bases: tuple[type, ...], attrs: dict[str, Any]):
commands: list[Command] = []
self = super().__new__(cls, name, bases, attrs)
for base in reversed(self.__mro__):
for value in base.__dict__.values():
if isinstance(value, Command):
commands.append(value)
self._commands = commands
return self
class CaseInsensitiveDict(dict):
def __setitem__(self, key: str, value: Any) -> None:
super().__setitem__(key.casefold(), value)
def __getitem__(self, key: str) -> Any:
return super().__getitem__(key.casefold())
def __contains__(self, key: str) -> bool:
return super().__contains__(key.casefold())
def get(self, key: str, default: Any = None) -> Any:
return super().get(key.casefold(), default)
def __delitem__(self, key: str) -> None:
super().__delitem__(key.casefold())
class CommandsClient(revolt.Client, metaclass=CommandsMeta):
"""Main class that adds commands, this class should be subclassed along with `revolt.Client`."""
_commands: list[Command]
def __init__(self, *args, help_command: Optional[HelpCommand] = None, case_insensitive: bool = False, **kwargs):
from .help import DefaultHelpCommand, HelpCommandImpl
self.all_commands: dict[str, Command] = {} if not case_insensitive else CaseInsensitiveDict()
self.cogs: dict[str, Cog] = {}
self.extensions: dict[str, ExtensionProtocol] = {}
for command in self._commands:
self.all_commands[command.name] = command
for alias in command.aliases:
self.all_commands[alias] = command
if help_command is None:
help_command = DefaultHelpCommand()
self.help_command = DefaultHelpCommand()
self.add_command(HelpCommandImpl(self))
super().__init__(*args, **kwargs)
@property
def commands(self) -> list[Command]:
return list(set(self.all_commands.values()))
async def get_prefix(self, message: revolt.Message) -> Union[str, list[str]]:
"""Overwrite this function to set the prefix used for commands, this function is called for every message.
Parameters
-----------
message: :class:`Message`
The message that was sent
Returns
--------
Union[:class:`str`, list[:class:`str`]]
The prefix(s) for the commands
"""
raise NotImplementedError
def get_command(self, name: str) -> Command:
"""Gets a command.
Parameters
-----------
name: :class:`str`
The name or alias of the command
Returns
--------
:class:`Command`
The command with the name
"""
return self.all_commands[name]
def add_command(self, command: Command):
"""Adds a command, this is typically only used for dynamic commands, you should use the `commands.command` decorator for most usecases.
Parameters
-----------
name: :class:`str`
The name or alias of the command
command: :class:`Command`
The command to be added
"""
self.all_commands[command.name] = command
for alias in command.aliases:
self.all_commands[alias] = command
def remove_command(self, name: str) -> Optional[Command]:
"""Removes a command.
Parameters
-----------
name: :class:`str`
The name or alias of the command
Returns
--------
Optional[:class:`Command`]
The command that was removed
"""
command = self.all_commands.pop(name, None)
if command is not None:
for alias in command.aliases:
self.all_commands.pop(alias, None)
return command
def get_view(self, message: revolt.Message) -> type[StringView]:
return StringView
def get_context(self, message: revolt.Message) -> type[Context[Self]]:
return Context
async def process_commands(self, message: revolt.Message) -> Any:
"""Processes commands, if you overwrite `Client.on_message` you should manually call this function inside the event.
Parameters
-----------
message: :class:`Message`
The message to process commands on
Returns
--------
Any
The return of the command, if any
"""
content = message.content
if not isinstance(content, str):
return
prefixes = await self.get_prefix(message)
if isinstance(prefixes, str):
prefixes = [prefixes]
for prefix in prefixes:
if content.startswith(prefix):
content = content[len(prefix):]
break
else:
return
if not content:
return
view = self.get_view(message)(content)
try:
command_name = view.get_next_word()
except StopIteration:
return
context_cls = self.get_context(message)
try:
command = self.get_command(command_name)
except KeyError:
context = context_cls(None, command_name, view, message, self)
return self.dispatch("command_error", context, CommandNotFound(command_name))
context = context_cls(command, command_name, view, message, self)
try:
self.dispatch("command", context)
if not await self.bot_check(context):
raise CheckError(f"the global check for the command failed")
if not await context.can_run():
raise CheckError(f"the check(s) for the command failed")
output = await context.invoke()
self.dispatch("after_command_invoke", context, output)
return output
except Exception as e:
await command._error_handler(command.cog or self, context, e)
self.dispatch("command_error", context, e)
@staticmethod
async def on_command_error(ctx: Context, error: Exception):
traceback.print_exception(type(error), error, error.__traceback__)
on_message = process_commands
async def bot_check(self, context: Context) -> bool:
"""A global check for the bot that stops commands from running on certain criteria.
Parameters
-----------
context: :class:`Context`
The context for the invokation of the command
Returns
--------
:class:`bool` represents if the command should run or not
"""
return True
def add_cog(self, cog: Cog):
"""Adds a cog to the bot, this cog must subclass `Cog`.
Parameters
-----------
cog: :class:`Cog`
The cog to be added
"""
cog._inject(self)
def remove_cog(self, cog_name: str) -> Cog:
"""Removes a cog from the bot.
Parameters
-----------
cog_name: :class:`str`
The name of the cog to be removed
Returns
--------
:class:`Cog`
The cog that was removed
"""
cog = self.cogs.pop(cog_name)
cog._uninject(self)
return cog
def load_extension(self, name: str):
"""Loads an extension, this takes a module name and runs the setup function inside of it.
Parameters
-----------
name: :class:`str`
The name of the extension to be loaded
"""
extension = import_module(name)
if not isinstance(extension, ExtensionProtocol):
raise MissingSetup(f"'{extension}' is missing a setup function")
self.extensions[name] = extension
extension.setup(self)
def unload_extension(self, name: str):
"""Unloads an extension, this takes a module name and runs the teardown function inside of it.
Parameters
-----------
name: :class:`str`
The name of the extension to be unloaded
"""
extension = self.extensions.pop(name)
del sys.modules[name]
if teardown := getattr(extension, "teardown", None):
teardown(self)
def reload_extension(self, name: str):
"""Reloads an extension, this will unload and reload the extension.
Parameters
-----------
name: :class:`str`
The name of the extension to be reloaded
"""
self.unload_extension(name)
self.load_extension(name)
def get_cog(self, name: str) -> Cog:
"""Gets a cog from the bot.
Parameters
-----------
name: :class:`str`
The name of the cog to get
Returns
--------
:class:`Cog`
The cog that was requested
"""
return self.cogs[name]
def get_extension(self, name: str) -> ExtensionProtocol:
"""Gets an extension from the bot.
Parameters
-----------
name: :class:`str`
The name of the extension to get
Returns
--------
:class:`ExtensionProtocol`
The extension that was requested
"""
return self.extensions[name]
+61
View File
@@ -0,0 +1,61 @@
from __future__ import annotations
from distutils import command
from typing import TYPE_CHECKING, Any, Optional
from .command import Command
if TYPE_CHECKING:
from .client import CommandsClient
__all__ = ("Cog", "CogMeta")
class CogMeta(type):
_commands: list[Command]
qualified_name: str
def __new__(cls, name: str, bases: tuple[type, ...], attrs: dict[str, Any], *, qualified_name: Optional[str] = None):
commands: list[Command] = []
self = super().__new__(cls, name, bases, attrs)
for base in reversed(self.__mro__):
for value in base.__dict__.values():
if isinstance(value, Command):
commands.append(value)
self._commands = commands
self.qualified_name = qualified_name or name
return self
class Cog(metaclass=CogMeta):
_commands: list[Command]
qualified_name: str
def cog_load(self):
"""A special method that is called when the cog gets loaded."""
pass
def cog_unload(self):
"""A special method that is called when the cog gets removed."""
pass
def _inject(self, client: CommandsClient):
client.cogs[self.qualified_name] = self
for command in self._commands:
command.cog = self
client.add_command(command)
self.cog_load()
def _uninject(self, client: CommandsClient):
for name, command in client.all_commands.copy().items():
if command in self._commands:
del client.all_commands[name]
self.cog_unload()
@property
def commands(self) -> list[Command]:
return self._commands
+162 -25
View File
@@ -1,23 +1,34 @@
from __future__ import annotations
import inspect
import traceback
from typing import TYPE_CHECKING, Any, Callable, Coroutine, Optional
from contextlib import suppress
from typing import (TYPE_CHECKING, Annotated, Any, Callable, Coroutine,
Literal, Optional, Union, cast, get_args, get_origin)
import revolt
from revolt.utils import copy_doc
from revolt.utils import copy_doc, maybe_coroutine
from .errors import InvalidLiteralArgument, UnionConverterError
from .utils import evaluate_parameters
if TYPE_CHECKING:
from .context import Context
from .checks import Check
from .group import Group
from .cog import Cog
__all__ = (
"Command",
"command"
)
NoneType = type(None)
class Command:
"""Class for holding info about a command.
Parameters
-----------
callback: Callable[..., Coroutine[Any, Any, Any]]
@@ -26,17 +37,29 @@ class Command:
The name of the command
aliases: list[:class:`str`]
The aliases of the command
parent: Optional[:class:`Group`]
The parent of the command if this command is a subcommand
cog: Optional[:class:`Cog`]
The cog the command is apart of.
usage: Optional[:class:`str`]
The usage string for the command
"""
__slots__ = ("callback", "name", "aliases", "_client")
__slots__ = ("callback", "name", "aliases", "signature", "checks", "parent", "_error_handler", "cog", "description", "usage", "parameters")
_client: revolt.Client
def __init__(self, callback: Callable[..., Coroutine[Any, Any, Any]], name: str, aliases: list[str]):
def __init__(self, callback: Callable[..., Coroutine[Any, Any, Any]], name: str, aliases: list[str], usage: Optional[str] = None):
self.callback = callback
self.name = name
self.aliases = aliases
self.usage = usage
self.signature = inspect.signature(self.callback)
self.parameters = evaluate_parameters(self.signature.parameters.values(), getattr(callback, "__globals__", {}))
self.checks: list[Check] = getattr(callback, "_checks", [])
self.parent: Optional[Group] = None
self.cog: Optional[Cog] = None
self._error_handler: Callable[[Any, Context, Exception], Coroutine[Any, Any, Any]] = type(self)._default_error_handler
self.description = callback.__doc__
async def invoke(self, context: Context, args: list[Any]) -> Any:
async def invoke(self, context: Context, *args, **kwargs) -> Any:
"""Runs the command and calls the error handler if the command errors.
Parameters
@@ -47,17 +70,17 @@ class Command:
The arguments for the command
"""
try:
return await self.callback(self._client, context, *args)
return await self.callback(self.cog or context.client, context, *args, **kwargs)
except Exception as err:
return await self._error_handler(context, err)
return await self._error_handler(self.cog or context.client, context, err)
@copy_doc(invoke)
def __call__(self, context: Context, args: list[Any]) -> Any:
return self.invoke(context, args)
def __call__(self, context: Context, *args, **kwargs) -> Any:
return self.invoke(context, *args, **kwargs)
def error(self, func: Callable[..., Coroutine[Any, Any, Any]]):
"""Sets the error handler for the command.
Parameters
-----------
func: Callable[..., Coroutine[Any, Any, Any]]
@@ -72,29 +95,143 @@ class Command:
await ctx.send(str(error))
"""
self._error_handler = func # type: ignore
self._error_handler = func
return func
@staticmethod
async def _error_handler(ctx: Context, error: Exception):
async def _default_error_handler(self, ctx: Context, error: Exception):
traceback.print_exception(type(error), error, error.__traceback__)
def command(*, name: Optional[str] = None, aliases: Optional[list[str]] = None, cls: type[Command] = Command):
"""Turns a function into a :class:`Command`.
@classmethod
async def handle_origin(cls, context: Context, origin: Any, annotation: Any, arg: str) -> Any:
if origin is Union:
for converter in get_args(annotation):
try:
return await cls.convert_argument(arg, converter, context)
except:
if converter is NoneType:
context.view.undo()
return None
raise UnionConverterError(arg)
elif origin is Annotated:
annotated_args = get_args(annotation)
if origin := get_origin(annotated_args[0]):
return await cls.handle_origin(context, origin, annotated_args[1], arg)
else:
return await cls.convert_argument(arg, annotated_args[1], context)
elif origin is Literal:
if arg in get_args(annotation):
return arg
else:
raise InvalidLiteralArgument(arg)
@classmethod
async def convert_argument(cls, arg: str, annotation: Any, context: Context) -> Any:
if annotation is not inspect.Signature.empty:
if annotation is str: # no converting is needed - its already a string
return arg
if origin := get_origin(annotation):
return await cls.handle_origin(context, origin, annotation, arg)
else:
return await maybe_coroutine(annotation, arg, context)
else:
return arg
async def parse_arguments(self, context: Context):
# please pr if you can think of a better way to do this
for parameter in self.parameters[2:]:
if parameter.kind == parameter.KEYWORD_ONLY:
try:
arg = await self.convert_argument(context.view.get_rest(), parameter.annotation, context)
except StopIteration:
if parameter.default is not parameter.empty:
arg = parameter.default
else:
raise
context.kwargs[parameter.name] = arg
elif parameter.kind == parameter.VAR_POSITIONAL:
with suppress(StopIteration):
while True:
context.args.append(await self.convert_argument(context.view.get_next_word(), parameter.annotation, context))
elif parameter.kind == parameter.POSITIONAL_OR_KEYWORD:
try:
rest = context.view.get_next_word()
arg = await self.convert_argument(rest, parameter.annotation, context)
except StopIteration:
if parameter.default is not parameter.empty:
arg = parameter.default
else:
raise
context.args.append(arg)
def __repr__(self) -> str:
return f"<{self.__class__.__name__} name=\"{self.name}\">"
@property
def short_description(self) -> Optional[str]:
"""Returns the first line of the description or None if there is no description."""
if self.description:
return self.description.split("\n")[0]
def get_usage(self) -> str:
"""Returns the usage string for the command."""
if self.usage:
return self.usage
parents = []
if self.parent:
parent = self.parent
while parent:
parents.append(parent.name)
parent = parent.parent
parameters = []
for parameter in self.parameters[2:]:
if parameter.kind == parameter.POSITIONAL_OR_KEYWORD:
if parameter.default is not parameter.empty:
parameters.append(f"[{parameter.name}]")
else:
parameters.append(f"<{parameter.name}>")
elif parameter.kind == parameter.KEYWORD_ONLY:
if parameter.default is not parameter.empty:
parameters.append(f"[{parameter.name}]")
else:
parameters.append(f"<{parameter.name}...>")
elif parameter.kind == parameter.VAR_POSITIONAL:
parameters.append(f"[{parameter.name}...]")
return f"{' '.join(parents[::-1])} {self.name} {' '.join(parameters)}"
def command(*, name: Optional[str] = None, aliases: Optional[list[str]] = None, cls: type[Command] = Command, usage: Optional[str] = None):
"""A decorator that turns a function into a :class:`Command`.
Parameters
-----------
name: Optional[:class:`str`]
The name of the command, this defaults to the functions name
aliases: Optional[list[:class:`str`]]
The aliases of the command, defaults to no aliases
cls: type[:class:`Command`]
The class used for creating the command, this defaults to :class:`Command` but can be used to use a custom command subclass
Returns
--------
:class:`Command`
The command
Callable[Callable[..., Coroutine], :class:`Command`]
A function that takes the command callback and returns a :class:`Command`
"""
def inner(func: Callable[..., Coroutine[Any, Any, Any]]):
return cls(func, name or func.__name__, aliases or [])
return cls(func, name or func.__name__, aliases or [], usage)
return inner
+60 -14
View File
@@ -1,20 +1,27 @@
from __future__ import annotations
from typing import Any, Optional
from typing import TYPE_CHECKING, Any, Generic, Optional, TypeVar
import revolt
from revolt.utils import copy_doc
from revolt.utils import maybe_coroutine
from .command import Command
from .group import Group
if TYPE_CHECKING:
from .client import CommandsClient
from .view import StringView
ClientT = TypeVar("ClientT", bound="CommandsClient")
__all__ = (
"Context",
)
class Context:
class Context(revolt.Messageable, Generic[ClientT]):
"""Stores metadata the commands execution.
Parameters
Attributes
-----------
command: Optional[:class:`Command`]
The command, this can be `None` when no command was found and the error handler is being executed
@@ -22,16 +29,39 @@ class Context:
The command name that was used, this can be an alias, the commands name or a command that doesnt exist
message: :class:`Message`
The message that was sent to invoke the command
channel: :class:`Messageable`
The channel the command was invoked in
server: :class:`Server`
The server the command was invoked in
author: Union[:class:`Member`, :class:`User`]
The user or member that invoked the commad, will be :class:`User` in DMs
args: list[:class:`str`]
The positional arguments being passed to the command
kwargs: dict[:class:`str`, Any]
The keyword arguments being passed to the command
client: :class:`CommandsClient`
The revolt client
"""
__slots__ = ("command", "invoked_with", "message")
__slots__ = ("command", "invoked_with", "args", "message", "server", "channel", "author", "view", "kwargs", "state", "client")
def __init__(self, command: Optional[Command], invoked_with: str, message: revolt.Message):
async def _get_channel_id(self) -> str:
return self.channel.id
def __init__(self, command: Optional[Command], invoked_with: str, view: StringView, message: revolt.Message, client: ClientT):
self.command = command
self.invoked_with = invoked_with
self.view = view
self.message = message
self.client = client
self.args = []
self.kwargs = {}
self.server = message.server
self.channel = message.channel
self.author = message.author
self.state = message.state
async def invoke(self, args: list[str]) -> Any:
"""Invokes the command, this is equal to `await context.command.invoke(context, args)`.
async def invoke(self) -> Any:
"""Invokes the command.
.. note:: If the command is `None`, this function will do nothing.
@@ -40,9 +70,25 @@ class Context:
args: list[:class:`str`]
The args being passed to the command
"""
if command := self.command:
return await command.invoke(self, args)
@copy_doc(revolt.Messageable.send)
async def send(self, content: Optional[str] = None, *, embeds: Optional[list[revolt.Embed]] = None, embed: Optional[revolt.Embed] = None, attachments: Optional[list[revolt.File]] = None) -> revolt.Message:
return await self.message.channel.send(content, embeds=embeds, embed=embed, attachments=attachments)
if command := self.command:
if isinstance(command, Group):
try:
subcommand_name = self.view.get_next_word()
except StopIteration:
pass
else:
if subcommand := command.subcommands.get(subcommand_name):
self.command = command = subcommand
return await self.invoke()
self.view.undo()
await command.parse_arguments(self)
return await command.invoke(self, *self.args, **self.kwargs)
async def can_run(self, command: Optional[Command] = None) -> bool:
"""Runs all of the commands checks, and returns true if all of them pass"""
command = command or self.command
return all([await maybe_coroutine(check, self) for check in (command.checks if command else [])])
+84
View File
@@ -0,0 +1,84 @@
import re
from typing import Annotated
from revolt import Category, Channel, Member, User, utils
from .context import Context
from .errors import (BadBoolArgument, CategoryConverterError,
ChannelConverterError, MemberConverterError, ServerOnly,
UserConverterError)
__all__ = ("bool_converter", "category_converter", "channel_converter", "user_converter", "member_converter", "IntConverter", "BoolConverter", "CategoryConverter", "UserConverter", "MemberConverter", "ChannelConverter")
channel_regex = re.compile("<#([A-z0-9]{26})>")
user_regex = re.compile("<@([A-z0-9]{26})>")
def bool_converter(arg: str, _):
lowered = arg.lower()
if lowered in ["yes", "true", "ye", "y", "1", "on", "enable"]:
return True
elif lowered in ('no', 'n', 'false', 'f', '0', 'disable', 'off'):
return False
else:
raise BadBoolArgument(lowered)
def category_converter(arg: str, context: Context) -> Category:
if not (server := context.server):
raise ServerOnly
try:
return server.get_category(arg)
except KeyError:
try:
return utils.get(server.categories, name=arg)
except LookupError:
raise CategoryConverterError(arg)
def channel_converter(arg: str, context: Context) -> Channel:
if not (server := context.server):
raise ServerOnly
if (match := channel_regex.match(arg)):
arg = match.group(1)
try:
return server.get_channel(arg)
except KeyError:
try:
return utils.get(server.channels, name=arg)
except LookupError:
raise ChannelConverterError(arg)
def user_converter(arg: str, context: Context) -> User:
if (match := user_regex.match(arg)):
arg = match.group(1)
try:
return context.client.get_user(arg)
except KeyError:
try:
return utils.get(context.client.users, name=arg)
except LookupError:
raise UserConverterError(arg)
def member_converter(arg: str, context: Context) -> Member:
if not (server := context.server):
raise ServerOnly
if (match := user_regex.match(arg)):
arg = match.group(1)
try:
return server.get_member(arg)
except KeyError:
try:
return utils.get(server.members, name=arg)
except LookupError:
raise MemberConverterError(arg)
IntConverter = Annotated[int, lambda arg, _: int(arg)]
BoolConverter = Annotated[bool, bool_converter]
CategoryConverter = Annotated[Category, category_converter]
UserConverter = Annotated[User, user_converter]
MemberConverter = Annotated[Member, member_converter]
ChannelConverter = Annotated[Channel, channel_converter]
+73 -2
View File
@@ -1,10 +1,29 @@
from revolt import RevoltError
__all__ = (
"CommandError",
"CommandNotFound",
"NoClosingQuote",
"CheckError",
"NotBotOwner",
"NotServerOwner",
"ServerOnly",
"ConverterError",
"InvalidLiteralArgument",
"BadBoolArgument",
"CategoryConverterError",
"ChannelConverterError",
"UserConverterError",
"MemberConverterError",
"MissingSetup",
)
class CommandNotFound(Exception):
class CommandError(RevoltError):
"""base error for all command's related errors"""
class CommandNotFound(CommandError):
"""Raised when a command isnt found.
Parameters
-----------
command_name: :class:`str`
@@ -14,3 +33,55 @@ class CommandNotFound(Exception):
def __init__(self, command_name: str):
self.command_name = command_name
class NoClosingQuote(CommandError):
"""Raised when there is no closing quote for a command argument"""
class CheckError(CommandError):
"""Raised when a check fails for a command"""
class NotBotOwner(CheckError):
"""Raised when the `is_bot_owner` check fails"""
class NotServerOwner(CheckError):
"""Raised when the `is_server_owner` check fails"""
class ServerOnly(CheckError):
"""Raised when a check requires the command to be ran in a server"""
class ConverterError(CommandError):
"""Base class for all converter errors"""
class InvalidLiteralArgument(ConverterError):
"""Raised when the argument is not a valid literal argument"""
class BadBoolArgument(ConverterError):
"""Raised when the bool converter fails"""
class CategoryConverterError(ConverterError):
"""Raised when the Category conveter fails"""
def __init__(self, argument: str):
self.argument = argument
class ChannelConverterError(ConverterError):
"""Raised when the Channel conveter fails"""
def __init__(self, argument: str):
self.argument = argument
class UserConverterError(ConverterError):
"""Raised when the Category conveter fails"""
def __init__(self, argument: str):
self.argument = argument
class MemberConverterError(ConverterError):
"""Raised when the Category conveter fails"""
def __init__(self, argument: str):
self.argument = argument
class UnionConverterError(ConverterError):
"""Raised when all converters in a union fails"""
def __init__(self, argument: str):
self.argument = argument
class MissingSetup(CommandError):
"""Raised when an extension is missing the `setup` function"""
+117
View File
@@ -0,0 +1,117 @@
from __future__ import annotations
from typing import TYPE_CHECKING, Optional, Callable, Coroutine, Any
from .command import Command
if TYPE_CHECKING:
from .context import Context
__all__ = (
"Group",
"group"
)
class Group(Command):
"""Class for holding info about a group command.
Parameters
-----------
callback: Callable[..., Coroutine[Any, Any, Any]]
The callback for the group command
name: :class:`str`
The name of the command
aliases: list[:class:`str`]
The aliases of the group command
subcommands: dict[:class:`str`, :class:`Command`]
The group's subcommands.
"""
__slots__ = ("subcommands",)
def __init__(self, callback: Callable[..., Coroutine[Any, Any, Any]], name: str, aliases: list[str]):
self.subcommands: dict[str, Command] = {}
super().__init__(callback, name, aliases)
def command(self, *, name: Optional[str] = None, aliases: Optional[list[str]] = None, cls: type[Command] = Command):
"""A decorator that turns a function into a :class:`Command` and registers the command as a subcommand.
Parameters
-----------
name: Optional[:class:`str`]
The name of the command, this defaults to the functions name
aliases: Optional[list[:class:`str`]]
The aliases of the command, defaults to no aliases
cls: type[:class:`Command`]
The class used for creating the command, this defaults to :class:`Command` but can be used to use a custom command subclass
Returns
--------
Callable[Callable[..., Coroutine], :class:`Command`]
A function that takes the command callback and returns a :class:`Command`
"""
def inner(func: Callable[..., Coroutine[Any, Any, Any]]):
command = cls(func, name or func.__name__, aliases or [])
command.parent = self
self.subcommands[command.name] = command
return command
return inner
def group(self, *, name: Optional[str] = None, aliases: Optional[list[str]] = None, cls: Optional[type["Group"]] = None):
"""A decorator that turns a function into a :class:`Group` and registers the command as a subcommand
Parameters
-----------
name: Optional[:class:`str`]
The name of the group command, this defaults to the functions name
aliases: Optional[list[:class:`str`]]
The aliases of the group command, defaults to no aliases
cls: type[:class:`Group`]
The class used for creating the command, this defaults to :class:`Group` but can be used to use a custom group subclass
Returns
--------
Callable[Callable[..., Coroutine], :class:`Group`]
A function that takes the command callback and returns a :class:`Group`
"""
cls = cls or type(self)
def inner(func: Callable[..., Coroutine[Any, Any, Any]]):
command = cls(func, name or func.__name__, aliases or [])
command.parent = self
self.subcommands[command.name] = command
return command
return inner
def __repr__(self) -> str:
return f"<Group name=\"{self.name}\">"
@property
def commands(self) -> list[Command]:
return list(self.subcommands.values())
def group(*, name: Optional[str] = None, aliases: Optional[list[str]] = None, cls: type[Group] = Group):
"""A decorator that turns a function into a :class:`Group`
Parameters
-----------
name: Optional[:class:`str`]
The name of the group command, this defaults to the functions name
aliases: Optional[list[:class:`str`]]
The aliases of the group command, defaults to no aliases
cls: type[:class:`Group`]
The class used for creating the command, this defaults to :class:`Group` but can be used to use a custom group subclass
Returns
--------
Callable[Callable[..., Coroutine], :class:`Group`]
A function that takes the command callback and returns a :class:`Group`
"""
def inner(func: Callable[..., Coroutine[Any, Any, Any]]):
return cls(func, name or func.__name__, aliases or [])
return inner
+195
View File
@@ -0,0 +1,195 @@
from __future__ import annotations
from abc import ABC, abstractmethod
from typing import TYPE_CHECKING, TypedDict, Union, Optional
from typing_extensions import NotRequired
from itertools import groupby
from .utils import evaluate_parameters
from .command import Command, command
from .client import CommandsClient
from .context import Context
from .group import Group
if TYPE_CHECKING:
from .cog import Cog
from revolt import SendableEmbed, File, MessageReply, Message, Messageable
__all__ = ("MessagePayload", "HelpCommand", "DefaultHelpCommand", "help_command_impl")
class MessagePayload(TypedDict):
content: str
embed: NotRequired[SendableEmbed]
embeds: NotRequired[list[SendableEmbed]]
attachments: NotRequired[list[File]]
replies: NotRequired[list[MessageReply]]
class HelpCommand(ABC):
@abstractmethod
async def create_bot_help(self, context: Context, commands: dict[Optional[Cog], list[Command]]) -> Union[str, SendableEmbed, MessagePayload]:
raise NotImplementedError
@abstractmethod
async def create_command_help(self, context: Context, command: Command) -> Union[str, SendableEmbed, MessagePayload]:
raise NotImplementedError
@abstractmethod
async def create_group_help(self, context: Context, group: Group) -> Union[str, SendableEmbed, MessagePayload]:
raise NotImplementedError
@abstractmethod
async def create_cog_help(self, context: Context, cog: Cog) -> Union[str, SendableEmbed, MessagePayload]:
raise NotImplementedError
async def send_help_command(self, context: Context, message_payload: MessagePayload) -> Message:
return await context.send(**message_payload)
async def filter_commands(self, context: Context, commands: list[Command]) -> list[Command]:
filtered: list[Command] = []
for command in commands:
try:
if await context.can_run(command):
filtered.append(command)
except Exception:
pass
return filtered
async def group_commands(self, context: Context, commands: list[Command]) -> dict[Optional[Cog], list[Command]]:
cogs = {}
for command in commands:
cogs.setdefault(command.cog, []).append(command)
return cogs
async def handle_message(self, context: Context, message: Message):
pass
async def get_channel(self, context: Context) -> Messageable:
return context
@abstractmethod
async def handle_no_command_found(self, context: Context, name: str):
raise NotImplementedError
@abstractmethod
async def handle_no_cog_found(self, context: Context, name: str):
raise NotImplementedError
class DefaultHelpCommand(HelpCommand):
def __init__(self, default_cog_name: str = "No Cog"):
self.default_cog_name = default_cog_name
async def create_bot_help(self, context: Context, commands: dict[Optional[Cog], list[Command]]) -> Union[str, SendableEmbed, MessagePayload]:
lines = ["```"]
for cog, cog_commands in commands.items():
cog_lines = []
cog_lines.append(f"{cog.qualified_name if cog else self.default_cog_name}:")
for command in cog_commands:
cog_lines.append(f" {command.name} - {command.short_description or 'No description'}")
lines.append("\n".join(cog_lines))
lines.append("```")
return "\n".join(lines)
async def create_cog_help(self, context: Context, cog: Cog) -> Union[str, SendableEmbed, MessagePayload]:
lines = ["```"]
lines.append(f"{cog.qualified_name}:")
for command in cog.commands:
lines.append(f" {command.name} - {command.short_description or 'No description'}")
lines.append("```")
return "\n".join(lines)
async def create_command_help(self, context: Context, command: Command) -> Union[str, SendableEmbed, MessagePayload]:
lines = ["```"]
lines.append(f"{command.name}:")
lines.append(f" Usage: {command.get_usage()}")
if command.aliases:
lines.append(f" Aliases: {', '.join(command.aliases)}")
if command.description:
lines.append(command.description)
lines.append("```")
return "\n".join(lines)
async def create_group_help(self, context: Context, group: Group) -> Union[str, SendableEmbed, MessagePayload]:
lines = ["```"]
lines.append(f"{group.name}:")
lines.append(f" Usage: {group.get_usage()}")
if group.aliases:
lines.append(f" Aliases: {', '.join(group.aliases)}")
if group.description:
lines.append(group.description)
for command in group.commands:
lines.append(f" {command.name} - {command.short_description or 'No description'}")
lines.append("```")
return "\n".join(lines)
async def handle_no_command_found(self, context: Context, name: str):
channel = await self.get_channel(context)
await channel.send(f"Command `{name}` not found.")
async def handle_no_cog_found(self, context: Context, name: str):
channel = await self.get_channel(context)
await channel.send(f"Cog `{name}` not found.")
class HelpCommandImpl(Command):
def __init__(self, client: CommandsClient):
self.client = client
super().__init__(callback=lambda _, context, *args: help_command_impl(self.client, context, *args), name="help", aliases=[])
self.description = "Shows help for a command, cog or the entire bot"
async def help_command_impl(self: CommandsClient, context: Context, *arguments: str):
filtered_commands = await context.client.help_command.filter_commands(context, self.commands)
commands = await self.help_command.group_commands(context, filtered_commands)
if not arguments:
payload = await self.help_command.create_bot_help(context, commands)
else:
command_name = arguments[0]
try:
command = self.get_command(command_name)
except KeyError:
cog = self.cogs.get(command_name)
if cog:
payload = await self.help_command.create_cog_help(context, cog)
else:
return await self.help_command.handle_no_command_found(context, command_name)
else:
if isinstance(command, Group):
payload = await self.help_command.create_group_help(context, command)
else:
payload = await self.help_command.create_command_help(context, command)
msg_payload: MessagePayload
if isinstance(payload, str):
msg_payload = {"content": payload}
elif isinstance(payload, SendableEmbed):
msg_payload = {"embed": payload, "content": " "}
else:
msg_payload = payload
await self.help_command.send_help_command(context, msg_payload)
-186
View File
@@ -1,186 +0,0 @@
from __future__ import annotations
from typing import Any, Callable, Union
import revolt
from .command import Command
from .context import Context
from .errors import CommandNotFound
__all__ = (
"CommandsMeta",
"CommandsMixin"
)
class CommandsMeta(type):
_commands: list[Command]
def __new__(cls, name: str, bases: tuple[type, ...], attrs: dict[str, Any]):
commands: list[Command] = []
for value in attrs.values():
if isinstance(value, Command):
commands.append(value)
self = super().__new__(cls, name, bases, attrs)
self._commands = commands
for command in commands:
command._client = self # type: ignore
return self
class CommandsMixin(metaclass=CommandsMeta):
"""Main class that adds commands, this class should be subclassed along with `revolt.Client`."""
__slots__ = ("_commands", "all_commands")
_commands: list[Command]
dispatch: Callable[..., None]
def __init__(self, *args, **kwargs):
self.all_commands = {}
for command in self._commands:
self.all_commands[command.name] = command
for alias in command.aliases:
self.all_commands[alias] = command
super().__init__(*args, **kwargs)
@property
def commands(self) -> list[Command]:
return list(set(self.all_commands.values()))
async def get_prefix(self, message: revolt.Message) -> Union[str, list[str]]:
"""Overwrite this function to set the prefix used for commands, this function is called for every message.
Parameters
-----------
message: :class:`Message`
The message that was sent
Returns
--------
Union[:class:`str`, list[:class:`str`]]
The prefix(s) for the commands
"""
raise NotImplementedError
def get_command(self, name: str) -> Command:
"""Gets a command.
Parameters
-----------
name: :class:`str`
The name or alias of the command
Returns
--------
:class:`Command`
The command with the name
"""
return self.all_commands[name]
def add_command(self, name: str, command: Command):
"""Adds a command, this is typically only used for dynamic commands, you should use the `commands.command` decorator for most usecases.
Parameters
-----------
name: :class:`str`
The name or alias of the command
command: :class:`Command`
The command to be added
"""
self.all_commands[name] = command
def split_content(self, content: str) -> list[str]:
"""Splits a string into seperate parameters, overwrite this function to change how arguments are split.
Parameters
-----------
content: :class:`str`
The content of the message
Returns
--------
list[:class:`str`]
The arguments from the content
"""
args = []
temp: list[str] = []
quoted = False
quote_char = ""
for char in content:
if char == " " and not quoted:
args.append("".join(temp))
temp = []
elif char in ["\"", "'"] and not quoted:
quoted = True
quote_char = char
elif char == quote_char and quoted:
quoted = False
args.append("".join(temp))
else:
temp.append(char)
return args
def get_context(self, message: revolt.Message) -> type[Context]:
return Context
async def process_commands(self, message: revolt.Message) -> Any:
"""Processes commands, if you overwrite `Client.on_message` you should manually call this function inside the event.
Parameters
-----------
message: :class:`Message`
The message to process commands on
Returns
--------
Any
The return of the command, if any
"""
content = message.content
if not isinstance(content, str):
return
prefixes = await self.get_prefix(message)
if isinstance(prefixes, str):
prefixes = [prefixes]
for prefix in prefixes:
if content.startswith(prefix):
content = content[len(prefix):]
break
else:
return
if not content:
return
command_name, *args = self.split_content(content)
try:
command = self.get_command(command_name)
except KeyError:
return self.dispatch("command_error", Context(None, command_name, message), CommandNotFound(command_name))
context = self.get_context(message)(command, command_name, message)
try:
return await context.invoke(args)
except Exception as e:
self.dispatch("command_error", context, e)
on_message = process_commands
+16
View File
@@ -0,0 +1,16 @@
from inspect import Parameter
from typing import Iterable, Any
__all__ = ("evaluate_parameters",)
def evaluate_parameters(parameters: Iterable[Parameter], globals: dict[str, Any]) -> list[Parameter]:
new_parameters = []
for parameter in parameters:
if parameter.annotation is not parameter.empty:
if isinstance(parameter.annotation, str):
parameter = parameter.replace(annotation=eval(parameter.annotation, globals))
new_parameters.append(parameter)
return new_parameters
+52
View File
@@ -0,0 +1,52 @@
from .errors import NoClosingQuote
class StringView:
def __init__(self, string: str):
self.value = iter(string)
self.temp = ""
self.should_undo = False
def undo(self):
self.should_undo = True
def next_char(self) -> str:
return next(self.value)
def get_rest(self) -> str:
if self.should_undo:
return f"{self.temp} {''.join(self.value)}"
return "".join(self.value)
def get_next_word(self) -> str:
if self.should_undo:
self.should_undo = False
return self.temp
char = self.next_char()
temp: list[str] = []
while char == " ":
char = self.next_char()
if char in ["\"", "'"]:
quote = char
try:
while (char := self.next_char()) != quote:
temp.append(char)
except StopIteration:
raise NoClosingQuote
else:
temp.append(char)
try:
while (char := self.next_char()) not in " \n":
temp.append(char)
except StopIteration:
pass
output = "".join(temp)
self.temp = output
return output
+146
View File
@@ -0,0 +1,146 @@
from __future__ import annotations
from typing import Callable, Iterator, Optional, TypeVar, Union, overload
__all__ = ("flag_value", "Flags", "UserBadges")
F_T = TypeVar("F_T", bound="Flags")
F_V = TypeVar("F_V", bound="flag_value")
class flag_value:
__slots__ = ("flag", "__doc__")
def __init__(self, func: Callable[[], int]):
self.flag = func()
self.__doc__ = func.__doc__
@overload
def __get__(self: F_V, instance: None, owner: type[F_T]) -> F_V:
...
@overload
def __get__(self, instance: F_T, owner: type[F_T]) -> bool:
...
def __get__(self: F_V, instance: Optional[F_T], owner: type[F_T]) -> Union[F_V, bool]:
if instance is None:
return self
return instance._check_flag(self.flag)
def __set__(self, instance: Flags, value: bool):
instance._set_flag(self.flag, value)
class Flags:
def __init__(self, **kwargs: bool):
self.value = 0
for k, v in kwargs.items():
setattr(self, k, v)
@classmethod
def _from_value(cls: type[F_T], value: int) -> F_T:
self = cls.__new__(cls)
self.value = value
return self
def _check_flag(self, flag: int) -> bool:
return (self.value & flag) == flag
def _set_flag(self, flag: int, value: bool):
if value:
self.value |= flag
else:
self.value &= ~flag
def __eq__(self: F_T, other: F_T) -> bool:
return self.value == other.value
def __ne__(self: F_T, other: F_T) -> bool:
return not self.__eq__(other)
def __or__(self: F_T, other: F_T) -> F_T:
return self.__class__._from_value(self.value | other.value)
def __and__(self: F_T, other: F_T) -> F_T:
return self.__class__._from_value(self.value & other.value)
def __invert__(self: F_T) -> F_T:
return self.__class__._from_value(~self.value)
def __add__(self: F_T, other: F_T) -> F_T:
return self | other
def __sub__(self: F_T, other: F_T) -> F_T:
return self & ~other
def __lt__(self: F_T, other: F_T) -> bool:
return self.value < other.value
def __gt__(self: F_T, other: F_T) -> bool:
return self.value > other.value
def __repr__(self):
return f"<{self.__class__.__name__} value={self.value}>"
def __iter__(self) -> Iterator[tuple[str, bool]]:
for name, value in self.__class__.__dict__.items():
if isinstance(value, flag_value):
yield name, value.__get__(self, self.__class__)
def __hash__(self) -> int:
return hash(self.value)
class UserBadges(Flags):
"""Contains all user badges"""
@flag_value
def developer():
""":class:`bool` The developer badge."""
return 1 << 0
@flag_value
def translator():
""":class:`bool` The translator badge."""
return 1 << 1
@flag_value
def supporter():
""":class:`bool` The supporter badge."""
return 1 << 2
@flag_value
def responsible_disclosure():
""":class:`bool` The responsible disclosure badge."""
return 1 << 3
@flag_value
def founder():
""":class:`bool` The founder badge."""
return 1 << 4
@flag_value
def platform_moderation():
""":class:`bool` The platform moderation badge."""
return 1 << 5
@flag_value
def active_supporter():
""":class:`bool` The active supporter badge."""
return 1 << 6
@flag_value
def paw():
""":class:`bool` The paw badge."""
return 1 << 7
@flag_value
def early_adopter():
""":class:`bool` The early adopter badge."""
return 1 << 8
@flag_value
def reserved_relevant_joke_badge_1():
""":class:`bool` The reserved relevant joke badge 1 badge."""
return 1 << 9
+90 -22
View File
@@ -6,6 +6,8 @@ from typing import (TYPE_CHECKING, Any, Coroutine, Literal, Optional, TypeVar,
import aiohttp
import ulid
from revolt.utils import Missing
from .errors import HTTPError, ServerError
from .file import File
@@ -23,13 +25,14 @@ if TYPE_CHECKING:
from .types import Autumn as AutumnPayload
from .types import Channel, DMChannel
from .types import Embed as EmbedPayload
from .types import GetServerMembers, Member
from .types import GetServerMembers, Invite
from .types import Masquerade as MasqueradePayload
from .types import Message as MessagePayload
from .types import (MessageWithUserData, Role, Server, ServerBans,
ServerInvite, TextChannel)
from .types import (MessageReplyPayload, MessageWithUserData,
PartialInvite, Role, Server, ServerBans, TextChannel)
from .types import User as UserPayload
from .types import UserProfile, VoiceChannel
from .types import UserProfile, VoiceChannel, GroupDMChannel, Member
from .types import SendableEmbed as SendableEmbedPayload
__all__ = ("HttpClient",)
@@ -37,22 +40,23 @@ T = TypeVar("T")
Request = Coroutine[Any, Any, T]
class HttpClient:
__slots__ = ("session", "token", "api_url", "api_info")
__slots__ = ("session", "token", "api_url", "api_info", "auth_header")
def __init__(self, session: aiohttp.ClientSession, token: str, api_url: str, api_info: ApiInfo):
def __init__(self, session: aiohttp.ClientSession, token: str, api_url: str, api_info: ApiInfo, bot: bool = True):
self.session = session
self.token = token
self.api_url = api_url
self.api_info = api_info
self.auth_header = "x-bot-token" if bot else "x-session-token"
async def request(self, method: Literal["GET", "POST", "PUT", "DELETE", "PATCH"], route: str, *, json: Optional[dict[str, Any]] = None, nonce: bool = True, params: Optional[dict[str, Any]] = None) -> Any:
url = f"{self.api_url}{route}"
kwargs = {}
headers = {
"User-Agent": "Revolt.py https://github.com/Zomatree/revolt.py",
"x-bot-token": self.token
"User-Agent": "Revolt.py (https://github.com/revoltchat/revolt.py)",
self.auth_header: self.token
}
if json:
@@ -71,7 +75,10 @@ class HttpClient:
async with self.session.request(method, url, **kwargs) as resp:
text = await resp.text()
if text:
response = _json.loads(await resp.text())
try:
response = _json.loads(await resp.text())
except ValueError:
raise HTTPError(f"Invalid json response:\n{text}") from None
else:
response = text
@@ -79,14 +86,14 @@ class HttpClient:
if 200 <= resp_code <= 300:
return response
elif resp_code == 400:
raise HTTPError
else:
raise HTTPError(resp_code)
async def upload_file(self, file: File, tag: str) -> AutumnPayload:
url = f"{self.api_info['features']['autumn']['url']}/{tag}"
headers = {
"User-Agent": "Revolt.py https://github.com/Zomatree/revolt.py"
"User-Agent": "Revolt.py (https://github.com/revoltchat/revolt.py)"
}
form = aiohttp.FormData()
@@ -104,12 +111,12 @@ class HttpClient:
else:
return response
async def send_message(self, channel: str, content: Optional[str], embeds: Optional[list[EmbedPayload]], attachments: Optional[list[File]]) -> MessagePayload:
async def send_message(self, channel: str, content: Optional[str], embeds: Optional[list[SendableEmbedPayload]], attachments: Optional[list[File]], replies: Optional[list[MessageReplyPayload]], masquerade: Optional[MasqueradePayload]) -> MessagePayload:
json: dict[str, Any] = {}
if content:
json["content"] = content
if embeds:
json["embeds"] = embeds
@@ -119,13 +126,26 @@ class HttpClient:
for attachment in attachments:
data = await self.upload_file(attachment, "attachments")
attachment_ids.append(data["id"])
json["attachments"] = attachment_ids
if replies:
json["replies"] = replies
if masquerade:
json["masquerade"] = masquerade
return await self.request("POST", f"/channels/{channel}/messages", json=json)
def edit_message(self, channel: str, message: str, content: str) -> Request[None]:
json = {"content": content}
def edit_message(self, channel: str, message: str, content: Optional[str], embeds: Optional[list[SendableEmbedPayload]] = None) -> Request[None]:
json = {}
if content is not None:
json["content"] = content
if embeds is not None:
json["embeds"] = embeds
return self.request("PATCH", f"/channels/{channel}/messages/{message}", json=json)
def delete_message(self, channel: str, message: str) -> Request[None]:
@@ -259,7 +279,7 @@ class HttpClient:
def fetch_default_avatar(self, user_id: str) -> Request[bytes]:
return self.request_file(f"{self.api_url}/users/{user_id}/default_avatar")
def fetch_dm_channels(self) -> Request[list[Channel]]:
def fetch_dm_channels(self) -> Request[list[Union[DMChannel, GroupDMChannel]]]:
return self.request("GET", "/users/dms")
def open_dm(self, user_id: str) -> Request[DMChannel]:
@@ -285,6 +305,14 @@ class HttpClient:
def delete_leave_server(self, server_id: str) -> Request[None]:
return self.request("DELETE", f"/servers/{server_id}")
@overload
def create_channel(self, server_id: str, channel_type: Literal["Text"], name: str, description: Optional[str]) -> Request[TextChannel]:
...
@overload
def create_channel(self, server_id: str, channel_type: Literal["Voice"], name: str, description: Optional[str]) -> Request[VoiceChannel]:
...
def create_channel(self, server_id: str, channel_type: Literal["Text", "Voice"], name: str, description: Optional[str]) -> Request[Union[TextChannel, VoiceChannel]]:
payload = {
"type": channel_type,
@@ -296,7 +324,7 @@ class HttpClient:
return self.request("POST", f"/servers/{server_id}/channels", json=payload)
def fetch_server_invites(self, server_id: str) -> Request[list[ServerInvite]]:
def fetch_server_invites(self, server_id: str) -> Request[list[PartialInvite]]:
return self.request("GET", f"/servers/{server_id}/invites")
def fetch_member(self, server_id: str, member_id: str) -> Request[Member]:
@@ -344,3 +372,43 @@ class HttpClient:
def delete_role(self, server_id: str, role_id: str) -> Request[None]:
return self.request("DELETE", f"/servers/{server_id}/roles/{role_id}")
def fetch_invite(self, code: str) -> Request[Invite]:
return self.request("GET", f"/invites/{code}")
def delete_invite(self, code: str) -> Request[None]:
return self.request("DELETE", f"/invites/{code}")
def edit_channel(self, channel_id: str, remove: Optional[str], values: dict[str, Any]):
if remove:
values["remove"] = remove
return self.request("PATCH", f"/channels/{channel_id}", json=values)
def edit_role(self, server_id: str, role_id: str, remove: Optional[str], values: dict[str, Any]):
if remove:
values["remove"] = remove
return self.request("PATCH", f"/servers/{server_id}/roles/{role_id}", json=values)
async def edit_self(self, remove: Optional[str], values: dict[str, Any]):
if remove:
values["remove"] = remove
if avatar := values.get("avatar"):
asset = await self.upload_file(avatar, "avatars")
values["avatar"] = asset["id"]
if profile := values.get("profile"):
if background := profile.background():
asset = await self.upload_file(background, "backgrounds")
profile["background"] = asset["id"]
if not values.get("profile", Missing):
del values["profile"]
if not values.get("status", Missing):
del values["status"]
print(remove, values)
return await self.request("PATCH", "/users/@me", json=values)
+67
View File
@@ -0,0 +1,67 @@
from __future__ import annotations
from typing import TYPE_CHECKING
from .asset import Asset
if TYPE_CHECKING:
from .state import State
from .types import Invite as InvitePayload
__all__ = ("Invite",)
class Invite:
"""Represents a server invite.
Attributes
-----------
code: :class:`str`
The code for the invite
server: :class:`Server`
The server this invite is for
channel: :class:`Channel`
The channel this invite is for
user_name: :class:`str`
The name of the user who made the invite
user: Optional[:class:`User`]
The user who made the invite, this is only set if this was fetched via :meth:`Server.fetch_invites`
user_avatar: Optional[:class:`Asset`]
The invite creator's avatar, if any
member_count: :class:`int`
The member count of the server this invite is for
"""
def __init__(self, data: InvitePayload, code: str, state: State):
self.state = state
self.code = code
self.server = state.get_server(data["server_id"])
self.channel = self.server.get_channel(data["channel_id"])
self.user_name = data["user_name"]
self.user = None
if avatar := data.get("user_avatar"):
self.user_avatar = Asset(avatar, state)
else:
self.user_avatar = None
self.member_count = data["member_count"]
@staticmethod
def _from_partial(code: str, server: str, creator: str, channel: str, state: State) -> Invite:
invite = Invite.__new__(Invite)
invite.state = state
invite.code = code
invite.server = state.get_server(server)
invite.channel = state.get_channel(channel)
invite.user = state.get_user(creator)
invite.user_name = invite.user.name
invite.user_avatar = invite.user.avatar
invite.member_count = len(invite.server.members)
return invite
async def delete(self):
"""Deletes the invite"""
await self.state.http.delete_invite(self.code)
+46 -13
View File
@@ -2,14 +2,15 @@ from __future__ import annotations
from typing import TYPE_CHECKING, Optional
from .asset import Asset
from .user import User
if TYPE_CHECKING:
from .server import Server
from .state import State
from .types import File
from .types import Member as MemberPayload
__all__ = ("Member",)
def flattern_user(member: Member, user: User):
@@ -27,31 +28,63 @@ class Member(User):
The roles of the member, ordered by the role's rank in decending order
server: :class:`Server`
The server the member belongs to
guild_avatar: Optional[:class:`Asset`]
The member's guild avatar if any
"""
__slots__ = ("_state", "nickname", "roles", "server")
__slots__ = ("_state", "nickname", "roles", "server", "guild_avatar")
def __init__(self, data: MemberPayload, server: Server, state: State):
user = state.get_user(data["_id"]["user"])
assert user
flattern_user(self, user)
self._state = state
self.nickname = data.get("nickname")
roles = []
for role in (server.get_role(role_id) for role_id in data.get("roles", [])):
if role:
roles.append(role)
if avatar := data.get("avatar"):
self.guild_avatar = Asset(avatar, state)
else:
self.guild_avatar = None
roles = [server.get_role(role_id) for role_id in data.get("roles", [])]
self.roles = sorted(roles, key=lambda role: role.rank, reverse=True)
self.server = server
@property
def owner(self) -> Optional[User]:
owner_id = self.owner_id
def avatar(self) -> Optional[Asset]:
"""Optional[:class:`Asset`] The avatar the member is displaying, this includes guild avatars and masqueraded avatar"""
return self.masquerade_avatar or self.guild_avatar or self.original_avatar
if not owner_id:
return
@property
def mention(self) -> str:
""":class:`str`: Returns a string that allows you to mention the given member."""
return f"<@{self.id}>"
return self.state.get_user(owner_id)
def _update(self, *, nickname: Optional[str] = None, avatar: Optional[File] = None, roles: Optional[list[str]] = None):
if nickname:
self.nickname = nickname
if avatar:
self.guild_avatar = Asset(avatar, self.state)
if roles:
member_roles = [self.server.get_role(role_id) for role_id in roles]
self.roles = sorted(member_roles, key=lambda role: role.rank, reverse=True)
async def kick(self):
"""Kicks the member from the server"""
await self.state.http.kick_member(self.server.id, self.id)
async def ban(self, *, reason: Optional[str] = None):
"""Bans the member from the server
Parameters
-----------
reason: Optional[:class:`str`]
The reason for the ban
"""
await self.state.http.ban_member(self.server.id, self.id, reason)
async def unban(self):
"""Unbans the member from the server"""
await self.state.http.unban_member(self.server.id, self.id)
+110 -20
View File
@@ -1,22 +1,29 @@
from __future__ import annotations
import datetime
from typing import TYPE_CHECKING, Optional
from typing import TYPE_CHECKING, NamedTuple, Optional
from .asset import Asset
from .asset import Asset, PartialAsset
from .channel import Messageable
from .embed import Embed
from .embed import to_embed, SendableEmbed
if TYPE_CHECKING:
from .state import State
from .types import Masquerade as MasqueradePayload
from .types import Message as MessagePayload
from .types import MessageReplyPayload
from .types import Embed as EmbedPayload
__all__ = ("Message",)
__all__ = (
"Message",
"MessageReply",
"Masquerade"
)
class Message:
"""Represents a message
Attributes
-----------
id: :class:`str`
@@ -25,7 +32,7 @@ class Message:
The content of the message, this will not include system message's content
attachments: list[:class:`Asset`]
The attachments of the message
embeds: list[:class:`Embed`]
embeds: list[Union[:class:`WebsiteEmbed`, :class:`ImageEmbed`, :class:`TextEmbed`, :class:`NoneEmbed`]]
The embeds of the message
channel: :class:`Messageable`
The channel the message was sent in
@@ -35,52 +42,135 @@ class Message:
The author of the message, will be :class:`User` in DMs
edited_at: Optional[:class:`datetime.datetime`]
The time at which the message was edited, will be None if the message has not been edited
mentions: list[Union[:class:`Member`, :class:`User`]]
The users or members that where mentioned in the message
replies: list[:class:`Message`]
The message's this message has replied to, this may not contain all the messages if they are outside the cache
reply_ids: list[:class:`str`]
The message's ids this message has replies to
"""
__slots__ = ("state", "id", "content", "attachments", "embeds", "channel", "server", "author", "edited_at")
__slots__ = ("state", "id", "content", "attachments", "embeds", "channel", "server", "author", "edited_at", "mentions", "replies", "reply_ids")
def __init__(self, data: MessagePayload, state: State):
self.state = state
self.id = data["_id"]
self.content = data["content"]
self.attachments = [Asset(attachment, state) for attachment in data.get("attachments", [])]
self.embeds = [Embed.from_dict(embed) for embed in data.get("embeds", [])]
self.embeds = [to_embed(embed, state) for embed in data.get("embeds", [])]
channel = state.get_channel(data["channel"])
assert isinstance(channel, Messageable)
self.channel = channel
self.server = self.channel and self.channel.server
if self.server:
author = state.get_member(self.server.id, data["author"])
else:
author = state.get_user(data["author"])
assert author
self.author = author
self.edited_at: Optional[datetime.datetime] = None
if masquerade := data.get("masquerade"):
if name := masquerade.get("name"):
self.author.masquerade_name = name
def _update(self, *, content: Optional[str] = None, edited_at: Optional[str] = None) -> Message:
if avatar := masquerade.get("avatar"):
self.author.masquerade_avatar = PartialAsset(avatar, state)
if edited_at := data.get("edited"):
self.edited_at: Optional[datetime.datetime] = datetime.datetime.strptime(edited_at["$date"], "%Y-%m-%dT%H:%M:%S.%f%z")
if self.server:
self.mentions = [self.server.get_member(member_id) for member_id in data.get("mentions", [])]
else:
self.mentions = [state.get_user(member_id) for member_id in data.get("mentions", [])]
self.replies = []
self.reply_ids = []
for reply in data.get("replies", []):
try:
message = state.get_message(reply)
self.replies.append(message)
except KeyError:
pass
self.reply_ids.append(reply)
def _update(self, *, content: Optional[str] = None, embeds: Optional[list[EmbedPayload]] = None, edited_at: str):
if content:
self.content = content
if edited_at:
self.edited_at = datetime.datetime.strptime(edited_at, "%Y-%m-%dT%H:%M:%S.%f%z")
# strptime is used here instead of fromisoformat because of its inability to parse `Z` (Zulu or UTC time) in the RFCC 3339 format provided by API
self.edited_at = datetime.datetime.strptime(edited_at, "%Y-%m-%dT%H:%M:%S.%f%z")
# strptime is used here instead of fromisoformat because of its inability to parse `Z` (Zulu or UTC time) in the RFCC 3339 format provided by API
return self
if embeds:
self.embeds = [to_embed(embed, self.state) for embed in embeds]
async def edit(self, *, content: str) -> None:
async def edit(self, *, content: Optional[str] = None, embeds: Optional[list[SendableEmbed]] = None) -> None:
"""Edits the message. The bot can only edit its own message
Parameters
-----------
content: :class:`str`
The new content of the message
"""
await self.state.http.edit_message(self.channel.id, self.id, content)
new_embeds = [embed.to_dict() for embed in embeds] if embeds else None
await self.state.http.edit_message(self.channel.id, self.id, content, new_embeds)
async def delete(self) -> None:
"""Deletes the message. The bot can only delete its own messages and messages it has permission to delete """
await self.state.http.delete_message(self.channel.id, self.id)
def reply(self, *args, mention: bool = False, **kwargs):
"""Replies to this message, equivilant to:
.. code-block:: python
await channel.send(..., replies=[MessageReply(message, mention)])
"""
return self.channel.send(*args, **kwargs, replies=[MessageReply(self, mention)])
class MessageReply(NamedTuple):
"""A namedtuple which represents a reply to a message.
Parameters
-----------
message: :class:`Message`
The message being replied to.
mention: :class:`bool`
Whether the reply should mention the author of the message. Defaults to false.
"""
message: Message
mention: bool = False
def to_dict(self) -> MessageReplyPayload:
return { "id": self.message.id, "mention": self.mention }
class Masquerade(NamedTuple):
"""A namedtuple which represents a message's masquerade.
Parameters
-----------
name: Optional[:class:`str`]
The name to display for the message
avatar: Optional[:class:`str`]
The avatar's url to display for the message
"""
name: Optional[str] = None
avatar: Optional[str] = None
def to_dict(self) -> MasqueradePayload:
output: MasqueradePayload = {}
if name := self.name:
output["name"] = name
if avatar := self.avatar:
output["avatar"] = avatar
return output
+87 -9
View File
@@ -2,10 +2,12 @@ from __future__ import annotations
from typing import TYPE_CHECKING, Optional
from .enums import SortType
if TYPE_CHECKING:
from .embed import Embed
from .embed import Embed, SendableEmbed
from .file import File
from .message import Message
from .message import Masquerade, Message, MessageReply
from .state import State
@@ -13,18 +15,20 @@ __all__ = ("Messageable",)
class Messageable:
"""Base class for all channels that you can send messages in
Attributes
-----------
id: :class:`str`
The id of the channel
"""
id: str
state: State
__slots__ = ()
async def send(self, content: Optional[str] = None, *, embeds: Optional[list[Embed]] = None, embed: Optional[Embed] = None, attachments: Optional[list[File]] = None) -> Message:
async def _get_channel_id(self) -> str:
raise NotImplementedError
async def send(self, content: Optional[str] = None, *, embeds: Optional[list[SendableEmbed]] = None, embed: Optional[SendableEmbed] = None, attachments: Optional[list[File]] = None, replies: Optional[list[MessageReply]] = None, reply: Optional[MessageReply] = None, masquerade: Optional[Masquerade] = None) -> Message:
"""Sends a message in a channel, you must send at least one of either `content`, `embeds` or `attachments`
Parameters
@@ -33,8 +37,12 @@ class Messageable:
The content of the message, this will not include system message's content
attachments: Optional[list[:class:`File`]]
The attachments of the message
embeds: Optional[list[:class:`Embed`]]
The embeds of the message
embed: Optional[:class:`SendableEmbed`]
The embed to send with the message
embeds: Optional[list[:class:`SendableEmbed`]]
The embeds to send with the message
replies: Optional[list[:class:`MessageReply`]]
The list of messages to reply to.
Returns
--------
@@ -44,7 +52,77 @@ class Messageable:
if embed:
embeds = [embed]
embed_payload = [embed.to_dict() for embed in embeds] if embeds else None
if reply:
replies = [reply]
message = await self.state.http.send_message(self.id, content, embed_payload, attachments)
embed_payload = [embed.to_dict() for embed in embeds] if embeds else None
reply_payload = [reply.to_dict() for reply in replies] if replies else None
masquerade_payload = masquerade.to_dict() if masquerade else None
message = await self.state.http.send_message(await self._get_channel_id(), content, embed_payload, attachments, reply_payload, masquerade_payload)
return self.state.add_message(message)
async def fetch_message(self, message_id: str) -> Message:
"""Fetches a message from the channel
Parameters
-----------
message_id: :class:`str`
The id of the message you want to fetch
Returns
--------
:class:`Message`
The message with the matching id
"""
payload = await self.state.http.fetch_message(await self._get_channel_id(), message_id)
return Message(payload, self.state)
async def history(self, *, sort: SortType = SortType.latest, limit: int = 100, before: Optional[str] = None, after: Optional[str] = None, nearby: Optional[str] = None) -> list[Message]:
"""Fetches multiple messages from the channel's history
Parameters
-----------
sort: :class:`SortType`
The order to sort the messages in
limit: :class:`int`
How many messages to fetch
before: Optional[:class:`str`]
The id of the message which should come *before* all the messages to be fetched
after: Optional[:class:`str`]
The id of the message which should come *after* all the messages to be fetched
nearby: Optional[:class:`str`]
The id of the message which should be nearby all the messages to be fetched
Returns
--------
list[:class:`Message`]
The messages found in order of the sort parameter
"""
payloads = await self.state.http.fetch_messages(await self._get_channel_id(), sort=sort, limit=limit, before=before, after=after, nearby=nearby)
return [Message(payload, self.state) for payload in payloads]
async def search(self, query: str, *, sort: SortType = SortType.latest, limit: int = 100, before: Optional[str] = None, after: Optional[str] = None) -> list[Message]:
"""searches the channel for a query
Parameters
-----------
query: :class:`str`
The query to search for in the channel
sort: :class:`SortType`
The order to sort the messages in
limit: :class:`int`
How many messages to fetch
before: Optional[:class:`str`]
The id of the message which should come *before* all the messages to be fetched
after: Optional[:class:`str`]
The id of the message which should come *after* all the messages to be fetched
Returns
--------
list[:class:`Message`]
The messages found in order of the sort parameter
"""
payloads = await self.state.http.search_messages(await self._get_channel_id(), query, sort=sort, limit=limit, before=before, after=after)
return [Message(payload, self.state) for payload in payloads]
+66 -265
View File
@@ -1,15 +1,11 @@
from __future__ import annotations
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from .types import Permission as PermissionTuple
from .flags import Flags, flag_value
__all__ = (
"ChannelPermissions",
"ServerPermissions"
)
)
# Channel permissions
#
@@ -37,315 +33,120 @@ __all__ = (
# ChangeAvatar = 0b00000000000000000100000000000000 // 16382
# RemoveAvatars = 0b00000000000000001000000000000000 // 32768
class _Permission:
__slots__ = ("_value",)
def __init__(self, value: int):
self._value = value
def __or__(self, p: _Permission):
self._value |= p._value
return self
def __and__(self, p: _Permission):
self._value &= p._value
return self
def __invert__(self):
self._value = ~self._value
return self
def __add__(self, p: _Permission):
# For example we have a bit array `0011` representing permissions
# To allow a permission we would convert the bit for that permission from 0 to 1
# Let's say we want to allow permissions with bit array `0101`
# Our desired result is `0111` which can be achieved by simple OR (A+B)
return self | p
def __sub__(self, p: _Permission):
# For example we have a bit array `0011` representing permissions
# To deny a permission we would convert the bit for that permission from 1 to 0
# Let's say we want to deny permissions with bit array `0101`
# Our desired result is `0010` which can be achieved by Selective Clear Algorithm (A.B')
return self & ~p
def __lt__(self, p: _Permission):
return self._value < p._value
def __gt__(self, p: _Permission):
return self._value > p._value
def __eq__(self, p: _Permission):
return self._value == p._value
def __repr__(self):
return f"{self.__class__.__name__}<{self._value:032b}>"
def _check(self, bit_pos: int):
# To check if a permission is present we would need to compare the bit for that position in our bit array
# For example if we have permission `0100` and we need to check if it is present in our bit array `0101`
# We need to compare the 3rd bit from the left, so we shift it 2 places (n-1) and perform AND with 1
# If the result is 1 the bit was 1 and the permission is present
return (self._value >> bit_pos) & 1 == 1
class ChannelPermissions(_Permission):
class ChannelPermissions(Flags):
"""Represents the channel permissions for a role as seen in channel settings."""
__slots__ = ()
@property
def value(self) -> int:
return self._value
@classmethod
def none(cls) -> ChannelPermissions:
return cls(0)
return cls._from_value(0)
@classmethod
def all(cls) -> ChannelPermissions:
# channel permissions here do not have manage messages permission
return cls(0b00000000000000000000000011111011)
return cls._from_value(0b11111111)
@classmethod
def view(cls) -> ChannelPermissions:
return cls(0b00000000000000000000000000000001)
# view permission is always present and therefore is included in every permission below
return cls._from_value(0b1)
@classmethod
def send_message(cls) -> ChannelPermissions:
return cls(0b00000000000000000000000000000011)
return cls._from_value(0b11)
@classmethod
def manage_channel(cls) -> ChannelPermissions:
return cls(0b00000000000000000000000000001001)
return cls._from_value(0b1001)
@classmethod
def voice_call(cls) -> ChannelPermissions:
return cls(0b00000000000000000000000000010001)
return cls._from_value(0b10001)
@classmethod
def invite_others(cls) -> ChannelPermissions:
return cls(0b00000000000000000000000000100001)
return cls._from_value(0b100001)
@classmethod
def embed_links(cls) -> ChannelPermissions:
return cls(0b00000000000000000000000001000001)
return cls._from_value(0b1000001)
@classmethod
def upload_files(cls) -> ChannelPermissions:
return cls(0b00000000000000000000000010000001)
return cls._from_value(0b10000001)
@property
def can_view(self) -> bool:
return self._check(0)
@flag_value
def can_view() -> int:
return 1 << 0
@property
def can_send_message(self) -> bool:
return self._check(1)
@flag_value
def can_send_message() -> int:
return 1 << 1
@property
def can_manage_channel(self) -> bool:
return self._check(3)
@flag_value
def can_manage_channel() -> int:
return 1 << 3
@property
def can_voice_call(self) -> bool:
return self._check(4)
@flag_value
def can_voice_call() -> int:
return 1 << 4
@property
def can_invite_others(self) -> bool:
return self._check(5)
@flag_value
def can_invite_others() -> int:
return 1 << 5
@property
def can_embed_links(self) -> bool:
return self._check(6)
@flag_value
def can_embed_links() -> int:
return 1 << 6
@property
def can_upload_files(self) -> bool:
return self._check(7)
@flag_value
def can_upload_files() -> int:
return 1 << 7
class ServerPermissions:
class ServerPermissions(Flags):
"""Represents the server permissions for a role as seen in server settings."""
__slots__ = ("_server_perms", "_channel_perms", )
def __init__(self, server_perms: int, channel_perms: int) -> None:
self._server_perms = _Permission(server_perms)
self._channel_perms = _Permission(channel_perms)
def __add__(self, p: ServerPermissions) -> ServerPermissions:
self._server_perms += p._server_perms
self._channel_perms += p._channel_perms
return self
def __sub__(self, p: ServerPermissions) -> ServerPermissions:
self._server_perms -= p._server_perms
self._channel_perms -= p._channel_perms
return self
def __lt__(self, p: ServerPermissions) -> bool:
return self._server_perms < p._server_perms and self._channel_perms < p._channel_perms
def __gt__(self, p: ServerPermissions) -> bool:
return self._server_perms > p._server_perms and self._channel_perms > p._channel_perms
def __eq__(self, p: ServerPermissions) -> bool:
return self._server_perms == p._server_perms and self._channel_perms == p._channel_perms
def __repr__(self) -> str:
return f"{self.__class__.__name__}<Server: {self._server_perms._value:032b} Channel: {self._channel_perms._value:032b}>"
@property
def value(self) -> PermissionTuple:
return self._server_perms._value, self._channel_perms._value
@classmethod
def none(cls) -> ServerPermissions:
return cls(0, 0)
return cls._from_value(0)
@classmethod
def all(cls) -> ServerPermissions:
# channel permissions here do not have manage channel permission
return cls(0b00000000000000001111000000111111, 0b00000000000000000000000011110111)
return cls._from_value(0b1111000000111111)
# view server and view channel are always present and therefore are included in every permission below
# server permissions
@flag_value
def view_server() -> int:
return 1 << 0
@classmethod
def view_server(cls) -> ServerPermissions:
return cls(0b00000000000000000000000000000001, 1)
@flag_value
def manage_roles() -> int:
return 1 << 1
@classmethod
def manage_roles(cls) -> ServerPermissions:
return cls(0b00000000000000000000000000000011, 1)
@flag_value
def manage_channels() -> int:
return 1 << 2
@classmethod
def manage_channels(cls) -> ServerPermissions:
return cls(0b00000000000000000000000000000101, 1)
@flag_value
def manage_server() -> int:
return 1 << 3
@classmethod
def manage_server(cls) -> ServerPermissions:
return cls(0b00000000000000000000000000001001, 1)
@flag_value
def kick_members() -> int:
return 1 << 4
@classmethod
def kick_members(cls) -> ServerPermissions:
return cls(0b00000000000000000000000000010001, 1)
@flag_value
def ban_members() -> int:
return 1 << 5
@classmethod
def ban_members(cls) -> ServerPermissions:
return cls(0b00000000000000000000000000100001, 1)
@flag_value
def change_nicknames() -> int:
return 1 << 12
@classmethod
def change_nicknames(cls) -> ServerPermissions:
return cls(0b00000000000000000001000000000001, 1)
@flag_value
def manage_nicknames() -> int:
return 1 << 13
@classmethod
def manage_nicknames(cls) -> ServerPermissions:
return cls(0b00000000000000000010000000000001, 1)
@flag_value
def change_avatar() -> int:
return 1 << 14
@classmethod
def change_avatar(cls) -> ServerPermissions:
return cls(0b00000000000000000100000000000001, 1)
@classmethod
def remove_avatars(cls) -> ServerPermissions:
return cls(0b00000000000000001000000000000001, 1)
@property
def can_view_server(self) -> bool:
return self._server_perms._check(0)
@property
def can_manage_roles(self) -> bool:
return self._server_perms._check(1)
@property
def can_manage_channels(self) -> bool:
return self._server_perms._check(2)
@property
def can_manage_server(self) -> bool:
return self._server_perms._check(3)
@property
def can_kick_members(self) -> bool:
return self._server_perms._check(4)
@property
def can_ban_members(self) -> bool:
return self._server_perms._check(5)
@property
def can_change_nicknames(self) -> bool:
return self._server_perms._check(12)
@property
def can_manage_nicknames(self) -> bool:
return self._server_perms._check(13)
@property
def can_change_avatar(self) -> bool:
return self._server_perms._check(14)
@property
def can_remove_avatars(self) -> bool:
return self._server_perms._check(15)
# channel permissions
@classmethod
def view_channels(cls) -> ServerPermissions:
return cls(1, 0b00000000000000000000000000000001)
@classmethod
def send_message(cls) -> ServerPermissions:
return cls(1, 0b00000000000000000000000000000011)
@classmethod
def manage_messages(cls) -> ServerPermissions:
return cls(1, 0b00000000000000000000000000000101)
@classmethod
def voice_call(cls) -> ServerPermissions:
return cls(1, 0b00000000000000000000000000010001)
@classmethod
def invite_others(cls) -> ServerPermissions:
return cls(1, 0b00000000000000000000000000100001)
@classmethod
def embed_links(cls) -> ServerPermissions:
return cls(1, 0b00000000000000000000000001000001)
@classmethod
def upload_files(cls) -> ServerPermissions:
return cls(1, 0b00000000000000000000000010000001)
@property
def can_view_channel(self) -> bool:
return self._channel_perms._check(0)
@property
def can_send_message(self) -> bool:
return self._channel_perms._check(1)
@property
def can_manage_messages(self) -> bool:
return self._channel_perms._check(2)
@property
def can_voice_call(self) -> bool:
return self._channel_perms._check(4)
@property
def can_invite_others(self) -> bool:
return self._channel_perms._check(5)
@property
def can_embed_links(self) -> bool:
return self._channel_perms._check(6)
@property
def can_upload_files(self) -> bool:
return self._channel_perms._check(7)
@flag_value
def remove_avatars() -> int:
return 1 << 15
View File
+59 -16
View File
@@ -1,8 +1,9 @@
from __future__ import annotations
from typing import TYPE_CHECKING
from typing import TYPE_CHECKING, Optional
from .permissions import ServerPermissions
from .utils import Missing
from .permissions import ChannelPermissions, ServerPermissions
if TYPE_CHECKING:
from .server import Server
@@ -14,14 +15,14 @@ __all__ = ("Role",)
class Role:
"""Represents a role
Attributes
-----------
id: :class:`str`
The id of the role
name: :class:`str`
The name of the role
colour: :class:`str`
colour: Optional[:class:`str`]
The colour of the role
hoist: :class:`bool`
Whether members with the role will display seperate from everyone else
@@ -29,30 +30,72 @@ class Role:
The position of the role in the role heirarchy
server: :class:`Server`
The server the role belongs to
permissions: :class:`ServerPermissions`
server_permissions: :class:`ServerPermissions`
The server permissions for the role
channel_permissions: :class:`ChannelPermissions`
The channel permissions for the role
"""
__slots__ = ("id", "name", "colour", "hoist", "rank", "state", "server", "permissions")
def __init__(self, data: RolePayload, role_id: str, state: State, server: Server):
__slots__ = ("id", "name", "colour", "hoist", "rank", "state", "server", "server_permissions", "channel_permissions")
def __init__(self, data: RolePayload, role_id: str, server: Server, state: State):
self.state = state
self.id = role_id
self.name = data["name"]
self.colour = data.get("colour")
self.hoist = data.get("hoist", False)
self.rank = data.get("rank", 0)
self.colour = None
self.hoist = False
self.rank = 0
self.server = server
self.permissions = ServerPermissions(*data.get("permissions"))
self.server_permissions = ServerPermissions._from_value(data["permissions"][0])
self.channel_permissions = ChannelPermissions._from_value(data["permissions"][1])
@property
def color(self):
return self.colour
async def set_permissions(self, permissions: ServerPermissions) -> None:
async def set_permissions(self, *, server_permissions: Optional[ServerPermissions] = None, channel_permissions: Optional[ChannelPermissions] = None) -> None:
"""Sets the permissions for a role in a server.
Parameters
-----------
permissions: :class:`ServerPermissions`
The new permissions for the role
server_permissions: Optional[:class:`ServerPermissions`]
The new server permissions for the role
channel_permissions: Optional[:class:`ChannelPermissions`]
The new channel permissions for the role
"""
await self.state.http.set_role_permissions(self.server.id, self.id, *permissions.value)
if not server_permissions and not channel_permissions:
return
server_value = (server_permissions or self.server_permissions).value
channel_value = (channel_permissions or self.channel_permissions).value
await self.state.http.set_role_permissions(self.server.id, self.id, server_value, channel_value)
def _update(self, *, name: Optional[str] = None, colour: Optional[str] = None, hoist: Optional[bool] = None, rank: Optional[int] = None):
if name:
self.name = name
if colour:
self.colour = colour
if hoist:
self.hoist = hoist
if rank:
self.rank = rank
async def delete(self):
"""Deletes the role"""
await self.state.http.delete_role(self.server.id, self.id)
async def edit(self, **kwargs):
"""Edits the role
Parameters
-----------
"""
if kwargs.get("colour", Missing) == None:
remove = "Colour"
else:
remove = None
await self.state.http.edit_role(self.server.id, self.id, remove, kwargs)
+263 -24
View File
@@ -2,49 +2,147 @@ from __future__ import annotations
from typing import TYPE_CHECKING, Optional, cast
from .channel import Channel
from .permissions import ServerPermissions
from .asset import Asset
from .category import Category
from .channel import Channel, VoiceChannel
from .invite import Invite
from .permissions import ChannelPermissions, ServerPermissions
from .role import Role
if TYPE_CHECKING:
from .channel import TextChannel
from .member import Member
from .state import State
from .types import Category as CategoryPayload
from .types import File as FilePayload
from .types import Permission as PermissionPayload
from .types import Server as ServerPayload
from .types import SystemMessagesConfig, Ban
__all__ = ("Server",)
__all__ = ("Server", "SystemMessages", "ServerBan")
class SystemMessages:
def __init__(self, data: SystemMessagesConfig, state: State):
self.state = state
self.user_joined_id = data.get("user_joined")
self.user_left_id = data.get("user_left")
self.user_kicked_id = data.get("user_kicked")
self.user_banned_id = data.get("user_banned")
@property
def user_joined(self) -> Optional[TextChannel]:
if not self.user_joined_id:
return
channel = self.state.get_channel(self.user_joined_id)
assert isinstance(channel, TextChannel)
return channel
@property
def user_left(self) -> Optional[TextChannel]:
if not self.user_left_id:
return
channel = self.state.get_channel(self.user_left_id)
assert isinstance(channel, TextChannel)
return channel
@property
def user_kicked(self) -> Optional[TextChannel]:
if not self.user_kicked_id:
return
channel = self.state.get_channel(self.user_kicked_id)
assert isinstance(channel, TextChannel)
return channel
@property
def user_banned(self) -> Optional[TextChannel]:
if not self.user_banned_id:
return
channel = self.state.get_channel(self.user_banned_id)
assert isinstance(channel, TextChannel)
return channel
class Server:
"""Represents a server
Attributes
-----------
id: :class:`str`
The id of the server
name: :class:`str`
The name of the server
owner: Optional[:class:`Member`]
The owner of the server
owner_id: :class:`str`
The owner's id of the server
description: Optional[:class:`str`]
The servers description
nsfw: :class:`bool`
Whether the server is nsfw or not
system_messages: :class:`SystemMessages`
The system message config for the server
icon: Optional[:class:`Asset`]
The servers icon
banner: Optional[:class:`Asset`]
The servers banner
"""
__slots__ = ("state", "id", "name", "owner_id", "default_permissions", "_members", "_roles", "_channels")
__slots__ = ("state", "id", "name", "owner_id", "default_server_permissions", "default_channel_permissions", "_members", "_roles", "_channels", "description", "icon", "banner", "nsfw", "system_messages", "_categories")
def __init__(self, data: ServerPayload, state: State):
self.state = state
self.id = data["_id"]
self.name = data["name"]
self.owner_id = data["owner"]
self.default_permissions = ServerPermissions(*data["default_permissions"])
self.default_server_permissions = ServerPermissions._from_value(data["default_permissions"][0])
self.default_channel_permissions = ChannelPermissions._from_value(data["default_permissions"][1])
self.description = data.get("description") or None
self.nsfw = data.get("nsfw", False)
self.system_messages = SystemMessages(data.get("system_messages", cast("SystemMessagesConfig", {})), state)
self._categories = {data["id"]: Category(data, state) for data in data.get("categories", [])}
if icon := data.get("icon"):
self.icon = Asset(icon, state)
else:
self.icon = None
if banner := data.get("banner"):
self.banner = Asset(banner, state)
else:
self.banner = None
self._members: dict[str, Member] = {}
self._roles: dict[str, Role] = {role_id: Role(role, role_id, state, self) for role_id, role in data.get("roles", {}).items()}
channels = cast(list[Channel], list(filter(bool, [state.get_channel(channel_id) for channel_id in data["channels"]])))
self._channels: dict[str, Channel] = {channel.id: channel for channel in channels}
self._roles: dict[str, Role] = {role_id: Role(role, role_id, self, state) for role_id, role in data.get("roles", {}).items()}
self._channels: dict[str, Channel] = {channel_id: state.get_channel(channel_id) for channel_id in data.get("channels", [])}
def _update(self, *, owner: Optional[str] = None, name: Optional[str] = None, description: Optional[str] = None, icon: Optional[FilePayload] = None, banner: Optional[FilePayload] = None, default_permissions: Optional[PermissionPayload] = None, nsfw: Optional[bool] = None, system_messages: Optional[SystemMessagesConfig] = None, categories: Optional[list[CategoryPayload]] = None):
if owner:
self.owner_id = owner
if name:
self.name = name
if description is not None:
self.description = description or None
if icon:
self.icon = Asset(icon, self.state)
if banner:
self.banner = Asset(banner, self.state)
if default_permissions:
self.default_server_permissions = ServerPermissions._from_value(default_permissions[0])
self.default_channel_permissions = ChannelPermissions._from_value(default_permissions[1])
if nsfw is not None:
self.nsfw = nsfw
if system_messages is not None:
self.system_messages = SystemMessages(system_messages, self.state)
if categories is not None:
self._categories = {data["id"]: Category(data, self.state) for data in categories}
@property
def roles(self) -> list[Role]:
"""list[:class:`Role`] Gets all roles in the server in decending order"""
return list(self._roles.values())
@property
def members(self) -> list[Member]:
"""list[:class:`Member`] Gets all members in the server"""
@@ -55,6 +153,11 @@ class Server:
"""list[:class:`Member`] Gets all channels in the server"""
return list(self._channels.values())
@property
def categories(self) -> list[Category]:
"""list[:class:`Category`] Gets all categories in the server"""
return list(self._categories.values())
def get_role(self, role_id: str) -> Role:
"""Gets a role from the cache
@@ -100,20 +203,156 @@ class Server:
"""
return self._channels[channel_id]
def get_category(self, category_id: str) -> Category:
"""Gets a category from the cache
Parameters
-----------
id: :class:`str`
The id of the category
Returns
--------
:class:`Category`
The category
"""
return self._categories[category_id]
@property
def owner(self) -> Optional[Member]:
owner_id = self.owner_id
def owner(self) -> Member:
""":class:`Member` The owner of the server"""
return self.get_member(self.owner_id)
if not owner_id:
return
return self.get_member(owner_id)
async def set_default_permissions(self, permissions: ServerPermissions) -> None:
async def set_default_permissions(self, *, server_permissions: Optional[ServerPermissions] = None, channel_permissions: Optional[ChannelPermissions] = None) -> None:
"""Sets the default server permissions.
Parameters
-----------
permissions: :class:`ServerPermissions`
server_permissions: Optional[:class:`ServerPermissions`]
The new default server permissions
channel_permissions: Optional[:class:`ChannelPermissions`]
the new default channel permissions
"""
await self.state.http.set_default_permissions(self.id, *permissions.value)
server_value = (server_permissions or self.default_server_permissions).value
channel_value = (channel_permissions or self.default_channel_permissions).value
await self.state.http.set_default_permissions(self.id, server_value, channel_value)
async def leave_server(self):
"""Leaves or deletes the server"""
await self.state.http.delete_leave_server(self.id)
async def delete_server(self):
"""Leaves or deletes a server, alias to :meth`Server.leave_server`"""
await self.leave_server()
async def create_text_channel(self, *, name: str, description: Optional[str] = None) -> TextChannel:
"""Creates a text channel in the server
Parameters
-----------
name: :class:`str`
The name of the channel
description: Optional[:class:`str`]
The channel's description
Returns
--------
:class:`TextChannel`
The text channel that was just created
"""
payload = await self.state.http.create_channel(self.id, "Text", name, description)
channel = TextChannel(payload, self.state)
self._channels[channel.id] = channel
return channel
async def create_voice_channel(self, *, name: str, description: Optional[str] = None) -> VoiceChannel:
"""Creates a voice channel in the server
Parameters
-----------
name: :class:`str`
The name of the channel
description: Optional[:class:`str`]
The channel's description
Returns
--------
:class:`VoiceChannel`
The voice channel that was just created
"""
payload = await self.state.http.create_channel(self.id, "Voice", name, description)
channel = VoiceChannel(payload, self.state)
self._channels[channel.id] = channel
return channel
async def fetch_invites(self) -> list[Invite]:
"""Fetches all invites in the server
Returns
--------
list[:class:`Invite`]
"""
invite_payloads = await self.state.http.fetch_server_invites(self.id)
return [Invite._from_partial(payload["_id"], payload["server"], payload["creator"], payload["channel"], self.state) for payload in invite_payloads]
async def fetch_member(self, member_id: str) -> Member:
"""Fetches a member from this server
Parameters
-----------
member_id: :class:`str`
The id of the member you are fetching
Returns
--------
:class:`Member`
The member with the matching id
"""
payload = await self.state.http.fetch_member(self.id, member_id)
return Member(payload, self, self.state)
async def fetch_bans(self) -> list[ServerBan]:
"""Fetches all invites in the server
Returns
--------
list[:class:`Invite`]
"""
payload = await self.state.http.fetch_bans(self.id)
return [ServerBan(ban, self.state) for ban in payload["bans"]]
async def create_role(self, name: str) -> Role:
"""Creates a role in the server
Parameters
-----------
name: :class:`str`
The name of the role
Returns
--------
:class:`Role`
The role that was just created
"""
payload = await self.state.http.create_role(self.id, name)
return Role(payload, name, self, self.state)
class ServerBan:
def __init__(self, ban: Ban, state: State):
self.reason = ban.get("reason")
self.server = state.get_server(ban["_id"]["server"])
self.user = state.get_user(ban["_id"]["user"])
self.state = state
async def unban(self):
"""Unbans the user"""
await self.state.http.unban_member(self.server.id, self.user.id)
+4 -4
View File
@@ -73,7 +73,7 @@ class State:
message = Message(payload, self)
if len(self.messages) >= self.max_messages:
self.messages.pop()
self.messages.appendleft(message)
return message
@@ -81,15 +81,15 @@ class State:
for msg in self.messages:
if msg.id == message_id:
return msg
raise KeyError
async def fetch_all_server_members(self):
for server_id in self.servers.keys():
data = await self.http.fetch_members(server_id)
for user in data["users"]:
self.add_user(user)
for member in data["members"]:
self.add_member(server_id, member)
+1
View File
@@ -1,3 +1,4 @@
from .category import *
from .channel import *
from .embed import *
from .file import *
+1 -1
View File
@@ -9,4 +9,4 @@ __all__ = ("Category",)
class Category(TypedDict):
id: str
title: str
channels: list[Channel]
channels: list[str]
+20 -27
View File
@@ -1,6 +1,7 @@
from __future__ import annotations
from typing import TYPE_CHECKING, Literal, TypedDict, Union
from typing_extensions import NotRequired
if TYPE_CHECKING:
from .file import File
@@ -10,60 +11,52 @@ if TYPE_CHECKING:
__all__ = (
"SavedMessages",
"DMChannel",
"Group",
"GroupDMChannel",
"TextChannel",
"VoiceChannel",
"Channel",
)
class _NonceChannel(TypedDict, total=False):
nonce: str
class BaseChannel(TypedDict):
_id: str
nonce: str
class SavedMessages(_NonceChannel, BaseChannel):
class SavedMessages(BaseChannel):
user: str
channel_type: Literal["SavedMessage"]
channel_type: Literal["SavedMessages"]
class DMChannel(_NonceChannel, BaseChannel):
class DMChannel(BaseChannel):
active: bool
recipients: list[str]
last_message: Message
channel_type: Literal["DirectMessage"]
class _GroupOptional(TypedDict):
icon: File
permissions: int
description: str
class Group(_NonceChannel, _GroupOptional, BaseChannel):
class GroupDMChannel(BaseChannel):
recipients: list[str]
name: str
owner: str
channel_type: Literal["Group"]
icon: NotRequired[File]
permissions: NotRequired[int]
description: NotRequired[str]
class _TextChannelOptional(TypedDict, total=False):
icon: File
default_permissions: int
role_permissions: dict[str, int]
class TextChannel(_NonceChannel, _TextChannelOptional, BaseChannel):
class TextChannel(BaseChannel):
server: str
name: str
description: str
last_message: str
channel_type: Literal["TextChannel"]
icon: NotRequired[File]
default_permissions: NotRequired[int]
role_permissions: NotRequired[dict[str, int]]
last_message: NotRequired[str]
class _VoiceChannelOptional(TypedDict, total=False):
icon: File
default_permissions: int
role_permissions: int
class VoiceChannel(_NonceChannel, _TextChannelOptional, BaseChannel):
class VoiceChannel(BaseChannel):
server: str
name: str
description: str
channel_type: Literal["VoiceChannel"]
icon: NotRequired[File]
default_permissions: NotRequired[int]
role_permissions: NotRequired[dict[str, int]]
Channel = Union[SavedMessages, DMChannel, Group, TextChannel, VoiceChannel]
Channel = Union[SavedMessages, DMChannel, GroupDMChannel, TextChannel, VoiceChannel]
+80 -4
View File
@@ -1,8 +1,84 @@
from __future__ import annotations
from typing import TYPE_CHECKING, TypedDict
from typing import TYPE_CHECKING, Literal, TypedDict, Union
from typing_extensions import NotRequired
__all__ = ("Embed",)
if TYPE_CHECKING:
from .file import File
__all__ = ("Embed", "SendableEmbed", "WebsiteEmbed", "ImageEmbed", "TextEmbed", "NoneEmbed", "YoutubeSpecial", "TwitchSpecial", "SpotifySpecial", "SoundcloudSpecial", "BandcampSpecial", "WebsiteSpecial", "JanuaryImage", "JanuaryVideo")
class YoutubeSpecial(TypedDict):
type: Literal["Youtube"]
id: str
timestamp: NotRequired[str]
class TwitchSpecial(TypedDict):
type: Literal["Twitch"]
content_type: Literal["Channel", "Video", "Clip"]
id: str
class SpotifySpecial(TypedDict):
type: Literal["Spotify"]
content_type: str
id: str
class SoundcloudSpecial(TypedDict):
type: Literal["Soundcloud"]
class BandcampSpecial(TypedDict):
type: Literal["Bandcamp"]
content_type: Literal["Album", "Track"]
id: str
WebsiteSpecial = Union[YoutubeSpecial, TwitchSpecial, SpotifySpecial, SoundcloudSpecial, BandcampSpecial]
class JanuaryImage(TypedDict):
url: str
width: int
height: int
size: Literal["Large", "Preview"]
class JanuaryVideo(TypedDict):
url: str
width: int
height: int
class WebsiteEmbed(TypedDict):
type: Literal["Website"]
url: NotRequired[str]
special: NotRequired[WebsiteSpecial]
title: NotRequired[str]
description: NotRequired[str]
image: NotRequired[JanuaryImage]
video: NotRequired[JanuaryVideo]
site_name: NotRequired[str]
icon_url: NotRequired[str]
colour: NotRequired[str]
class ImageEmbed(JanuaryImage):
type: Literal["Image"]
class TextEmbed(TypedDict):
type: Literal["Text"]
icon_url: NotRequired[str]
url: NotRequired[str]
title: NotRequired[str]
description: NotRequired[str]
media: NotRequired[File]
colour: NotRequired[str]
class NoneEmbed(TypedDict):
type: Literal["None"]
Embed = Union[WebsiteEmbed, ImageEmbed, TextEmbed, NoneEmbed]
class SendableEmbed(TypedDict):
type: Literal["Text"]
icon_url: NotRequired[str]
url: NotRequired[str]
title: NotRequired[str]
description: NotRequired[str]
media: NotRequired[str]
colour: NotRequired[str]
class Embed(TypedDict):
pass # TODO
+91 -8
View File
@@ -1,16 +1,20 @@
from __future__ import annotations
from typing import TYPE_CHECKING, TypedDict, Union
from typing import TYPE_CHECKING, Literal, TypedDict, Union
from .channel import (Channel, DMChannel, Group, SavedMessages, TextChannel,
VoiceChannel)
from .channel import (Channel, DMChannel, GroupDMChannel, SavedMessages,
TextChannel, VoiceChannel)
from .message import Message
from .user import Status
from .file import File
if TYPE_CHECKING:
from .member import Member
from .member import Member, MemberID
from .server import Server
from .user import User
from .role import Permission
from .category import Category
from .server import SystemMessagesConfig
__all__ = (
"BasePayload",
@@ -25,7 +29,16 @@ __all__ = (
"ChannelUpdateEventPayload",
"ChannelDeleteEventPayload",
"ChannelStartTypingEventPayload",
"ChannelDeleteTypingEventPayload"
"ChannelDeleteTypingEventPayload",
"ServerUpdateEventPayload",
"ServerDeleteEventPayload",
"ServerMemberUpdateEventPayload",
"ServerMemberJoinEventPayload",
"ServerMemberLeaveEventPayload",
"ServerRoleUpdateEventPayload",
"ServerRoleDeleteEventPayload",
"UserUpdateEventPayload",
"UserRelationshipEventPayload"
)
class BasePayload(TypedDict):
@@ -61,7 +74,7 @@ class MessageDeleteEventPayload(BasePayload):
class ChannelCreateEventPayload_SavedMessages(BasePayload, SavedMessages):
pass
class ChannelCreateEventPayload_Group(BasePayload, Group):
class ChannelCreateEventPayload_Group(BasePayload, GroupDMChannel):
pass
class ChannelCreateEventPayload_TextChannel(BasePayload, TextChannel):
@@ -78,7 +91,7 @@ ChannelCreateEventPayload = Union[ChannelCreateEventPayload_Group, ChannelCreate
class ChannelUpdateEventPayload(BasePayload):
id: str
data: ...
clear: ...
clear: Literal["Icon", "Description"]
class ChannelDeleteEventPayload(BasePayload):
id: str
@@ -88,3 +101,73 @@ class ChannelStartTypingEventPayload(BasePayload):
user: str
ChannelDeleteTypingEventPayload = ChannelStartTypingEventPayload
class ServerUpdateEventPayloadData(TypedDict, total=False):
owner: str
name: str
description: str
icon: File
banner: File
default_permissions: Permission
nsfw: bool
system_messages: SystemMessagesConfig
categories: list[Category]
class ServerUpdateEventPayload(BasePayload):
id: str
data: ServerUpdateEventPayloadData
clear: Literal["Icon", "Banner", "Description"]
class ServerDeleteEventPayload(BasePayload):
id: str
class ServerMemberUpdateEventPayloadData(TypedDict, total=False):
nickname: str
avatar: File
roles: list[str]
class ServerMemberUpdateEventPayload(BasePayload):
id: MemberID
data: ServerMemberUpdateEventPayloadData
clear: Literal["Nickname", "Avatar"]
class ServerMemberJoinEventPayload(BasePayload):
id: str
user: str
ServerMemberLeaveEventPayload = ServerMemberJoinEventPayload
class ServerRoleUpdateEventPayloadData(TypedDict, total=False):
name: str
colour: str
hoist: bool
rank: int
class ServerRoleUpdateEventPayload(BasePayload):
id: str
role_id: str
data: ServerRoleUpdateEventPayloadData
clear: Literal["Color"]
class ServerRoleDeleteEventPayload(BasePayload):
id: str
role_id: str
UserUpdateEventPayloadData = TypedDict("UserUpdateEventPayloadData", {
"status": Status,
"profile.background": File,
"profile.content": str,
"avatar": File,
"online": bool
}, total=False)
class UserUpdateEventPayload(BasePayload):
id: str
data: UserUpdateEventPayloadData
clear: Literal["ProfileContent", "ProfileBackground", "StatusText", "Avatar"]
class UserRelationshipEventPayload(BasePayload):
id: str
user: str
status: Status
+1 -1
View File
@@ -7,7 +7,7 @@ if TYPE_CHECKING:
from .message import Message
from .user import User
__all__ = (
"VosoFeature",
"ApiInfo",
+23 -15
View File
@@ -1,22 +1,30 @@
from typing import Literal, TypedDict, Union
from __future__ import annotations
__all__ = (
"GroupInvite",
"ServerInvite",
"Invite",
)
from typing import TYPE_CHECKING, Literal, TypedDict
class GroupInvite(TypedDict):
type: Literal["Group"]
_id: str
creator: str
channel: str
from typing_extensions import NotRequired
class ServerInvite(TypedDict):
if TYPE_CHECKING:
from .file import File
__all__ = ("Invite", "PartialInvite")
class Invite(TypedDict):
type: Literal["Server"]
server_id: str
server_name: str
server_icon: NotRequired[str]
server_banner: NotRequired[str]
channel_id: str
channel_name: str
channel_description: NotRequired[str]
user_name: str
user_avatar: NotRequired[File]
member_count: int
class PartialInvite(TypedDict):
_id: str
server: str
creator: str
channel: str
Invite = Union[ServerInvite, GroupInvite]
creator: str
+5 -6
View File
@@ -1,6 +1,7 @@
from __future__ import annotations
from typing import TYPE_CHECKING, TypedDict
from typing_extensions import NotRequired
if TYPE_CHECKING:
from .file import File
@@ -8,14 +9,12 @@ if TYPE_CHECKING:
__all__ = ("Member",)
class _MemberOptional(TypedDict, total=False):
nickname: str
avatar: File
roles: list[str]
class MemberID(TypedDict):
server: str
user: str
class Member(_MemberOptional):
class Member(TypedDict):
_id: MemberID
nickname: NotRequired[str]
avatar: NotRequired[File]
roles: NotRequired[list[str]]
+22 -5
View File
@@ -1,13 +1,18 @@
from __future__ import annotations
from typing import TYPE_CHECKING, TypedDict, Union
from typing_extensions import NotRequired
if TYPE_CHECKING:
from .embed import Embed
from .file import File
__all__ = ("Message",)
__all__ = (
"Message",
"MessageReplyPayload",
"Masquerade"
)
class UserAddContent(TypedDict):
id: str
@@ -40,12 +45,24 @@ class ChannelDescriptionChangeContent(TypedDict):
class ChannelIconChangeContent(TypedDict):
by: str
class _OptionalMessage(TypedDict):
attachments: list[File]
embeds: list[Embed]
MessageEdited = TypedDict("MessageEdited", {"$date": str})
class Message(_OptionalMessage):
class Masquerade(TypedDict, total=False):
name: str
avatar: str
class Message(TypedDict):
_id: str
channel: str
author: str
content: Union[str, UserAddContent, UserRemoveContent, UserJoinedContent, UserLeftContent, UserKickedContent, UserBannedContent, ChannelRenameContent, ChannelDescriptionChangeContent, ChannelIconChangeContent]
attachments: NotRequired[list[File]]
embeds: NotRequired[list[Embed]]
mentions: NotRequired[list[str]]
replies: NotRequired[list[str]]
edited: NotRequired[MessageEdited]
masquerade: NotRequired[Masquerade]
class MessageReplyPayload(TypedDict):
id: str
mention: bool
+1 -6
View File
@@ -9,11 +9,6 @@ __all__ = (
Permission = tuple[int, int]
class _RoleOptional(TypedDict, total=False):
colour: str
hoist: bool
rank: int
class Role(_RoleOptional):
class Role(TypedDict):
name: str
permissions: Permission
+18 -16
View File
@@ -1,6 +1,7 @@
from __future__ import annotations
from typing import TYPE_CHECKING, TypedDict
from typing_extensions import NotRequired
if TYPE_CHECKING:
from .category import Category
@@ -13,6 +14,7 @@ __all__ = (
"BannedUser",
"Ban",
"ServerBans",
"SystemMessagesConfig"
)
class SystemMessagesConfig(TypedDict, total=False):
@@ -21,14 +23,6 @@ class SystemMessagesConfig(TypedDict, total=False):
user_kicked: str
user_banned: str
class _ServerOptional(TypedDict, total=False):
nonce: str
description: str
categories: list[Category]
system_messages: SystemMessagesConfig
roles: list[Role]
icon: File
banner: File
class Server(TypedDict):
_id: str
@@ -36,19 +30,27 @@ class Server(TypedDict):
name: str
channels: list[str]
default_permissions: Permission
nonce: NotRequired[str]
description: NotRequired[str]
categories: NotRequired[list[Category]]
system_messages: NotRequired[SystemMessagesConfig]
roles: NotRequired[dict[str, Role]]
icon: NotRequired[File]
banner: NotRequired[File]
nsfw: NotRequired[bool]
class _OptionalBannedUser(TypedDict, total=False):
avatar: File
class BannedUser(_OptionalBannedUser):
class BannedUser(TypedDict):
_id: str
username: str
avatar: NotRequired[File]
class _OptionalBan(TypedDict, total=False):
reason: str
class BanId(TypedDict):
server: str
user: str
class Ban(_OptionalBan):
_id: str
class Ban(TypedDict):
_id: BanId
reason: NotRequired[str]
class ServerBans(TypedDict):
users: list[BannedUser]
+10 -11
View File
@@ -1,6 +1,7 @@
from __future__ import annotations
from typing import TYPE_CHECKING, Literal, TypedDict
from typing_extensions import NotRequired
if TYPE_CHECKING:
from .file import File
@@ -27,19 +28,17 @@ class UserRelation(TypedDict):
status: Relation
_id: str
class _OptionalUser(TypedDict, total=False):
avatar: File
relations: list[UserRelation]
badges: int
status: Status
relationship: Relation
online: bool
flags: int
bot: UserBot
class User(_OptionalUser):
class User(TypedDict):
_id: str
username: str
avatar: NotRequired[File]
relations: NotRequired[list[UserRelation]]
badges: NotRequired[int]
status: NotRequired[Status]
relationship: NotRequired[Relation]
online: NotRequired[bool]
flags: NotRequired[int]
bot: NotRequired[UserBot]
class UserProfile(TypedDict, total=False):
content: str
+99 -16
View File
@@ -1,17 +1,21 @@
from __future__ import annotations
from typing import TYPE_CHECKING, NamedTuple, Optional
from typing import TYPE_CHECKING, NamedTuple, Optional, Union
from .asset import Asset
from .asset import Asset, PartialAsset
from .channel import DMChannel
from .enums import PresenceType, RelationshipType
from .flags import UserBadges
from .messageable import Messageable
if TYPE_CHECKING:
from .state import State
from .types import File
from .types import Status as StatusPayload
from .types import User as UserPayload
from .types import UserRelation
__all__ = ("User",)
__all__ = ("User", "Status", "Relation", "UserProfile")
class Relation(NamedTuple):
"""A namedtuple representing a relation between the bot and a user"""
@@ -23,42 +27,46 @@ class Status(NamedTuple):
text: Optional[str]
presence: Optional[PresenceType]
class User:
class UserProfile(NamedTuple):
"""A namedtuple representing a users profile"""
content: Optional[str]
background: Optional[Asset]
class User(Messageable):
"""Represents a user
Attributes
-----------
id: :class:`str`
The users id
name: :class:`str`
The users name
bot: :class:`bool`
Whether or not the user is a bot
owner: Optional[:class:`User`]
The bot's owner if the user is a bot
badges: :class:`int`
badges: :class:`UserBadges`
The users badges
online: :class:`bool`
Whether or not the user is online
flags: :class:`int`
The user flags
avatar: :class:`Asset`
The users avatar if they have one
relations: list[:class:`Relation`]
A list of the users relations
relationship: Optional[:class:`RelationshipType`]
The relationship between the user and the bot
status: Optional[:class:`Status`]
The users status
dm_channel: Optional[:class:`DMChannel`]
The dm channel between the client and the user, this will only be set if the client has dm'ed the user or :meth:`User.open_dm` was run
"""
__flattern_attributes__ = ("id", "name", "bot", "owner_id", "badges", "online", "flags", "avatar", "relations", "relationship", "status")
__flattern_attributes__ = ("id", "bot", "owner_id", "badges", "online", "flags", "relations", "relationship", "status", "masquerade_avatar", "masquerade_name", "original_name", "original_avatar", "profile", "dm_channel")
__slots__ = (*__flattern_attributes__, "state")
def __init__(self, data: UserPayload, state: State):
self.state = state
self.id = data["_id"]
self.name = data["username"]
self.original_name = data["username"]
self.dm_channel = None
bot = data.get("bot")
if bot:
self.bot = True
@@ -67,14 +75,14 @@ class User:
self.bot = False
self.owner_id = None
self.badges = data.get("badges", 0)
self.badges = UserBadges._from_value(data.get("badges", 0))
self.online = data.get("online", False)
self.flags = data.get("flags", 0)
avatar = data.get("avatar")
self.avatar = Asset(avatar, state) if avatar else None
self.original_avatar = Asset(avatar, state) if avatar else None
relations = []
relations: list[Relation] = []
for relation in data.get("relations", []):
user = state.get_user(relation["_id"])
@@ -92,6 +100,18 @@ class User:
else:
self.status = None
self.profile: Optional[UserProfile] = None
self.masquerade_avatar: Optional[PartialAsset] = None
self.masquerade_name: Optional[str] = None
async def _get_channel_id(self):
if not self.dm_channel:
payload = await self.state.http.open_dm(self.id)
self.dm_channel = DMChannel(payload, self.state)
return self.id
@property
def owner(self) -> Optional[User]:
owner_id = self.owner_id
@@ -100,3 +120,66 @@ class User:
return
return self.state.get_user(owner_id)
@property
def name(self) -> str:
""":class:`str` The name the user is displaying, this includes there orginal name and masqueraded name"""
return self.masquerade_name or self.original_name
@property
def avatar(self) -> Union[Asset, PartialAsset, None]:
"""Optional[:class:`Asset`] The avatar the member is displaying, this includes there orginal avatar and masqueraded avatar"""
return self.masquerade_avatar or self.original_avatar
@property
def mention(self) -> str:
""":class:`str`: Returns a string that allows you to mention the given user."""
return f"<@{self.id}>"
def _update(self, *, status: Optional[StatusPayload] = None, profile_content: Optional[str] = None, profile_background: Optional[File] = None, avatar: Optional[File] = None, online: Optional[bool] = None):
if status:
presence = status.get("presence")
self.status = Status(status.get("text"), PresenceType(presence) if presence else None)
if profile_background:
self.profile = UserProfile(self.profile.content if self.profile else None, Asset(profile_background, self.state))
if profile_content:
self.profile = UserProfile(profile_content, self.profile.background if self.profile else None)
if avatar:
self.original_avatar = Asset(avatar, self.state)
if online:
self.online = online
async def default_avatar(self) -> bytes:
"""Returns the default avatar for this user
Returns
--------
:class:`bytes`
The bytes of the image
"""
return await self.state.http.fetch_default_avatar(self.id)
async def fetch_profile(self) -> UserProfile:
"""Fetches the user's profile
Returns
--------
:class:`UserProfile`
The user's profile
"""
if profile := self.profile:
return profile
payload = await self.state.http.fetch_profile(self.id)
if file := payload.get("background"):
background = Asset(file, self.state)
else:
background = None
self.profile = UserProfile(payload.get("content"), background)
return self.profile
+89 -3
View File
@@ -1,6 +1,11 @@
from typing import Callable, TypeVar
import inspect
from operator import attrgetter
from typing import Any, Callable, Coroutine, Iterable, TypeVar, Union
from contextlib import asynccontextmanager
from typing_extensions import ParamSpec
from aiohttp import ClientSession
__all__ = ("Missing", "copy_doc")
__all__ = ("Missing", "copy_doc", "maybe_coroutine", "get", "client_session")
class _Missing:
def __repr__(self):
@@ -14,5 +19,86 @@ def copy_doc(from_t: T) -> Callable[[T], T]:
def inner(to_t: T) -> T:
to_t.__doc__ = from_t.__doc__
return to_t
return inner
R_T = TypeVar("R_T")
P = ParamSpec("P")
# it is impossible to type this function correctly for a couple reasons:
# 1. isawaitable does not narrow while keeping typevars - there is an open PR for this (typeshed#5658) but it cannot be merged because mypy does not support the feature fully
# 2. typeguard does not narrow for the negative case which is dumb in my opinion, so `value` would stay being a union even after the if statement (PEP 647 - "The type is not narrowed in the negative case")
async def maybe_coroutine(func: Callable[P, Union[R_T, Coroutine[Any, Any, R_T]]], *args: P.args, **kwargs: P.kwargs) -> R_T:
value = func(*args, **kwargs)
if inspect.isawaitable(value):
value = await value
return value # type: ignore
def get(iterable: Iterable[T], **attrs: Any) -> T:
"""A convenience function to help get a value from an iterable with a specific attribute
Examples
---------
.. code-block:: python
:emphasize-lines: 3
from revolt import utils
channel = utils.get(server.channels, name="General")
await channel.send("Hello general chat.")
Parameters
-----------
iterable: Iterable
The values to search though
**attrs: Any
The attributes to check
Returns
--------
Any
The value from the iterable with the met attributes
Raises
-------
LookupError
Raises when none of the values in the iterable matches the attributes
"""
converted = [(attrgetter(attr.replace('__', '.')), value) for attr, value in attrs.items()]
for elem in iterable:
if all(pred(elem) == value for pred, value in converted):
return elem
raise LookupError
@asynccontextmanager
async def client_session():
"""A context manager that creates a new aiohttp.ClientSession() and closes it when exiting the context.
Examples
---------
.. code-block:: python
:emphasize-lines: 3
async def main():
async with client_session() as session:
client = revolt.Client(session, "TOKEN")
await client.start()
asyncio.run(main())
"""
session = ClientSession()
try:
yield session
finally:
await session.close()
+156 -19
View File
@@ -4,12 +4,21 @@ import asyncio
import logging
from copy import copy
from typing import TYPE_CHECKING, Callable, cast
from traceback import print_exception;
from .types import (ChannelCreateEventPayload, ChannelDeleteEventPayload,
from .enums import RelationshipType
from .types import Message as MessagePayload
from .types import (MessageDeleteEventPayload, MessageUpdateEventPayload,
ServerDeleteEventPayload, ServerMemberJoinEventPayload,
ServerMemberLeaveEventPayload,
ServerMemberUpdateEventPayload,
ServerRoleDeleteEventPayload, ServerRoleUpdateEventPayload,
ServerUpdateEventPayload, UserRelationshipEventPayload,
UserUpdateEventPayload, ChannelCreateEventPayload, ChannelDeleteEventPayload,
ChannelDeleteTypingEventPayload,
ChannelStartTypingEventPayload, ChannelUpdateEventPayload)
from .types import Message as MessagePayload
from .types import MessageDeleteEventPayload, MessageUpdateEventPayload
from .user import Status, UserProfile
from .channel import TextChannel, GroupDMChannel, VoiceChannel
try:
import ujson as json
@@ -36,7 +45,7 @@ __all__ = ("WebsocketHandler",)
logger = logging.getLogger("revolt")
class WebsocketHandler:
__slots__ = ("session", "token", "ws_url", "dispatch", "state", "websocket", "loop")
__slots__ = ("session", "token", "ws_url", "dispatch", "state", "websocket", "loop", "user", "ready")
def __init__(self, session: aiohttp.ClientSession, token: str, ws_url: str, dispatch: Callable[..., None], state: State):
self.session = session
@@ -46,6 +55,8 @@ class WebsocketHandler:
self.state = state
self.websocket: aiohttp.ClientWebSocketResponse
self.loop = asyncio.get_running_loop()
self.user = None
self.ready = asyncio.Event()
async def send_payload(self, payload: BasePayload):
if use_msgpack:
@@ -71,6 +82,9 @@ class WebsocketHandler:
event_type = payload["type"].lower()
logger.debug("Recieved event %s %s", event_type, payload)
try:
if event_type != "ready":
await self.ready.wait()
func = getattr(self, f"handle_{event_type}")
except:
logger.debug("Unknown event '%s'", event_type)
@@ -82,8 +96,11 @@ class WebsocketHandler:
logger.info("Successfully authenticated")
async def handle_ready(self, payload: ReadyEventPayload):
for user in payload["users"]:
self.state.add_user(user)
for user_payload in payload["users"]:
user = self.state.add_user(user_payload)
if user.relationship == RelationshipType.user:
self.user = user
for channel in payload["channels"]:
self.state.add_channel(channel)
@@ -97,6 +114,7 @@ class WebsocketHandler:
await self.state.fetch_all_server_members()
self.ready.set()
self.dispatch("ready")
async def handle_message(self, payload: MessageEventPayload):
@@ -111,11 +129,13 @@ class WebsocketHandler:
data = payload["data"]
kwargs = {}
if data["content"]:
kwargs["content"] = data["content"]
if content := data.get("content"):
kwargs["content"] = content
if data["edited"]["$date"]:
kwargs["edited_at"] = data["edited"]["$date"]
kwargs["edited_at"] = data["edited"]["$date"]
if embeds := data.get("embeds"):
kwargs["embeds"] = embeds
message._update(**kwargs)
@@ -124,10 +144,13 @@ class WebsocketHandler:
async def handle_messagedelete(self, payload: MessageDeleteEventPayload):
self.dispatch("raw_message_delete", payload)
message = self.state.get_message(payload["id"])
if message:
self.state.messages.remove(message)
self.dispatch("message_delete", message)
try:
message = self.state.get_message(payload["id"])
except:
return
self.state.messages.remove(message)
self.dispatch("message_delete", message)
async def handle_channelcreate(self, payload: ChannelCreateEventPayload):
channel = self.state.add_channel(payload)
@@ -143,10 +166,12 @@ class WebsocketHandler:
if clear := payload.get("clear"):
if clear == "Icon":
pass # TODO
if isinstance(channel, (TextChannel, VoiceChannel, GroupDMChannel)):
channel.icon = None
elif clear == "Description":
channel.description = None # type: ignore
if isinstance(channel, (TextChannel, VoiceChannel, GroupDMChannel)):
channel.description = None
self.dispatch("channel_update", old_channel, channel)
@@ -161,11 +186,118 @@ class WebsocketHandler:
self.dispatch("typing_start", channel, user)
async def handle_channeldeletetyping(self, payload: ChannelDeleteTypingEventPayload):
async def handle_channelstoptyping(self, payload: ChannelDeleteTypingEventPayload):
channel = self.state.get_channel(payload["id"])
user = self.state.get_user(payload["user"])
self.dispatch("typing_delete", channel, user)
self.dispatch("typing_stop", channel, user)
async def handle_serverupdate(self, payload: ServerUpdateEventPayload):
server = self.state.get_server(payload["id"])
old_server = copy(server)
server._update(**payload["data"])
if clear := payload.get("clear"):
if clear == "Icon":
server.icon = None
elif clear == "Banner":
server.banner = None
elif clear == "Description":
server.description = None
self.dispatch("server_update", old_server, server)
async def handle_serverdelete(self, payload: ServerDeleteEventPayload):
server = self.state.servers.pop(payload["id"])
for channel in server.channels:
del self.state.channels[channel.id]
self.dispatch("server_delete", server)
async def handle_servermemberupdate(self, payload: ServerMemberUpdateEventPayload):
member = self.state.get_member(payload["id"]["server"], payload["id"]["user"])
old_member = copy(member)
if clear := payload.get("clear"):
if clear == "Nickname":
member.nickname = None
elif clear == "Avatar":
member.guild_avatar = None
member._update(**payload["data"])
self.dispatch("member_update", old_member, member)
async def handle_servermemberjoin(self, payload: ServerMemberJoinEventPayload):
member = self.state.add_member(payload["id"], {"_id": {"server": payload["id"], "user": payload["user"]}})
self.dispatch("member_join", member)
async def handle_memberleave(self, payload: ServerMemberLeaveEventPayload):
server = self.state.get_server(payload["id"])
member = server._members.pop(payload["user"])
self.dispatch("member_leave", member)
async def handle_serveroleupdate(self, payload: ServerRoleUpdateEventPayload):
server = self.state.get_server(payload["id"])
role = server.get_role(payload["role_id"])
old_role = copy(role)
if clear := payload.get("clear"):
if clear == "Colour":
role.colour = None
role._update(**payload["data"])
self.dispatch("role_update", old_role, role)
async def handle_serverroledelete(self, payload: ServerRoleDeleteEventPayload):
server = self.state.get_server(payload["id"])
role = server._roles.pop(payload["role_id"])
self.dispatch("role_delete", role)
async def handle_userupdate(self, payload: UserUpdateEventPayload):
user = self.state.get_user(payload["id"])
old_user = copy(user)
if clear := payload.get("clear"):
if clear == "ProfileContent":
if profile := user.profile:
user.profile = UserProfile(None, profile.background)
elif clear == "ProfileBackground":
if profile := user.profile:
user.profile = UserProfile(profile.content, None)
elif clear == "StatusText":
user.status = Status(None, user.status.presence if user.status else None)
elif clear == "Avatar":
user.original_avatar = None
# the keys have . in them so I need to replace with _
# type: ignore is for it to stop complaining about the keys not existing in the typeddict
data = payload["data"]
data["profile_content"] = data.pop("profile.content", None) # type: ignore
data["profile_background"] = data.pop("profile.background", None) # type: ignore
user._update(**data) # type: ignore
self.dispatch("user_update", old_user, user)
async def handle_userrelationship(self, payload: UserRelationshipEventPayload):
user = self.state.get_user(payload["user"])
old_relationship = user.relationship
user.relationship = RelationshipType(payload["status"])
self.dispatch("user_relationship_update", user, old_relationship, user.relationship)
async def start(self):
if use_msgpack:
@@ -183,4 +315,9 @@ class WebsocketHandler:
else:
payload = json.loads(msg.data)
self.loop.create_task(self.handle_event(payload))
task = self.loop.create_task(self.handle_event(payload))
# task.add_done_callback(task_done)
def task_done(task: asyncio.Task[None]):
if exception := task.exception():
print_exception(type(exception), exception, exception.__traceback__)
-39
View File
@@ -1,39 +0,0 @@
import pathlib
from setuptools import find_packages, setup
here = pathlib.Path(__file__).parent.resolve()
long_description = (here / "README.md").read_text(encoding="utf-8")
setup(
name="revolt.py",
version="0.1.0",
description="Python wrapper around revolt.chat",
long_description=long_description,
long_description_content_type="text/markdown",
url="https://github.com/Zomatree/revolt.py",
author="Zomatree",
classifiers=[
"Development Status :: 3 - Beta",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.9",
"Programming Language :: Python :: 3 :: Only",
],
keywords="wrapper, async, api, websockets, http",
packages=find_packages(),
python_requires=">=3.9",
extras_require={
"speedups": ["ujson", "aiohttp[speedups]==3.7.4.post0", "msgpack==1.0.2"],
},
project_urls={
"Bug Reports": "https://github.com/Zomatree/revolt.py/issues",
"Source": "https://github.com/Zomatree/revolt.py/",
},
)