1198: Update modhelp.py r=Learath2 a=heinrich5991

Make a couple of things customizable using environment variables.

Co-authored-by: heinrich5991 <heinrich5991@gmail.com>
This commit is contained in:
bors[bot] 2018-07-10 17:08:18 +00:00
commit fed898b1cd

View file

@ -1,16 +1,19 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
from flask import Flask, make_response, request from flask import Flask, make_response, request
import http import http
import os
import re import re
import requests import requests
SERVER=None SERVER=os.getenv('MODHELP_SERVER')
# Generate one by right-clicking on the server icon in the sidebar, clicking on # Generate one by right-clicking on the server icon in the sidebar, clicking on
# "Server Settings" → "Webhooks" → "Create Webhook". You can then select the # "Server Settings" → "Webhooks" → "Create Webhook". You can then select the
# channel in which the messages should appear. Copy the "Webhook URL" to the # channel in which the messages should appear. Copy the "Webhook URL" to the
# following config variable: # following config variable:
# DISCORD_WEBHOOK="https://discordapp.com/api/webhooks/.../..." # 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__) app = Flask(__name__)
@ -20,6 +23,9 @@ def sanitize(s):
def no_content(): def no_content():
return make_response("", http.HTTPStatus.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']) @app.route("/modhelp", methods=['POST'])
def modhelp(): def modhelp():
json = request.get_json() json = request.get_json()
@ -32,11 +38,13 @@ def modhelp():
user = "{port}".format(**json) user = "{port}".format(**json)
else: else:
user = "{server}:{port}".format(**json) 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: if DISCORD_WEBHOOK:
try: 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: except requests.HTTPError as e:
print(repr(e)) print(repr(e))
raise raise