nerimity 1.2.1__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- nerimity-1.2.1/LICENSE.TXT +7 -0
- nerimity-1.2.1/PKG-INFO +8 -0
- nerimity-1.2.1/README.md +200 -0
- nerimity-1.2.1/nerimity/__init__.py +16 -0
- nerimity-1.2.1/nerimity/_enums.py +53 -0
- nerimity-1.2.1/nerimity/attachment.py +74 -0
- nerimity-1.2.1/nerimity/button.py +42 -0
- nerimity-1.2.1/nerimity/buttoninteraction.py +44 -0
- nerimity-1.2.1/nerimity/channel.py +186 -0
- nerimity-1.2.1/nerimity/client.py +518 -0
- nerimity-1.2.1/nerimity/context.py +48 -0
- nerimity-1.2.1/nerimity/invite.py +21 -0
- nerimity-1.2.1/nerimity/member.py +330 -0
- nerimity-1.2.1/nerimity/message.py +142 -0
- nerimity-1.2.1/nerimity/post.py +185 -0
- nerimity-1.2.1/nerimity/roles.py +66 -0
- nerimity-1.2.1/nerimity/server.py +354 -0
- nerimity-1.2.1/nerimity/status.py +58 -0
- nerimity-1.2.1/nerimity.egg-info/PKG-INFO +8 -0
- nerimity-1.2.1/nerimity.egg-info/SOURCES.txt +23 -0
- nerimity-1.2.1/nerimity.egg-info/dependency_links.txt +1 -0
- nerimity-1.2.1/nerimity.egg-info/requires.txt +3 -0
- nerimity-1.2.1/nerimity.egg-info/top_level.txt +1 -0
- nerimity-1.2.1/setup.cfg +4 -0
- nerimity-1.2.1/setup.py +13 -0
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
Copyright 2023 "Fiiral"
|
|
2
|
+
Maintained by "Deutscher775" as of 02.02.2025
|
|
3
|
+
|
|
4
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
|
5
|
+
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
|
6
|
+
|
|
7
|
+
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
nerimity-1.2.1/PKG-INFO
ADDED
nerimity-1.2.1/README.md
ADDED
|
@@ -0,0 +1,200 @@
|
|
|
1
|
+
# nerimity.py
|
|
2
|
+
|
|
3
|
+
Python API wrapper for Nerimity originating from [Fiiral](https://github.com/F-iiral), maintained by [Deutscher775](https://github.com/Deutscher775)
|
|
4
|
+
### **[Nerimity Server](https://nerimity.com/i/493CV)** <br>
|
|
5
|
+
For questions, help or anything else feel free to join the **[nerimity.py](https://nerimity.com/i/493CV)** Nerimity server.
|
|
6
|
+
# Quick jumps
|
|
7
|
+
- **[Current Features](#current-features)** <br>
|
|
8
|
+
See the features that the framework currently supports.
|
|
9
|
+
- **[Installation](#installation)** <br>
|
|
10
|
+
Guide on how to install nerimity.py.
|
|
11
|
+
- **[Example Bot](#example-commands-bot)** <br>
|
|
12
|
+
An example bot you can directly use.
|
|
13
|
+
- **[Use-case-examples](#use-case-examples)** <br>
|
|
14
|
+
Many various examples on how to use specific functions.
|
|
15
|
+
|
|
16
|
+
# Current features
|
|
17
|
+
#### Command Handling:
|
|
18
|
+
- Define and register commands using the @client.command decorator.
|
|
19
|
+
- Execute commands with parameters.
|
|
20
|
+
Register event listeners using the @client.listen decorator.
|
|
21
|
+
Handle various events such as:
|
|
22
|
+
- on_ready
|
|
23
|
+
- on_message_create
|
|
24
|
+
- on_message_updated
|
|
25
|
+
- on_message_deleted
|
|
26
|
+
- on_button_clicked
|
|
27
|
+
- on_presence_change
|
|
28
|
+
- on_reaction_add
|
|
29
|
+
- on_member_updated
|
|
30
|
+
- on_role_updated
|
|
31
|
+
- on_role_deleted
|
|
32
|
+
- on_role_created
|
|
33
|
+
- on_channel_updated
|
|
34
|
+
- on_channel_deleted
|
|
35
|
+
- on_channel_created
|
|
36
|
+
- on_server_updated
|
|
37
|
+
- on_member_join
|
|
38
|
+
- on_member_left
|
|
39
|
+
- on_server_joined
|
|
40
|
+
- on_server_left
|
|
41
|
+
- on_friend_request_sent
|
|
42
|
+
- on_friend_request_pending
|
|
43
|
+
- on_friend_request_accepted
|
|
44
|
+
- on_friend_removed
|
|
45
|
+
- on_minute_pulse
|
|
46
|
+
- on_hour_pulse
|
|
47
|
+
|
|
48
|
+
#### Message Handling:
|
|
49
|
+
- Send messages to channels.
|
|
50
|
+
- add attachments
|
|
51
|
+
- add buttons with custom callback
|
|
52
|
+
- Edit and delete messages.
|
|
53
|
+
- React and unreact to messages.
|
|
54
|
+
|
|
55
|
+
#### Attachment Handling:
|
|
56
|
+
- Create and upload attachments.
|
|
57
|
+
- Deserialize attachments from JSON.
|
|
58
|
+
|
|
59
|
+
#### Channel Management:
|
|
60
|
+
- Update channel information.
|
|
61
|
+
- Send messages to channels.
|
|
62
|
+
- Get messages from channels.
|
|
63
|
+
- Purge messages from channels.
|
|
64
|
+
- Deserialize channels from JSON.
|
|
65
|
+
|
|
66
|
+
#### Context Handling:
|
|
67
|
+
- Send messages, remove messages, and react to messages within a command context.
|
|
68
|
+
|
|
69
|
+
#### Invite Management:
|
|
70
|
+
- Create and delete server invites.
|
|
71
|
+
- Deserialize invites from JSON.
|
|
72
|
+
|
|
73
|
+
#### Member Management:
|
|
74
|
+
- Follow, unfollow, add friend, remove friend, and send direct messages to members.
|
|
75
|
+
- Kick, ban, and unban server members.
|
|
76
|
+
- Deserialize members and server members from JSON.
|
|
77
|
+
|
|
78
|
+
#### Post Management:
|
|
79
|
+
- Create, delete, comment on, like, and unlike posts.
|
|
80
|
+
- Get comments on posts.
|
|
81
|
+
- Deserialize posts from JSON.
|
|
82
|
+
|
|
83
|
+
#### Role Management:
|
|
84
|
+
- Create, update, and delete roles.
|
|
85
|
+
- Deserialize roles from JSON.
|
|
86
|
+
|
|
87
|
+
#### Server Management:
|
|
88
|
+
- Get server details and ban list.
|
|
89
|
+
- Create, update, and delete channels and roles.
|
|
90
|
+
- Create and delete invites.
|
|
91
|
+
- Update server members.
|
|
92
|
+
- Deserialize servers from JSON.
|
|
93
|
+
|
|
94
|
+
#### Status Management:
|
|
95
|
+
- Change the presence status of the bot.
|
|
96
|
+
|
|
97
|
+
#### Button Interaction:
|
|
98
|
+
- Handle button interactions and send popups.
|
|
99
|
+
- Deserialize button interactions from JSON.
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
# Installation
|
|
103
|
+
Currently there is no direct installation method. (WIP)
|
|
104
|
+
### Follow these 2 simple steps:
|
|
105
|
+
1. Clone the repository
|
|
106
|
+
```shell
|
|
107
|
+
git clone https://github.com/deutscher775/nerimity.py.git
|
|
108
|
+
```
|
|
109
|
+
2. Copy the `nerimity` folder and insert it into your workspace. It should look like this:
|
|
110
|
+

|
|
111
|
+
|
|
112
|
+
### Done!
|
|
113
|
+
## Example commands bot
|
|
114
|
+
```py
|
|
115
|
+
import nerimity
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
client = nerimity.Client(
|
|
119
|
+
token="YOUR_BOT_TOKEN",
|
|
120
|
+
prefix='!',
|
|
121
|
+
)
|
|
122
|
+
|
|
123
|
+
@client.command(name="ping")
|
|
124
|
+
async def ping(ctx: nerimity.Context, params: str):
|
|
125
|
+
await ctx.send("Pong!")
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
@client.listen("on_ready")
|
|
129
|
+
async def on_ready(params):
|
|
130
|
+
print(f"Logged in as {client.account.username}")
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
client.run()
|
|
134
|
+
```
|
|
135
|
+
|
|
136
|
+
## Use case examples
|
|
137
|
+
### Sending an attachment
|
|
138
|
+
```py
|
|
139
|
+
@client.command(name="testattachment")
|
|
140
|
+
async def testattachment(ctx: nerimity.Context, params):
|
|
141
|
+
file = await nerimity.Attachment.construct("test.png").upload()
|
|
142
|
+
result = await ctx.send("Test", attachment=file)
|
|
143
|
+
```
|
|
144
|
+
|
|
145
|
+
### Sending buttons with messages
|
|
146
|
+
```py
|
|
147
|
+
@client.command(name="testbutton")
|
|
148
|
+
async def testbutton(ctx: nerimity.Context, params):
|
|
149
|
+
popup_button = nerimity.Button.construct(label="Popup!", id="popuptestbutton", alert=True)
|
|
150
|
+
async def popup_callback(buttoninteraction: nerimity.ButtonInteraction):
|
|
151
|
+
user = client.get_user(buttoninteraction.userId)
|
|
152
|
+
buttoninteraction.send_popup("Test", f"Hello, {user.username}!")
|
|
153
|
+
await popup_button.set_callback(popup_callback)
|
|
154
|
+
|
|
155
|
+
message_button = nerimity.Button.construct(label="Message!", id="messagetestbutton")
|
|
156
|
+
async def message_callback(buttoninteraction: nerimity.ButtonInteraction):
|
|
157
|
+
user = client.get_user(buttoninteraction.userId)
|
|
158
|
+
await ctx.send(f"Hello, {user.username}!")
|
|
159
|
+
await message_button.set_callback(message_callback)
|
|
160
|
+
await ctx.send("Test", buttons=[message_button, popup_button])
|
|
161
|
+
```
|
|
162
|
+
|
|
163
|
+
### Creating a post
|
|
164
|
+
```py
|
|
165
|
+
@client.command(name="createpost")
|
|
166
|
+
async def createpost(ctx: nerimity.Context, params):
|
|
167
|
+
content = ""
|
|
168
|
+
for param in params:
|
|
169
|
+
content += param + " "
|
|
170
|
+
await ctx.send("Creating post with text: " + content)
|
|
171
|
+
post = nerimity.Post.create_post(content)
|
|
172
|
+
print(post)
|
|
173
|
+
await ctx.send("Post created.")
|
|
174
|
+
```
|
|
175
|
+
|
|
176
|
+
### Commenting on a post
|
|
177
|
+
```py
|
|
178
|
+
@client.command(name="comment")
|
|
179
|
+
async def comment(ctx: nerimity.Context, params):
|
|
180
|
+
post_id = int(params[0])
|
|
181
|
+
content = ""
|
|
182
|
+
for param in params[1:]:
|
|
183
|
+
content += param + " "
|
|
184
|
+
post = nerimity.Post.get_post(post_id)
|
|
185
|
+
post.create_comment(content)
|
|
186
|
+
await ctx.send("Commented on post.")
|
|
187
|
+
```
|
|
188
|
+
|
|
189
|
+
### Deleting a post
|
|
190
|
+
```py
|
|
191
|
+
@client.command(name="deletepost")
|
|
192
|
+
async def deletepost(ctx: nerimity.Context, params):
|
|
193
|
+
post_id = int(params[0])
|
|
194
|
+
post = nerimity.Post.get_post(post_id)
|
|
195
|
+
post.delete_post()
|
|
196
|
+
await ctx.send("Deleted post.")
|
|
197
|
+
```
|
|
198
|
+
|
|
199
|
+
## Issues
|
|
200
|
+
If you encounter any issues while using the framework feel free to open an [Issue](https://github.com/deutscher775/nerimity.py).
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
from nerimity._enums import GlobalClientInformation, Colors, ChannelTypes, PresenceTypes, BadgeTypes, AttachmentTypes
|
|
2
|
+
from nerimity.attachment import Attachment
|
|
3
|
+
from nerimity.channel import Channel
|
|
4
|
+
from nerimity.client import Client
|
|
5
|
+
from nerimity.context import Context
|
|
6
|
+
from nerimity.member import Member, ServerMember
|
|
7
|
+
from nerimity.message import Message
|
|
8
|
+
from nerimity.server import Server
|
|
9
|
+
from nerimity.roles import Role
|
|
10
|
+
from nerimity.invite import Invite
|
|
11
|
+
from nerimity.post import Post
|
|
12
|
+
from nerimity.status import Status
|
|
13
|
+
from nerimity.button import Button
|
|
14
|
+
from nerimity.buttoninteraction import ButtonInteraction
|
|
15
|
+
|
|
16
|
+
pass
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import datetime
|
|
2
|
+
|
|
3
|
+
class GlobalClientInformation():
|
|
4
|
+
TOKEN = ''
|
|
5
|
+
SERVERS = {}
|
|
6
|
+
BUTTONS = []
|
|
7
|
+
|
|
8
|
+
class ConsoleShortcuts():
|
|
9
|
+
def log(): return f"{Colors.MAGENTA}[{datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')}]{Colors.WHITE} |"
|
|
10
|
+
def ok(): return f"{Colors.GREEN}[{datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')}]{Colors.WHITE} |"
|
|
11
|
+
def warn(): return f"{Colors.YELLOW}[{datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')}]{Colors.WHITE} |"
|
|
12
|
+
def error(): return f"{Colors.RED}[{datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')}]{Colors.WHITE} |"
|
|
13
|
+
|
|
14
|
+
class Colors():
|
|
15
|
+
BLACK = "\u001b[30m"
|
|
16
|
+
RED = "\u001b[31m"
|
|
17
|
+
GREEN = "\u001b[32m"
|
|
18
|
+
YELLOW = "\u001b[33m"
|
|
19
|
+
BLUE = "\u001b[34m"
|
|
20
|
+
MAGENTA = "\u001b[35m"
|
|
21
|
+
CYAN = "\u001b[36m"
|
|
22
|
+
WHITE = "\u001b[37m"
|
|
23
|
+
|
|
24
|
+
class ChannelTypes():
|
|
25
|
+
DM_TEXT = 0
|
|
26
|
+
SERVER_TEXT = 1
|
|
27
|
+
CATEGORY = 2
|
|
28
|
+
|
|
29
|
+
class PresenceTypes():
|
|
30
|
+
OFFLINE = 0
|
|
31
|
+
ONLINE = 1
|
|
32
|
+
LTP = 2
|
|
33
|
+
AFK = 3
|
|
34
|
+
DND = 4
|
|
35
|
+
|
|
36
|
+
class BadgeTypes():
|
|
37
|
+
OWNER = 1
|
|
38
|
+
ADMIN = 2
|
|
39
|
+
CONTRIBUTOR = 4
|
|
40
|
+
SUPPORTER = 8
|
|
41
|
+
BOT = 16
|
|
42
|
+
|
|
43
|
+
class MessageType():
|
|
44
|
+
CONTENT = 0
|
|
45
|
+
JOIN_SERVER = 1
|
|
46
|
+
LEAVE_SERVER = 2
|
|
47
|
+
KICK_USER = 3
|
|
48
|
+
BAN_USER = 4
|
|
49
|
+
CALL_STARTED = 5
|
|
50
|
+
|
|
51
|
+
class AttachmentTypes():
|
|
52
|
+
INCOMING = 0
|
|
53
|
+
OUTGOING = 1
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
from nerimity._enums import AttachmentTypes, GlobalClientInformation
|
|
2
|
+
import aiohttp
|
|
3
|
+
import mimetypes
|
|
4
|
+
|
|
5
|
+
class Attachment():
|
|
6
|
+
"""
|
|
7
|
+
Represents an attachment in Nerimity.
|
|
8
|
+
|
|
9
|
+
construct(file_path): static | Creates a new Attachment object from a file path.
|
|
10
|
+
upload(): |coro| Uploads the attachment to the CDN.
|
|
11
|
+
deserialize(): static | Deserialize a json string to a Attachment object.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
def __init__(self) -> None:
|
|
15
|
+
self.internal_type : int = None
|
|
16
|
+
self.data_type : str | None = None
|
|
17
|
+
self.size : int | None = None
|
|
18
|
+
self.data : str | None = None
|
|
19
|
+
self.height : int | None = None
|
|
20
|
+
self.width : int | None = None
|
|
21
|
+
self.name : str | None = None
|
|
22
|
+
self.id : int | None = None
|
|
23
|
+
self.provider : str | None = None
|
|
24
|
+
self.file_id : str | None = None
|
|
25
|
+
self.mime : str | None = None
|
|
26
|
+
self.created_at : float | None = None
|
|
27
|
+
|
|
28
|
+
# Public Static: Creates a new Attachment object from a file.
|
|
29
|
+
@staticmethod
|
|
30
|
+
def construct(file_path) -> 'Attachment':
|
|
31
|
+
"""Creates a new Attachment object from a file path."""
|
|
32
|
+
|
|
33
|
+
new_attachment = Attachment()
|
|
34
|
+
new_attachment.internal_type = AttachmentTypes.OUTGOING
|
|
35
|
+
|
|
36
|
+
with open(file_path, 'rb') as file:
|
|
37
|
+
new_attachment.data = file.read()
|
|
38
|
+
new_attachment.data_type, _ = mimetypes.guess_type(file_path)
|
|
39
|
+
new_attachment.size = len(new_attachment.data)
|
|
40
|
+
new_attachment.name = file_path.split("/")[-1] if "/" in file_path else file_path
|
|
41
|
+
|
|
42
|
+
return new_attachment
|
|
43
|
+
|
|
44
|
+
# Public: Uploads the attachment to the CDN.
|
|
45
|
+
async def upload(self):
|
|
46
|
+
"""|coro| Uploads the attachment to the CDN. Returns the file ID. This is not a usable file yet. It will be automatically uploaded with the send_message method."""
|
|
47
|
+
formdata = aiohttp.FormData()
|
|
48
|
+
formdata.add_field("f", self.data, filename=self.name, content_type=self.data_type)
|
|
49
|
+
headers = {
|
|
50
|
+
"Authorization": GlobalClientInformation.TOKEN,
|
|
51
|
+
}
|
|
52
|
+
async with aiohttp.ClientSession() as session:
|
|
53
|
+
async with session.post("https://cdn.nerimity.com/upload", headers=headers, data=formdata) as cdn_response:
|
|
54
|
+
json = await cdn_response.json()
|
|
55
|
+
self.file_id = json.get("fileId")
|
|
56
|
+
return self
|
|
57
|
+
|
|
58
|
+
# Public Static: Deserialize a json string to a Attachment object.
|
|
59
|
+
@staticmethod
|
|
60
|
+
def deserialize(json: dict) -> 'Attachment':
|
|
61
|
+
"""Deserialize a json string to a Attachment object."""
|
|
62
|
+
|
|
63
|
+
new_attachment = Attachment()
|
|
64
|
+
new_attachment.internal_type = AttachmentTypes.INCOMING
|
|
65
|
+
new_attachment.height = json["height"]
|
|
66
|
+
new_attachment.width = json["width"]
|
|
67
|
+
new_attachment.path = json["path"]
|
|
68
|
+
new_attachment.id = int(json["id"]) if json["id"] is not None else None
|
|
69
|
+
new_attachment.provider = json["provider"]
|
|
70
|
+
new_attachment.file_id = json["fileId"]
|
|
71
|
+
new_attachment.mime = json["mime"]
|
|
72
|
+
new_attachment.created_at = json["createdAt"]
|
|
73
|
+
|
|
74
|
+
return new_attachment
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
class Button():
|
|
2
|
+
"""Represents a button.
|
|
3
|
+
## Attributes
|
|
4
|
+
|
|
5
|
+
label: string | The label of the button.
|
|
6
|
+
id: string | The ID of the button.
|
|
7
|
+
alert: bool | Whether the button is an alert button. (Button will be red if true)
|
|
8
|
+
"""
|
|
9
|
+
def __init__(self) -> None:
|
|
10
|
+
self.label : str = None
|
|
11
|
+
self.id : str = None
|
|
12
|
+
self.alert : bool = False
|
|
13
|
+
self._callback = None
|
|
14
|
+
|
|
15
|
+
@classmethod
|
|
16
|
+
def construct(cls, label: str, id: str, alert: bool = False) -> 'Button':
|
|
17
|
+
"""Constructs a button."""
|
|
18
|
+
button = cls()
|
|
19
|
+
button.label = label
|
|
20
|
+
button.id = id
|
|
21
|
+
button.alert = alert
|
|
22
|
+
return button
|
|
23
|
+
|
|
24
|
+
async def callback(self, buttoninteraction):
|
|
25
|
+
"""Callback function for the button."""
|
|
26
|
+
if self._callback:
|
|
27
|
+
await self._callback(buttoninteraction)
|
|
28
|
+
|
|
29
|
+
async def set_callback(self, callback_func):
|
|
30
|
+
"""Sets the callback function for the button."""
|
|
31
|
+
self._callback = callback_func
|
|
32
|
+
|
|
33
|
+
# Public: Serializes the button to a json string.
|
|
34
|
+
@staticmethod
|
|
35
|
+
def deserialize(json: dict) -> 'Button':
|
|
36
|
+
"""Deserialize a json string to a Button object."""
|
|
37
|
+
button = Button()
|
|
38
|
+
button.label = str(json["label"])
|
|
39
|
+
button.id = str(json["id"])
|
|
40
|
+
button.alert = bool(json["alert"])
|
|
41
|
+
|
|
42
|
+
return button
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
from nerimity.button import Button
|
|
2
|
+
import requests
|
|
3
|
+
from nerimity._enums import ConsoleShortcuts, GlobalClientInformation
|
|
4
|
+
|
|
5
|
+
class ButtonInteraction():
|
|
6
|
+
def __init__(self, messageId: int = None, channelId: int = None, button: Button = None, userId: int = None) -> None:
|
|
7
|
+
self.messageId = messageId
|
|
8
|
+
self.channelId = channelId
|
|
9
|
+
self.button = button
|
|
10
|
+
self.userId = userId
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def send_popup(self, title: str, content: str) -> None:
|
|
14
|
+
"""Sends a popup to the user who clicked the button."""
|
|
15
|
+
api_url = f"https://nerimity.com/api/channels/{self.channelId}/messages/{self.messageId}/buttons/{self.button.id}/callback"
|
|
16
|
+
|
|
17
|
+
headers = {
|
|
18
|
+
"Authorization": GlobalClientInformation.TOKEN
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
data = {
|
|
22
|
+
"userId": str(self.userId),
|
|
23
|
+
"title": title,
|
|
24
|
+
"content": content
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
response = requests.post(api_url, json=data, headers=headers)
|
|
28
|
+
if response.status_code != 200:
|
|
29
|
+
print(f"{ConsoleShortcuts.error} Failed to send popup: {response.text}")
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
@staticmethod
|
|
33
|
+
def deserialize(json: dict) -> 'ButtonInteraction':
|
|
34
|
+
"""Deserialize a json string to a ButtonInteraction object."""
|
|
35
|
+
print(json)
|
|
36
|
+
buttonInteraction = ButtonInteraction()
|
|
37
|
+
buttonInteraction.messageId = int(json["messageId"])
|
|
38
|
+
buttonInteraction.channelId = int(json["channelId"])
|
|
39
|
+
buttonInteraction.button = json["button"]
|
|
40
|
+
buttonInteraction.userId = int(json["userId"])
|
|
41
|
+
|
|
42
|
+
return buttonInteraction
|
|
43
|
+
|
|
44
|
+
|
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
import aiohttp
|
|
2
|
+
import asyncio
|
|
3
|
+
import json
|
|
4
|
+
from nerimity.message import Message
|
|
5
|
+
from nerimity.attachment import Attachment
|
|
6
|
+
from nerimity._enums import GlobalClientInformation, ConsoleShortcuts
|
|
7
|
+
from nerimity.button import Button
|
|
8
|
+
|
|
9
|
+
class Channel():
|
|
10
|
+
"""
|
|
11
|
+
Represents a channel in Nerimity.
|
|
12
|
+
|
|
13
|
+
id: Snowflake ID of the channel
|
|
14
|
+
name: Name of the channel.
|
|
15
|
+
type: Type of the channel
|
|
16
|
+
creator_id: ID of the creator of the channel.
|
|
17
|
+
server_id: ID of the server the channel is in.
|
|
18
|
+
category_id: ID of the category the channel is in.
|
|
19
|
+
last_messaged_at: Timestamp from when the last message was send.
|
|
20
|
+
created_at: Timestamp from when the channel was created.
|
|
21
|
+
order: Priority of the channel in its category.
|
|
22
|
+
|
|
23
|
+
update_channel(): Updates itself with specified information.
|
|
24
|
+
send_message(): Sends a message to the channel.
|
|
25
|
+
get_messages(): Gets a list of up to 50 message from the channel.
|
|
26
|
+
|
|
27
|
+
deserialize(json): static | Deserialize a json string to a Channel object.
|
|
28
|
+
"""
|
|
29
|
+
|
|
30
|
+
def __init__(self) -> None:
|
|
31
|
+
self.id : int = None
|
|
32
|
+
self.name : str = None
|
|
33
|
+
self.type : int = None
|
|
34
|
+
self.creator_id : int = None
|
|
35
|
+
self.server_id : int = None
|
|
36
|
+
self.category_id : int = None
|
|
37
|
+
self.last_messaged_at : float | None = None
|
|
38
|
+
self.created_at : float = None
|
|
39
|
+
self.order : int | None = None
|
|
40
|
+
|
|
41
|
+
# Public: Updates itself with specified information.
|
|
42
|
+
async def update_channel(self, server_id: int, name: str=None, icon: str=None, content: str=None) -> None:
|
|
43
|
+
"""Updates itself with specified information."""
|
|
44
|
+
|
|
45
|
+
api_endpoint = f"https://nerimity.com/api/servers/{server_id}/channels/{self.id}"
|
|
46
|
+
|
|
47
|
+
headers = {
|
|
48
|
+
"Authorization": GlobalClientInformation.TOKEN,
|
|
49
|
+
"Content-Type": "application/json",
|
|
50
|
+
}
|
|
51
|
+
data = {
|
|
52
|
+
"name": name,
|
|
53
|
+
"icon": icon,
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
if icon is None:
|
|
57
|
+
del data["icon"]
|
|
58
|
+
|
|
59
|
+
async with aiohttp.ClientSession() as session:
|
|
60
|
+
async with session.post(api_endpoint, headers=headers, json=data) as response:
|
|
61
|
+
if response.status != 200:
|
|
62
|
+
print(f"{ConsoleShortcuts.error()} Failed to update a channel for {self}. Status code: {response.status}. Response Text: {await response.text()}")
|
|
63
|
+
raise aiohttp.ClientResponseError(response.request_info, response.history)
|
|
64
|
+
|
|
65
|
+
if content is not None:
|
|
66
|
+
api_endpoint = f"https://nerimity.com/api/servers/{server_id}/channels/{self.id}/notice"
|
|
67
|
+
|
|
68
|
+
if content == "":
|
|
69
|
+
async with session.delete(api_endpoint, headers=headers) as response:
|
|
70
|
+
if response.status != 200:
|
|
71
|
+
print(f"{ConsoleShortcuts.error()} Failed to update a channel for {self}. Status code: {response.status}. Response Text: {await response.text()}")
|
|
72
|
+
raise aiohttp.ClientResponseError(response.request_info, response.history)
|
|
73
|
+
else:
|
|
74
|
+
async with session.put(api_endpoint, headers=headers, json={"content": content}) as response:
|
|
75
|
+
if response.status != 200:
|
|
76
|
+
print(f"{ConsoleShortcuts.error()} Failed to update a channel for {self}. Status code: {response.status}. Response Text: {await response.text()}")
|
|
77
|
+
raise aiohttp.ClientResponseError(response.request_info, response.history)
|
|
78
|
+
|
|
79
|
+
# Public: Sends a message to the channel.
|
|
80
|
+
async def send_message(self, message_content: str, attachment: Attachment | None = None, buttons: list[Button] | None = None) -> Message:
|
|
81
|
+
"""Sends a message to the channel."""
|
|
82
|
+
|
|
83
|
+
api_endpoint = f"https://nerimity.com/api/channels/{self.id}/messages"
|
|
84
|
+
headers = {
|
|
85
|
+
"Authorization": GlobalClientInformation.TOKEN,
|
|
86
|
+
"Content-Type": "application/json",
|
|
87
|
+
}
|
|
88
|
+
data = {
|
|
89
|
+
"content": message_content,
|
|
90
|
+
"buttons": []
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
if buttons is not None:
|
|
94
|
+
for button in buttons:
|
|
95
|
+
data["buttons"].append({
|
|
96
|
+
"label": str(button.label),
|
|
97
|
+
"id": str(button.id),
|
|
98
|
+
"alert": button.alert
|
|
99
|
+
})
|
|
100
|
+
GlobalClientInformation.BUTTONS.append(button)
|
|
101
|
+
print(data["buttons"])
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
async with aiohttp.ClientSession() as session:
|
|
105
|
+
if attachment is not None:
|
|
106
|
+
async with session.post(f"https://cdn.nerimity.com/attachments/{str(self.id)}/{attachment.file_id}") as response:
|
|
107
|
+
if response.status != 200:
|
|
108
|
+
print(f"{ConsoleShortcuts.error()} Failed to send attachment to {self}. Status code: {response.status}. Response Text: {await response.text()}")
|
|
109
|
+
raise aiohttp.ClientResponseError(response.request_info, response.history)
|
|
110
|
+
data["nerimityCdnFileId"] = (await response.json()).get("fileId")
|
|
111
|
+
|
|
112
|
+
async with session.post(api_endpoint, headers=headers, json=data) as response:
|
|
113
|
+
if response.status != 200:
|
|
114
|
+
print(f"{ConsoleShortcuts.error()} Failed to send message to {self}. Status code: {response.status}. Response Text: {await response.text()}")
|
|
115
|
+
raise aiohttp.ClientResponseError(response.request_info, response.history)
|
|
116
|
+
message_data = await response.json()
|
|
117
|
+
return Message.deserialize(message_data)
|
|
118
|
+
|
|
119
|
+
# Private: Gets a raw string of messages.
|
|
120
|
+
async def _get_messages_raw(self, amount: int) -> str:
|
|
121
|
+
if amount > 50:
|
|
122
|
+
amount = 50
|
|
123
|
+
elif amount < 1:
|
|
124
|
+
raise ValueError("Amount of requested messages must be positive.")
|
|
125
|
+
|
|
126
|
+
api_endpoint = f"https://nerimity.com/api/channels/{self.id}/messages?limit={amount}"
|
|
127
|
+
|
|
128
|
+
headers = {
|
|
129
|
+
"Authorization": GlobalClientInformation.TOKEN,
|
|
130
|
+
"Content-Type": "application/json",
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
async with aiohttp.ClientSession() as session:
|
|
134
|
+
async with session.get(api_endpoint, headers=headers) as response:
|
|
135
|
+
if response.status != 200:
|
|
136
|
+
print(f"Failed to get messages from {self}. Status code: {response.status}. Response Text: {await response.text()}")
|
|
137
|
+
raise aiohttp.ClientResponseError(response.request_info, response.history)
|
|
138
|
+
|
|
139
|
+
return await response.text()
|
|
140
|
+
|
|
141
|
+
# Public: Gets a list of up to 50 message from the channel.
|
|
142
|
+
async def get_messages(self, amount: int) -> list[Message]:
|
|
143
|
+
"""Gets a list of up to 50 message from the channel."""
|
|
144
|
+
|
|
145
|
+
messages_raw = json.loads(await self._get_messages_raw(amount))
|
|
146
|
+
messages = []
|
|
147
|
+
for message_raw in messages_raw:
|
|
148
|
+
message = Message.deserialize(message_raw)
|
|
149
|
+
messages.append(message)
|
|
150
|
+
|
|
151
|
+
return messages
|
|
152
|
+
|
|
153
|
+
# Public: Purge the channel of the specified amount of messages.
|
|
154
|
+
async def purge(self, amount: int) -> None:
|
|
155
|
+
"""Purges the channel of the specified amount of messages."""
|
|
156
|
+
|
|
157
|
+
if amount > 50:
|
|
158
|
+
print(f"{ConsoleShortcuts.warn()} Attempted to purge an illegal amount '{amount}' of messages in {self}.")
|
|
159
|
+
amount = 50
|
|
160
|
+
if amount <= 0:
|
|
161
|
+
print(f"{ConsoleShortcuts.warn()} Attempted to purge an illegal amount '{amount}' of messages in {self}.")
|
|
162
|
+
return
|
|
163
|
+
|
|
164
|
+
messages = await self.get_messages(amount)
|
|
165
|
+
messages.reverse()
|
|
166
|
+
messages = messages[:amount]
|
|
167
|
+
for message in messages:
|
|
168
|
+
await message.delete()
|
|
169
|
+
|
|
170
|
+
# Public Static: Deserialize a json string to a Channel object.
|
|
171
|
+
@staticmethod
|
|
172
|
+
def deserialize(json: dict) -> 'Channel':
|
|
173
|
+
"""static | Deserialize a json string to a Channel object."""
|
|
174
|
+
|
|
175
|
+
new_channel = Channel()
|
|
176
|
+
new_channel.id = int(json["id"])
|
|
177
|
+
new_channel.name = str(json["name"])
|
|
178
|
+
new_channel.type = int(json["type"])
|
|
179
|
+
new_channel.creator_id = int(json["createdById"]) if json["createdById"] is not None else 0
|
|
180
|
+
new_channel.server_id = int(json["serverId"]) if json["serverId"] is not None else 0
|
|
181
|
+
new_channel.category_id = int(json["categoryId"]) if json["categoryId"] is not None else 0
|
|
182
|
+
new_channel.last_messaged_at = float(json["lastMessagedAt"]) if json["lastMessagedAt"] is not None else None
|
|
183
|
+
new_channel.created_at = float(json["createdAt"])
|
|
184
|
+
new_channel.order = json["order"]
|
|
185
|
+
|
|
186
|
+
return new_channel
|