From fe1c54c11e612d0c3037952c947e944b24034bbd Mon Sep 17 00:00:00 2001 From: heinrich5991 Date: Tue, 10 Jul 2018 18:59:40 +0200 Subject: [PATCH] Update modhelp.py Make a couple of things customizable using environment variables. --- src/modhelp/server.py | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/src/modhelp/server.py b/src/modhelp/server.py index 311853c26..88b534fb5 100755 --- a/src/modhelp/server.py +++ b/src/modhelp/server.py @@ -1,16 +1,19 @@ #!/usr/bin/env python3 from flask import Flask, make_response, request import http +import os import re import requests -SERVER=None +SERVER=os.getenv('MODHELP_SERVER') # Generate one by right-clicking on the server icon in the sidebar, clicking on # "Server Settings" → "Webhooks" → "Create Webhook". You can then select the # channel in which the messages should appear. Copy the "Webhook URL" to the # following config variable: # DISCORD_WEBHOOK="https://discordapp.com/api/webhooks/.../..." -DISCORD_WEBHOOK=None +DISCORD_WEBHOOK=os.getenv('MODHELP_DISCORD_WEBHOOK') +DISCORD_MESSAGE=os.getenv('MODHELP_DISCORD_FORMAT', "<{player_id}:**{player_name}**> {message}") +DISCORD_MESSAGE_PREFIX=os.getenv('MODHELP_DISCORD_PREFIX') app = Flask(__name__) @@ -20,6 +23,9 @@ def sanitize(s): def no_content(): return make_response("", http.HTTPStatus.NO_CONTENT) +def sanitize_string_values(dictionary): + return {k: v if not isinstance(v, str) else sanitize(v) for k, v in dictionary.items()} + @app.route("/modhelp", methods=['POST']) def modhelp(): json = request.get_json() @@ -32,11 +38,13 @@ def modhelp(): user = "{port}".format(**json) else: user = "{server}:{port}".format(**json) - message = "<{player_id}:{player_name}> {message}".format(**json) + + discord_prefix = DISCORD_MESSAGE_PREFIX + " " if DISCORD_MESSAGE_PREFIX is not None else "" + discord_message = discord_prefix + DISCORD_MESSAGE.format(**sanitize_string_values(json)) if DISCORD_WEBHOOK: try: - requests.post(DISCORD_WEBHOOK, data={"username": user, "content": sanitize(message)}).raise_for_status() + requests.post(DISCORD_WEBHOOK, data={"username": user, "content": discord_message}).raise_for_status() except requests.HTTPError as e: print(repr(e)) raise