Skip to content

Commit

Permalink
Fix webhook endpoint + hypercorn
Browse files Browse the repository at this point in the history
  • Loading branch information
SonOfLope committed Oct 2, 2024
1 parent 9adbc3b commit c2ce49b
Show file tree
Hide file tree
Showing 6 changed files with 142 additions and 15 deletions.
3 changes: 1 addition & 2 deletions cogs/webhooks/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,9 @@ async def create_webhook(ctx,
guild_id = ctx.guild_id
unique_url = generate_unique_webhook_url()

# Save the unique URL and associated channel to your database
trema_db.create_webhook(webhook_name, channel_id, unique_url, guild_id)

embed=Embed(title="Webhook créé", description=f"Le webhook '{webhook_name}' a été créé avec succès.\n```webhook url endpoint : {unique_url}```", color=Color.blurple())
embed=Embed(title="Webhook créé", description=f"Le webhook '{webhook_name}' a été créé avec succès.\nwebhook uuid : ```{unique_url}```", color=Color.blurple())
await ctx.respond(embed=embed, ephemeral=True)

@webhook.command(name="list",
Expand Down
20 changes: 20 additions & 0 deletions docs/apiShell.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
How to test webhooks:
Run the docker-compose file first.
Then, create a webhook with the bot using the command /webhook create.
Copy the webhook id.
Then, do the following commands on your terminal :

curl -X POST http://localhost:6000/webhooks/webhook-id\
-H "Content-Type: application/json" \
-d '{
"embeds": [
{
"title": "Your Title Here",
"description": "Your Description Here",
"color": "16745728",
"footer": {
"text": "Footer Text"
}
}
]
}'
18 changes: 13 additions & 5 deletions main.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,14 @@
from datetime import datetime
from quart import Quart
import asyncio
import hypercorn.asyncio
from hypercorn.config import Config
from cogs.events import create_event_reactions
from cogs import create_slash_cmds
from db.database import get_trema_database
from routes import create_routes
from logger import logger
from prometheus_client import start_http_server, Counter, Summary
from prometheus_client import start_http_server

start_time = datetime.now()

Expand Down Expand Up @@ -49,21 +51,27 @@

start_http_server(8000)

async def run_quart_app(app, host, port):
config = Config()
config.bind = [f"{host}:{port}"]
await hypercorn.asyncio.serve(app, config)

async def main():
loop = asyncio.get_event_loop()

logger.info("Starting the bot and API")

bot_coro = loop.create_task(trema.start(bot_token))
api_coro = loop.create_task(app.run_task(host=api_address, port=api_port))
bot_coro = asyncio.create_task(trema.start(bot_token))
api_coro = asyncio.create_task(run_quart_app(app, api_address, api_port))

await asyncio.gather(bot_coro, api_coro)

if __name__ == '__main__':
logger.info("Main application starting")
loop = asyncio.get_event_loop()
try:
loop.run_until_complete(main())
asyncio.ensure_future(main())

loop.run_forever()
except Exception as e:
logger.error(f"Unhandled exception in main application: {e}")
raise
Expand Down
101 changes: 101 additions & 0 deletions monitoring/grafana/dashboard.json
Original file line number Diff line number Diff line change
Expand Up @@ -330,6 +330,107 @@
"title": "Requête reçu par Calidum-Rotae",
"transparent": true,
"type": "timeseries"
},
{
"datasource": {
"default": true,
"type": "prometheus",
"uid": "adyj475ll2xoga"
},
"fieldConfig": {
"defaults": {
"color": {
"mode": "palette-classic"
},
"custom": {
"axisBorderShow": false,
"axisCenteredZero": false,
"axisColorMode": "text",
"axisLabel": "",
"axisPlacement": "auto",
"barAlignment": 0,
"barWidthFactor": 0.6,
"drawStyle": "line",
"fillOpacity": 0,
"gradientMode": "none",
"hideFrom": {
"legend": false,
"tooltip": false,
"viz": false
},
"insertNulls": false,
"lineInterpolation": "linear",
"lineWidth": 1,
"pointSize": 5,
"scaleDistribution": {
"type": "linear"
},
"showPoints": "auto",
"spanNulls": false,
"stacking": {
"group": "A",
"mode": "none"
},
"thresholdsStyle": {
"mode": "off"
}
},
"mappings": [],
"thresholds": {
"mode": "absolute",
"steps": [
{
"color": "green",
"value": null
},
{
"color": "red",
"value": 80
}
]
}
},
"overrides": []
},
"gridPos": {
"h": 8,
"w": 12,
"x": 12,
"y": 8
},
"id": 4,
"options": {
"legend": {
"calcs": [],
"displayMode": "list",
"placement": "bottom",
"showLegend": true
},
"tooltip": {
"mode": "single",
"sort": "none"
}
},
"targets": [
{
"datasource": {
"type": "prometheus",
"uid": "adyj475ll2xoga"
},
"disableTextWrap": false,
"editorMode": "builder",
"expr": "trema_http_errors_total",
"fullMetaSearch": false,
"includeNullMetadata": true,
"instant": false,
"legendFormat": "__auto",
"range": true,
"refId": "A",
"useBackend": false
}
],
"title": "POST /webhooks errors",
"type": "timeseries"
}
],
"refresh": "",
Expand Down
3 changes: 2 additions & 1 deletion requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,5 @@ urllib3<1.27,>=1.26.6
requests==2.31.0
pytz~=2023.3
prometheus_client~=0.13.1
aiohttp~=3.10.5
aiohttp~=3.10.5
hypercorn~=0.17.3
12 changes: 5 additions & 7 deletions routes/routes.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,10 @@
from quart import request, jsonify
from prometheus_client import Counter, Summary
import traceback
import logging
from logger import logger
import re
from discord import Embed

logger = logging.getLogger(__name__)

REQUEST_COUNT = Counter('trema_http_requests_total', 'Total HTTP Requests')
REQUEST_LATENCY = Summary('trema_http_request_latency_seconds', 'Latency of HTTP requests')
ERROR_COUNT = Counter('trema_http_errors_total', 'Total HTTP Errors')
Expand All @@ -16,12 +14,11 @@ def create_routes(app, database, trema):

@app.before_request
@REQUEST_LATENCY.time()
async def before_request():
REQUEST_COUNT.inc()
logger.info(f"Handling request: {request.path}")
def before_request():
REQUEST_COUNT.inc()

@app.after_request
async def after_request(response):
def after_request(response):
if response.status_code >= 400:
ERROR_COUNT.inc()
return response
Expand All @@ -34,6 +31,7 @@ async def handle_webhook(uuid):
try:
channelID = database.get_channel_by_webhook(uuid)
if channelID is None:
logger.error(f"Webhook called with UUID: {uuid} - Invalid UUID")
return jsonify({'error': 'Invalid webhook UUID'}), 400

incoming_data = await request.json
Expand Down

0 comments on commit c2ce49b

Please sign in to comment.