Skip to content

Commit

Permalink
APIClient, wrapper around httpx client requests
Browse files Browse the repository at this point in the history
  • Loading branch information
Xithrius committed Jul 16, 2023
1 parent 612f9fa commit b19d7fa
Show file tree
Hide file tree
Showing 4 changed files with 54 additions and 53 deletions.
28 changes: 28 additions & 0 deletions xythrion/api.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
from httpx import Response, AsyncClient

class APIClient:
def __init__(self, base_url: str) -> None:
self.http_client = AsyncClient()
self.base_url = base_url

async def close(self) -> None:
await self.http_client.aclose()

def full_url(self, partial_endpoint: str) -> str:
return f"{self.base_url}/{partial_endpoint}"

async def request(self, method: str, partial_endpoint: str, **kwargs) -> dict:
r: Response = await self.http_client.request(method.upper(), self.full_url(partial_endpoint), **kwargs)

r.raise_for_status()

return r.json()

async def get(self, partial_endpoint: str, **kwargs) -> dict:
return await self.request("GET", partial_endpoint, **kwargs)

async def post(self, partial_endpoint: str, **kwargs) -> dict:
return await self.request("POST", partial_endpoint, **kwargs)

async def delete(self, partial_endpoint: str, **kwargs) -> dict:
return await self.request("DELETE", partial_endpoint, **kwargs)
21 changes: 6 additions & 15 deletions xythrion/bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,29 +3,18 @@
import traceback
from datetime import timedelta, timezone

import httpx
from discord import AllowedMentions, Embed, Intents, Interaction, Message, app_commands
from discord.ext.commands import (
Bot,
CommandError,
)
from discord.ext.commands import Bot, CommandError
from dotenv import load_dotenv
from loguru import logger as log

from xythrion.api import APIClient
from xythrion.context import Context
from xythrion.extensions import EXTENSIONS

load_dotenv()


POSTGRES_CREDENTIALS = {
"user": "xythrion",
"password": "xythrion",
"database": "xythrion",
"port": 7777,
}


class Xythrion(Bot):
"""A subclass where important tasks and connections are created."""

Expand Down Expand Up @@ -66,7 +55,9 @@ async def on_command_error(

async def setup_hook(self) -> None:
"""Things to setup before the bot logs on."""
self.http_client = httpx.AsyncClient()
api_url = os.getenv("API_URL", "http://localhost:8000")

self.api = APIClient(api_url)

for extension in EXTENSIONS:
await self.load_extension(extension)
Expand All @@ -84,7 +75,7 @@ async def start(self) -> None:

async def close(self) -> None:
"""Things to run before the bot logs off."""
await self.http_client.aclose()
await self.api.close()

await super().close()

Expand Down
4 changes: 2 additions & 2 deletions xythrion/extensions/info/ping.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,6 @@ async def ping(self, ctx: Context) -> None:
@ping.command()
async def api(self, ctx: Context) -> None:
"""Is *that* thing on?"""
r = await self.bot.http_client.get("http://localhost:8000/ping/")
j = await self.bot.api.get("ping/")

await ctx.send(r.json())
await ctx.send(j)
54 changes: 18 additions & 36 deletions xythrion/extensions/mapping/link_map.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@

from discord import Message
from discord.ext.commands import Cog, group, is_owner
from httpx import Response

from xythrion.bot import Xythrion
from xythrion.context import Context
Expand All @@ -14,6 +13,20 @@ class LinkMapper(Cog):
def __init__(self, bot: Xythrion):
self.bot = bot

@Cog.listener()
async def on_message(self, message: Message) -> None:
data = {"sid": message.guild.id, "uid": message.author.id}

rows = await self.bot.api.get("link_map/", params=data)

for row in rows:
if row["from_match"] in message.content:
res = message.content.replace(row["from_match"], row["to_match"])

await message.reply(res)

break

@group(aliases=("linkmap",))
@is_owner()
async def link_map(self, ctx: Context) -> None:
Expand All @@ -33,8 +46,8 @@ async def create_link_map(
"to_match": to_match,
}

await self.bot.http_client.post(
"http://localhost:8000/link_map/",
await self.bot.api.post(
"link_map/",
data=json.dumps(data, default=str),
)

Expand All @@ -43,40 +56,9 @@ async def create_link_map(
async def get_user_link_maps(self, ctx: Context) -> None:
data = {"sid": ctx.guild.id, "uid": ctx.author.id}

r: Response = await self.bot.http_client.get(
"http://localhost:8000/link_map/", params=data
)

await ctx.send(r.json())

@Cog.listener()
async def on_message(self, message: Message) -> None:
data = {"sid": message.guild.id, "uid": message.author.id}

r: Response = await self.bot.http_client.get(
"http://localhost:8000/link_map/", params=data
)

rows = r.json()

for row in rows:
if row["from_match"] in message.content:
res = message.content.replace(row["from_match"], row["to_match"])

await message.reply(res)
j = await self.bot.api.get("link_map/", params=data)

break

# @group()
# async def link_remap(self, ctx: Context) -> None:
# if ctx.invoked_subcommand is None:
# await ctx.send("Missing subcommand")

# @link_remap.group()
# @is_owner()
# async def force(self, ctx: Context, from_match: str, to_match: str) -> None:
# if ctx.invoked_subcommand is None:
# await ctx.send("Missing sub-subcommand")
await ctx.send(j)

# @force.command(aliases=("add",))
# @is_owner()
Expand Down

0 comments on commit b19d7fa

Please sign in to comment.