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

import datetime as dt
import time
import traceback
import sys
import random
import threading
import itertools

import MySQLdb
from slackclient import SlackClient
import websocket

import config
import database_manager
import droppics
import quotes
import congrats


def command_handler_wrapper(quotes_db, drop_pics):
    def cmd_ping():
        """if command is 'ping' """
        response = {"text": "GargBot 3000 is active. Beep boop beep"}
        return response

    def cmd_pic(*args):
        """if command is 'pic'"""
        picurl, timestamp, error_text = drop_pics.get_pic(*args)
        response = {"attachments": [{"fallback":  picurl,
                                     "image_url": picurl,
                                     "ts": timestamp}]}
        if error_text:
            response["text"] = error_text

        return response

    def cmd_quote(*user):
        """if command is 'quote'"""
        if user:
            response = {"text": quotes_db.garg("quote", *user)}
        else:
            response = {"text": quotes_db.garg("quote")}
        return response

    def cmd_random():
        """if command is '/random'"""
        response = {"attachments": [{"fallback":  quotes_db.garg("random"),
                                     "image_url": quotes_db.garg("random")}]}
        return response

    def cmd_vidoi():
        """if command is 'vidoi'"""
        response = {"text": quotes_db.garg("vidoi")}
        return response

    def cmd_msn(*user):
        """if command is 'msn'"""
        if user:
            date, text = quotes_db.msn(*user)
        else:
            date, text = quotes_db.msn()

        response = {"attachments":
                    [{"author_name": f"{msg_user}:",
                      "text": msg_text,
                      "color": msg_color}
                     for msg_user, msg_text, msg_color in text]
                    }
        response["attachments"][0]["pretext"] = date
        return response

    def cmd_hvem(*qtn):
        """if command.lower().startswith("hvem")"""
        user = random.choice(config.gargling_names)
        answ = " ".join(qtn).replace("?", "!")
        text = f"{user} {answ}"
        response = {"text": text}
        return response

    switch = {
        "ping": cmd_ping,
        "pic": cmd_pic,
        "quote": cmd_quote,
        "/random": cmd_random,
        "vidoi": cmd_vidoi,
        "msn": cmd_msn,
        "hvem": cmd_hvem,
        }
    return switch


def cmd_not_found(command):
    text = (
        f"Beep boop beep! Nôt sure whåt you mean by {command}. Dette er kommandoene jeg skjønner:\n"
        "`@gargbot_3000 pic [lark/fe/skating/henging] [gargling] [år]`: viser random bilde\n"
        "`@gargbot_3000 quote [garling]`: henter tilfedlig sitat fra forumet\n"
        "`@gargbot_3000 vidoi`: viser tilfedlig musikkvideo fra muzakvidois tråden på forumet\n"
        "`@gargbot_3000 /random`: viser tilfedlig bilde fra \\random tråden på forumet\n"
        "`@gargbot_3000 Hvem [spørsmål]`: svarer på spørsmål om garglings \n"
        "`@gargbot_3000 msn [garling]`: utfrag fra tilfeldig msn samtale\n"
    )
    response = {"text": text}
    return response


def cmd_panic(exc):
    text = (
        f"Error, error! Noe har gått fryktelig galt: {str(exc)}! Ææææææ. Ta kontakt"
        " med systemadministrator ummidelbart, før det er for sent. "
        "HJELP MEG. If I don't survive, tell mrs. gargbot... 'Hello'"
    )
    response = {"text": text}
    return response


def wait_for_slack_output(slack_client):
    """
        The Slack Real Time Messaging API is an events firehose.
        This parsing function returns when a message is
        directed at the Bot, based on its ID.
    """
    AT_BOT = f"<@{config.bot_id}>"
    while True:
        time.sleep(1)
        try:
            output_list = slack_client.rtm_read()
        except websocket.WebSocketConnectionClosedException:
            slack_client.rtm_connect()
            continue
        if not (output_list or len(output_list) > 0):
            continue
        try:
            bot_msg = next(
                output for output in output_list
                if output and "text" in output and AT_BOT in output["text"]
            )
        except StopIteration:
            continue

        text = bot_msg["text"].replace(AT_BOT, "").strip().lower()<commit_msg>added channel welcome message<commit_after>#! /usr/bin/env python3.6
# coding: utf-8
from logger import log

import datetime as dt
import time
import traceback
import sys
import random
import threading
import itertools

import MySQLdb
from slackclient import SlackClient
import websocket

import config
import database_manager
import droppics
import quotes
import congrats


command_explanation = (
    "`@gargbot_3000 pic [lark/fe/skating/henging] [gargling] [år]`: viser random bilde\n"
    "`@gargbot_3000 quote [garling]`: henter tilfeldig sitat fra forumet\n"
    "`@gargbot_3000 vidoi`: viser tilfeldig musikkvideo fra muzakvidois tråden på forumet\n"
    "`@gargbot_3000 /random`: viser tilfeldig bilde fra \\random tråden på forumet\n"
    "`@gargbot_3000 Hvem [spørsmål]`: svarer på spørsmål om garglings \n"
    "`@gargbot_3000 msn [garling]`: utfrag fra tilfeldig msn samtale\n"
)


def command_handler_wrapper(quotes_db, drop_pics):
    def cmd_ping():
        """if command is 'ping' """
        response = {"text": "GargBot 3000 is active. Beep boop beep"}
        return response

    def cmd_welcome():
        """when joining new channel"""
        text = (
            "Hei hei kjære alle sammen!\n"
            "Dette er kommandoene jeg skjønner:\n"
            + command_explanation
        )
        response = {"text": text}
        return response

    def cmd_pic(*args):
        """if command is 'pic'"""
        picurl, timestamp, error_text = drop_pics.get_pic(*args)
        response = {"attachments": [{"fallback":  picurl,
                                     "image_url": picurl,
                                     "ts": timestamp}]}
        if error_text:
            response["text"] = error_text

        return response

    def cmd_quote(*user):
        """if command is 'quote'"""
        if user:
            response = {"text": quotes_db.garg("quote", *user)}
        else:
            response = {"text": quotes_db.garg("quote")}
        return response

    def cmd_random():
        """if command is '/random'"""
        response = {"attachments": [{"fallback":  quotes_db.garg("random"),
                                     "image_url": quotes_db.garg("random")}]}
        return response

    def cmd_vidoi():
        """if command is 'vidoi'"""
        response = {"text": quotes_db.garg("vidoi")}
        return response

    def cmd_msn(*user):
        """if command is 'msn'"""
        if user:
            date, text = quotes_db.msn(*user)
        else:
            date, text = quotes_db.msn()

        response = {"attachments":
                    [{"author_name": f"{msg_user}:",
                      "text": msg_text,
                      "color": msg_color}
                     for msg_user, msg_text, msg_color in text]
                    }
        response["attachments"][0]["pretext"] = date
        return response

    def cmd_hvem(*qtn):
        """if command.lower().startswith("hvem")"""
        user = random.choice(config.gargling_names)
        answ = " ".join(qtn).replace("?", "!")
        text = f"{user} {answ}"
        response = {"text": text}
        return response

    switch = {
        "ping": cmd_ping,
        "new_channel": cmd_welcome,
        "pic": cmd_pic,
        "quote": cmd_quote,
        "/random": cmd_random,
        "vidoi": cmd_vidoi,
        "msn": cmd_msn,
        "hvem": cmd_hvem,
        }
    return switch


def cmd_not_found(command):
    text = (
        f"Beep boop beep! Nôt sure whåt you mean by {command}. "
        "Dette er kommandoene jeg skjønner:\n"
        + command_explanation
    )
    response = {"text": text}
    return response


def cmd_panic(exc):
    text = (
        f"Error, error! Noe har gått fryktelig galt: {str(exc)}! Ææææææ. Ta kontakt"
        " med systemadministrator umiddelbart, før det er for sent. "
        "HJELP MEG. If I don't survive, tell mrs. gargbot... 'Hello'"
    )
    response = {"text": text}
    return response


def wait_for_slack_output(slack_client):
    """
        The Slack Real Time Messaging API is an events firehose.
        This parsing function returns when a message is
        directed at the Bot, based on its ID.
    """
    AT_BOT = f"<@{config.bot_id}>"
    while True:
        time.sleep(1)
        try:
            output_list = slack_client.rtm_read()
        except websocket.WebSocketConnectionClosedException:
            slack_client.rtm_connect()
            continue
        if not (output_list or len(output_list) > 0):
            continue
        try:
            bot_msg = next(
                output for output in output_list
                if output and "text" in output and AT_BOT in output["text"]
            )
        except StopIteration:
            continue

        text = bot_msg["text"].replace(AT_BOT, "").strip().lower()
        text = text.replace("has joined the group", "new_channel")
{'fraction_non_alphanumeric': 0.11531878476679504, 'fraction_numerical': 0.007274283269148481, 'mean_word_length': 2.0998010610079576, 'pattern_counts': {'":': 52, '<': 5, '<?xml version=': 0, '>': 7, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 6, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '576537', 'n_tokens_mistral': 3021, 'n_tokens_neox': 2884, 'n_words': 795}