<commit_before>#! /usr/bin/env python3.6
# coding: utf-8
from gargbot_3000.logger import log
import json
from copy import deepcopy

from flask import Flask, request, g, Response

from gargbot_3000 import config
from gargbot_3000 import commands
from gargbot_3000 import database_manager
from gargbot_3000 import quotes
from gargbot_3000 import droppics

app = Flask(__name__)


def get_db():
    db_connection = getattr(g, '_database', None)
    if db_connection is None:
        db_connection = database_manager.connect_to_database()
        g._database = db_connection
    return db_connection


@app.teardown_appcontext
def close_connection(exception):
    db_connection = getattr(g, '_database', None)
    if db_connection is not None:
        db_connection.close()


def attach_buttons(callback_id, result, func, args):
    actions = [
            {
                "name": "Send",
                "text": "send",
                "type": "button",
                "style": "primary",
                "value": json.dumps({"original_func": func, "original_args": args})
            },
            {
                "name": "Shuffle",
                "text": "shuffle",
                "type": "button",
                "value": json.dumps({"original_response": result})
            },
            {
                "name": "Avbryt",
                "text": "avbryt",
                "value": "avbryt",
                "type": "button",
                "style": "danger"
            },
    ]
    result["attachments"][0]["actions"] = actions
    result["attachments"][0]["callback_id"] = callback_id


@app.route('/')
def hello_world() -> str:
    return "home"


@app.route('/interactive', methods=['POST'])
def interactive():
    log.info("incoming interactive request:")
    data = request.form
    log.info(data)
    if not data.get('token') == config.v2_verification_token:
        return Response(status=403)
    callback_id = data["callback_id"]
    action = data["actions"][0]["name"]
    log.info(f"prev_request_data: {prev_request_data}")

    if action == "Send":
        result = json.loads(data["actions"][0]["value"]["original_response"])
        result["response_type"] = "in_channel"
        del result["attachments"]["actions"]
        return Response(
            response=json.dumps(result),
            status=200,
            mimetype='application/json'
        )
    elif action == "Avbryt":
        #  Unfinished
        result = {
            "response_type": "ephemeral",
            "replace_original": True,
            "text": "Canceled!"
        }
        return Response(
            status=200,
            response=json.dumps(result),
            mimetype='application/json'
        )
    elif action == "Shuffle":
        command_str = json.loads(data["actions"][0]["value"]["original_func"])
        args = json.loads(data["actions"][0]["value"]["original_args"])

        # duplicate code follows
        try:
            command_function = commands.command_switch[command_str]
        except KeyError:
            command_function = commands.cmd_not_found
            args = [command_str]

        if command_str in {"msn", "quote", "pic"}:
            db_connection = get_db()
            command_function.keywords["db"] = db_connection

        result = commands.try_or_panic(command_function, args)
        if not result.get("text", "").startswith("Error"):
            attach_buttons(
                callback_id=callback_id,
                result=result,
                func=command_str,
                args=args
            )
            result["response_type"] = "ephemeral"
        log.info(f"result: {result}")
        return Response(
            response=json.dumps(result),
            status=200,
            mimetype='application/json'
        )
<commit_msg>add more logging to interactive requests<commit_after>#! /usr/bin/env python3.6
# coding: utf-8
from gargbot_3000.logger import log
import json
from copy import deepcopy

from flask import Flask, request, g, Response

from gargbot_3000 import config
from gargbot_3000 import commands
from gargbot_3000 import database_manager
from gargbot_3000 import quotes
from gargbot_3000 import droppics

app = Flask(__name__)


def get_db():
    db_connection = getattr(g, '_database', None)
    if db_connection is None:
        db_connection = database_manager.connect_to_database()
        g._database = db_connection
    return db_connection


@app.teardown_appcontext
def close_connection(exception):
    db_connection = getattr(g, '_database', None)
    if db_connection is not None:
        db_connection.close()


def attach_buttons(callback_id, result, func, args):
    actions = [
            {
                "name": "Send",
                "text": "send",
                "type": "button",
                "style": "primary",
                "value": json.dumps({"original_func": func, "original_args": args})
            },
            {
                "name": "Shuffle",
                "text": "shuffle",
                "type": "button",
                "value": json.dumps({"original_response": result})
            },
            {
                "name": "Avbryt",
                "text": "avbryt",
                "value": "avbryt",
                "type": "button",
                "style": "danger"
            },
    ]
    result["attachments"][0]["actions"] = actions
    result["attachments"][0]["callback_id"] = callback_id


@app.route('/')
def hello_world() -> str:
    return "home"


@app.route('/interactive', methods=['POST'])
def interactive():
    log.info("incoming interactive request:")
    data = request.form
    log.info(data)
    if not data.get('token') == config.v2_verification_token:
        return Response(status=403)
    callback_id = data["callback_id"]
    action = data["actions"][0]["name"]
    log.info(f"prev_request_data: {prev_request_data}")

    if action == "Send":
        log.info("Interactive: Send")
        result = json.loads(data["actions"][0]["value"]["original_response"])
        result["response_type"] = "in_channel"
        del result["attachments"]["actions"]
        return Response(
            response=json.dumps(result),
            status=200,
            mimetype='application/json'
        )
    elif action == "Avbryt":
        log.info("Interactive: Avbryt")
        #  Unfinished
        result = {
            "response_type": "ephemeral",
            "replace_original": True,
            "text": "Canceled!"
        }
        return Response(
            status=200,
            response=json.dumps(result),
            mimetype='application/json'
        )
    elif action == "Shuffle":
        log.info("Interactive: Shuffle")
        command_str = json.loads(data["actions"][0]["value"]["original_func"])
        args = json.loads(data["actions"][0]["value"]["original_args"])

        # duplicate code follows
        log.info(f"command: {command_str}")
        log.info(f"args: {args}")

        try:
            command_function = commands.command_switch[command_str]
        except KeyError:
            command_function = commands.cmd_not_found
            args = [command_str]

        if command_str in {"msn", "quote", "pic"}:
            db_connection = get_db()
            command_function.keywords["db"] = db_connection

        result = commands.try_or_panic(command_function, args)
        if not result.get("text", "").startswith("Error"):
            attach_buttons(
                callback_id=callback_id,
                result=result,
                func=command_str,
                args=args
            )
            result["response_type"] = "ephemeral"
        log.info(f"result: {result}")
        return Response(
            response=json.dumps(result),
            status=200,
            mimetype='application/json'
        )

{'fraction_non_alphanumeric': 0.12762705387848683, 'fraction_numerical': 0.011718252451916954, 'mean_word_length': 2.176375404530744, 'pattern_counts': {'":': 46, '<': 3, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '476069', 'n_tokens_mistral': 2336, 'n_tokens_neox': 2244, 'n_words': 461}