Skip to content

Commit

Permalink
added new post functions and changable presences
Browse files Browse the repository at this point in the history
  • Loading branch information
Deutscher775 committed Feb 19, 2025
1 parent 8ce20e9 commit 644a54a
Show file tree
Hide file tree
Showing 7 changed files with 142 additions and 19 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
test.py
test.png
*.pyc
.vscode/settings.json
46 changes: 46 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,54 @@ async def ping(ctx: nerimity.Context, params: str):
async def on_ready():
print(f"Logged in as {client.account.username}")


client.run()
```

## Use case examples
### Sending an attachment
```py
@client.command(name="testattachment")
async def testattachment(ctx: nerimity.Context, params):
file = await nerimity.Attachment.construct("test.png").upload()
result = await ctx.send("Test", attachment=file)
```

### Creating a post
```py
@client.command(name="createpost")
async def createpost(ctx: nerimity.Context, params):
content = ""
for param in params:
content += param + " "
await ctx.send("Creating post with text: " + content)
post = nerimity.Post.create_post(content)
print(post)
await ctx.send("Post created.")
```

### Commenting on a post
```py
@client.command(name="comment")
async def comment(ctx: nerimity.Context, params):
post_id = int(params[0])
content = ""
for param in params[1:]:
content += param + " "
post = nerimity.Post.get_post(post_id)
post.create_comment(content)
await ctx.send("Commented on post.")
```

### Deleting a post
```py
@client.command(name="deletepost")
async def deletepost(ctx: nerimity.Context, params):
post_id = int(params[0])
post = nerimity.Post.get_post(post_id)
post.delete_post()
await ctx.send("Deleted post.")
```

## Issues
If you encounter any issues while using the framework feel free to open an [Issue](https://github.com/deutscher775/nerimity.py).
1 change: 1 addition & 0 deletions nerimity/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,5 +9,6 @@
from nerimity.roles import Role
from nerimity.invite import Invite
from nerimity.post import Post
from nerimity.status import Status

pass
3 changes: 2 additions & 1 deletion nerimity/attachment.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@ class Attachment():
"""
Represents an attachment in Nerimity.
construct(): static | Creates a new Attachment object from a file path.
construct(file_path): static | Creates a new Attachment object from a file path.
upload(): |coro| Uploads the attachment to the CDN.
deserialize(): static | Deserialize a json string to a Attachment object.
"""

Expand Down
22 changes: 19 additions & 3 deletions nerimity/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
from nerimity.server import Server
from nerimity.roles import Role
from nerimity.post import Post
from nerimity.status import Status
from functools import wraps
import websockets
import asyncio
Expand Down Expand Up @@ -57,6 +58,9 @@ def __init__(self, token: str, prefix: str) -> None:
self.pending_friends: dict[str, Member] = {}

GlobalClientInformation.TOKEN = token

def change_presence(self, status: Status.StatusType.type = None, text: str = None) -> None:
Status.change_presence(status=status, text=text)

def command(self, name: str = None, aliases: list[str] = None):
"""Decorator to register a prefixed command."""
Expand Down Expand Up @@ -97,7 +101,7 @@ async def async_wrapper(ctx, *args, **kwargs):


# Public: Decorator to register to an event listener.
def listen(self, event: str) -> None:
def listen(self, event: str):
"""
Decorator to register to an event listener. Unless noted otherwise a 'dict' with relevent is passed.
Expand Down Expand Up @@ -183,7 +187,7 @@ async def _process_commands(self, message: Message) -> None:

# Private: Listens to the webhook and calls commands/listeners.
async def _listen_webhook(self, websocket: 'websockets.legacy.client.WebSocketClientProtocol') -> None:
print(f"{ConsoleShortcuts.log()} The bot is now listening to incoming connections.")
print(f"{ConsoleShortcuts.ok()} The bot is now listening to incoming connections.")
while True:
message_raw: str = await websocket.recv()

Expand Down Expand Up @@ -348,6 +352,11 @@ async def _listen_webhook(self, websocket: 'websockets.legacy.client.WebSocketCl
pass
elif message_raw.startswith("42[\"notification:dismissed"):
pass
elif message_raw.startswith("42[\"user:auth_queue_position"):

message = json.loads(message_raw.removeprefix("42"))[1]
print(f"{ConsoleShortcuts.warn()} Authentication queue position: {message['pos']}")

elif message_raw.startswith("0{\"sid"):
await websocket.send("40")

Expand Down Expand Up @@ -385,10 +394,17 @@ async def main():
await websocket.send(f"42[\"user:authenticate\",{{\"token\":\"{GlobalClientInformation.TOKEN}\"}}]")

message: str = await websocket.recv()
print(f"{ConsoleShortcuts.log()} Authentication process finished successfully!")
print(f"{ConsoleShortcuts.ok()} Authentication process finished successfully!")

# Load everything they send over to the servers dict
message_auth = json.loads(message.removeprefix("42"))[1]
if message_auth.get("pos") != 0:
print(f"{ConsoleShortcuts.warn()} Authentication queue position: {message_auth.get('pos')}")
while message_auth.get("pos") and message_auth.get("pos") != 0:
message = await websocket.recv()
if message.startswith("42[\"user:auth_queue_position"):
message_auth = json.loads(message.removeprefix("42"))[1]
print(f"{ConsoleShortcuts.warn()} Authentication queue position: {message_auth.get('pos')}")
self.account = ClientMember.deserialize(message_auth["user"])

for server_raw in message_auth["servers"]:
Expand Down
30 changes: 15 additions & 15 deletions nerimity/post.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,12 +44,12 @@ def get_post(post_id: int) -> 'Post':
"Content-Type": "application/json",
}

response = requests.get(api_endpoint, headers=headers)
if response.status_code != 200:
print(f"{ConsoleShortcuts.error()} Failed to get post by ID. Status code: {response.status_code}. Response Text: {response.text}")
raise requests.RequestException
# response = requests.get(api_endpoint, headers=headers)
# if response.status_code != 200:
# print(f"{ConsoleShortcuts.error()} Failed to get post by ID. Status code: {response.status_code}. Response Text: {response.text}")
# raise requests.RequestException

return Post.deserialize(response.json())
return Post.deserialize({"id": post_id})


# static | Creates a new Post and publishes it.
Expand Down Expand Up @@ -171,15 +171,15 @@ def deserialize(json: dict) -> 'Post':

new_post = Post()
new_post.id = int(json["id"])
new_post.creator_id = int(json["createdById"])
new_post.content = str(json["content"])
new_post.created_at = float(json["createdAt"])
new_post.edited_at = float(json["editedAt"]) if json["editedAt"] is not None else None
new_post.quoted_post_id = json["quotedPostId"]
new_post.comment_to_id = int(json["commentToId"]) if json["commentToId"] is not None else None
new_post.deleted = bool(json["deleted"]) if json["deleted"] is not None else False
new_post.creator = Member.deserialize(json["createdBy"])
new_post.liked_by = [int(i["id"]) for i in json["likedBy"]]
new_post.attachments = json["attachments"]
#new_post.creator_id = int(json["createdById"])
#new_post.content = str(json["content"])
#new_post.created_at = float(json["createdAt"])
#new_post.edited_at = float(json["editedAt"]) if json["editedAt"] is not None else None
#new_post.quoted_post_id = json["quotedPostId"]
#new_post.comment_to_id = int(json["commentToId"]) if json["commentToId"] is not None else None
#new_post.deleted = bool(json["deleted"]) if json["deleted"] is not None else False
#new_post.creator = Member.deserialize(json["createdBy"])
#new_post.liked_by = [int(i["id"]) for i in json["likedBy"]]
#new_post.attachments = json["attachments"]

return new_post
58 changes: 58 additions & 0 deletions nerimity/status.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
import nerimity
from nerimity._enums import GlobalClientInformation
from nerimity._enums import ConsoleShortcuts
import requests
import json

class Status():
"""
Represents the status of the user.
status: The current status of the user.
activity: The current activity of the user.
"""

def __init__(self, status: str, activity: str):
self.status: str = status
self.activity: str = activity

class StatusType():
"""
Represents the status type of the user.
online: The user is online.
looking: The user is idle.
idle : The user is idle.
dnd: The user is in Do Not Disturb mode.
offline: The user is invisible.
"""
type = int
online = 1
looking_to_play = 2
idle = 3
dnd = 4
offline = 5

# Public: Changes the status of the user.
@staticmethod
def change_presence(status: StatusType = None, text: str = None) -> None:
"""Changes the status of the user."""
api_endpoint = f"https://nerimity.com/api/users/presence"
headers = {
"Authorization": GlobalClientInformation.TOKEN,
"Content-Type": "application/json",
}
data = {
}
if status:
data["status"] = status
if text:
data["custom"] = text

response = requests.post(api_endpoint, headers=headers, data=json.dumps(data))
if response.status_code != 200:
print(f"{ConsoleShortcuts.error()} Failed to change presence. Status code: {response.status_code}. Response Text: {response.text}")
raise requests.RequestException



0 comments on commit 644a54a

Please sign in to comment.