123 Commits

Author SHA1 Message Date
Zomatree 32d6b1d6e8 Add missing checks to __all__ 2023-04-12 16:41:37 +01:00
Zomatree f9ba869e75 fix fetch_emoji not returning an Emoji instance 2023-04-12 16:37:05 +01:00
Zomatree ba3f74dcd0 Add docs 2023-04-11 22:23:12 +01:00
Zomatree 625dd4eac2 finish implementation of permissions 2023-04-11 22:07:56 +01:00
Zomatree 0a6db1dc9c inital permissions calculations 2023-04-11 19:05:56 +01:00
Zomatree a672f949a1 fix servermemberjoin, closes #48 2023-03-27 00:43:12 +01:00
Zomatree df9893aaff add bulk message delete 2023-03-26 21:44:04 +01:00
Zomatree 35a4614b61 fix incorrect routes 2023-03-26 18:42:16 +01:00
Zomatree 263f99f281 use is not None in _update 2023-03-26 18:09:35 +01:00
Zomatree e99b6edee3 correctly handle role creation 2023-03-26 18:08:30 +01:00
Zomatree 720272d3cb switch from deprecated config 2023-03-26 18:08:06 +01:00
Zomatree ab5a2751df fix docs 2023-03-15 19:41:31 +00:00
Zomatree 6059e4e4dc remove bugged dep 2023-03-15 19:30:41 +00:00
Zomatree 63491ec76e update docs 2023-03-15 19:00:49 +00:00
Zomatree 76364572f1 timeout and upload_file 2023-02-22 18:49:55 +00:00
Zomatree 75f980e0f9 use our own msgpack types 2023-02-22 18:40:06 +00:00
Zomatree 8db036e131 fix CI 2023-01-02 22:10:07 +00:00
Zomatree 4d35de3ac8 qol updates 2023-01-02 22:06:25 +00:00
Zomatree ce5bf29f59 rework flags 2023-01-02 22:05:51 +00:00
Zomatree 656b9e6483 convert to hatch from poetry 2023-01-02 22:04:37 +00:00
Zomatree a92324149e fix issues stemming from bugs in the revolt api 2022-11-16 23:06:31 +00:00
Zomatree 9504c05e7b bump aiohttp dep to fix python 3.11 2022-11-16 23:05:45 +00:00
Zomatree d3f7275d1b add created_at to all models with ids 2022-11-16 23:05:06 +00:00
Zomatree 588d62e093 Use revolt.utils.client_session in example (#46) 2022-10-10 09:38:06 +01:00
Zomatree 8534458e28 fix type narrowing 2022-10-10 00:29:29 +01:00
Zomatree 95100a5b77 fix typing issues 2022-10-10 00:20:35 +01:00
Zomatree 81de5a6539 allow passing None to help_command to disable it 2022-10-10 00:19:37 +01:00
Zomatree b3e1ffa3bb reword typeguard comment to be updated 2022-10-10 00:18:24 +01:00
Zomatree c531aa649e bump doc deps 2022-10-08 14:38:39 +01:00
Zomatree 23354d030b make metaclass not generic 2022-09-26 01:26:03 +01:00
Zomatree bf8ded7588 make client generic 2022-09-26 01:16:33 +01:00
Zomatree 7ddfa2635c Fix colour always being none 2022-09-11 19:17:41 +01:00
Zomatree 7c412a056a fix race condition when joining a server 2022-08-21 13:19:45 +01:00
Zomatree 19cfa0a96c implement interactions 2022-08-18 22:51:47 +01:00
Zomatree 88af87a4e1 rename server_create event to server_join 2022-08-18 21:58:20 +01:00
Zomatree 6436901e6f move _members to a instance attr due being read only 2022-08-18 21:50:12 +01:00
Zomatree bdafa57437 fix incorrect __all__ 2022-08-18 21:04:18 +01:00
Zomatree 46c3cf893e fix varies bugs 2022-08-18 20:16:29 +01:00
Zomatree 737515f9b5 remove unnessary channel parameter 2022-08-18 03:25:51 +01:00
Zomatree 285974feef add reactions and interactions 2022-08-18 02:19:54 +01:00
Zomatree a065cd40c7 bump version 2022-08-08 19:31:00 +01:00
Zomatree 1ab91658c2 handle server join event 2022-08-08 19:23:25 +01:00
Zomatree 64ccd58b8f cleanup channel.edit 2022-07-16 00:21:26 +01:00
Zomatree d187fff90b add masquerade colour 2022-07-15 23:37:26 +01:00
Zomatree e34af623b3 fix last_message_id, fixes #41 2022-07-15 22:40:01 +01:00
Zomatree 2de49e6a6c change all keyerrors to lookup errors 2022-07-05 17:54:56 +00:00
Zomatree 424fa10208 cleanup code 2022-07-05 16:37:45 +00:00
Zomatree 052130d721 fix text channel docs 2022-07-05 16:36:55 +00:00
Zomatree efbb667fef handle channels in serverupdate event, fixes #39 2022-06-30 20:24:49 +01:00
Zomatree 09c50a0e97 fix incorrect docs 2022-06-30 20:24:13 +01:00
Zomatree 99b974f96e bump version 2022-06-23 02:10:19 +01:00
Zomatree 357fd7b071 update docs 2022-05-31 01:57:22 +01:00
Zomatree 1f411c12bf fix CI issues 2022-05-31 01:47:07 +01:00
Zomatree 25f3b4e4fc inital updated permissions system 2022-05-31 01:44:41 +01:00
Zomatree 6871754a27 remove trailing whitespace 2022-04-25 13:42:37 +01:00
Zomatree 0fdca7eb7d isort 2022-04-25 13:40:39 +01:00
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
65 changed files with 4041 additions and 1046 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,docs]
- uses: jakebailey/pyright-action@v1
with:
lib: true
python-version: 3.9.7
python-version: 3.9
working-directory: revolt
+1
View File
@@ -7,3 +7,4 @@ docs/_build
.vscode
.env
.mypy_cache
build
+9 -5
View File
@@ -1,12 +1,16 @@
version: 2
sphinx:
configuration: docs/conf.py
configuration: docs/conf.py
python:
version: "3.9"
install:
- requirements: docs_requirements.txt
install:
- method: pip
path: .
extra_requirements:
- docs
build:
image: testing
tools:
python: "3.9"
os: "ubuntu-22.04"
+5 -13
View File
@@ -1,25 +1,17 @@
set dotenv-load := true
activate:
source .venv/bin/activate
venv:
python -m venv .venv
just activate
python -m pip install -r requirements.txt
python -m pip install -r docs_requirements.txt
test:
python test.py
build: venv
build:
rm -rf dist/*
python -m build
upload: venv
python -m twine upload dist/* -u $PYPI_USERNAME -p $PYPI_PASSWORD
upload:
python -m twine upload dist/*
lint:
pyright . --venv-path .venv
pyright --lib
coverage:
pyright --lib --ignoreexternal --verifytypes revolt
+16 -7
View File
@@ -1,21 +1,30 @@
# 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
import asyncio
import aiohttp
class Client(revolt.Client):
async def on_message(self, message: revolt.Message):
@@ -23,7 +32,7 @@ class Client(revolt.Client):
await message.channel.send("hi how are you")
async def main():
async with aiohttp.ClientSession() as session:
async with revolt.utils.client_session() as session:
client = Client(session, "BOT TOKEN HERE")
await client.start()
+139 -72
View File
@@ -4,152 +4,154 @@ API Reference
===============
Client
~~~~~~~
.. autoclass:: Client
:members:
Asset
~~~~~~
:inherited-members:
.. autoclass:: Asset
:members:
:inherited-members:
Channel
~~~~~~~~
.. autoclass:: PartialAsset
:members:
:inherited-members:
.. autoclass:: Channel
:members:
:inherited-members:
SavedMessageChannel
~~~~~~~~~~~~~~~~~~~~
.. autoclass:: ServerChannel
:members:
:inherited-members:
.. autoclass:: SavedMessageChannel
:members:
DMChannel
~~~~~~~~~~
:inherited-members:
.. autoclass:: DMChannel
:members:
GroupDMChannel
~~~~~~~~~~~~~~~
:inherited-members:
.. autoclass:: GroupDMChannel
:members:
TextChannel
~~~~~~~~~~~~
:inherited-members:
.. autoclass:: TextChannel
:members:
VoiceChannel
~~~~~~~~~~~~
:inherited-members:
.. autoclass:: VoiceChannel
:members:
Embed
~~~~~~
:inherited-members:
.. autoclass:: Embed
:members:
:inherited-members:
.. autoclass:: WebsiteEmbed
:members:
:inherited-members:
File
~~~~~
.. autoclass:: ImageEmbed
:members:
:inherited-members:
.. autoclass:: TextEmbed
:members:
:inherited-members:
.. autoclass:: NoneEmbed
:members:
:inherited-members:
.. autoclass:: SendableEmbed
:members:
:inherited-members:
.. autoclass:: File
:members:
Member
~~~~~~~
:inherited-members:
.. autoclass:: Member
:members:
Message
~~~~~~~
:inherited-members:
.. autoclass:: Message
:members:
:inherited-members:
.. autoclass:: MessageReply
:members:
:inherited-members:
Messageable
~~~~~~~~~~~~
.. autoclass:: Masquerade
:members:
:inherited-members:
.. autoclass:: Messageable
:members:
:inherited-members:
Permissions
~~~~~~~~~~~~
.. autoclass:: ChannelPermissions
.. autoclass:: Permissions
:members:
:inherited-members:
.. autoclass:: ServerPermissions
.. autoclass:: UserPermissions
:members:
:inherited-members:
Role
~~~~~
.. autoclass:: PermissionsOverwrite
:members:
:inherited-members:
.. autoclass:: Role
:members:
Server
~~~~~~~
:inherited-members:
.. autoclass:: Server
:members:
:inherited-members:
Category
~~~~~~~~~
.. autoclass:: ServerBan
:members:
:inherited-members:
.. autoclass:: Category
:members:
SystemMessages
~~~~~~~~~~~~~~~
:inherited-members:
.. autoclass:: SystemMessages
:members:
User
~~~~~
:inherited-members:
.. autoclass:: User
:members:
Relation
~~~~~~~~~
:inherited-members:
.. autonamedtuple:: Relation
Status
~~~~~~~
.. autonamedtuple:: Status
UserBadges
~~~~~~~~~~~
.. autoclass:: UserBadges
:members:
.. autoclass:: UserProfile
:members:
.. autoclass:: Invite
:members:
.. autoclass:: Emoji
:members:
.. autoclass:: MessageInteractions
: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`.
@@ -161,10 +163,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
@@ -194,7 +196,7 @@ All enums subclass `aenum.Enum`.
The user is offline or invisible
.. attribute:: RelationshipType
.. class:: RelationshipType
Specifies the relationship between two users
@@ -211,12 +213,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
.. autofunction:: client_session
+2 -1
View File
@@ -17,13 +17,14 @@ import sphinx_nameko_theme
sys.path.insert(0, os.path.abspath('..'))
import revolt
# -- Project information -----------------------------------------------------
project = 'Revolt.py'
copyright = '2021-present, Zomatree'
author = 'Zomatree'
version = "0.0.1"
version = ".".join(map(str, revolt.__version__))
# -- General configuration ---------------------------------------------------
+20
View File
@@ -19,6 +19,11 @@ Command
.. autoclass:: revolt.ext.commands.Command
:members:
Cog
~~~~
.. autoclass:: revolt.ext.commands.Cog
:members:
command
~~~~~~~~
.. autodecorator:: revolt.ext.commands.command
@@ -88,3 +93,18 @@ 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
Executable
+60
View File
@@ -0,0 +1,60 @@
[project]
name = "revolt.py"
dynamic = ["version"]
description = "Python wrapper for the revolt.chat API"
requires-python = ">=3.9"
license = "MIT"
readme = "README.md"
keywords = ["wrapper", "async", "api", "websockets", "http"]
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",
]
dependencies = [
"aiohttp==3.8.*",
"ulid-py==1.1.*",
"aenum==3.1.*",
"typing_extensions>=4.4.0"
]
[project.optional-dependencies]
speedups = [
"ujson==5.1.*",
"msgpack==1.0.*"
]
docs = [
"Sphinx==5.2.*",
"sphinx-nameko-theme==0.0.*",
"sphinx-toolbox==3.2.*",
"setuptools==65.4.*"
]
[project.urls]
Homepage = "https://github.com/revoltchat/revolt.py"
Documentation = "https://revoltpy.readthedocs.io/en/latest/"
"Source Code" = "https://github.com/revoltchat/revolt.py"
"Bug Tracker" = "https://github.com/revoltchat/revolt.py/issues"
[[project.authors]]
name = "Zomatree"
email = "me@zomatree.live"
[tool.hatch.version]
path = "revolt/__init__.py"
[tool.hatch.build]
only-packages = true
[tool.pyright]
reportPrivateUsage = false
reportImportCycles = false
reportIncompatibleMethodOverride = false
[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"
-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
+20 -19
View File
@@ -1,20 +1,21 @@
from .asset import Asset
from .category import Category
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 .flags import UserBadges
from .member import Member
from .message import Masquerade, Message, MessageReply
from .messageable import Messageable
from .permissions import ChannelPermissions, ServerPermissions
from .role import Role
from .server import Server, SystemMessages
from .user import Relation, Status, User
from . import utils as utils
from .asset import *
from .category import *
from .channel import *
from .client import *
from .embed import *
from .emoji 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, 1)
__version__ = "0.1.9"
+8 -8
View File
@@ -4,7 +4,7 @@ import mimetypes
from typing import TYPE_CHECKING
from .enums import AssetType
from .errors import AutumnDisabled
from .utils import Ulid
if TYPE_CHECKING:
from io import IOBase
@@ -13,11 +13,11 @@ if TYPE_CHECKING:
from .types import File as FilePayload
__all__ = ("Asset",)
__all__ = ("Asset", "PartialAsset")
class Asset:
class Asset(Ulid):
"""Represents a file on revolt
Attributes
-----------
id: :class:`str`
@@ -40,7 +40,7 @@ class Asset:
The assets url
"""
__slots__ = ("state", "id", "tag", "size", "filename", "content_type", "width", "height", "type", "url")
def __init__(self, data: FilePayload, state: State):
self.state = state
@@ -48,10 +48,10 @@ class Asset:
self.tag = data['tag']
self.size = data['size']
self.filename = data['filename']
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:
@@ -70,7 +70,7 @@ class Asset:
async def save(self, fp: IOBase):
"""Reads the files content and saves it to a file
Parameters
-----------
fp: IOBase
+3 -1
View File
@@ -2,6 +2,8 @@ from __future__ import annotations
from typing import TYPE_CHECKING
from .utils import Ulid
if TYPE_CHECKING:
from .channel import Channel
from .state import State
@@ -9,7 +11,7 @@ if TYPE_CHECKING:
__all__ = ("Category",)
class Category:
class Category(Ulid):
"""Represents a category in a server that stores channels.
Attributes
+320 -104
View File
@@ -1,10 +1,12 @@
from __future__ import annotations
from typing import TYPE_CHECKING, Optional, cast
from typing import TYPE_CHECKING, Any, Optional, Union
from .asset import Asset
from .enums import ChannelType
from .messageable import Messageable
from .permissions import ChannelPermissions
from .permissions import Permissions, PermissionsOverwrite
from .utils import Missing, Ulid
if TYPE_CHECKING:
from .message import Message
@@ -13,25 +15,67 @@ 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 File as FilePayload
from .types import GroupDMChannel as GroupDMChannelPayload
from .types import Overwrite as OverwritePayload
from .types import SavedMessages as SavedMessagesPayload
from .types import ServerChannel as ServerChannelPayload
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", "ServerChannel")
class Channel:
class EditableChannel:
__slots__ = ()
state: State
id: str
async def edit(self, **kwargs: Any):
"""Edits the channel
Passing ``None`` to the parameters that accept it will remove them.
Parameters
-----------
name: str
The new name for the channel
description: Optional[str]
The new description for the channel
owner: User
The new owner for the group dm channel
icon: Optional[File]
The new icon for the channel
nsfw: bool
Sets whether the channel is nsfw or not
"""
remove: list[str] = []
if kwargs.get("icon", Missing) == None:
remove.append("Icon")
elif kwargs.get("description", Missing) == None:
remove.append("Description")
if icon := kwargs.get("icon"):
asset = await self.state.http.upload_file(icon, "icons")
kwargs["icon"] = asset["id"]
if owner := kwargs.get("owner"):
kwargs["owner"] = owner.id
await self.state.http.edit_channel(self.id, remove, kwargs)
class Channel(Ulid):
"""Base class for all channels
Attributes
-----------
id: :class:`str`
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,14 +83,31 @@ 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
async def _get_channel_id(self) -> str:
return self.id
def _update(self, **_: Any):
pass
async def delete(self):
"""Deletes or closes the channel"""
await self.state.http.close_channel(self.id)
@property
def server(self) -> Optional[Server]:
return self.state.get_server(self.server_id) if self.server_id else None
def server(self) -> Server:
""":class:`Server` The server this voice channel belongs too"""
if not self.server_id:
raise LookupError
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}>"
def _update(self):
pass
class SavedMessageChannel(Channel, Messageable):
"""The Saved Message Channel"""
@@ -54,133 +115,288 @@ class SavedMessageChannel(Channel, Messageable):
super().__init__(data, state)
class DMChannel(Channel, Messageable):
"""A DM channel"""
"""A DM channel
Attributes
-----------
last_message_id: Optional[:class:`str`]
The id of the last message in this channel, if any
"""
__slots__ = ("last_message_id", "recipient_ids")
def __init__(self, data: DMChannelPayload, state: State):
super().__init__(data, state)
self.recipient_ids: tuple[str, str] = tuple(data["recipients"])
self.last_message_id = data.get("last_message_id")
class GroupDMChannel(Channel, Messageable):
__slots__ = ("recipients", "name", "owner", "permissions")
@property
def recipients(self) -> tuple[User, User]:
a, b = self.recipient_ids
return (self.state.get_user(a), self.state.get_user(b))
@property
def recipient(self) -> User:
if self.recipient_ids[0] != self.state.user_id:
user_id = self.recipient_ids[0]
else:
user_id = self.recipient_ids[1]
return self.state.get_user(user_id)
@property
def last_message(self) -> 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:
raise LookupError
return self.state.get_message(self.last_message_id)
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
last_message_id: Optional[:class:`str`]
The id of the last message in this channel, if any
"""
__slots__ = ("recipient_ids", "name", "owner_id", "permissions", "icon", "description", "last_message_id")
"""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.recipient_ids = data["recipients"]
self.name = data["name"]
self.owner = state.get_user(data["owner"])
self.owner_id = data["owner"]
self.description: Optional[str] = data.get("description")
self.last_message_id = data.get("last_message_id")
if perms := data.get("permissions"):
self.permissions = ChannelPermissions._from_value(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):
if name:
self.permissions = Permissions(data.get("permissions", 0))
def _update(self, *, name: Optional[str] = None, recipients: Optional[list[str]] = None, description: Optional[str] = None):
if name is not None:
self.name = name
if recipients:
self.recipients = [self.state.get_user(user_id) for user_id in recipients]
if recipients is not None:
self.recipient_ids = recipients
async def set_default_permissions(self, permissions: ChannelPermissions) -> None:
if description is not None:
self.description = description
@property
def recipients(self) -> list[User]:
return [self.state.get_user(user_id) for user_id in self.recipient_ids]
@property
def owner(self) -> User:
return self.state.get_user(self.owner_id)
async def set_default_permissions(self, permissions: Permissions) -> None:
"""Sets the default permissions for a group.
Parameters
-----------
permissions: :class:`ChannelPermissions`
The new default group permissions
"""
await self.state.http.set_channel_default_permissions(self.id, permissions.value)
await self.state.http.set_group_channel_default_permissions(self.id, permissions.value)
class TextChannel(Channel, Messageable):
__slots__ = ("name", "description", "last_message_id", "server_id", "default_permissions", "role_permissions")
@property
def last_message(self) -> Message:
"""Gets the last message from the channel, shorthand for `client.get_message(channel.last_message_id)`
"""A text channel"""
def __init__(self, data: TextChannelPayload, state: State):
Returns
--------
:class:`Message` the last message in the channel
"""
if not self.last_message_id:
raise LookupError
return self.state.get_message(self.last_message_id)
class ServerChannel(Channel):
"""Base class for all guild channels
Attributes
-----------
server_id: :class:`str`
The id of the server this text channel belongs to
name: :class:`str`
The name of the text channel
description: Optional[:class:`str`]
The description of the channel, if any
nsfw: bool
Sets whether the channel is nsfw or not
default_permissions: :class:`ChannelPermissions`
The default permissions for all users in the text channel
"""
def __init__(self, data: ServerChannelPayload, 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")
self.nsfw = data.get("nsfw", False)
self.active = False
self.default_permissions = PermissionsOverwrite._from_overwrite(data.get("default_permissions", {"a": 0, "d": 0}))
last_message_id = data.get("last_message")
self.last_message_id = last_message_id
permissions: dict[str, PermissionsOverwrite] = {}
if perms := data.get("default_permissions"):
self.default_permissions = ChannelPermissions._from_value(perms)
for role_name, overwrite_data in data.get("role_permissions", {}).items():
overwrite = PermissionsOverwrite._from_overwrite(overwrite_data)
permissions[role_name] = overwrite
if role_perms := data.get("role_permissions"):
self.role_permissions = {role_id: ChannelPermissions._from_value(perms) for role_id, perms in role_perms.items()}
self.permissions = permissions
if icon := data.get("icon"):
self.icon = Asset(icon, state)
else:
self.icon = None
def _get_channel_id(self) -> str:
async def set_default_permissions(self, permissions: PermissionsOverwrite) -> None:
"""Sets the default permissions for the channel.
Parameters
-----------
permissions: :class:`ChannelPermissions`
The new default channel permissions
"""
allow, deny = permissions.to_pair()
await self.state.http.set_guild_channel_default_permissions(self.id, allow.value, deny.value)
async def set_role_permissions(self, role: Role, permissions: PermissionsOverwrite) -> None:
"""Sets the permissions for a role in the channel.
Parameters
-----------
permissions: :class:`ChannelPermissions`
The new channel permissions
"""
allow, deny = permissions.to_pair()
await self.state.http.set_guild_channel_role_permissions(self.id, role.id, allow.value, deny.value)
def _update(self, *, name: Optional[str] = None, description: Optional[str] = None, icon: Optional[FilePayload] = None, nsfw: Optional[bool] = None, active: Optional[bool] = None, role_permissions: Optional[dict[str, OverwritePayload]] = None, default_permissions: Optional[OverwritePayload] = None):
if name is not None:
self.name = name
if description is not None:
self.description = description
if icon is not None:
self.icon = Asset(icon, self.state)
if nsfw is not None:
self.nsfw = nsfw
if active is not None:
self.active = active
if role_permissions is not None:
permissions = {}
for role_name, overwrite_data in role_permissions.items():
overwrite = PermissionsOverwrite._from_overwrite(overwrite_data)
permissions[role_name] = overwrite
self.permissions = permissions
if default_permissions is not None:
self.default_permissions = PermissionsOverwrite._from_overwrite(default_permissions)
class TextChannel(ServerChannel, Messageable, EditableChannel):
"""A text channel
Subclasses :class:`ServerChannel` and :class:`Messageable`
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
"""
__slots__ = ("name", "description", "last_message_id", "default_permissions", "icon", "overwrites")
def __init__(self, data: TextChannelPayload, state: State):
super().__init__(data, state)
self.last_message_id = data.get("last_message_id")
async def _get_channel_id(self) -> str:
return self.id
@property
def last_message(self) -> 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:
raise LookupError
return self.state.get_message(self.last_message_id)
def _update(self, *, name: Optional[str] = None, description: Optional[str] = None):
if name:
self.name = name
class VoiceChannel(ServerChannel, EditableChannel):
"""A voice channel
if description:
self.description = description
Subclasses :class:`ServerChannel`
async def set_default_permissions(self, permissions: ChannelPermissions) -> None:
"""Sets the default permissions for a channel.
Parameters
-----------
permissions: :class:`ChannelPermissions`
The new default channel permissions
"""
await self.state.http.set_channel_default_permissions(self.id, permissions.value)
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
"""
async def set_role_permissions(self, role: Role, permissions: ChannelPermissions) -> None:
"""Sets the permissions for a role in a channel.
Parameters
-----------
permissions: :class:`ChannelPermissions`
The new channel permissions
"""
await self.state.http.set_channel_role_permissions(self.id, role.id, permissions.value)
class VoiceChannel(Channel):
"""A voice channel"""
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")
if perms := data.get("default_permissions"):
self.default_permissions = ChannelPermissions._from_value(perms)
if role_perms := data.get("role_permissions"):
self.role_permissions = {role_id: ChannelPermissions._from_value(perms) for role_id, perms in role_perms.items()}
def _update(self, *, name: Optional[str] = None, description: Optional[str] = None):
if name:
self.name = name
if description:
self.description = description
async def set_default_permissions(self, permissions: ChannelPermissions) -> None:
"""Sets the default permissions for a voice channel.
Parameters
-----------
permissions: :class:`ChannelPermissions`
The new default channel permissions
"""
await self.state.http.set_channel_default_permissions(self.id, permissions.value)
async def set_role_permissions(self, role: Role, permissions: ChannelPermissions) -> None:
"""Sets the permissions for a role in a voice channel
Parameters
-----------
permissions: :class:`ChannelPermissions`
The new channel permissions
"""
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)
+249 -24
View File
@@ -2,12 +2,17 @@ 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, Literal, 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 .utils import Missing, Ulid
from .websocket import WebsocketHandler
try:
@@ -17,18 +22,19 @@ except ImportError:
if TYPE_CHECKING:
from .channel import Channel
from .emoji import Emoji
from .file import File
from .server import Server
from .types import ApiInfo
from .user import User
__all__ = ("Client",)
logger = logging.getLogger("revolt")
class Client:
"""The client for interacting with revolt
Parameters
-----------
session: :class:`aiohttp.ClientSession`
@@ -40,13 +46,14 @@ class Client:
max_messages: :class:`int`
The max amount of messages stored in the cache, by default this is 5k
"""
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
@@ -58,7 +65,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`
@@ -86,59 +93,62 @@ 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]:
async def stop(self):
await self.websocket.websocket.close()
def get_user(self, id: str) -> User:
"""Gets a user from the cache
Parameters
-----------
id: :class:`str`
The id of the user
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
-----------
id: :class:`str`
The id of the channel
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
-----------
id: :class:`str`
The id of the server
Returns
--------
Optional[:class:`Server`]
The server if found
:class:`Server`
The server
"""
return self.state.get_server(id)
async def wait_for(self, event: str, *, check: Optional[Callable[..., bool]] = None, timeout: Optional[float] = None) -> Any:
"""Waits for an event
Parameters
-----------
event: :class:`str`
@@ -168,7 +178,222 @@ class Client:
@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())
@property
def global_emojis(self) -> list[Emoji]:
return self.state.global_emojis
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: Any):
"""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) is None:
del kwargs["avatar"]
remove = ["Avatar"]
else:
remove = None
await self.state.http.edit_self(remove, kwargs)
async def edit_status(self, **kwargs: Any):
"""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) is 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: Any):
"""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
"""
remove = []
if kwargs.get("content", Missing) is None:
del kwargs["content"]
remove.append("ProfileContent")
if kwargs.get("background", Missing) is None:
del kwargs["background"]
remove.append("ProfileBackground")
await self.state.http.edit_self(remove, {"profile": kwargs})
async def fetch_emoji(self, emoji_id: str) -> Emoji:
"""Fetches an emoji
Parameters
-----------
emoji_id: str
The id of the emoji
Returns
--------
:class:`Emoji`
The emoji with the corrasponding id
"""
emoji = await self.state.http.fetch_emoji(emoji_id)
return Emoji(emoji, self.state)
async def upload_file(self, file: File, tag: Literal['attachments', 'avatars', 'backgrounds', 'icons', 'banners', 'emojis']) -> Ulid:
"""Uploads a file to revolt
Parameters
-----------
file: :class:`File`
The file to upload
tag: :class:`str`
The type of file to upload, this should a string of either `'attachments'`, `'avatars'`, `'backgrounds'`, `'icons'`, `'banners'` or `'emojis'`
Returns
--------
:class:`Ulid`
The id of the file that was uploaded
"""
asset = await self.http.upload_file(file, tag)
ulid = Ulid()
ulid.id = asset["id"]
return ulid
+136 -8
View File
@@ -1,17 +1,145 @@
from __future__ import annotations
from typing import TYPE_CHECKING
from typing import TYPE_CHECKING, Optional, TypedDict, Union
from typing_extensions import NotRequired, Unpack
from .asset import Asset
from .enums import EmbedType
if TYPE_CHECKING:
from .state import State
from .types import Embed as EmbedPayload
from .types import ImageEmbed as ImageEmbedPayload
from .types import SendableEmbed as SendableEmbedPayload
from .types import TextEmbed as TextEmbedPayload
from .types import WebsiteEmbed as WebsiteEmbedPayload
__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 EmbedParameters(TypedDict):
title: NotRequired[str]
description: NotRequired[str]
media: NotRequired[str]
icon_url: NotRequired[str]
colour: NotRequired[str]
url: NotRequired[str]
class SendableEmbed:
"""
Represents an embed that can be sent in a message, you will never receive this, you will receive :class:`Embed`.
Attributes
-----------
title: Optional[:class:`str`]
The title of the embed
description: Optional[:class:`str`]
The description of the embed
media: Optional[:class:`str`]
The file inside the embed, this is the ID of the file, you can use :meth:`Client.upload_file` to get an ID.
icon_url: Optional[:class:`str`]
The url of the icon url
colour: Optional[:class:`str`]
The embed's accent colour, this is any valid `CSS color <https://developer.mozilla.org/en-US/docs/Web/CSS/color_value>`_
url: Optional[:class:`str`]
URL for hyperlinking the embed's title
"""
def __init__(self, **attrs: Unpack[EmbedParameters]):
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:
"""Converts the embed to a dictionary which Revolt accepts
Returns
--------
:class:`dict[str, Any]`
The embed
"""
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
+55
View File
@@ -0,0 +1,55 @@
from __future__ import annotations
from typing import TYPE_CHECKING, Optional
from .utils import Ulid
if TYPE_CHECKING:
from .server import Server
from .state import State
from .types import Emoji as EmojiPayload
__all__ = ("Emoji",)
class Emoji(Ulid):
"""Represents a custom emoji.
Attributes
-----------
id: :class:`str`
The id of the emoji
author_id: :class:`str`
The id of the of user who created the emoji
name: :class:`str`
The name of the emoji
animated: :class:`bool`
Whether or not the emoji is animated
nsfw: :class:`bool`
Whether or not the emoji is nsfw
server_id: Optional[:class:`str`]
The server id this emoji belongs to, if any
"""
def __init__(self, payload: EmojiPayload, state: State):
self.state = state
self.id = payload["_id"]
self.author_id = payload["creator_id"]
self.name = payload["name"]
self.animated = payload.get("animated", False)
self.nsfw = payload.get("nsfw", False)
self.server_id: Optional[str] = payload["parent"].get("id")
async def delete(self):
"""Deletes the emoji."""
await self.state.http.delete_emoji(self.id)
@property
def server(self) -> Server:
"""Returns the server this emoji is part of
Returns
--------
:class:`Server`
The Server this emoji is part of
"""
return self.state.get_server(self.server_id) # type: ignore
+10 -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"
@@ -28,6 +29,7 @@ class PresenceType(enum.Enum):
idle = "Idle"
invisible = "Invisible"
online = "Online"
focus = "Focus"
class RelationshipType(enum.Enum):
blocked = "Blocked"
@@ -49,3 +51,9 @@ class SortType(enum.Enum):
latest = "Latest"
oldest = "Oldest"
relevance = "Relevance"
class EmbedType(enum.Enum):
website = "Website"
image = "Image"
text = "Text"
none = "None"
+5 -2
View File
@@ -16,7 +16,10 @@ 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"""
"The autumn feature is disabled"
class Forbidden(HTTPError):
"Missing permissions"
+4
View File
@@ -1,5 +1,9 @@
from .checks import *
from .client import *
from .cog import *
from .command import *
from .context import *
from .converters import *
from .errors import *
from .group import *
from .help import *
+41 -16
View File
@@ -1,35 +1,37 @@
from typing import Any, Callable, Coroutine, TypeVar, Union
from __future__ import annotations
from typing import Any, Callable, Coroutine, TypeVar, Union, cast
import revolt
from .command import Command
from .context import Context
from .errors import NotBotOwner, NotServerOwner, ServerOnly
from .errors import (MissingPermissionsError, NotBotOwner, NotServerOwner,
ServerOnly)
from .utils import ClientT
__all__ = ("check", "Check", "is_bot_owner", "is_server_owner")
Check = Callable[[Context], Union[Any, Coroutine[Any, Any, Any]]]
__all__ = ("check", "Check", "is_bot_owner", "is_server_owner", "has_permissions", "has_channel_permissions")
T = TypeVar("T", Callable[..., Any], Command)
def check(check: Check):
Check = Callable[[Context[ClientT]], Union[Any, Coroutine[Any, Any, Any]]]
def check(check: Check[ClientT]):
"""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
The function to be called, must take one parameter, context and optionally be a coroutine, the return value denoating whether the check should pass or fail
"""
def inner(func: T) -> T:
if isinstance(func, Command):
func.checks.append(check)
command = cast(Command[ClientT], func) # cant verify generic at runtime so must cast
command.checks.append(check)
else:
checks = getattr(func, "_checks", [])
checks.append(check)
func._checks = checks
func._checks = checks # type: ignore
return func
@@ -38,7 +40,7 @@ def check(check: Check):
def is_bot_owner():
"""A command check for limiting the command to only the bot's owner"""
@check
def inner(context: Context):
def inner(context: Context[ClientT]):
if context.author.id == context.client.user.owner_id:
return True
@@ -49,7 +51,7 @@ def is_bot_owner():
def is_server_owner():
"""A command check for limiting the command to only a server's owner"""
@check
def inner(context: Context):
def inner(context: Context[ClientT]):
if not context.server:
raise ServerOnly
@@ -59,3 +61,26 @@ def is_server_owner():
raise NotServerOwner
return inner
def has_permissions(**permissions: bool):
@check
def inner(context: Context[ClientT]):
author = context.author
if not author.has_permissions(**permissions):
raise MissingPermissionsError
return inner
def has_channel_permissions(**permissions: bool):
@check
def inner(context: Context[ClientT]):
author = context.author
if isinstance(author, revolt.User):
raise MissingPermissionsError
if not author.has_channel_permissions(context.channel, **permissions):
raise MissingPermissionsError
return inner
+195 -23
View File
@@ -1,14 +1,22 @@
from __future__ import annotations
import re
import sys
import traceback
from typing import Any, Callable, Union
from importlib import import_module
from typing import (TYPE_CHECKING, Any, Optional, Protocol, TypeVar, Union,
overload, runtime_checkable)
from typing_extensions import Self
import revolt
if TYPE_CHECKING:
from .help import HelpCommand
from .cog import Cog
from .command import Command
from .context import Context
from .errors import CheckError, CommandNotFound
from .errors import CheckError, CommandNotFound, MissingSetup
from .view import StringView
__all__ = (
@@ -16,17 +24,21 @@ __all__ = (
"CommandsClient"
)
quote_regex = re.compile(r"[\"']")
chunk_regex = re.compile(r"\S+")
V = TypeVar("V")
T = TypeVar("T")
@runtime_checkable
class ExtensionProtocol(Protocol):
@staticmethod
def setup(client: CommandsClient) -> None:
raise NotImplementedError
class CommandsMeta(type):
_commands: list[Command]
_commands: list[Command[Any]]
def __new__(cls, name: str, bases: tuple[type, ...], attrs: dict[str, Any]):
commands: list[Command] = []
commands: list[Command[Any]] = []
self = super().__new__(cls, name, bases, attrs)
for base in reversed(self.__mro__):
for value in base.__dict__.values():
if isinstance(value, Command):
@@ -34,18 +46,48 @@ class CommandsMeta(type):
self._commands = commands
for command in commands:
command._client = self # type: ignore
return self
class CaseInsensitiveDict(dict[str, V]):
def __setitem__(self, key: str, value: V) -> None:
super().__setitem__(key.casefold(), value)
def __getitem__(self, key: str) -> V:
return super().__getitem__(key.casefold())
def __contains__(self, key: object) -> bool:
if isinstance(key, str):
return super().__contains__(key.casefold())
else:
return False
@overload
def get(self, key: str) -> V | None:
...
@overload
def get(self, key: str, default: V | T) -> V | T:
...
def get(self, key: str, default: Optional[T] = None) -> V | T | None:
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]
_commands: list[Command[Self]]
def __init__(self, *args, **kwargs):
self.all_commands: dict[str, Command] = {}
def __init__(self, *args: Any, help_command: Union[HelpCommand[Self], None, revolt.utils._Missing] = revolt.utils.Missing, case_insensitive: bool = False, **kwargs: Any):
from .help import DefaultHelpCommand, HelpCommandImpl
self.all_commands: dict[str, Command[Self]] = {} if not case_insensitive else CaseInsensitiveDict()
self.cogs: dict[str, Cog[Self]] = {}
self.extensions: dict[str, ExtensionProtocol] = {}
for command in self._commands:
self.all_commands[command.name] = command
@@ -53,10 +95,16 @@ class CommandsClient(revolt.Client, metaclass=CommandsMeta):
for alias in command.aliases:
self.all_commands[alias] = command
if help_command is not None:
self.help_command = help_command or DefaultHelpCommand[Self]()
self.add_command(HelpCommandImpl(self))
else:
self.help_command = None
super().__init__(*args, **kwargs)
@property
def commands(self) -> list[Command]:
def commands(self) -> list[Command[Self]]:
return list(set(self.all_commands.values()))
async def get_prefix(self, message: revolt.Message) -> Union[str, list[str]]:
@@ -74,7 +122,7 @@ class CommandsClient(revolt.Client, metaclass=CommandsMeta):
"""
raise NotImplementedError
def get_command(self, name: str) -> Command:
def get_command(self, name: str) -> Command[Self]:
"""Gets a command.
Parameters
@@ -89,7 +137,7 @@ class CommandsClient(revolt.Client, metaclass=CommandsMeta):
"""
return self.all_commands[name]
def add_command(self, name: str, command: Command):
def add_command(self, command: Command[Self]):
"""Adds a command, this is typically only used for dynamic commands, you should use the `commands.command` decorator for most usecases.
Parameters
@@ -99,13 +147,37 @@ class CommandsClient(revolt.Client, metaclass=CommandsMeta):
command: :class:`Command`
The command to be added
"""
self.all_commands[name] = command
self.all_commands[command.name] = command
for alias in command.aliases:
self.all_commands[alias] = command
def remove_command(self, name: str) -> Optional[Command[Self]]:
"""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]:
return Context
def get_context(self, message: revolt.Message) -> type[Context[Self]]:
return Context[Self]
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.
@@ -171,15 +243,15 @@ class CommandsClient(revolt.Client, metaclass=CommandsMeta):
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):
async def on_command_error(self, ctx: Context[Self], error: Exception, /):
traceback.print_exception(type(error), error, error.__traceback__)
on_message = process_commands
async def bot_check(self, context: Context) -> bool:
async def bot_check(self, context: Context[Self]) -> bool:
"""A global check for the bot that stops commands from running on certain criteria.
Parameters
@@ -193,3 +265,103 @@ class CommandsClient(revolt.Client, metaclass=CommandsMeta):
"""
return True
def add_cog(self, cog: Cog[Self]):
"""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[Self]:
"""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[Self]:
"""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]
+58
View File
@@ -0,0 +1,58 @@
from __future__ import annotations
from typing import Any, Generic, Optional, cast
from .command import Command
from .utils import ClientT
__all__ = ("Cog", "CogMeta")
class CogMeta(type, Generic[ClientT]):
_commands: list[Command[ClientT]]
qualified_name: str
def __new__(cls, name: str, bases: tuple[type, ...], attrs: dict[str, Any], *, qualified_name: Optional[str] = None):
commands: list[Command[ClientT]] = []
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(cast(Command[ClientT], value)) # cant verify generic at runtime so must cast
self._commands = commands
self.qualified_name = qualified_name or name
return self
class Cog(Generic[ClientT], metaclass=CogMeta):
_commands: list[Command[ClientT]]
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: ClientT):
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: ClientT):
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[ClientT]]:
return self._commands
+126 -55
View File
@@ -4,23 +4,28 @@ import inspect
import traceback
from contextlib import suppress
from typing import (TYPE_CHECKING, Annotated, Any, Callable, Coroutine,
Literal, Optional, Union, get_args, get_origin)
Generic, Literal, Optional, Union, get_args, get_origin)
import revolt
from revolt.utils import copy_doc, maybe_coroutine
from .errors import InvalidLiteralArgument
from .errors import InvalidLiteralArgument, UnionConverterError
from .utils import ClientT, evaluate_parameters
if TYPE_CHECKING:
from .checks import Check
from .cog import Cog
from .context import Context
from .group import Group
__all__ = (
"Command",
"command"
)
class Command:
NoneType = type(None)
class Command(Generic[ClientT]):
"""Class for holding info about a command.
Parameters
@@ -31,19 +36,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", "signature", "checks")
__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.checks: list[Check] = getattr(callback, "_checks", [])
self.parameters = evaluate_parameters(self.signature.parameters.values(), getattr(callback, "__globals__", {}))
self.checks: list[Check[ClientT]] = getattr(callback, "_checks", [])
self.parent: Optional[Group[ClientT]] = None
self.cog: Optional[Cog[ClientT]] = None
self._error_handler: Callable[[Any, Context[ClientT], Exception], Coroutine[Any, Any, Any]] = type(self)._default_error_handler
self.description = callback.__doc__
async def invoke(self, context: Context, *args, **kwargs) -> Any:
async def invoke(self, context: Context[ClientT], *args: Any, **kwargs: Any) -> Any:
"""Runs the command and calls the error handler if the command errors.
Parameters
@@ -54,12 +69,12 @@ class Command:
The arguments for the command
"""
try:
return await self.callback(self._client, context, *args, **kwargs)
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, **kwargs) -> Any:
def __call__(self, context: Context[ClientT], *args: Any, **kwargs: Any) -> Any:
return self.invoke(context, *args, **kwargs)
def error(self, func: Callable[..., Coroutine[Any, Any, Any]]):
@@ -79,70 +94,126 @@ 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[ClientT], error: Exception):
traceback.print_exception(type(error), error, error.__traceback__)
@staticmethod
def extract_type(t):
if origin := get_origin(t):
if origin is Annotated:
return get_args(t)[1]
@classmethod
async def handle_origin(cls, context: Context[ClientT], 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
return t
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, parameter: inspect.Parameter, context: Context):
if annot := parameter.annotation:
if annot is str: # no converting is needed - its already a string
async def convert_argument(cls, arg: str, annotation: Any, context: Context[ClientT]) -> 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(annot):
if origin is Union:
for converter in get_args(annot):
try:
return await maybe_coroutine(converter, arg, context)
except:
if converter is None:
context.view.undo()
return None
elif origin is Annotated:
converter: Callable[[str, Context], Any] = get_args(annot)[1] # the typehint affects the other if statement somehow
return await maybe_coroutine(converter, arg, context)
elif origin is Literal:
if arg in get_args(annot):
return arg
else:
raise InvalidLiteralArgument(arg)
if origin := get_origin(annotation):
return await cls.handle_origin(context, origin, annotation, arg)
else:
annot: Callable[..., Any]
return await maybe_coroutine(annot, arg, context)
return await maybe_coroutine(annotation, arg, context)
else:
return arg
async def parse_arguments(self, context: Context):
for name, parameter in list(self.signature.parameters.items())[2:]:
async def parse_arguments(self, context: Context[ClientT]):
# 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:
context.kwargs[name] = await self.convert_argument(context.view.get_rest(), parameter, context)
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, context))
context.args.append(await self.convert_argument(context.view.get_next_word(), parameter.annotation, context))
elif parameter.kind == parameter.POSITIONAL_OR_KEYWORD:
context.args.append(await self.convert_argument(context.view.get_next_word(), parameter, context))
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"<Command name=\"{self.name}\">"
return f"<{self.__class__.__name__} name=\"{self.name}\">"
def command(*, name: Optional[str] = None, aliases: Optional[list[str]] = None, cls: type[Command] = Command):
@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: list[str] = []
if self.parent:
parent = self.parent
while parent:
parents.append(parent.name)
parent = parent.parent
parameters: list[str] = []
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[ClientT]] = Command, usage: Optional[str] = None):
"""A decorator that turns a function into a :class:`Command`.
Parameters
@@ -160,6 +231,6 @@ def command(*, name: Optional[str] = None, aliases: Optional[list[str]] = None,
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
+24 -11
View File
@@ -1,21 +1,22 @@
from __future__ import annotations
from typing import TYPE_CHECKING, Any, Optional
from typing import TYPE_CHECKING, Any, Generic, Optional
import revolt
from revolt.utils import maybe_coroutine
from .command import Command
from .group import Group
from .utils import ClientT
if TYPE_CHECKING:
from .client import CommandsClient
from .view import StringView
__all__ = (
"Context",
)
class Context(revolt.Messageable):
class Context(revolt.Messageable, Generic[ClientT]):
"""Stores metadata the commands execution.
Attributes
@@ -41,24 +42,24 @@ class Context(revolt.Messageable):
"""
__slots__ = ("command", "invoked_with", "args", "message", "server", "channel", "author", "view", "kwargs", "state", "client")
def _get_channel_id(self) -> str:
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: CommandsClient):
def __init__(self, command: Optional[Command[ClientT]], 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.args: list[Any] = []
self.kwargs: dict[str, Any] = {}
self.server = message.server
self.channel = message.channel
self.author = message.author
self.state = message.state
async def invoke(self) -> Any:
"""Invokes the command, this is equal to `await command.invoke(context, context.args)`.
"""Invokes the command.
.. note:: If the command is `None`, this function will do nothing.
@@ -69,11 +70,23 @@ class Context(revolt.Messageable):
"""
if command := self.command:
await command.parse_arguments(self)
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) -> bool:
async def can_run(self, command: Optional[Command[ClientT]] = None) -> bool:
"""Runs all of the commands checks, and returns true if all of them pass"""
return all([await maybe_coroutine(check, self) for check in (self.command.checks if self.command else [])])
command = command or self.command
return all([await maybe_coroutine(check, self) for check in (command.checks if command else [])])
+81 -3
View File
@@ -1,8 +1,24 @@
from typing import Annotated
from __future__ import annotations
from .errors import BadBoolArgument
import re
from typing import TYPE_CHECKING, Annotated, TypeVar
IntConverter = Annotated[int, lambda arg, _: int(arg)]
from revolt import Category, Channel, Member, User, utils
from .context import Context
from .errors import (BadBoolArgument, CategoryConverterError,
ChannelConverterError, MemberConverterError, ServerOnly,
UserConverterError)
if TYPE_CHECKING:
from .client import CommandsClient
__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})>")
ClientT = TypeVar("ClientT", bound="CommandsClient")
def bool_converter(arg: str, _):
lowered = arg.lower()
@@ -13,4 +29,66 @@ def bool_converter(arg: str, _):
else:
raise BadBoolArgument(lowered)
def category_converter(arg: str, context: Context[ClientT]) -> 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[ClientT]) -> 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[ClientT]) -> 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[ClientT]) -> 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)
def int_converter(arg: str, context: Context[ClientT]) -> int:
return int(arg)
IntConverter = Annotated[int, int_converter]
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]
+37 -1
View File
@@ -10,7 +10,12 @@ __all__ = (
"ServerOnly",
"ConverterError",
"InvalidLiteralArgument",
"BadBoolArgument"
"BadBoolArgument",
"CategoryConverterError",
"ChannelConverterError",
"UserConverterError",
"MemberConverterError",
"MissingSetup",
)
class CommandError(RevoltError):
@@ -44,6 +49,9 @@ class NotServerOwner(CheckError):
class ServerOnly(CheckError):
"""Raised when a check requires the command to be ran in a server"""
class MissingPermissionsError(CheckError):
"""Raised when a check requires permissions the user does not have"""
class ConverterError(CommandError):
"""Base class for all converter errors"""
@@ -52,3 +60,31 @@ class InvalidLiteralArgument(ConverterError):
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"""
+119
View File
@@ -0,0 +1,119 @@
from __future__ import annotations
from typing import TYPE_CHECKING, Any, Callable, Coroutine, Optional, TypeVar
from .command import Command
if TYPE_CHECKING:
from .client import CommandsClient
__all__ = (
"Group",
"group"
)
ClientT = TypeVar("ClientT", bound="CommandsClient")
class Group(Command[ClientT]):
"""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[ClientT]] = {}
super().__init__(callback, name, aliases)
def command(self, *, name: Optional[str] = None, aliases: Optional[list[str]] = None, cls: type[Command[ClientT]] = Command[ClientT]):
"""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[ClientT]]] = 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[ClientT]]:
return list(self.subcommands.values())
def group(*, name: Optional[str] = None, aliases: Optional[list[str]] = None, cls: type[Group[ClientT]] = 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
+204
View File
@@ -0,0 +1,204 @@
from __future__ import annotations
from abc import ABC, abstractmethod
from typing import TYPE_CHECKING, Any, Generic, Optional, TypedDict, Union
from typing_extensions import NotRequired
from .cog import Cog
from .command import Command
from .context import Context
from .group import Group
from .utils import ClientT
if TYPE_CHECKING:
from revolt import File, Message, Messageable, MessageReply, SendableEmbed
from .cog import Cog
__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, Generic[ClientT]):
@abstractmethod
async def create_bot_help(self, context: Context[ClientT], commands: dict[Optional[Cog[ClientT]], list[Command[ClientT]]]) -> Union[str, SendableEmbed, MessagePayload]:
raise NotImplementedError
@abstractmethod
async def create_command_help(self, context: Context[ClientT], command: Command[ClientT]) -> Union[str, SendableEmbed, MessagePayload]:
raise NotImplementedError
@abstractmethod
async def create_group_help(self, context: Context[ClientT], group: Group[ClientT]) -> Union[str, SendableEmbed, MessagePayload]:
raise NotImplementedError
@abstractmethod
async def create_cog_help(self, context: Context[ClientT], cog: Cog[ClientT]) -> Union[str, SendableEmbed, MessagePayload]:
raise NotImplementedError
async def send_help_command(self, context: Context[ClientT], message_payload: MessagePayload) -> Message:
return await context.send(**message_payload)
async def filter_commands(self, context: Context[ClientT], commands: list[Command[ClientT]]) -> list[Command[ClientT]]:
filtered: list[Command[ClientT]] = []
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[ClientT], commands: list[Command[ClientT]]) -> dict[Optional[Cog[ClientT]], list[Command[ClientT]]]:
cogs: dict[Optional[Cog[ClientT]], list[Command[ClientT]]] = {}
for command in commands:
cogs.setdefault(command.cog, []).append(command)
return cogs
async def handle_message(self, context: Context[ClientT], message: Message):
pass
async def get_channel(self, context: Context[ClientT]) -> Messageable:
return context
@abstractmethod
async def handle_no_command_found(self, context: Context[ClientT], name: str) -> Any:
raise NotImplementedError
@abstractmethod
async def handle_no_cog_found(self, context: Context[ClientT], name: str) -> Any:
raise NotImplementedError
class DefaultHelpCommand(HelpCommand[ClientT]):
def __init__(self, default_cog_name: str = "No Cog"):
self.default_cog_name = default_cog_name
async def create_bot_help(self, context: Context[ClientT], commands: dict[Optional[Cog[ClientT]], list[Command[ClientT]]]) -> Union[str, SendableEmbed, MessagePayload]:
lines = ["```"]
for cog, cog_commands in commands.items():
cog_lines: list[str] = []
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[ClientT], cog: Cog[ClientT]) -> 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[ClientT], command: Command[ClientT]) -> 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[ClientT], group: Group[ClientT]) -> 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[ClientT], 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[ClientT], name: str):
channel = await self.get_channel(context)
await channel.send(f"Cog `{name}` not found.")
class HelpCommandImpl(Command[ClientT]):
def __init__(self, client: ClientT):
self.client = client
async def callback(_: Union[ClientT, Cog[ClientT]], context: Context[ClientT], *args: str):
await help_command_impl(context.client, context, *args)
super().__init__(callback=callback, name="help", aliases=[])
self.description = "Shows help for a command, cog or the entire bot"
async def help_command_impl(self: ClientT, context: Context[ClientT], *arguments: str):
help_command = self.help_command
if not help_command:
return
filtered_commands = await help_command.filter_commands(context, self.commands)
commands = await help_command.group_commands(context, filtered_commands)
if not arguments:
payload = await 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 help_command.create_cog_help(context, cog)
else:
return await help_command.handle_no_command_found(context, command_name)
else:
if isinstance(command, Group):
payload = await help_command.create_group_help(context, command)
else:
payload = await 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 help_command.send_help_command(context, msg_payload)
+27
View File
@@ -0,0 +1,27 @@
from __future__ import annotations
from inspect import Parameter
from typing import TYPE_CHECKING, Any, Iterable
from typing_extensions import TypeVar
if TYPE_CHECKING:
from .client import CommandsClient
__all__ = ("evaluate_parameters",)
ClientT = TypeVar("ClientT", bound="CommandsClient", default="CommandsClient")
def evaluate_parameters(parameters: Iterable[Parameter], globals: dict[str, Any]) -> list[Parameter]:
new_parameters: list[Parameter] = []
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
+5 -2
View File
@@ -14,6 +14,9 @@ class StringView:
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:
@@ -22,7 +25,7 @@ class StringView:
return self.temp
char = self.next_char()
temp = []
temp: list[str] = []
while char == " ":
char = self.next_char()
@@ -38,7 +41,7 @@ class StringView:
else:
temp.append(char)
try:
while (char := self.next_char()) != " ":
while (char := self.next_char()) not in " \n":
temp.append(char)
except StopIteration:
pass
+5 -6
View File
@@ -1,12 +1,11 @@
import io
import os
from typing import Optional, Union
__all__ = ("File",)
class File:
"""Respresents a file about to be uploaded to revolt
Parameters
-----------
file: Union[str, bytes]
@@ -17,19 +16,19 @@ class File:
Determines if the file will be a spoiler, this prefexes the filename with `SPOILER_`
"""
__slots__ = ("f", "spoiler", "filename")
def __init__(self, file: Union[str, bytes], *, filename: Optional[str] = None, spoiler: bool = False):
if isinstance(file, str):
self.f = open(file, "rb")
elif isinstance(file, bytes):
else:
self.f = io.BytesIO(file)
if filename is None and isinstance(file, str):
filename = self.f.name
self.spoiler = spoiler or (filename and filename.startswith("SPOILER_"))
if self.spoiler and (filename and not filename.startswith("SPOILER_")):
filename = f"SPOILER_{filename}"
self.filename = filename
self.filename = filename
+37 -33
View File
@@ -1,14 +1,13 @@
from __future__ import annotations
from typing import Callable, Iterator, Optional, TypeVar, Union, overload
from typing import Callable, Iterator, Optional, Union, overload
__all__ = ("flag_value", "Flags", "UserBadges")
from typing_extensions import Self
F_T = TypeVar("F_T", bound="Flags")
F_V = TypeVar("F_V", bound="flag_value")
__all__ = ("Flag", "Flags", "UserBadges")
class flag_value:
class Flag:
__slots__ = ("flag", "__doc__")
def __init__(self, func: Callable[[], int]):
@@ -16,14 +15,14 @@ class flag_value:
self.__doc__ = func.__doc__
@overload
def __get__(self: F_V, instance: None, owner: type[F_T]) -> F_V:
def __get__(self: Self, instance: None, owner: type[Flags]) -> Self:
...
@overload
def __get__(self, instance: F_T, owner: type[F_T]) -> bool:
def __get__(self, instance: Flags, owner: type[Flags]) -> bool:
...
def __get__(self: F_V, instance: Optional[F_T], owner: type[F_T]) -> Union[F_V, bool]:
def __get__(self: Self, instance: Optional[Flags], owner: type[Flags]) -> Union[Self, bool]:
if instance is None:
return self
@@ -33,14 +32,19 @@ class flag_value:
instance._set_flag(self.flag, value)
class Flags:
def __init__(self, **kwargs: bool):
self.value = 0
FLAG_NAMES: list[str]
for k, v in kwargs.items():
def __init_subclass__(cls) -> None:
cls.FLAG_NAMES = []
def __init__(self, value: int = 0, **flags: bool):
self.value = value
for k, v in flags.items():
setattr(self, k, v)
@classmethod
def _from_value(cls: type[F_T], value: int) -> F_T:
def _from_value(cls, value: int) -> Self:
self = cls.__new__(cls)
self.value = value
return self
@@ -54,31 +58,31 @@ class Flags:
else:
self.value &= ~flag
def __eq__(self: F_T, other: F_T) -> bool:
def __eq__(self, other: Self) -> bool:
return self.value == other.value
def __ne__(self: F_T, other: F_T) -> bool:
def __ne__(self, other: Self) -> bool:
return not self.__eq__(other)
def __or__(self: F_T, other: F_T) -> F_T:
def __or__(self, other: Self) -> Self:
return self.__class__._from_value(self.value | other.value)
def __and__(self: F_T, other: F_T) -> F_T:
def __and__(self, other: Self) -> Self:
return self.__class__._from_value(self.value & other.value)
def __invert__(self: F_T) -> F_T:
def __invert__(self) -> Self:
return self.__class__._from_value(~self.value)
def __add__(self: F_T, other: F_T) -> F_T:
def __add__(self, other: Self) -> Self:
return self | other
def __sub__(self: F_T, other: F_T) -> F_T:
def __sub__(self, other: Self) -> Self:
return self & ~other
def __lt__(self: F_T, other: F_T) -> bool:
def __lt__(self, other: Self) -> bool:
return self.value < other.value
def __gt__(self: F_T, other: F_T) -> bool:
def __gt__(self, other: Self) -> bool:
return self.value > other.value
def __repr__(self):
@@ -86,8 +90,8 @@ class Flags:
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__)
if isinstance(value, Flag):
yield name, self._check_flag(value.flag)
def __hash__(self) -> int:
return hash(self.value)
@@ -95,52 +99,52 @@ class Flags:
class UserBadges(Flags):
"""Contains all user badges"""
@flag_value
@Flag
def developer():
""":class:`bool` The developer badge."""
return 1 << 0
@flag_value
@Flag
def translator():
""":class:`bool` The translator badge."""
return 1 << 1
@flag_value
@Flag
def supporter():
""":class:`bool` The supporter badge."""
return 1 << 2
@flag_value
@Flag
def responsible_disclosure():
""":class:`bool` The responsible disclosure badge."""
return 1 << 3
@flag_value
@Flag
def founder():
""":class:`bool` The founder badge."""
return 1 << 4
@flag_value
@Flag
def platform_moderation():
""":class:`bool` The platform moderation badge."""
return 1 << 5
@flag_value
@Flag
def active_supporter():
""":class:`bool` The active supporter badge."""
return 1 << 6
@flag_value
@Flag
def paw():
""":class:`bool` The paw badge."""
return 1 << 7
@flag_value
@Flag
def early_adopter():
""":class:`bool` The early adopter badge."""
return 1 << 8
@flag_value
@Flag
def reserved_relevant_joke_badge_1():
""":class:`bool` The reserved relevant joke badge 1 badge."""
return 1 << 9
+163 -88
View File
@@ -6,8 +6,9 @@ from typing import (TYPE_CHECKING, Any, Coroutine, Literal, Optional, TypeVar,
import aiohttp
import ulid
from .errors import HTTPError, ServerError
from .errors import Forbidden, HTTPError, ServerError
from .file import File
from .utils import Missing
try:
import ujson as _json
@@ -22,39 +23,44 @@ if TYPE_CHECKING:
from .types import ApiInfo
from .types import Autumn as AutumnPayload
from .types import Channel, DMChannel
from .types import Embed as EmbedPayload
from .types import GetServerMembers
from .types import Emoji as EmojiPayload
from .types import EmojiParent, GetServerMembers, GroupDMChannel
from .types import Interactions as InteractionsPayload
from .types import Invite
from .types import Masquerade as MasqueradePayload
from .types import Member
from .types import Member as MemberPayload
from .types import Message as MessagePayload
from .types import (MessageReplyPayload, MessageWithUserData, Role, Server,
ServerBans, ServerInvite, TextChannel)
from .types import (MessageReplyPayload, MessageWithUserData,
PartialInvite, Role)
from .types import SendableEmbed as SendableEmbedPayload
from .types import Server, ServerBans, TextChannel
from .types import User as UserPayload
from .types import UserProfile, VoiceChannel
__all__ = ("HttpClient",)
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:
@@ -73,7 +79,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
@@ -81,14 +90,16 @@ class HttpClient:
if 200 <= resp_code <= 300:
return response
elif resp_code == 401:
raise Forbidden("401: Missing Permissions")
else:
raise HTTPError(resp_code)
async def upload_file(self, file: File, tag: str) -> AutumnPayload:
async def upload_file(self, file: File, tag: Literal["attachments", "avatars", "backgrounds", "icons", "banners", "emojis"]) -> 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()
@@ -106,7 +117,7 @@ class HttpClient:
else:
return response
async def send_message(self, channel: str, content: Optional[str], embeds: Optional[list[EmbedPayload]], attachments: Optional[list[File]], replies: Optional[list[MessageReplyPayload]], masquerade: Optional[MasqueradePayload]) -> 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], interactions: Optional[InteractionsPayload]) -> MessagePayload:
json: dict[str, Any] = {}
if content:
@@ -130,10 +141,20 @@ class HttpClient:
if masquerade:
json["masquerade"] = masquerade
if interactions:
json["interactions"] = interactions
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]:
@@ -141,44 +162,44 @@ class HttpClient:
def fetch_message(self, channel: str, message: str) -> Request[MessagePayload]:
return self.request("GET", f"/channels/{channel}/messages/{message}")
@overload
def fetch_messages(
self,
channel: str,
self,
channel: str,
sort: SortType,
*,
limit: Optional[int] = ...,
before: Optional[str] = ...,
after: Optional[str] = ...,
nearby: Optional[str] = ...,
*,
limit: Optional[int] = ...,
before: Optional[str] = ...,
after: Optional[str] = ...,
nearby: Optional[str] = ...,
include_users: Literal[False] = ...
) -> Request[list[MessagePayload]]:
...
@overload
def fetch_messages(
self,
channel: str,
self,
channel: str,
sort: SortType,
*,
limit: Optional[int] = ...,
before: Optional[str] = ...,
after: Optional[str] = ...,
nearby: Optional[str] = ...,
*,
limit: Optional[int] = ...,
before: Optional[str] = ...,
after: Optional[str] = ...,
nearby: Optional[str] = ...,
include_users: Literal[True] = ...
) -> Request[MessageWithUserData]:
...
def fetch_messages(
self,
channel: str,
self,
channel: str,
sort: SortType,
*,
limit: Optional[int] = None,
before: Optional[str] = None,
after: Optional[str] = None,
nearby: Optional[str] = None,
*,
limit: Optional[int] = None,
before: Optional[str] = None,
after: Optional[str] = None,
nearby: Optional[str] = None,
include_users: bool = False
) -> Request[Union[list[MessagePayload], MessageWithUserData]]:
@@ -200,12 +221,12 @@ class HttpClient:
@overload
def search_messages(
self,
channel: str,
self,
channel: str,
query: str,
*,
limit: Optional[int] = ...,
before: Optional[str] = ...,
*,
limit: Optional[int] = ...,
before: Optional[str] = ...,
after: Optional[str] = ...,
sort: Optional[SortType] = ...,
include_users: Literal[False] = ...
@@ -214,12 +235,12 @@ class HttpClient:
@overload
def search_messages(
self,
channel: str,
self,
channel: str,
query: str,
*,
limit: Optional[int] = ...,
before: Optional[str] = ...,
*,
limit: Optional[int] = ...,
before: Optional[str] = ...,
after: Optional[str] = ...,
sort: Optional[SortType] = ...,
include_users: Literal[True] = ...
@@ -227,18 +248,18 @@ class HttpClient:
...
def search_messages(
self,
channel: str,
self,
channel: str,
query: str,
*,
limit: Optional[int] = None,
before: Optional[str] = None,
*,
limit: Optional[int] = None,
before: Optional[str] = None,
after: Optional[str] = None,
sort: Optional[SortType] = None,
include_users: bool = False
) -> Request[Union[list[MessagePayload], MessageWithUserData]]:
json = {"query": query, "include_users": include_users}
json: dict[str, Any] = {"query": query, "include_users": include_users}
if limit:
json["limit"] = limit
@@ -266,8 +287,8 @@ 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]:
@@ -279,20 +300,20 @@ class HttpClient:
def close_channel(self, channel_id: str) -> Request[None]:
return self.request("DELETE", f"/channels/{channel_id}")
def set_channel_role_permissions(self, channel_id: str, role_id: str, channel_permissions: int) -> Request[None]:
payload = {"permissions": channel_permissions}
return self.request("PUT", f"/channels/{channel_id}/permissions/{role_id}", json=payload)
def set_channel_default_permissions(self, channel_id: str, channel_permissions: int) -> Request[None]:
payload = {"permissions": channel_permissions}
return self.request("PUT", f"/channels/{channel_id}/permissions/default", json=payload)
def fetch_server(self, server_id: str) -> Request[Server]:
return self.request("GET", f"/servers/{server_id}")
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,
@@ -304,7 +325,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]:
@@ -323,32 +344,86 @@ class HttpClient:
def unban_member(self, server_id: str, member_id: str) -> Request[None]:
return self.request("DELETE", f"/servers/{server_id}/bans/{member_id}")
def fetch_bans(self, server_id: str) -> Request[ServerBans]:
return self.request("GET", f"/servers/{server_id}/bans")
def set_role_permissions(self, server_id: str, role_id: str, server_permissions: int, channel_permissions: int) -> Request[None]:
payload = {
"permissions": {
"server": server_permissions,
"channel": channel_permissions
}
}
return self.request("PUT", f"/servers/{server_id}/permissions/{role_id}", json=payload, nonce=False)
def set_default_permissions(self, server_id: str, server_permissions: int, channel_permissions: int) -> Request[None]:
payload = {
"permissions": {
"server": server_permissions,
"channel": channel_permissions
}
}
return self.request("PUT", f"/servers/{server_id}/permissions/default", json=payload, nonce=False)
def create_role(self, server_id: str, name: str) -> Request[Role]:
return self.request("POST", f"/servers/{server_id}/roles", json={"name": name}, nonce=False)
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: list[str] | None, 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: list[str] | None, 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: list[str] | None, 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"]
return await self.request("PATCH", "/users/@me", json=values)
def set_guild_channel_default_permissions(self, channel_id: str, allow: int, deny: int) -> Request[None]:
return self.request("PUT", f"/channels/{channel_id}/permissions/default", json={"permissions": {"allow": allow, "deny": deny}})
def set_guild_channel_role_permissions(self, channel_id: str, role_id: str, allow: int, deny: int) -> Request[None]:
return self.request("PUT", f"/channels/{channel_id}/permissions/{role_id}", json={"permissions": {"allow": allow, "deny": deny}})
def set_group_channel_default_permissions(self, channel_id: str, value: int):
return self.request("PUT", f"/channels/{channel_id}/permissions/default", json={"permissions": value})
def set_server_role_permissions(self, server_id: str, role_id: str, allow: int, deny: int):
return self.request("PUT", f"/servers/{server_id}/permissions/{role_id}", json={"permissions": {"allow": allow, "deny": deny}})
def set_server_default_permissions(self, server_id: str, value: int):
return self.request("PUT", f"/servers/{server_id}/permissions/default", json={"permissions": value})
def add_reaction(self, channel_id: str, message_id: str, emoji: str):
return self.request("PUT", f"/channels/{channel_id}/messages/{message_id}/reactions/{emoji}")
def remove_reaction(self, channel_id: str, message_id: str, emoji: str, user_id: Optional[str], remove_all: bool):
return self.request("PUT", f"/channels/{channel_id}/messages/{message_id}/reactions/{emoji}")
def remove_all_reactions(self, channel_id: str, message_id: str):
return self.request("DELETE", f"/channels/{channel_id}/messages/{message_id}/reactions")
def delete_emoji(self, emoji_id: str):
return self.request("DELETE", f"/custom/emoji/{emoji_id}")
def fetch_emoji(self, emoji_id: str) -> Request[EmojiPayload]:
return self.request("GET", f"/custom/emoji/{emoji_id}")
async def create_emoji(self, name: str, file: File, nsfw: bool, parent: EmojiParent) -> EmojiPayload:
asset = await self.upload_file(file, "emojis")
return await self.request("PUT", f"/custom/emoji/{asset['id']}", json={"name": name, "parent": parent, "nsfw": nsfw})
def edit_member(self, server_id: str, member_id: str, remove: list[str] | None, values: dict[str, Any]) -> Request[MemberPayload]:
return self.request("PATCH", f"/servers/{server_id}/members/{member_id}", json={"remove": remove, **values})
def delete_messages(self, channel_id: str, messages: list[str]):
return self.request("DELETE", f"/channels/{channel_id}/messages/bulk", json={"ids": messages})
+74
View File
@@ -0,0 +1,74 @@
from __future__ import annotations
from typing import TYPE_CHECKING
from .asset import Asset
from .utils import Ulid
if TYPE_CHECKING:
from .state import State
from .types import Invite as InvitePayload
__all__ = ("Invite",)
class Invite(Ulid):
"""Represents a server invite.
Attributes
-----------
code: :class:`str`
The code for the invite
id: :class:`str`
Alias for :attr:`code`
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
"""
__slots__ = ("state", "code", "id", "server", "channel", "user_name", "user_avatar", "user", "member_count")
def __init__(self, data: InvitePayload, code: str, state: State):
self.state = state
self.code = code
self.id = 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)
+122 -9
View File
@@ -1,11 +1,15 @@
from __future__ import annotations
import datetime
from typing import TYPE_CHECKING, Optional
from .asset import Asset
from .permissions import Permissions
from .permissions_calculator import calculate_permissions
from .user import User
if TYPE_CHECKING:
from .channel import Channel
from .server import Server
from .state import State
from .types import File
@@ -19,7 +23,7 @@ def flattern_user(member: Member, user: User):
class Member(User):
"""Represents a member of a server, subclasses :class:`User`
Attributes
-----------
nickname: Optional[:class:`str`]
@@ -31,14 +35,16 @@ class Member(User):
guild_avatar: Optional[:class:`Asset`]
The member's guild avatar if any
"""
__slots__ = ("_state", "nickname", "roles", "server", "guild_avatar")
__slots__ = ("state", "nickname", "roles", "server", "guild_avatar", "joined_at", "current_timeout")
def __init__(self, data: MemberPayload, server: Server, state: State):
user = state.get_user(data["_id"]["user"])
flattern_user(self, user)
self._state = state
self.nickname = data.get("nickname")
# due to not having a user payload and only a user object we have to manually add all the attributes instead of calling User.__init__
flattern_user(self, user)
user._members.add(self)
self.state = state
if avatar := data.get("avatar"):
self.guild_avatar = Asset(avatar, state)
@@ -49,19 +55,126 @@ class Member(User):
self.roles = sorted(roles, key=lambda role: role.rank, reverse=True)
self.server = server
self.nickname = data.get("nickname")
joined_at = data["joined_at"]
if isinstance(joined_at, int):
self.joined_at = datetime.datetime.fromtimestamp(joined_at / 1000)
else:
self.joined_at = datetime.datetime.strptime(joined_at, "%Y-%m-%dT%H:%M:%S.%f%z")
self.current_timeout = None
if current_timeout := data.get("timeout"):
self.current_timeout = datetime.datetime.strptime(current_timeout, "%Y-%m-%dT%H:%M:%S.%f%z")
@property
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
@property
def mention(self) -> str:
""":class:`str`: Returns a string that allows you to mention the given member."""
return f"<@{self.id}>"
def _update(self, *, nickname: Optional[str] = None, avatar: Optional[File] = None, roles: Optional[list[str]] = None):
if nickname:
if nickname is not None:
self.nickname = nickname
if avatar:
if avatar is not None:
self.guild_avatar = Asset(avatar, self.state)
if roles:
if roles is not None:
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)
async def timeout(self, length: datetime.timedelta):
"""Timeouts the member
Parameters
-----------
length: :class:`datetime.timedelta`
The length of the timeout
"""
ends_at = datetime.datetime.utcnow() + length
await self.state.http.edit_member(self.server.id, self.id, None, {"timeout": ends_at.isoformat()})
def get_permissions(self) -> Permissions:
"""Gets the permissions for the member in the server
Returns
--------
:class:`Permissions`
The members permissions
"""
return calculate_permissions(self, self.server)
def get_channel_permissions(self, channel: Channel):
"""Gets the permissions for the member in the server taking into account the channel as well
Parameters
-----------
channel: :class:`Channel`
The channel to calculate permissions with
Returns
--------
:class:`Permissions`
The members permissions
"""
return calculate_permissions(self, channel)
def has_permissions(self, **permissions: bool) -> bool:
"""Computes if the member has the specified permissions
Parameters
-----------
permissions: :class:`bool`
The permissions to check, this also accepted `False` if you need to check if the member does not have the permission
Returns
--------
:class:`bool`
Whether or not they have the permissions
"""
calculated_perms = self.get_permissions()
return all([getattr(calculated_perms, key, False) == value for key, value in permissions.items()])
def has_channel_permissions(self, channel: Channel, **permissions: bool) -> bool:
"""Computes if the member has the specified permissions, taking into account the channel as well
Parameters
-----------
channel: :class:`Channel`
The channel to calculate permissions with
permissions: :class:`bool`
The permissions to check, this also accepted `False` if you need to check if the member does not have the permission
Returns
--------
:class:`bool`
Whether or not they have the permissions
"""
calculated_perms = self.get_channel_permissions(channel)
return all([getattr(calculated_perms, key, False) == value for key, value in permissions.items()])
+118 -35
View File
@@ -1,26 +1,31 @@
from __future__ import annotations
import datetime
from typing import TYPE_CHECKING, NamedTuple, Optional
from typing import TYPE_CHECKING, Any, Optional
from .asset import Asset, PartialAsset
from .channel import Messageable
from .embed import Embed
from .embed import SendableEmbed, to_embed
from .utils import Ulid
if TYPE_CHECKING:
from .server import Server
from .state import State
from .types import Embed as EmbedPayload
from .types import Interactions as InteractionsPayload
from .types import Masquerade as MasqueradePayload
from .types import Message as MessagePayload
from .types import MessageReplyPayload
from .user import User
__all__ = (
"Message",
"MessageReply",
"Masquerade"
"Masquerade",
"MessageInteractions"
)
class Message:
class Message(Ulid):
"""Represents a message
Attributes
@@ -31,12 +36,10 @@ 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
server: :class:`Server`
The server the message was sent in
author: Union[:class:`Member`, :class:`User`]
The author of the message, will be :class:`User` in DMs
edited_at: Optional[:class:`datetime.datetime`]
@@ -47,25 +50,27 @@ 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
reactions: dict[str, list[:class:`User`]]
The reactions on the message
interactions: Optional[:class:`MessageInteractions`]
The interactions on the message, if any
"""
__slots__ = ("state", "id", "content", "attachments", "embeds", "channel", "server", "author", "edited_at", "mentions", "replies", "reply_ids")
__slots__ = ("state", "id", "content", "attachments", "embeds", "channel", "author", "edited_at", "mentions", "replies", "reply_ids", "reactions", "interactions")
def __init__(self, data: MessagePayload, state: State):
self.state = state
self.id = data["_id"]
self.content = data["content"]
self.content = data.get("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"])
if server_id := self.channel.server_id:
author = state.get_member(server_id, data["author"])
else:
author = state.get_user(data["author"])
@@ -79,50 +84,89 @@ class Message:
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")
self.edited_at: Optional[datetime.datetime] = datetime.datetime.strptime(edited_at, "%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 = []
self.replies: list[Message] = []
self.reply_ids: list[str] = []
for reply in data.get("replies", []):
try:
message = state.get_message(reply)
self.replies.append(message)
except KeyError:
except LookupError:
pass
self.reply_ids.append(reply)
def _update(self, *, content: Optional[str] = None, edited_at: Optional[str] = None) -> Message:
if content:
reactions = data.get("reactions", {})
self.reactions: dict[str, list[User]] = {}
for emoji, users in reactions.items():
self.reactions[emoji] = [self.state.get_user(user_id) for user_id in users]
if interactions := data.get("interactions"):
self.interactions = MessageInteractions(reactions=interactions.get("reactions"), restrict_reactions=interactions.get("restrict_reactions", False))
else:
self.interactions = None
def _update(self, *, content: Optional[str] = None, embeds: Optional[list[EmbedPayload]] = None, edited: int):
if content is not None:
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 = datetime.datetime.fromtimestamp(edited / 1000)
return self
if embeds is not None:
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)
class MessageReply(NamedTuple):
"""A namedtuple which represents a reply to a message.
def reply(self, *args: Any, mention: bool = False, **kwargs: Any):
"""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)])
async def add_reaction(self, emoji: str):
await self.state.http.add_reaction(self.channel.id, self.id, emoji)
async def remove_reaction(self, emoji: str, user: Optional[User] = None, remove_all: bool = False):
await self.state.http.remove_reaction(self.channel.id, self.id, emoji, user.id if user else None, remove_all)
async def remove_all_reactions(self):
await self.state.http.remove_all_reactions(self.channel.id, self.id)
@property
def server(self) -> Server:
""":class:`Server` The server this voice channel belongs too"""
return self.channel.server
class MessageReply:
"""represents a reply to a message.
Parameters
-----------
@@ -131,14 +175,17 @@ class MessageReply(NamedTuple):
mention: :class:`bool`
Whether the reply should mention the author of the message. Defaults to false.
"""
message: Message
mention: bool = False
__slots__ = ("message", "mention")
def __init__(self, message: Message, mention: bool = False):
self.message = message
self.mention = mention
def to_dict(self) -> MessageReplyPayload:
return { "id": self.message.id, "mention": self.mention }
class Masquerade(NamedTuple):
"""A namedtuple which represents a message's masquerade.
class Masquerade:
"""represents a message's masquerade.
Parameters
-----------
@@ -146,9 +193,15 @@ class Masquerade(NamedTuple):
The name to display for the message
avatar: Optional[:class:`str`]
The avatar's url to display for the message
colour: Optional[:class:`str`]
The colour of the name, similar to role colours
"""
name: Optional[str] = None
avatar: Optional[str] = None
__slots__ = ("name", "avatar", "colour")
def __init__(self, name: Optional[str] = None, avatar: Optional[str] = None, colour: Optional[str] = None):
self.name = name
self.avatar = avatar
self.colour = colour
def to_dict(self) -> MasqueradePayload:
output: MasqueradePayload = {}
@@ -159,4 +212,34 @@ class Masquerade(NamedTuple):
if avatar := self.avatar:
output["avatar"] = avatar
if colour := self.colour:
output["colour"] = colour
return output
class MessageInteractions:
"""Represents a message's interactions, this is for allowing preset reactions and restricting adding reactions to only those.
Parameters
-----------
reactions: Optional[list[:class:`str`]]
The preset reactions on the message
restrict_reactions: bool
Whether or not users can only react to the interaction's reactions
"""
__slots__ = ("reactions", "restrict_reactions")
def __init__(self, *, reactions: Optional[list[str]] = None, restrict_reactions: bool = False):
self.reactions = reactions
self.restrict_reactions = restrict_reactions
def to_dict(self):
output: InteractionsPayload = {}
if reactions := self.reactions:
output["reactions"] = reactions
if restrict_reactions := self.restrict_reactions:
output["restrict_reactions"] = restrict_reactions
return output
+100 -7
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 SendableEmbed
from .file import File
from .message import Masquerade, Message, MessageReply
from .message import Masquerade, Message, MessageInteractions, MessageReply
from .state import State
@@ -23,10 +25,10 @@ class Messageable:
__slots__ = ()
def _get_channel_id(self) -> str:
async def _get_channel_id(self) -> str:
raise NotImplementedError
async def send(self, content: Optional[str] = None, *, embeds: Optional[list[Embed]] = None, embed: Optional[Embed] = None, attachments: Optional[list[File]] = None, replies: Optional[list[MessageReply]] = None, reply: Optional[MessageReply] = None, masquerade: Optional[Masquerade] = None) -> Message:
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, interactions: Optional[MessageInteractions] = None) -> Message:
"""Sends a message in a channel, you must send at least one of either `content`, `embeds` or `attachments`
Parameters
@@ -35,10 +37,16 @@ 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.
masquerade: Optional[:class:`Masquerade`]
The masquerade for the message, this can overwrite the username and avatar shown
interactions: Optional[:class:`MessageInteractions`]
The interactions for the message
Returns
--------
@@ -54,6 +62,91 @@ class Messageable:
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
interactions_payload = interactions.to_dict() if interactions else None
message = await self.state.http.send_message(self._get_channel_id(), content, embed_payload, attachments, reply_payload, masquerade_payload)
message = await self.state.http.send_message(await self._get_channel_id(), content, embed_payload, attachments, reply_payload, masquerade_payload, interactions_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
"""
from .message import Message
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
"""
from .message import Message
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
"""
from .message import Message
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]
async def delete_messages(self, messages: list[Message]):
"""Bulk deletes messages from the channel
.. note:: The messages must have been sent in the last 7 days.
Parameters
-----------
messages: list[:class:`Message`]
The messages for deletion, this can be up to 100 messages
"""
await self.state.http.delete_messages(await self._get_channel_id(), [message.id for message in messages])
+209 -129
View File
@@ -1,153 +1,233 @@
from __future__ import annotations
from .flags import Flags, flag_value
from typing import TYPE_CHECKING, Any, Optional, cast
from typing_extensions import Self
__all__ = (
"ChannelPermissions",
"ServerPermissions"
)
from .flags import Flag, Flags
from .types.permissions import Overwrite
# Channel permissions
#
# View = 0b00000000000000000000000000000001 // 1
# SendMessage = 0b00000000000000000000000000000010 // 2
# ManageMessages = 0b00000000000000000000000000000100 // 4
# ManageChannel = 0b00000000000000000000000000001000 // 8
# VoiceCall = 0b00000000000000000000000000010000 // 16
# InviteOthers = 0b00000000000000000000000000100000 // 32
# EmbedLinks = 0b00000000000000000000000001000000 // 64
# UploadFiles = 0b00000000000000000000000010000000 // 128
__all__ = ("Permissions", "PermissionsOverwrite", "UserPermissions")
class UserPermissions(Flags):
"""Permissions for users"""
# Server permissions
#
# View = 0b00000000000000000000000000000001 // 1
# ManageRoles = 0b00000000000000000000000000000010 // 2
# ManageChannels = 0b00000000000000000000000000000100 // 4
# ManageServer = 0b00000000000000000000000000001000 // 8
# KickMembers = 0b00000000000000000000000000010000 // 16
# BanMembers = 0b00000000000000000000000000100000 // 32
# ChangeNickname = 0b00000000000000000001000000000000 // 4096
# ManageNicknames = 0b00000000000000000010000000000000 // 8192
# ChangeAvatar = 0b00000000000000000100000000000000 // 16382
# RemoveAvatars = 0b00000000000000001000000000000000 // 32768
class ChannelPermissions(Flags):
"""Represents the channel permissions for a role as seen in channel settings."""
@classmethod
def none(cls) -> ChannelPermissions:
return cls._from_value(0)
@classmethod
def all(cls) -> ChannelPermissions:
return cls._from_value(0b11111011)
@classmethod
def view(cls) -> ChannelPermissions:
return cls._from_value(0b1)
@classmethod
def send_message(cls) -> ChannelPermissions:
return cls._from_value(0b11)
@classmethod
def manage_channel(cls) -> ChannelPermissions:
return cls._from_value(0b1001)
@classmethod
def voice_call(cls) -> ChannelPermissions:
return cls._from_value(0b10001)
@classmethod
def invite_others(cls) -> ChannelPermissions:
return cls._from_value(0b100001)
@classmethod
def embed_links(cls) -> ChannelPermissions:
return cls._from_value(0b1000001)
@classmethod
def upload_files(cls) -> ChannelPermissions:
return cls._from_value(0b10000001)
@flag_value
def can_view() -> int:
@Flag
def access() -> int:
return 1 << 0
@flag_value
def can_send_message() -> int:
@Flag
def view_profile() -> int:
return 1 << 1
@flag_value
def can_manage_channel() -> int:
return 1 << 3
@flag_value
def can_voice_call() -> int:
return 1 << 4
@flag_value
def can_invite_others() -> int:
return 1 << 5
@flag_value
def can_embed_links() -> int:
return 1 << 6
@flag_value
def can_upload_files() -> int:
return 1 << 7
class ServerPermissions(Flags):
"""Represents the server permissions for a role as seen in server settings."""
@classmethod
def none(cls) -> ServerPermissions:
return cls._from_value(0)
@classmethod
def all(cls) -> ServerPermissions:
return cls._from_value(0b1111000000111111)
@flag_value
def view_server() -> int:
return 1 << 0
@flag_value
def manage_roles() -> int:
return 1 << 1
@flag_value
def manage_channels() -> int:
@Flag
def send_message() -> int:
return 1 << 2
@flag_value
def manage_server() -> int:
@Flag
def invite() -> int:
return 1 << 3
@flag_value
@classmethod
def all(cls) -> Self:
return cls(access=True, view_profile=True, send_message=True, invite=True)
class Permissions(Flags):
"""Server permissions for members and roles"""
@Flag
def manage_channel() -> int:
return 1 << 0
@Flag
def manage_server() -> int:
return 1 << 1
@Flag
def manage_permissions() -> int:
return 1 << 2
@Flag
def manage_role() -> int:
return 1 << 3
@Flag
def kick_members() -> int:
return 1 << 4
return 1 << 6
@flag_value
@Flag
def ban_members() -> int:
return 1 << 5
return 1 << 7
@flag_value
def change_nicknames() -> int:
@Flag
def timeout_members() -> int:
return 1 << 8
@Flag
def asign_roles() -> int:
return 1 << 9
@Flag
def change_nickname() -> int:
return 1 << 10
@Flag
def manage_nicknames() -> int:
return 1 << 11
@Flag
def change_avatars() -> int:
return 1 << 12
@flag_value
def manage_nicknames() -> int:
@Flag
def remove_avatars() -> int:
return 1 << 13
@flag_value
def change_avatar() -> int:
return 1 << 14
@Flag
def view_channel() -> int:
return 1 << 20
@flag_value
def remove_avatars() -> int:
return 1 << 15
@Flag
def read_message_history() -> int:
return 1 << 21
@Flag
def send_messages() -> int:
return 1 << 22
@Flag
def manage_messages() -> int:
return 1 << 23
@Flag
def manage_webhooks() -> int:
return 1 << 24
@Flag
def invite_others() -> int:
return 1 << 25
@Flag
def send_embeds() -> int:
return 1 << 26
@Flag
def upload_files() -> int:
return 1 << 27
@Flag
def masquerade() -> int:
return 1 << 28
@Flag
def connect() -> int:
return 1 << 30
@Flag
def speak() -> int:
return 1 << 31
@Flag
def video() -> int:
return 1 << 32
@Flag
def mute_members() -> int:
return 1 << 33
@Flag
def deafen_members() -> int:
return 1 << 34
@Flag
def move_members() -> int:
return 1 << 35
@classmethod
def all(cls) -> Self:
return cls(0x000F_FFFF_FFFF_FFFF)
@classmethod
def default_view_only(cls) -> Self:
return cls(view_channel=True, read_message_history=True)
@classmethod
def default(cls) -> Self:
return cls.default_view_only() | cls(send_messages=True, invite_others=True, send_embeds=True, upload_files=True, connect=True, speak=True)
@classmethod
def default_direct_message(cls) -> Self:
return cls.default_view_only() | cls(react=True, manage_channel=True)
class PermissionsOverwrite:
"""A permissions overwrite in a channel"""
def __init__(self, allow: Permissions, deny: Permissions):
self._allow = allow
self._deny = deny
for perm in Permissions.FLAG_NAMES:
if getattr(allow, perm):
value = True
elif getattr(deny, perm):
value = False
else:
value = None
super().__setattr__(perm, value)
def __setattr__(self, key: str, value: Any):
if key in Permissions.FLAG_NAMES:
if key is True:
setattr(self._allow, key, True)
super().__setattr__(key, True)
elif key is False:
setattr(self._deny, key, True)
super().__setattr__(key, False)
else:
setattr(self._allow, key, False)
setattr(self._deny, key, False)
super().__setattr__(key, None)
else:
super().__setattr__(key, value)
if TYPE_CHECKING:
manage_channel: Optional[bool]
manage_server: Optional[bool]
manage_permissions: Optional[bool]
manage_role: Optional[bool]
kick_members: Optional[bool]
ban_members: Optional[bool]
timeout_members: Optional[bool]
asign_roles: Optional[bool]
change_nickname: Optional[bool]
manage_nicknames: Optional[bool]
change_avatars: Optional[bool]
remove_avatars: Optional[bool]
view_channel: Optional[bool]
read_message_history: Optional[bool]
send_messages: Optional[bool]
manage_messages: Optional[bool]
manage_webhooks: Optional[bool]
invite_others: Optional[bool]
send_embeds: Optional[bool]
upload_files: Optional[bool]
masquerade: Optional[bool]
connect: Optional[bool]
speak: Optional[bool]
video: Optional[bool]
mute_members: Optional[bool]
deafen_members: Optional[bool]
move_members: Optional[bool]
def to_pair(self) -> tuple[Permissions, Permissions]:
return self._allow, self._deny
@classmethod
def _from_overwrite(cls, overwrite: Overwrite) -> Self:
allow = Permissions(overwrite["a"])
deny = Permissions(overwrite["d"])
return cls(allow, deny)
+80
View File
@@ -0,0 +1,80 @@
from __future__ import annotations
from datetime import datetime
from typing import TYPE_CHECKING, cast
from revolt.enums import ChannelType
from .permissions import Permissions
from .server import Server
if TYPE_CHECKING:
from .channel import Channel, DMChannel, GroupDMChannel, ServerChannel
from .member import Member
def calculate_permissions(member: Member, target: Server | Channel) -> Permissions:
if member.privileged:
return Permissions.all()
if isinstance(target, Server):
if target.owner_id == member.id:
return Permissions.all()
permissions = target.default_permissions
for role in member.roles:
permissions = (permissions | role.permissions._allow) & (~role.permissions._deny)
if member.current_timeout and member.current_timeout > datetime.now():
permissions = permissions & Permissions.default_view_only()
return permissions
else:
channel_type = target.channel_type
if channel_type is ChannelType.saved_messages:
return Permissions.all()
elif channel_type is ChannelType.direct_message:
target = cast("DMChannel", target)
user_permissions = target.recipient.get_permissions()
if user_permissions.send_message:
return Permissions.default_direct_message()
else:
return Permissions.default_view_only()
elif channel_type is ChannelType.group:
target = cast("GroupDMChannel", target)
if target.owner.id != member.id:
return Permissions.default_direct_message()
else:
if target.permissions.value == 0:
return Permissions.default_direct_message()
else:
return target.permissions
else:
target = cast("ServerChannel", target)
server = target.server
if server.owner_id == member.id:
return Permissions.all()
else:
perms = calculate_permissions(member, server)
perms = (perms | target.default_permissions._allow) & (~target.default_permissions._deny)
for role in server.roles[::-1]:
if overwrite :=target.permissions.get(role.id):
perms = (perms | overwrite._allow) & (~overwrite._deny)
if member.current_timeout and member.current_timeout > datetime.now():
perms = perms & Permissions(view_channel=True, read_message_history=True)
return perms
+47 -27
View File
@@ -1,10 +1,9 @@
from __future__ import annotations
from typing import TYPE_CHECKING, Optional
from typing import TYPE_CHECKING, Any, Optional
from revolt.types import server
from .permissions import ChannelPermissions, ServerPermissions
from .permissions import Overwrite, PermissionsOverwrite
from .utils import Missing, Ulid
if TYPE_CHECKING:
from .server import Server
@@ -14,7 +13,7 @@ if TYPE_CHECKING:
__all__ = ("Role",)
class Role:
class Role(Ulid):
"""Represents a role
Attributes
@@ -23,7 +22,7 @@ class Role:
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
@@ -36,24 +35,23 @@ class Role:
channel_permissions: :class:`ChannelPermissions`
The channel permissions for the role
"""
__slots__ = ("id", "name", "colour", "hoist", "rank", "state", "server", "server_permissions", "channel_permissions")
__slots__ = ("id", "name", "colour", "hoist", "rank", "state", "server", "permissions")
def __init__(self, data: RolePayload, role_id: str, state: State, server: Server):
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 = data.get("colour", None)
self.hoist = False
self.rank = 0
self.server = server
self.server_permissions = ServerPermissions._from_value(data["permissions"][0])
self.channel_permissions = ChannelPermissions._from_value(data["permissions"][1])
self.permissions = PermissionsOverwrite._from_overwrite(data.get("permissions", {"a": 0, "d": 0}))
@property
def color(self):
return self.colour
async def set_permissions(self, *, server_permissions: Optional[ServerPermissions] = None, channel_permissions: Optional[ChannelPermissions] = None) -> None:
async def set_permissions_overwrite(self, *, permissions: PermissionsOverwrite) -> None:
"""Sets the permissions for a role in a server.
Parameters
-----------
@@ -62,24 +60,46 @@ class Role:
channel_permissions: Optional[:class:`ChannelPermissions`]
The new channel permissions for the role
"""
allow, deny = permissions.to_pair()
await self.state.http.set_server_role_permissions(self.server.id, self.id, allow.value, deny.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:
def _update(self, *, name: Optional[str] = None, colour: Optional[str] = None, hoist: Optional[bool] = None, rank: Optional[int] = None, permissions: Optional[Overwrite] = None):
if name is not None:
self.name = name
if colour:
if colour is not None:
self.colour = colour
if hoist:
if hoist is not None:
self.hoist = hoist
if rank:
if rank is not None:
self.rank = rank
if permissions is not None:
self.permissions = PermissionsOverwrite._from_overwrite(permissions)
async def delete(self):
"""Deletes the role"""
await self.state.http.delete_role(self.server.id, self.id)
async def edit(self, **kwargs: Any):
"""Edits the role
Parameters
-----------
name: str
The name of the role
colour: str
The colour of the role
hoist: bool
Whether the role should make the member display seperately in the member list
rank: int
The position of the role
"""
if kwargs.get("colour", Missing) is None:
remove = ["Colour"]
else:
remove = None
await self.state.http.edit_role(self.server.id, self.id, remove, kwargs)
+251 -40
View File
@@ -1,25 +1,27 @@
from __future__ import annotations
from typing import TYPE_CHECKING, Optional
from typing import TYPE_CHECKING, Optional, cast
from .asset import Asset
from .category import Category
from .channel import Channel
from .permissions import ChannelPermissions, ServerPermissions
from .invite import Invite
from .permissions import Permissions
from .role import Role
from .utils import Ulid
if TYPE_CHECKING:
from .channel import TextChannel
from .channel import Channel, TextChannel, VoiceChannel
from .emoji import Emoji
from .file import File
from .member import Member
from .state import State
from .types import Ban
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
__all__ = ("Server", "SystemMessages")
__all__ = ("Server", "SystemMessages", "ServerBan")
class SystemMessages:
def __init__(self, data: SystemMessagesConfig, state: State):
@@ -65,7 +67,7 @@ class SystemMessages:
assert isinstance(channel, TextChannel)
return channel
class Server:
class Server(Ulid):
"""Represents a server
Attributes
@@ -82,26 +84,25 @@ class Server:
Whether the server is nsfw or not
system_messages: :class:`SystemMessages`
The system message config for the server
categories: list[:class:`Category`]
The categories in the server
icon: Optional[:class:`Asset`]
The servers icon
banner: Optional[:class:`Asset`]
The servers banner
default_permissions: :class:`Permissions`
The permissions for the default role
"""
__slots__ = ("state", "id", "name", "owner_id", "default_server_permissions", "default_channel_permissions", "_members", "_roles", "_channels", "description", "icon", "banner", "nsfw", "system_messages", "categories")
__slots__ = ("state", "id", "name", "owner_id", "default_permissions", "_members", "_roles", "_channels", "description", "icon", "banner", "nsfw", "system_messages", "_categories", "_emojis")
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_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", {}), state)
self.categories = [Category(data, state) for data in data.get("categories", [])]
self.system_messages = SystemMessages(data.get("system_messages", cast("SystemMessagesConfig", {})), state)
self._categories = {data["id"]: Category(data, state) for data in data.get("categories", [])}
self.default_permissions = Permissions(data["default_permissions"])
if icon := data.get("icon"):
self.icon = Asset(icon, state)
@@ -114,37 +115,46 @@ class Server:
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()}
self._roles: dict[str, Role] = {role_id: Role(role, role_id, self, state) for role_id, role in data.get("roles", {}).items()}
channels = [state.get_channel(channel_id) for channel_id in data["channels"]]
self._channels: dict[str, Channel] = {channel.id: channel for channel in channels}
self._channels: dict[str, Channel] = {}
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:
# The api doesnt send us all the channels but sends us all the ids, this is because channels we dont have permissions to see are not sent
# this causes get_channel to error so we have to first check ourself if its in the cache.
for channel_id in data["channels"]:
if channel := state.channels.get(channel_id):
self._channels[channel_id] = channel
self._emojis: dict[str, Emoji] = {}
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[int] = None, nsfw: Optional[bool] = None, system_messages: Optional[SystemMessagesConfig] = None, categories: Optional[list[CategoryPayload]] = None, channels: Optional[list[str]] = None):
if owner is not None:
self.owner_id = owner
if name:
if name is not None:
self.name = name
if description is not None:
self.description = description or None
if icon:
if icon is not None:
self.icon = Asset(icon, self.state)
if banner:
if banner is not None:
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 default_permissions is not None:
self.default_permissions = Permissions(default_permissions)
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 = [Category(data, self.state) for data in categories]
self._categories = {data["id"]: Category(data, self.state) for data in categories}
if channels is not None:
self._channels = {channel_id: self.state.get_channel(channel_id) for channel_id in channels}
@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"""
@@ -155,14 +165,24 @@ 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())
@property
def emojis(self) -> list[Emoji]:
"""list[:class:`Emoji`] Gets all emojis in the server"""
return list(self._emojis.values())
def get_role(self, role_id: str) -> Role:
"""Gets a role from the cache
Parameters
-----------
id: :class:`str`
The id of the role
Returns
--------
:class:`Role`
@@ -172,40 +192,82 @@ class Server:
def get_member(self, member_id: str) -> Member:
"""Gets a member from the cache
Parameters
-----------
id: :class:`str`
The id of the member
Returns
--------
:class:`Member`
The member
"""
return self._members[member_id]
try:
return self._members[member_id]
except KeyError:
raise LookupError from None
def get_channel(self, channel_id: str) -> Channel:
"""Gets a channel from the cache
Parameters
-----------
id: :class:`str`
The id of the channel
Returns
--------
:class:`Channel`
The channel
"""
return self._channels[channel_id]
try:
return self._channels[channel_id]
except KeyError:
raise LookupError from None
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
"""
try:
return self._categories[category_id]
except KeyError:
raise LookupError from None
def get_emoji(self, emoji_id: str) -> Emoji:
"""Gets a emoji from the cache
Parameters
-----------
id: :class:`str`
The id of the emoji
Returns
--------
:class:`Emoji`
The emoji
"""
try:
return self._emojis[emoji_id]
except KeyError as e:
raise LookupError from e
@property
def owner(self) -> Member:
""":class:`Member` The owner of the server"""
return self.get_member(self.owner_id)
async def set_default_permissions(self, *, server_permissions: Optional[ServerPermissions] = None, channel_permissions: Optional[ChannelPermissions] = None) -> None:
async def set_default_permissions(self, permissions: Permissions) -> None:
"""Sets the default server permissions.
Parameters
-----------
@@ -214,7 +276,156 @@ class Server:
channel_permissions: Optional[:class:`ChannelPermissions`]
the new default channel permissions
"""
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)
await self.state.http.set_server_default_permissions(self.id, permissions.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 = self.state.add_channel(payload)
self._channels[channel.id] = channel
return cast("VoiceChannel", 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)
async def create_emoji(self, name: str, file: File, *, nsfw: bool = False):
"""Creates an emoji
Parameters
-----------
name: :class:`str`
The name for the emoji
file: :class:`File`
The image for the emoji
nsfw: :class:`bool`
Whether or not the emoji is nsfw
"""
payload = await self.state.http.create_emoji(name, file, nsfw, {"type": "Server", "id": self.id})
return self.state.add_emoji(payload)
class ServerBan:
"""Represents a server ban
Attributes
-----------
reason: Optional[:class:str`]
The reason the user was banned
server: :class:`Server`
The server the user was banned in
user_id: :class:`str`
The id of the user who was banned
"""
__slots__ = ("reason", "server", "user_id", "state")
def __init__(self, ban: Ban, state: State):
self.reason = ban.get("reason")
self.server = state.get_server(ban["_id"]["server"])
self.user_id = 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)
+50 -17
View File
@@ -1,9 +1,10 @@
from __future__ import annotations
from collections import deque
from typing import TYPE_CHECKING, Optional
from typing import TYPE_CHECKING
from .channel import Channel, channel_factory
from .emoji import Emoji
from .member import Member
from .message import Message
from .server import Server
@@ -13,42 +14,60 @@ if TYPE_CHECKING:
from .http import HttpClient
from .types import ApiInfo
from .types import Channel as ChannelPayload
from .types import Emoji as EmojiPayload
from .types import Member as MemberPayload
from .types import Message as MessagePayload
from .types import Server as ServerPayload
from .types import User as UserPayload
__all__ = ("State",)
class State:
__slots__ = ("http", "api_info", "max_messages", "users", "channels", "servers", "messages")
__slots__ = ("http", "api_info", "max_messages", "users", "channels", "servers", "messages", "global_emojis", "user_id", "me")
def __init__(self, http: HttpClient, api_info: ApiInfo, max_messages: int):
self.http = http
self.api_info = api_info
self.max_messages = max_messages
self.me: User
self.users: dict[str, User] = {}
self.channels: dict[str, Channel] = {}
self.servers: dict[str, Server] = {}
self.messages: deque[Message] = deque()
self.global_emojis: list[Emoji] = []
def get_user(self, id: str) -> User:
return self.users[id]
try:
return self.users[id]
except KeyError:
raise LookupError from None
def get_member(self, server_id: str, member_id: str) -> Member:
server = self.servers[server_id]
return server.get_member(member_id)
def get_channel(self, id: str) -> Channel:
return self.channels[id]
try:
return self.channels[id]
except KeyError:
raise LookupError from None
def get_server(self, id: str) -> Server:
return self.servers[id]
try:
return self.servers[id]
except KeyError:
raise LookupError from None
def add_user(self, payload: UserPayload) -> User:
user = User(payload, self)
if payload.get("relationship") == "User":
self.me = user
self.users[user.id] = user
return user
@@ -73,23 +92,37 @@ class State:
message = Message(payload, self)
if len(self.messages) >= self.max_messages:
self.messages.pop()
self.messages.appendleft(message)
return message
def add_emoji(self, payload: EmojiPayload) -> Emoji:
emoji = Emoji(payload, self)
if server_id := emoji.server_id:
server = self.get_server(server_id)
server._emojis[emoji.id] = emoji
else:
self.global_emojis.append(emoji)
return emoji
def get_message(self, message_id: str) -> Message:
for msg in self.messages:
if msg.id == message_id:
return msg
raise KeyError
raise LookupError
async def fetch_server_members(self, server_id: str):
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)
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)
for server_id in self.servers:
await self.fetch_server_members(server_id)
+2
View File
@@ -1,12 +1,14 @@
from .category import *
from .channel import *
from .embed import *
from .emoji import *
from .file import *
from .gateway import *
from .http import *
from .invite import *
from .member import *
from .message import *
from .permissions import *
from .role import *
from .server import *
from .user import *
+1 -5
View File
@@ -1,8 +1,4 @@
from typing import TYPE_CHECKING, TypedDict
if TYPE_CHECKING:
from .channel import Channel
from typing import TypedDict
__all__ = ("Category",)
+29 -30
View File
@@ -2,68 +2,67 @@ from __future__ import annotations
from typing import TYPE_CHECKING, Literal, TypedDict, Union
from typing_extensions import NotRequired
if TYPE_CHECKING:
from .file import File
from .message import Message
from .permissions import Overwrite
__all__ = (
"SavedMessages",
"DMChannel",
"Group",
"GroupDMChannel",
"TextChannel",
"VoiceChannel",
"ServerChannel",
"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
last_message_id: NotRequired[str]
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]
nsfw: NotRequired[bool]
last_message_id: 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[Overwrite]
role_permissions: NotRequired[dict[str, Overwrite]]
nsfw: NotRequired[bool]
last_message_id: 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[Overwrite]
role_permissions: NotRequired[dict[str, Overwrite]]
nsfw: NotRequired[bool]
Channel = Union[SavedMessages, DMChannel, Group, TextChannel, VoiceChannel]
ServerChannel = Union[TextChannel, VoiceChannel]
Channel = Union[SavedMessages, DMChannel, GroupDMChannel, TextChannel, VoiceChannel]
+81 -4
View File
@@ -1,8 +1,85 @@
from __future__ import annotations
from typing import TYPE_CHECKING, TypedDict
from typing import TYPE_CHECKING, Literal, TypedDict, Union
__all__ = ("Embed",)
from typing_extensions import NotRequired
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
+21
View File
@@ -0,0 +1,21 @@
from typing import Literal, TypedDict, Union
from typing_extensions import NotRequired
class EmojiParentServer(TypedDict):
type: Literal["Server"]
id: str
class EmojiParentDetached(TypedDict):
type: Literal["Detached"]
EmojiParent = Union[EmojiParentServer, EmojiParentDetached]
class Emoji(TypedDict):
_id: str
parent: EmojiParent
creator_id: str
name: str
animated: NotRequired[bool]
nsfw: NotRequired[bool]
+1 -1
View File
@@ -1,6 +1,6 @@
from __future__ import annotations
from typing import TYPE_CHECKING, Literal, TypedDict, Union
from typing import Literal, TypedDict, Union
__all__ = ("File",)
+85 -16
View File
@@ -2,21 +2,27 @@ from __future__ import annotations
from typing import TYPE_CHECKING, Literal, TypedDict, Union
from .channel import (Channel, DMChannel, Group, SavedMessages, TextChannel,
VoiceChannel)
from typing_extensions import NotRequired
from .channel import (Channel, DMChannel, GroupDMChannel, SavedMessages,
TextChannel, VoiceChannel)
from .message import Message
from .permissions import Overwrite
if TYPE_CHECKING:
from .category import Category
from .emoji import Emoji
from .file import File
from .member import Member, MemberID
from .server import Server
from .user import Status, User
from .server import Server, SystemMessagesConfig
from .user import Status, User, UserProfile
__all__ = (
"BasePayload",
"AuthenticatePayload",
"ReadyEventPayload",
"MessageEventPayload",
"MessageUpdateEditedData",
"MessageUpdateData",
"MessageUpdateEventPayload",
"MessageDeleteEventPayload",
@@ -33,7 +39,12 @@ __all__ = (
"ServerRoleUpdateEventPayload",
"ServerRoleDeleteEventPayload",
"UserUpdateEventPayload",
"UserRelationshipEventPayload"
"UserRelationshipEventPayload",
"ServerCreateEventPayload",
"MessageReactEventPayload",
"MessageUnreactEventPayload",
"MessageRemoveReactionEventPayload",
"BulkMessageDeleteEventPayload"
)
class BasePayload(TypedDict):
@@ -47,15 +58,14 @@ class ReadyEventPayload(BasePayload):
servers: list[Server]
channels: list[Channel]
members: list[Member]
emojis: list[Emoji]
class MessageEventPayload(BasePayload, Message):
pass
MessageUpdateEditedData = TypedDict("MessageUpdateEditedData", {"$date": str})
class MessageUpdateData(TypedDict):
content: str
edited: MessageUpdateEditedData
edited: int
class MessageUpdateEventPayload(BasePayload):
channel: str
@@ -69,7 +79,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):
@@ -83,9 +93,18 @@ class ChannelCreateEventPayload_DMChannel(BasePayload, DMChannel):
ChannelCreateEventPayload = Union[ChannelCreateEventPayload_Group, ChannelCreateEventPayload_Group, ChannelCreateEventPayload_TextChannel, ChannelCreateEventPayload_VoiceChannel, ChannelCreateEventPayload_DMChannel]
class ChannelUpdateEventPayloadData(TypedDict, total=False):
name: str
description: str
icon: File
nsfw: bool
active: bool
role_permissions: dict[str, Overwrite]
default_permissions: Overwrite
class ChannelUpdateEventPayload(BasePayload):
id: str
data: ...
data: ChannelUpdateEventPayloadData
clear: Literal["Icon", "Description"]
class ChannelDeleteEventPayload(BasePayload):
@@ -97,17 +116,38 @@ class ChannelStartTypingEventPayload(BasePayload):
ChannelDeleteTypingEventPayload = ChannelStartTypingEventPayload
class ServerUpdateEventPayloadData(TypedDict, total=False):
owner: str
name: str
description: str
icon: File
banner: File
default_permissions: int
nsfw: bool
system_messages: SystemMessagesConfig
categories: list[Category]
class ServerUpdateEventPayload(BasePayload):
id: str
data: dict
data: ServerUpdateEventPayloadData
clear: Literal["Icon", "Banner", "Description"]
class ServerDeleteEventPayload(BasePayload):
id: str
class ServerCreateEventPayload(BasePayload):
id: str
server: Server
channels: list[Channel]
class ServerMemberUpdateEventPayloadData(TypedDict, total=False):
nickname: str
avatar: File
roles: list[str]
class ServerMemberUpdateEventPayload(BasePayload):
id: MemberID
data: dict
data: ServerMemberUpdateEventPayloadData
clear: Literal["Nickname", "Avatar"]
class ServerMemberJoinEventPayload(BasePayload):
@@ -116,22 +156,51 @@ class ServerMemberJoinEventPayload(BasePayload):
ServerMemberLeaveEventPayload = ServerMemberJoinEventPayload
class ServerRoleUpdateEventPayloadData(TypedDict, total=False):
name: str
colour: str
hoist: bool
rank: int
class ServerRoleUpdateEventPayload(BasePayload):
id: str
role_id: str
data: dict
clear: Literal["Color"]
data: ServerRoleUpdateEventPayloadData
clear: Literal["Colour"]
class ServerRoleDeleteEventPayload(BasePayload):
id: str
role_id: str
class UserUpdateEventPayloadData(TypedDict):
status: NotRequired[Status]
avatar: NotRequired[File]
online: NotRequired[bool]
profile: NotRequired[UserProfile]
class UserUpdateEventPayload(BasePayload):
id: str
data: dict
data: UserUpdateEventPayloadData
clear: Literal["ProfileContent", "ProfileBackground", "StatusText", "Avatar"]
class UserRelationshipEventPayload(BasePayload):
id: str
user: str
status: Status
class MessageReactEventPayload(BasePayload):
id: str
channel_id: str
user_id: str
emoji_id: str
MessageUnreactEventPayload = MessageReactEventPayload
class MessageRemoveReactionEventPayload(BasePayload):
id: str
channel_id: str
emoji_id: str
class BulkMessageDeleteEventPayload(BasePayload):
channel: str
ids: list[str]
+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
+9 -7
View File
@@ -2,20 +2,22 @@ from __future__ import annotations
from typing import TYPE_CHECKING, TypedDict
from typing_extensions import NotRequired
if TYPE_CHECKING:
from .file import File
__all__ = ("Member",)
class _MemberOptional(TypedDict, total=False):
nickname: str
avatar: File
roles: list[str]
__all__ = ("Member", "MemberID")
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]]
joined_at: int | str
timeout: NotRequired[str]
+26 -11
View File
@@ -2,15 +2,27 @@ 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__ = (
"UserAddContent",
"UserRemoveContent",
"UserJoinedContent",
"UserLeftContent",
"UserKickedContent",
"UserBannedContent",
"ChannelRenameContent",
"ChannelDescriptionChangeContent",
"ChannelIconChangeContent",
"Masquerade",
"Interactions",
"Message",
"MessageReplyPayload",
"Masquerade"
)
class UserAddContent(TypedDict):
@@ -44,25 +56,28 @@ class ChannelDescriptionChangeContent(TypedDict):
class ChannelIconChangeContent(TypedDict):
by: str
MessageEdited = TypedDict("MessageEdited", {"$date": str})
class Masquerade(TypedDict, total=False):
name: str
avatar: str
colour: str
class _OptionalMessage(TypedDict):
attachments: list[File]
embeds: list[Embed]
mentions: list[str]
replies: list[str]
edited: MessageEdited
masquerade: Masquerade
class Interactions(TypedDict):
reactions: NotRequired[list[str]]
restrict_reactions: NotRequired[bool]
class Message(_OptionalMessage):
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[str]
masquerade: NotRequired[Masquerade]
interactions: NotRequired[Interactions]
reactions: dict[str, list[str]]
class MessageReplyPayload(TypedDict):
id: str
+8
View File
@@ -0,0 +1,8 @@
from __future__ import annotations
from typing import TypedDict
class Overwrite(TypedDict):
a: int
d: int
+11 -11
View File
@@ -1,19 +1,19 @@
from __future__ import annotations
from typing import TypedDict
from typing import TYPE_CHECKING, TypedDict
from typing_extensions import NotRequired
if TYPE_CHECKING:
from .permissions import Overwrite
__all__ = (
"Permission",
"Role",
)
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
permissions: Overwrite
colour: NotRequired[str]
hoist: NotRequired[bool]
rank: int
+21 -21
View File
@@ -2,11 +2,12 @@ from __future__ import annotations
from typing import TYPE_CHECKING, TypedDict
from typing_extensions import NotRequired
if TYPE_CHECKING:
from .category import Category
from .channel import Channel
from .file import File
from .role import Permission, Role
from .role import Role
__all__ = (
"Server",
@@ -22,35 +23,34 @@ 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
nsfw: bool
class Server(_ServerOptional):
class Server(TypedDict):
_id: str
owner: str
name: str
channels: list[str]
default_permissions: Permission
default_permissions: int
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]
+12 -11
View File
@@ -2,6 +2,8 @@ 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 +29,18 @@ 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]
privileged: NotRequired[bool]
class UserProfile(TypedDict, total=False):
content: str
+132 -22
View File
@@ -1,19 +1,25 @@
from __future__ import annotations
from typing import TYPE_CHECKING, NamedTuple, Optional, Union
from weakref import WeakSet
from .asset import Asset, PartialAsset
from .channel import DMChannel, GroupDMChannel
from .enums import PresenceType, RelationshipType
from .flags import UserBadges
from .messageable import Messageable
from .permissions import UserPermissions
from .utils import Ulid
if TYPE_CHECKING:
from .member import Member
from .state import State
from .types import File
from .types import Status as StatusPayload
from .types import User as UserPayload
from .types import UserProfile as UserProfileData
__all__ = ("User",)
__all__ = ("User", "Status", "Relation", "UserProfile")
class Relation(NamedTuple):
"""A namedtuple representing a relation between the bot and a user"""
@@ -30,17 +36,17 @@ class UserProfile(NamedTuple):
content: Optional[str]
background: Optional[Asset]
class User:
class User(Messageable, Ulid):
"""Represents a user
Attributes
-----------
id: :class:`str`
The users id
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
owner_id: Optional[:class:`str`]
The bot's owner id if the user is a bot
badges: :class:`UserBadges`
The users badges
online: :class:`bool`
@@ -53,14 +59,20 @@ class User:
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
privileged: :class:`bool`
Whether the user is privileged
"""
__flattern_attributes__ = ("id", "bot", "owner_id", "badges", "online", "flags", "relations", "relationship", "status", "masquerade_avatar", "masquerade_name", "original_name", "original_avatar", "profile")
__slots__ = (*__flattern_attributes__, "state")
__flattern_attributes__ = ("id", "bot", "owner_id", "badges", "online", "flags", "relations", "relationship", "status", "masquerade_avatar", "masquerade_name", "original_name", "original_avatar", "profile", "dm_channel", "privileged")
__slots__ = (*__flattern_attributes__, "state", "_members")
def __init__(self, data: UserPayload, state: State):
self.state = state
self._members: WeakSet[Member] = WeakSet() # we store all member versions of this user to avoid having to check every guild when needing to update.
self.id = data["_id"]
self.original_name = data["username"]
self.dm_channel = None
bot = data.get("bot")
if bot:
@@ -73,11 +85,12 @@ class User:
self.badges = UserBadges._from_value(data.get("badges", 0))
self.online = data.get("online", False)
self.flags = data.get("flags", 0)
self.privileged = data.get("privileged", False)
avatar = data.get("avatar")
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"])
@@ -100,14 +113,67 @@ class User:
self.masquerade_avatar: Optional[PartialAsset] = None
self.masquerade_name: Optional[str] = None
def get_permissions(self) -> UserPermissions:
"""Gets the permissions for the user
Returns
--------
:class:`UserPermissions`
The users permissions
"""
permissions = UserPermissions()
if self.relationship in [RelationshipType.friend, RelationshipType.user]:
return UserPermissions.all()
elif self.relationship in [RelationshipType.blocked, RelationshipType.blocked_other]:
return UserPermissions(access=True)
elif self.relationship in [RelationshipType.incoming_friend_request, RelationshipType.outgoing_friend_request]:
permissions.access = True
for channel in self.state.channels.values():
if (isinstance(channel, (GroupDMChannel, DMChannel)) and self.id in channel.recipient_ids) or any(self.id in (m.id for m in server.members) for server in self.state.servers.values()):
if self.state.me.bot or self.bot:
permissions.send_message = True
permissions.access = True
permissions.view_profile = True
return permissions
def has_permissions(self, **permissions: bool) -> bool:
"""Computes if the user has the specified permissions
Parameters
-----------
permissions: :class:`bool`
The permissions to check, this also accepted `False` if you need to check if the user does not have the permission
Returns
--------
:class:`bool`
Whether or not they have the permissions
"""
perms = self.get_permissions()
return all([getattr(perms, key, False) == value for key, value in permissions.items()])
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
def owner(self) -> User:
""":class:`User` the owner of the bot account"""
if not owner_id:
return
if not self.owner_id:
raise LookupError
return self.state.get_user(owner_id)
return self.state.get_user(self.owner_id)
@property
def name(self) -> str:
@@ -119,19 +185,63 @@ class User:
"""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
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:
@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: Optional[UserProfileData] = None, avatar: Optional[File] = None, online: Optional[bool] = None):
if status is not None:
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 is not None:
if background_file := profile.get("background"):
background = Asset(background_file, self.state)
else:
background = None
if profile_content:
self.profile = UserProfile(profile_content, self.profile.background if self.profile else None)
self.profile = UserProfile(profile.get("content"), background)
if avatar:
if avatar is not None:
self.original_avatar = Asset(avatar, self.state)
if online:
if online is not None:
self.online = online
# update user infomation for all members
if self.__class__ is User:
for member in self._members:
User._update(member, status=status, profile=profile, avatar=avatar, 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
+87 -6
View File
@@ -1,14 +1,22 @@
import datetime
import inspect
from typing import Any, Callable, Coroutine, TypeVar, Union
from contextlib import asynccontextmanager
from operator import attrgetter
from typing import Any, Callable, Coroutine, Iterable, Literal, TypeVar, Union
import ulid
from aiohttp import ClientSession
from typing_extensions import ParamSpec
__all__ = ("Missing", "copy_doc", "maybe_coroutine")
__all__ = ("Missing", "copy_doc", "maybe_coroutine", "get", "client_session")
class _Missing:
def __repr__(self):
return "<Missing>"
def __bool__(self) -> Literal[False]:
return False
Missing = _Missing()
T = TypeVar("T")
@@ -17,15 +25,15 @@ 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")
# its impossible to type this function correctly for a couple reasons:
# 1. isawaitable doesnt narrow while keeping typevars - there is an open pr for this (typeshed#5658) but it cant be merged because mypy doesnt support the feature fully
# 2. typeguard doesnt narrow for the negative case which is dumb imo, so `value` would stay being a union even after the if statement (PEP 647 - "The type is not narrowed in the negative case")
# it is impossible to type this function correctly as typeguard does not narrow for the negative case,
# so `value` would stay being a union even after the if statement (PEP 647 - "The type is not narrowed in the negative case")
# see typing#926, typing#930, typing#996
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)
@@ -34,3 +42,76 @@ async def maybe_coroutine(func: Callable[P, Union[R_T, Coroutine[Any, Any, R_T]]
value = await value
return value # type: ignore
class Ulid:
id: str
def created_at(self) -> datetime.datetime:
return ulid.from_str(self.id).timestamp().datetime
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()
+214 -52
View File
@@ -2,22 +2,32 @@ from __future__ import annotations
import asyncio
import logging
import time
from copy import copy
from typing import TYPE_CHECKING, Callable, cast
from . import utils
from .channel import GroupDMChannel, TextChannel, VoiceChannel
from .enums import RelationshipType
from .types import (ChannelCreateEventPayload, ChannelDeleteEventPayload,
ChannelDeleteTypingEventPayload,
from .role import Role
from .types import (BulkMessageDeleteEventPayload, ChannelCreateEventPayload,
ChannelDeleteEventPayload, ChannelDeleteTypingEventPayload,
ChannelStartTypingEventPayload, ChannelUpdateEventPayload)
from .types import Member as MemberPayload
from .types import MemberID as MemberIDPayload
from .types import Message as MessagePayload
from .types import (MessageDeleteEventPayload, MessageUpdateEventPayload,
ServerDeleteEventPayload, ServerMemberJoinEventPayload,
from .types import (MessageDeleteEventPayload, MessageReactEventPayload,
MessageRemoveReactionEventPayload,
MessageUnreactEventPayload, MessageUpdateEventPayload)
from .types import Role as RolePayload
from .types import (ServerCreateEventPayload, ServerDeleteEventPayload,
ServerMemberJoinEventPayload,
ServerMemberLeaveEventPayload,
ServerMemberUpdateEventPayload,
ServerRoleDeleteEventPayload, ServerRoleUpdateEventPayload,
ServerUpdateEventPayload, UserRelationshipEventPayload,
UserUpdateEventPayload)
from .user import Status
from .user import Status, UserProfile
try:
import ujson as json
@@ -34,9 +44,8 @@ if TYPE_CHECKING:
import aiohttp
from .state import State
from .types import AuthenticatePayload, BasePayload
from .types import Member as MemberPayload
from .types import MessageEventPayload, ReadyEventPayload
from .types import (AuthenticatePayload, BasePayload, MessageEventPayload,
ReadyEventPayload)
__all__ = ("WebsocketHandler",)
@@ -44,7 +53,7 @@ __all__ = ("WebsocketHandler",)
logger = logging.getLogger("revolt")
class WebsocketHandler:
__slots__ = ("session", "token", "ws_url", "dispatch", "state", "websocket", "loop", "user", "ready")
__slots__ = ("session", "token", "ws_url", "dispatch", "state", "websocket", "loop", "user", "ready", "server_events")
def __init__(self, session: aiohttp.ClientSession, token: str, ws_url: str, dispatch: Callable[..., None], state: State):
self.session = session
@@ -56,10 +65,15 @@ class WebsocketHandler:
self.loop = asyncio.get_running_loop()
self.user = None
self.ready = asyncio.Event()
self.server_events: dict[str, asyncio.Event] = {}
async def _wait_for_server_ready(self, server_id: str):
if event := self.server_events.get(server_id):
await event.wait()
async def send_payload(self, payload: BasePayload):
if use_msgpack:
await self.websocket.send_bytes(msgpack.packb(payload)) # type: ignore
await self.websocket.send_bytes(msgpack.packb(payload))
else:
await self.websocket.send_str(json.dumps(payload))
@@ -85,9 +99,8 @@ class WebsocketHandler:
await self.ready.wait()
func = getattr(self, f"handle_{event_type}")
except:
logger.debug("Unknown event '%s'", event_type)
return
except AttributeError:
return logger.debug("Unknown event '%s'", event_type)
await func(payload)
@@ -111,30 +124,35 @@ class WebsocketHandler:
for member in payload["members"]:
self.state.add_member(member["_id"]["server"], member)
for emoji in payload["emojis"]:
emoji = self.state.add_emoji(emoji)
await self.state.fetch_all_server_members()
self.ready.set()
self.dispatch("ready")
async def handle_message(self, payload: MessageEventPayload):
if server := self.state.get_channel(payload["channel"]).server_id:
await self._wait_for_server_ready(server)
message = self.state.add_message(cast(MessagePayload, payload))
self.dispatch("message", message)
async def handle_messageupdate(self, payload: MessageUpdateEventPayload):
self.dispatch("raw_message_update", payload)
message = self.state.get_message(payload["id"])
try:
message = self.state.get_message(payload["id"])
except LookupError:
return
data = payload["data"]
kwargs = {}
if server_id := message.channel.server_id:
await self._wait_for_server_ready(server_id)
if data["content"]:
kwargs["content"] = data["content"]
if data["edited"]["$date"]:
kwargs["edited_at"] = data["edited"]["$date"]
message._update(**kwargs)
message._update(**payload["data"])
self.dispatch("message_update", message)
@@ -143,19 +161,33 @@ class WebsocketHandler:
try:
message = self.state.get_message(payload["id"])
except:
except LookupError:
return
if server_id := message.channel.server_id:
await self._wait_for_server_ready(server_id)
self.state.messages.remove(message)
self.dispatch("message_delete", message)
async def handle_channelcreate(self, payload: ChannelCreateEventPayload):
channel = self.state.add_channel(payload)
if server_id := channel.server_id:
await self._wait_for_server_ready(server_id)
self.dispatch("channel_create", channel)
async def handle_channelupdate(self, payload: ChannelUpdateEventPayload):
channel = self.state.get_channel(payload["id"])
# Revolt sends channel updates for channels we dont have permissions to see, a bug, but still can cause issues as its not in the cache
if not (channel := self.state.channels.get(payload["id"], None)):
return
if server_id := channel.server_id:
await self._wait_for_server_ready(server_id)
old_channel = copy(channel)
@@ -163,31 +195,47 @@ 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)
async def handle_channeldelete(self, payload: ChannelDeleteEventPayload):
channel = self.state.channels.pop(payload["id"])
if server_id := channel.server_id:
await self._wait_for_server_ready(server_id)
self.dispatch("channel_delete", channel)
async def handle_channelstarttyping(self, payload: ChannelStartTypingEventPayload):
channel = self.state.get_channel(payload["id"])
if server_id := channel.server_id:
await self._wait_for_server_ready(server_id)
user = self.state.get_user(payload["user"])
self.dispatch("typing_start", channel, user)
async def handle_channelstoptyping(self, payload: ChannelDeleteTypingEventPayload):
channel = self.state.get_channel(payload["id"])
if server_id := channel.server_id:
await self._wait_for_server_ready(server_id)
user = self.state.get_user(payload["user"])
self.dispatch("typing_stop", channel, user)
async def handle_serverupdate(self, payload: ServerUpdateEventPayload):
await self._wait_for_server_ready(payload["id"])
server = self.state.get_server(payload["id"])
old_server = copy(server)
@@ -204,6 +252,7 @@ class WebsocketHandler:
elif clear == "Description":
server.description = None
self.dispatch("server_update", old_server, server)
async def handle_serverdelete(self, payload: ServerDeleteEventPayload):
@@ -212,9 +261,26 @@ class WebsocketHandler:
for channel in server.channels:
del self.state.channels[channel.id]
await self._wait_for_server_ready(server.id)
self.dispatch("server_delete", server)
async def handle_servercreate(self, payload: ServerCreateEventPayload):
for channel in payload["channels"]:
self.state.add_channel(channel)
server = self.state.add_server(payload["server"])
# lock all server events until we fetch all the members, otherwise the cache will be incomplete
self.server_events[server.id] = asyncio.Event()
await self.state.fetch_server_members(server.id)
self.server_events.pop(server.id).set()
self.dispatch("server_join", server)
async def handle_servermemberupdate(self, payload: ServerMemberUpdateEventPayload):
await self._wait_for_server_ready(payload["id"]["server"])
member = self.state.get_member(payload["id"]["server"], payload["id"]["user"])
old_member = copy(member)
@@ -229,32 +295,57 @@ class WebsocketHandler:
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"]}})
# avoid an api request if possible
if payload["user"] not in self.state.users:
user = await self.state.http.fetch_user(payload["user"])
self.state.add_user(user)
member = self.state.add_member(payload["id"], MemberPayload(_id=MemberIDPayload(server=payload["id"], user=payload["user"]), joined_at=int(time.time()))) # revolt doesnt give us the joined at time
self.dispatch("member_join", member)
async def handle_memberleave(self, payload: ServerMemberLeaveEventPayload):
await self._wait_for_server_ready(payload["id"])
server = self.state.get_server(payload["id"])
member = server._members.pop(payload["user"])
# remove the member from the user
user = self.state.get_user(payload["user"])
user._members.remove(member)
self.dispatch("member_leave", member)
async def handle_serveroleupdate(self, payload: ServerRoleUpdateEventPayload):
async def handle_serverroleupdate(self, payload: ServerRoleUpdateEventPayload):
server = self.state.get_server(payload["id"])
role = server.get_role(payload["role_id"])
old_role = copy(role)
await self._wait_for_server_ready(server.id)
if clear := payload.get("clear"):
if clear == "Colour":
role.colour = None
try:
role = server.get_role(payload["role_id"])
except LookupError:
# the role wasnt found meaning it was just created
role._update(**payload["data"])
role = Role(cast(RolePayload, payload["data"]), payload["role_id"], server, self.state)
server._roles[role.id] = role
self.dispatch("role_create", role)
else:
old_role = copy(role)
self.dispatch("role_update", old_role, 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"])
await self._wait_for_server_ready(server.id)
self.dispatch("role_delete", role)
async def handle_userupdate(self, payload: UserUpdateEventPayload):
@@ -263,26 +354,20 @@ class WebsocketHandler:
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 will never be none because they are trying to remove the text
if user.status.presence is None: # type: ignore
user.status = None
else:
user.status = Status(None, user.status.presence) # type: ignore
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 _
data = payload["data"]
data["profile_content"] = data.get("profile.content", None)
data["profile_background"] = data.get("profile.background", None)
user._update(**data)
user._update(**payload["data"])
self.dispatch("user_update", old_user, user)
@@ -293,6 +378,79 @@ class WebsocketHandler:
self.dispatch("user_relationship_update", user, old_relationship, user.relationship)
async def handle_messagereact(self, payload: MessageReactEventPayload):
if server := self.state.get_channel(payload["channel_id"]).server_id:
await self._wait_for_server_ready(server)
self.dispatch("raw_reaction_add", payload["channel_id"], payload["id"], payload["user_id"], payload["emoji_id"])
try:
message = utils.get(self.state.messages, id=payload["id"])
except LookupError:
return
user = self.state.get_user(payload["user_id"])
message.reactions.setdefault(payload["emoji_id"], []).append(user)
emoji_id = payload["emoji_id"]
self.dispatch("reaction_add", message, user, emoji_id)
async def handle_messageunreact(self, payload: MessageUnreactEventPayload):
if server := self.state.get_channel(payload["channel_id"]).server_id:
await self._wait_for_server_ready(server)
self.dispatch("raw_reaction_remove", payload["channel_id"], payload["id"], payload["user_id"], payload["emoji_id"])
try:
message = utils.get(self.state.messages, id=payload["id"])
except LookupError:
return
user = self.state.get_user(payload["user_id"])
message.reactions[payload["emoji_id"]].remove(user)
self.dispatch("reaction_remove", message, user, payload["emoji_id"])
async def handle_messageremovereaction(self, payload: MessageRemoveReactionEventPayload):
if server := self.state.get_channel(payload["channel_id"]).server_id:
await self._wait_for_server_ready(server)
self.dispatch("raw_reaction_clear", payload["channel_id"], payload["id"], payload["emoji_id"])
try:
message = utils.get(self.state.messages, id=payload["id"])
except LookupError:
return
users = message.reactions.pop(payload["emoji_id"])
self.dispatch("reaction_clear", message, users, payload["emoji_id"])
async def handle_bulkmessagedelete(self, payload: BulkMessageDeleteEventPayload):
channel = self.state.get_channel(payload["channel"])
self.dispatch("raw_bulk_message_delete", payload)
messages = []
for message_id in payload["ids"]:
if server_id := channel.server_id:
await self._wait_for_server_ready(server_id)
self.dispatch("raw_message_delete", MessageDeleteEventPayload(type="messagedelete", channel=payload["channel"], id=message_id))
try:
message = self.state.get_message(message_id)
except LookupError:
pass
else:
self.state.messages.remove(message)
self.dispatch("message_delete", message)
messages.append(message)
self.dispatch("bulk_message_delete", messages)
async def start(self):
if use_msgpack:
url = f"{self.ws_url}?format=msgpack"
@@ -305,8 +463,12 @@ class WebsocketHandler:
async for msg in self.websocket:
if use_msgpack:
payload = msgpack.unpackb(msg.data)
data = cast(bytes, msg.data)
payload = msgpack.unpackb(data)
else:
payload = json.loads(msg.data)
data = cast(str, msg.data)
payload = json.loads(data)
self.loop.create_task(self.handle_event(payload))
-46
View File
@@ -1,46 +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")
requirements = []
with open('requirements.txt') as f:
requirements = f.read().splitlines()
setup(
name="revolt.py",
version="0.1.1",
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 :: 4 - 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"],
},
install_requires=requirements,
project_urls={
"Bug Reports": "https://github.com/Zomatree/revolt.py/issues",
"Source": "https://github.com/Zomatree/revolt.py/",
},
)
+40
View File
@@ -0,0 +1,40 @@
from __future__ import annotations
from typing import Any, Callable, Dict, List, Optional, Tuple
from typing_extensions import Protocol
class _FileLike(Protocol):
def read(self, n: int) -> bytes: ...
def unpackb(
packed: bytes,
file_like: Optional[_FileLike] = ...,
read_size: int = ...,
use_list: bool = ...,
raw: bool = ...,
timestamp: int = ...,
strict_map_key: bool = ...,
object_hook: Optional[Callable[[Dict[Any, Any]], Any]] = ...,
object_pairs_hook: Optional[Callable[[List[Tuple[Any, Any]]], Any]] = ...,
list_hook: Optional[Callable[[List[Any]], Any]] = ...,
unicode_errors: Optional[str] = ...,
max_buffer_size: int = ...,
ext_hook: Callable[[int, bytes], Any] = ...,
max_str_len: int = ...,
max_bin_len: int = ...,
max_array_len: int = ...,
max_map_len: int = ...,
max_ext_len: int = ...,
) -> Any: ...
def packb(
o: Any,
default: Optional[Callable[[Any], Any]] = ...,
use_single_float: bool = ...,
autoreset: bool = ...,
use_bin_type: bool = ...,
strict_types: bool = ...,
datetime: bool = ...,
unicode_errors: Optional[str] = ...,
) -> bytes: ...