Skip to content

Commit

Permalink
adds logging
Browse files Browse the repository at this point in the history
  • Loading branch information
SonOfLope committed Dec 2, 2023
1 parent 2a9fa09 commit 4521712
Show file tree
Hide file tree
Showing 4 changed files with 71 additions and 37 deletions.
4 changes: 3 additions & 1 deletion events.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,9 @@ def _get_welcome_chan(guild, trema_db):
welcome_chan = guild.get_channel(welcome_chan_id)
return welcome_chan

import logging

logger = logging.getLogger(__name__)

def create_event_reactions(trema_bot, trema_db):
@trema_bot.event
Expand Down Expand Up @@ -55,4 +57,4 @@ async def on_member_remove(member):

@trema_bot.event
async def on_ready():
print(f"{trema_bot.user} fonctionne.")
logger.info('{0.user} fonctionne.'.format(trema_bot))
6 changes: 5 additions & 1 deletion requirements.txt
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
flask>=2.0.0
click>=8.0.0
Werkzeug~=2.2.2
jsonschema==4.7.2
pymongo==4.1.1
pytest~=7.2.0
discord~=2.1.0
pytz~=2023.3
quart~=0.18.4
quart~=0.18.4
urllib3<1.27,>=1.26.6
56 changes: 36 additions & 20 deletions routes/routes.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,37 +2,53 @@
Embed
import re
from quart import request, jsonify
import traceback
import logging

logger = logging.getLogger(__name__)

def create_routes(app, database, trema):
create_routes_webhooks(app, database, trema)

def create_routes_webhooks(app, database, trema):
@app.route('/webhooks/<uuid>', methods=['POST'])
async def handle_webhook(uuid):
channelID = database.get_channel_by_webhook(uuid)
if channelID is None:
return jsonify({'error': 'Invalid webhook UUID'}), 400
logger.info(f"Processing webhook called with UUID: {uuid}")

try:
channelID = database.get_channel_by_webhook(uuid)
if channelID is None:
return jsonify({'error': 'Invalid webhook UUID'}), 400

incoming_data = await request.json
embed_data = incoming_data.get('embeds', [])[0]
incoming_data = await request.json
embed_data = incoming_data.get('embeds', [])[0]

embed = Embed(
title=embed_data.get('title', 'N/A'),
color=int(embed_data.get('color', '0'))
)
embed = Embed(
title=embed_data.get('title', 'N/A'),
color=int(embed_data.get('color', '0'))
)

description = embed_data.get('description', 'N/A')
description = embed_data.get('description', 'N/A')

fields = re.findall(r"\*\*(.+?):\*\* (.+?)(?=\n|$)", description)
for name, value in fields:
embed.add_field(name=name, value=value, inline=False if "Details" in name else True)
fields = re.findall(r"\*\*(.+?):\*\* (.+?)(?=\n|$)", description)
for name, value in fields:
embed.add_field(name=name, value=value, inline=False if "Details" in name else True)

footer_data = embed_data.get('footer', {})
footer_text = footer_data.get('text', '')
if footer_text:
embed.set_footer(text=footer_text)
footer_data = embed_data.get('footer', {})
footer_text = footer_data.get('text', '')
if footer_text:
embed.set_footer(text=footer_text)

channel = trema.get_channel(int(channelID))
await channel.send(embed=embed)
channel = trema.get_channel(int(channelID))
await channel.send(embed=embed)

return jsonify({'status': 'success'}), 200
logger.info(f"Webhook called with UUID: {uuid} - Success")
return jsonify({'status': 'success'}), 200
except Exception as e:
error_info = {
'error': 'Internal Server Error',
'message': str(e),
'trace': traceback.format_exc()
}
logger.error(f"Webhook called with UUID: {uuid} - Error: {error_info}")
return jsonify(error_info), 500
42 changes: 27 additions & 15 deletions trema.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,31 +8,32 @@
from datetime import datetime
from quart import Quart
import asyncio
from events import\
create_event_reactions
from slash_commands import\
create_slash_cmds
from trema_database import\
get_trema_database
from routes import\
create_routes
from events import create_event_reactions
from slash_commands import create_slash_cmds
from trema_database import get_trema_database
from routes import create_routes
import logging

# Set up logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

start_time = datetime.now()

bot_token = os.getenv('DISCORD_TOKEN')
if not bot_token:
print('ERROR: Token var is missing: DISCORD_TOKEN')
logger.error('ERROR: Token var is missing: DISCORD_TOKEN')
sys.exit(-1)

api_address = os.getenv('API_ADDRESS')
if not api_address:
print('ERROR: API address var is missing: API_ADDRESS')
sys.exit(-1)
logger.error('ERROR: API address var is missing: API_ADDRESS')
sys.exit(-1)

api_port = os.getenv('API_PORT')
if not api_port:
print('ERROR: API port var is missing: API_PORT')
sys.exit(-1)
logger.error('ERROR: API port var is missing: API_PORT')
sys.exit(-1)

app = Quart(__name__)

Expand All @@ -49,12 +50,23 @@
async def main():
loop = asyncio.get_event_loop()

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

# Start the bot and the API
bot_coro = loop.create_task(trema.start(bot_token))
api_coro = loop.create_task(app.run_task(host=api_address, port=api_port))

await asyncio.gather(bot_coro, api_coro)

if __name__ == '__main__':
logger.info("Main application starting")
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
try:
loop.run_until_complete(main())
except Exception as e:
logger.error(f"Unhandled exception in main application: {e}")
raise
finally:
logger.info("Main application shutting down")
loop.close()

0 comments on commit 4521712

Please sign in to comment.