Skip to content

Commit

Permalink
nerimity bot now publicly avaiblabe + more file types supported now
Browse files Browse the repository at this point in the history
  • Loading branch information
Deutscher775 committed Oct 31, 2024
1 parent fd86c7f commit 2417983
Show file tree
Hide file tree
Showing 18 changed files with 2,081 additions and 2 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -22,3 +22,4 @@ src/Bot/nerimity_servers/1528027692992208896.json
src/tokens.json
assets/517057624072519680.png
src/astroidapi/test.py
/src/astroidapi/TMP_attachments
2 changes: 1 addition & 1 deletion src/Bot/discord.py
Original file line number Diff line number Diff line change
Expand Up @@ -148,7 +148,7 @@ async def on_message(message: nextcord.Message):
async with session.post(f"https://astroid.deutscher775.de/update/{message.channel.guild.id}?message_content={message.content}&message_author_name={message.author.name}&message_author_avatar={message.author.avatar.url if message.author.avatar.url else 'https://astroid.deutscher775.de/assets/Astroid PFP not found.png'}&message_author_id={message.author.id}&trigger=true&sender=discord&token={config.MASTER_TOKEN}&sender_channel={message.channel.id}&message_embed={embed}") as update_request:
pass
if message.attachments:
print(3)
print(3)
if len(message.attachments) == 1:
# Update the message content with attachment in the API
async with session.post(f"https://astroid.deutscher775.de/update/{message.channel.guild.id}?message_content={message.content}&message_author_name={message.author.name}&message_author_avatar={message.author.avatar.url if message.author.avatar.url else 'https://astroid.deutscher775.de/assets/Astroid PFP not found.png'}&message_author_id={message.author.id}&trigger=true&sender=discord&token={config.MASTER_TOKEN}&sender_channel={message.channel.id}&message_attachments={message.attachments[0].url}") as update_request:
Expand Down
6 changes: 6 additions & 0 deletions src/Bot/nerimity/LICENSE.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
Copyright 2023 "Fiiral"

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
13 changes: 13 additions & 0 deletions src/Bot/nerimity/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
from nerimity._enums import GlobalClientInformation, Colors, ChannelPermissions, RolePermissions, ChannelTypes, PresenceTypes, BadgeTypes, AttachmentTypes
from nerimity.attachment import Attachment
from nerimity.channel import Channel
from nerimity.client import Client
from nerimity.context import Context
from nerimity.member import Member, ServerMember
from nerimity.message import Message
from nerimity.server import Server
from nerimity.roles import Role
from nerimity.invite import Invite
from nerimity.post import Post

pass
66 changes: 66 additions & 0 deletions src/Bot/nerimity/_enums.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
import datetime

class GlobalClientInformation():
TOKEN = ''
SERVERS = {}

class ConsoleShortcuts():
def log(): return f"{Colors.MAGENTA}[{datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')}]{Colors.WHITE} |"
def ok(): return f"{Colors.GREEN}[{datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')}]{Colors.WHITE} |"
def warn(): return f"{Colors.YELLOW}[{datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')}]{Colors.WHITE} |"
def error(): return f"{Colors.RED}[{datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')}]{Colors.WHITE} |"

class Colors():
BLACK = "\u001b[30m"
RED = "\u001b[31m"
GREEN = "\u001b[32m"
YELLOW = "\u001b[33m"
BLUE = "\u001b[34m"
MAGENTA = "\u001b[35m"
CYAN = "\u001b[36m"
WHITE = "\u001b[37m"

class ChannelPermissions():
PRIVATE_CHANNEL = 1
SEND_MESSAGES = 2
JOIN_VOICE = 4

class RolePermissions():
ADMINISTRATOR = 1
SEND_MESSAGES = 2
MANAGE_ROLES = 4
MANAGE_CHANNELS = 8
KICK_USER = 16
BAN_USER = 32
MENTION_EVERYONE = 64

class ChannelTypes():
DM_TEXT = 0
SERVER_TEXT = 1
CATEGORY = 2

class PresenceTypes():
OFFLINE = 0
ONLINE = 1
LTP = 2
AFK = 3
DND = 4

class BadgeTypes():
OWNER = 1
ADMIN = 2
CONTRIBUTOR = 4
SUPPORTER = 8
BOT = 16

class MessageType():
CONTENT = 0
JOIN_SERVER = 1
LEAVE_SERVER = 2
KICK_USER = 3
BAN_USER = 4
CALL_STARTED = 5

class AttachmentTypes():
INCOMING = 0
OUTGOING = 1
56 changes: 56 additions & 0 deletions src/Bot/nerimity/attachment.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
from nerimity._enums import AttachmentTypes

class Attachment():
"""
Represents an attachment in Nerimity.
construct(): static | Creates a new Attachment object from a file path.
deserialize(): static | Deserialize a json string to a Attachment object.
"""

def __init__(self) -> None:
self.internal_type : int = None
self.data_type : str | None = None
self.size : int | None = None
self.data : str | None = None
self.height : int | None = None
self.width : int | None = None
self.path : str | None = None
self.id : int | None = None
self.provider : str | None = None
self.file_id : str | None = None
self.mime : str | None = None
self.created_at : float | None = None

# Public Static: Creates a new Attachment object from a file.
@staticmethod
def construct(file_path) -> 'Attachment':
"""Creates a new Attachment object from a file path."""

new_attachment = Attachment()
new_attachment.internal_type = AttachmentTypes.OUTGOING

with open(file_path, 'rb') as file:
new_attachment.data = file.read()
new_attachment.data_type = 'application/octet-stream'
new_attachment.size = len(new_attachment.data)

return new_attachment

# Public Static: Deserialize a json string to a Attachment object.
@staticmethod
def deserialize(json: dict) -> 'Attachment':
"""Deserialize a json string to a Attachment object."""

new_attachment = Attachment()
new_attachment.internal_type = AttachmentTypes.INCOMING
new_attachment.height = json["height"]
new_attachment.width = json["width"]
new_attachment.path = json["path"]
new_attachment.id = int(json["id"]) if json["id"] is not None else None
new_attachment.provider = json["provider"]
new_attachment.file_id = json["fileId"]
new_attachment.mime = json["mime"]
new_attachment.created_at = json["createdAt"]

return new_attachment
169 changes: 169 additions & 0 deletions src/Bot/nerimity/channel.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,169 @@
from nerimity.message import Message
from nerimity.attachment import Attachment
from nerimity._enums import GlobalClientInformation, ConsoleShortcuts

import requests
import json

class Channel():
"""
Represents a channel in Nerimity.
id: Snowflake ID of the channel
name: Name of the channel.
permissions: Integer that represents the permissions of the channel.
type: Type of the channel
creator_id: ID of the creator of the channel.
server_id: ID of the server the channel is in.
category_id: ID of the category the channel is in.
last_messaged_at: Timestamp from when the last message was send.
created_at: Timestamp from when the channel was created.
order: Priority of the channel in its category.
update_channel(): Updates itself with specified information.
send_message(): Sends a message to the channel.
get_messages(): Gets a list of up to 50 message from the channel.
deserialize(json): static | Deserialize a json string to a Channel object.
"""

def __init__(self) -> None:
self.id : int = None
self.name : str = None
self.permissions : int = None
self.type : int = None
self.creator_id : int = None
self.server_id : int = None
self.category_id : int = None
self.last_messaged_at : float | None = None
self.created_at : float = None
self.order : int | None = None

# Public: Updates itself with specified information.
def update_channel(self, server_id: int, permissions: int=None, name: str=None, icon: str=None, content: str=None) -> None:
"""Updates itself with specified information."""

api_endpoint = f"https://nerimity.com/api/servers/{server_id}/channels/{self.id}"

headers = {
"Authorization": GlobalClientInformation.TOKEN,
"Content-Type": "application/json",
}
data = {
"permissions": permissions,
"name": name,
"icon": icon,
}

if icon == None: del data["icon"]

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

if (content != None):
api_endpoint = f"https://nerimity.com/api/servers/{server_id}/channels/{self.id}/notice"

if content == "":
response = requests.delete(api_endpoint, headers=headers)

if response.status_code != 200:
print(f"{ConsoleShortcuts.error()} Failed to update a channel for {self}. Status code: {response.status_code}. Response Text: {response.text}")
raise requests.RequestException
else:
response = requests.put(api_endpoint, headers=headers, data=json.dumps({"content": content}))

if response.status_code != 200:
print(f"{ConsoleShortcuts.error()} Failed to update a channel for {self}. Status code: {response.status_code}. Response Text: {response.text}")
raise requests.RequestException

# Public: Sends a message to the channel.
def send_message(self, message_content: str, attachments: list[Attachment] | None = None) -> None:
"""Sends a message to the channel."""

api_endpoint = f"https://nerimity.com/api/channels/{self.id}/messages"

headers = {
"Authorization": GlobalClientInformation.TOKEN,
}
data = {
"content": message_content,
}
files = None

if attachments is not None:
for attachment in attachments:
files = {
'attachment': ('Unbenannt.PNG', attachment.data),
}

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

# Private: Gets a raw string of messages.
def _get_messages_raw(self, amount: int) -> str:
if amount > 50:
amount = 50
elif amount < 1:
raise ValueError("Amount of requested messages must be positive.")

api_endpoint = f"https://nerimity.com/api/channels/{self.id}/messages?limit={amount}"

headers = {
"Authorization": GlobalClientInformation.TOKEN,
"Content-Type": "application/json",
}

response = requests.get(api_endpoint, headers=headers)
if response.status_code != 200:
print(f"Failed to get messages from {self}. Status code: {response.status_code}. Response Text: {response.text}")
raise requests.RequestException

return response.text

# Public: Gets a list of up to 50 message from the channel.
def get_messages(self, amount: int) -> list[Message]:
"""Gets a list of up to 50 message from the channel."""

messages_raw = json.loads(self._get_messages_raw(amount))
messages = []
for message_raw in messages_raw:
message = Message.deserialize(message_raw)
messages.append(message)

return messages

# Public: Purge the channel of the specified amount of messages.
def purge(self, amount: int) -> None:
"""Purges the channel of the specified amount of messages."""

if amount > 50: print(f"{ConsoleShortcuts.warn()} Attempted to purge an illegal amount '{amount}' of mesages in {self}."); amount = 50
if amount <= 0: print(f"{ConsoleShortcuts.warn()} Attempted to purge an illegal amount '{amount}' of mesages in {self}."); return

messages = self.get_messages()
messages.reverse()
messages = messages[:amount]
for message in messages:
message.delete()

# Public Static: Deserialize a json string to a Channel object.
@staticmethod
def deserialize(json: dict) -> 'Channel':
"""static | Deserialize a json string to a Channel object."""

new_channel = Channel()
new_channel.id = int(json["id"])
new_channel.name = str(json["name"])
new_channel.permissions = int(json["permissions"]) if json["permissions"] is not None else 0
new_channel.type = int(json["type"])
new_channel.creator_id = int(json["createdById"]) if json["createdById"] is not None else 0
new_channel.server_id = int(json["serverId"]) if json["serverId"] is not None else 0
new_channel.category_id = int(json["categoryId"]) if json["categoryId"] is not None else 0
new_channel.last_messaged_at = float(json["lastMessagedAt"]) if json["lastMessagedAt"] is not None else None
new_channel.created_at = float(json["createdAt"])
new_channel.order = json["order"]

return new_channel
Loading

0 comments on commit 2417983

Please sign in to comment.