Created
March 2, 2017 18:15
-
-
Save gyli/4be3345828d2e4ecac10adbb674b8af4 to your computer and use it in GitHub Desktop.
Format JSON with Slack slash command and Flask
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python | |
# -*-coding: utf-8 -*- | |
# This is a Flask app that accepts raw JSON from Slack with /json command and returns indented JSON | |
from flask import Flask, request, jsonify, abort | |
import json | |
import demjson | |
import requests | |
app = Flask(__name__) | |
config = json.loads(open('config.json').read()) | |
def format_json(text, decoder): | |
return json.dumps(decoder(text), indent=4, ensure_ascii=False) | |
def pre_json(text): | |
return '```{0}```'.format(text) | |
@app.route('/', methods=['POST']) | |
def slash_command(): | |
# Parse the parameters | |
token = request.form.get('token', None) | |
command = request.form.get('command', None) | |
raw_text = request.form.get('text', None) | |
response_url = request.form.get('response_url', None) | |
# Validate token | |
if not token or token != config['slash_token']: | |
abort(400) | |
if command == '/json': | |
attachments = [] | |
try: | |
text = pre_json(format_json(raw_text, json.loads)) | |
except Exception: | |
try: | |
text = pre_json(format_json(raw_text, demjson.decode)) | |
error_text = 'Unrestricted Mode' | |
# Use demjson to print friendly error | |
except Exception as demjson_error: | |
text = pre_json(raw_text) | |
error_text = demjson_error.message | |
attachments = [{"text": "", "footer": error_text}] | |
# Post message with another request | |
requests.post(response_url, | |
json={ | |
"response_type": "in_channel", | |
"text": text, | |
"attachments": attachments, | |
}) | |
# Return empty string to original slash command to hide the original message | |
return "" | |
if __name__ == '__main__': | |
app.run() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment