Skip to content

Commit

Permalink
feat: added embed, colours and file classes. Moved interaction reques…
Browse files Browse the repository at this point in the history
…ts to goldy interaction method. #113
  • Loading branch information
THEGOLDENPRO committed Jan 13, 2024
1 parent 939e6c1 commit 9685b41
Show file tree
Hide file tree
Showing 13 changed files with 413 additions and 59 deletions.
3 changes: 3 additions & 0 deletions goldy_bot/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,5 +14,8 @@
from .objects import *
from .errors import *
from .intents import *
from .colours import *
from .helpers import *
from .files import *

__version__ = "5.1dev1"
42 changes: 42 additions & 0 deletions goldy_bot/colours.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
from __future__ import annotations
from typing import TYPE_CHECKING

if TYPE_CHECKING:
from GoldyBot import File

from enum import Enum
from colorthief import ColorThief

class Colours(Enum):
"""Colours enum class for 🥞 pancake ported over from legacy api."""
AKI_PINK = 0xFF1493
AKI_ORANGE = 0xF4900C
AKI_RED = 0xff0051
AKI_BLUE = 0X75E6DA
BLUE = 0x3061f2
GREEN = 0x00FF00
LIME_GREEN = 0x8AFF65
YELLOW = 0xffff4d
PURPLE = 0xFF00FF
RED = 0xFF0000
BROWN = 0xFFBA6D
GREY = 0x3B3B3B
WHITE = 0xFFFFFF
BLACK = 0x000000

INVISIBLE = 0x2B2D31
"""Makes the embed colour the same as the background essentially giving the embed colour a transparent look."""

def __init__(self, colour: int):
...

@classmethod
def from_rgb(cls, r: int, g:int, b:int) -> int:
"""Converts rgb values into colour."""
return (r << 16) + (g << 8) + b

@classmethod
def from_image(cls, file: File, accuracy: int = 5) -> int:
"""Returns the dominant colour in that image."""
r, g, b = ColorThief(file.file_io).get_color(accuracy)
return cls.from_rgb(r, g, b)
2 changes: 1 addition & 1 deletion goldy_bot/commands/command.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
from devgoldyutils import LoggerAdapter

from .types import CommandType
from ..helper import DictHelper
from ..helpers.helper import DictHelper
from ..errors import GoldyBotError
from ..logger import goldy_bot_logger

Expand Down
2 changes: 1 addition & 1 deletion goldy_bot/commands/slash_option.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@

from GoldyBot import utils

from ..helper import DictHelper
from ..helpers.helper import DictHelper

__all__ = (
"SlashOptionTypes",
Expand Down
53 changes: 53 additions & 0 deletions goldy_bot/files.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
from __future__ import annotations
from typing import TYPE_CHECKING

if TYPE_CHECKING:
from typing import Optional, BinaryIO
from typing_extensions import Self

import os
import io
from requests import Response
from .errors import GoldyBotError

__all__ = (
"File",
)

class File():
"""
Goldy bot's basic file object for 🥞 pancake.
"""
def __init__(self, file: BinaryIO, file_name: Optional[str] = None) -> None:
self.file = file

try:
self.name = file_name or os.path.split(file.name)[1]
except AttributeError as e:
raise GoldyBotError(
f"This file object does not have the .name attribute, 'file_name' must be specified! Error >> {e}"
)

self.attachment_url = f"attachment://{file_name}"
"""Returns the attachment url string. Useful when attaching images to Embeds."""

@classmethod
def from_response(cls, response: Response) -> Self:
content_type = response.headers.get("Content-Type")

if content_type is None:
raise GoldyBotError("'response' does not have 'Content-Type' header!")

return cls(
file = io.BytesIO(response.content),
file_name = f"image.{content_type.split('/')[1]}"
)

@property
def contents(self) -> bytes:
"""Returns the contents of this file. Useful for uploading."""
return self.file.read()

def close(self) -> None:
"""Closes the mf."""
self.file.close()
2 changes: 1 addition & 1 deletion goldy_bot/goldy/goldy.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ async def start(self) -> None:

# Log when shards are ready.
self.shard_manager.event_dispatcher.add_listener(
lambda x: self.logger.info(
lambda _: self.logger.info(
f"Nextcore shards are {Colours.GREEN.apply('connected')} and {Colours.BLUE.apply('READY!')}"
),
event_name = "READY"
Expand Down
81 changes: 79 additions & 2 deletions goldy_bot/goldy/wrappers/discord/interaction.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,22 @@
from typing import TYPE_CHECKING

if TYPE_CHECKING:
from typing import List, Optional
from typing import List, Optional, Dict
from typing_extensions import Self

from discord_typings import (
InteractionMessageCallbackData,
ApplicationCommandPayload,
ApplicationCommandData,
MessageData
)

from ....files import File
from ....typings import GoldySelfT

from aiohttp import FormData
from nextcore.http import Route
from nextcore.common import json_dumps

__all__ = (
"Interaction",
Expand Down Expand Up @@ -137,4 +141,77 @@ async def get_interaction_message(self: GoldySelfT[Self], interaction_token: str
)

data = await r.json()
return data
return data

async def send_interaction_callback(
self: GoldySelfT[Self],
interaction_id: str,
interaction_token: str,
payload: InteractionMessageCallbackData,
files: Optional[List[File]] = None
) -> None:
form_data = FormData()

if files is not None:

for file in files:
form_data.add_field(**self.__file_to_form_field(file))

form_data.add_field(
"payload_json", json_dumps(
{
"type": 4,
"data": payload
}
)
)

await self.client.request(
Route(
"POST",
"/interactions/{interaction_id}/{interaction_token}/callback",
interaction_id = interaction_id,
interaction_token = interaction_token
),
rate_limit_key = self.key_and_headers["rate_limit_key"],
data = form_data
)

async def send_interaction_follow_up(
self: GoldySelfT[Self],
interaction_token: str,
payload: InteractionMessageCallbackData,
files: Optional[List[File]] = None
) -> MessageData:
form_data = FormData()
app_data = await self.get_application_data()

if files is not None:

for file in files:
form_data.add_field(**self.__file_to_form_field(file))

form_data.add_field(
"payload_json", json_dumps(payload)
)

r = await self.client.request(
Route(
"POST",
"/webhooks/{application_id}/{interaction_token}",
application_id = app_data["id"],
interaction_token = interaction_token
),
rate_limit_key = self.key_and_headers["rate_limit_key"],
data = form_data
)

message_data = await r.json()
return message_data

def __file_to_form_field(self, file: File) -> Dict[str, str]:
return {
"name": file.name.split(".")[-2],
"value": file.contents,
"filename": file.name
}
1 change: 1 addition & 0 deletions goldy_bot/helpers/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
from .embed import *
Loading

0 comments on commit 9685b41

Please sign in to comment.