コード例 #1
0
def set_language():
    global USER_LANGUAGE_MAPPINGS

    payload = json.loads(request.form.get('payload'))
    channel_id = payload.get('channel').get('id')
    selected_language_iso_code = payload.get('actions')[0].get(
        'selected_options')[0].get('value')
    user_id = payload.get('user').get('id')
    user_name = get_name_from_user_id(user_id)
    selected_language_text = get_language_from_iso_code(
        selected_language_iso_code)

    if not channel_id in USER_LANGUAGE_MAPPINGS:
        USER_LANGUAGE_MAPPINGS[channel_id] = {}
    USER_LANGUAGE_MAPPINGS[channel_id].update(
        {user_id: selected_language_iso_code})
    with open(f'{Path(__file__).parent}/user_language_mapping.json',
              'w') as fp:
        json.dump(USER_LANGUAGE_MAPPINGS, fp, sort_keys=True, indent=4)

    logger.info(
        f"{user_name}'s language changed to {selected_language_text} in channel {channel_id}"
    )

    selection_success = {
        "text":
        f"Thank You *{user_name}.* Your language has been set to *{selected_language_text}.* Please use */change_language* to change it again."
    }

    return jsonify(selection_success)
コード例 #2
0
def insert_malicious_record(json_record):
    try:
        json_record = json_util.loads(json_record)
        db[MONGO_COLLECTION].insert_one(json_record)
        logger.info("Inserted record into Mongo")
        return True
    except Exception as e:
        logger.error("Error inserting record into mongo: {}".format(str(e)))
        return False
コード例 #3
0
def get_audio_file(url, user_id):
    r = requests.get(
        url, headers={'Authorization': 'Bearer %s' % SLACK_BOT_ACCESS_TOKEN})
    logger.info(f"Input Url is {url}")
    AUDIO_FILE_DIR.mkdir(parents=True, exist_ok=True)
    file_name = f"{AUDIO_FILE_DIR}/{user_id}-{(datetime.utcnow().strftime(r'%Y-%m-%d-%H_%M_%S'))}.mp3"
    # file_name = f'{Path(__file__).absolute().parent.parent}/app/input/audio_files/' + user_id + (datetime.utcnow().strftime('%Y-%m-%d-%H_%M_%S')) + '.mp3'
    # file_name=f'{user_id}-{(datetime.utcnow().strftime("%Y-%m-%d-%H_%M_%S"))}.mp3'
    file_data = r.content
    with open(file_name, 'w+b') as f:
        f.write(bytearray(file_data))
        logger.info("Saved " + file_name)
    return file_name
コード例 #4
0
ファイル: chat.py プロジェクト: odty101/PyCryptoChat
    def send_message(self, message):

        # Update the Chat log and send the message if it contains any info
        if message:
            self.update_chat(message, self.manager.user)
        else:
            logger.info('Blank Message')

        # Clear the last sent message
        self.ids['message'].text = ''

        # Refocus to the message box
        self.ids['message'].focus = True
コード例 #5
0
ファイル: chat.py プロジェクト: odty101/PyCryptoChat
    def update_chat(self, message, user):
        # Get current Chat and Time
        current_chat = self.ids['chat_logs'].text
        current_time = strftime(settings.time_format)

        # Create the new chat line
        new_line = settings.chat_line.format(time=current_time,
                                             user=user,
                                             message=message)
        logger.info('Chat Line added: {}'.format(new_line))

        # Add the new line to chat
        new_chat = current_chat + '\n' + new_line
        self.ids['chat_logs'].text = new_chat
コード例 #6
0
def message(payload):
    global USER_LANGUAGE_MAPPINGS
    logger.debug("A message was posted in the channel")

    # Get the event data from the payload
    event = payload.get("event", {})
    logger.debug(
        f"Message event received at {datetime.utcnow().strftime(r'%Y-%m-%dT%H:%M:%S')}"
    )
    logger.debug(event)
    # Handle edited messages
    if "subtype" in event and event.get("subtype", '') == 'message_changed':
        logger.debug("It is an edited message")
        # If the message was edited by bot. Return
        if event.get("message", {}).get("subtype", '') == 'bot_message':
            logger.debug("The message was edited by the bot! Doing nothing")
            return
        else:
            text = event.get("message", {}).get("text")
            user_id = event.get("message", {}).get("user")

    elif event.get("subtype", '') == 'bot_add':
        logger.debug("Bot was added to the channel")
        return

    else:
        text = event.get("text")
        user_id = event.get("user")

    channel_id = event.get("channel")
    if user_id == "U01AUR3FS2V" or text == 'Please choose your preferred language':
        logger.info("Beep Bop. I am a bot. Doing nothing")
        return
    x = threading.Thread(target=process_message,
                         args=(event, user_id, channel_id, text),
                         daemon=True)
    x.start()
    return
コード例 #7
0
def translate_message_api():
    start_time = time.time()
    data = request.get_json()
    logger.debug(f"Message received via the API: {data}")
    # text = json.loads(request.form.get('text'))
    # target_language = json.loads(request.form.get('target'))
    text = data['text']
    target_language = data['target']
    if text:
        text = text.replace("'", "\\'")
    source_language = translate_api.detect_language(GOOGLE_TRANSLATE_API_KEY,
                                                    text)
    logger.info(
        f"Detected language of the message is {get_language_from_iso_code(source_language)}"
    )
    translated_text = get_translated_message(text, source_language,
                                             target_language)
    end_time = time.time()
    logger.info(
        f"Time taken to translate the message received via API: {end_time - start_time} seconds"
    )
    logger.info(f"Translated message is {translated_text}")
    return translated_text
コード例 #8
0
import requests, csv, json, mongo_handler
from config import RANSOMWARE_TRACKER_URL
from app_logger import logger
from sys import exit
from time import sleep
import watchguard_handler

abuse_csv_response = requests.get(RANSOMWARE_TRACKER_URL)

if abuse_csv_response.status_code != 200:
    logger.error("Ransomware call returned a status code of {}".format(str(abuse_csv_response.status_code)))
    exit(1)
else:
    logger.info("Successfully retrieved Ransomware CSV")


# Firstseen (UTC),Threat,Malware,Host,URL,Status,Registrar,IP address(es),ASN(s),Country
ransom_csv = csv.reader(abuse_csv_response.text.splitlines(), delimiter=',')

# Try to turn this CSV into a list
try:
    ransom_list = list(ransom_csv)
except Exception as e:
    logger.error("Unable to listify CSV :: {}".format(str(e)))

json_record = {}

record_count = 0

for row in ransom_list:
    if len(row) < 2:
コード例 #9
0
def add_alias_member(ip_address):

    exp = "\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}"

    r = re.search(exp, ip_address)
    """
    Make sure we receive a valid IP address
    """
    if r is None:
        logger.error("Did not receive a valid IP address")
        return False

    # Connect to WatchGuard, set disable looking for keys
    # If you're using pubkey auth, you'll need to change some params here
    try:
        client.connect(WATCHGUARD_IP,
                       port=WATCHGUARD_PORT,
                       username=WATCHGUARD_USER,
                       password=WATCHGUARD_PASSWORD,
                       allow_agent=False,
                       look_for_keys=False)
        logger.info("Connect to WatchGuard")
    except Exception as e:
        print("Error connecting to WatchGuard: {}".format(str(e)))
        return False

    # Invoke a shell that we can work with
    shell = client.invoke_shell()

    # Change to configure mode
    shell.send("configure\n")
    sleep(2)

    # Change to policy mode
    shell.send("policy\n")
    sleep(2)

    # Add the IP to our alias containing blocked IPs
    shell.send("alias {} host-ip {} \n".format(WATCHGUARD_ALIAS, ip_address))
    sleep(2)

    shell.send("apply\n")
    sleep(2)
    # This response is a bytes-object
    response = shell.recv(2024)
    logger.info(f"Response from WatchGuard\n: {str(response)}")

    # Exit policy mode
    shell.send("exit\n")
    sleep(2)

    # Exit configure mode
    shell.send("exit\n")
    sleep(2)

    # Exit WatchGuard CLI
    shell.send("exit\n")
    sleep(2)

    # Close the shell we invoked
    shell.close()

    # Close the connection
    client.close()

    logger.info("Closed connection to WatchGuard")

    return True
コード例 #10
0
def process_message(event, user_id, channel_id, text):
    global USER_LANGUAGE_MAPPINGS
    user_name = get_name_from_user_id(user_id)
    logger.info(f"Sender of the message is {user_name}")

    # When a new user joins
    if event.get("subtype") == 'channel_join':
        if not channel_id in USER_LANGUAGE_MAPPINGS:
            USER_LANGUAGE_MAPPINGS[channel_id] = {}
        USER_LANGUAGE_MAPPINGS[channel_id].update({user_id: 'en'})
        with open(f'{Path(__file__).parent}/user_language_mapping.json',
                  'w') as fp:
            json.dump(USER_LANGUAGE_MAPPINGS, fp, sort_keys=True, indent=4)
        try:
            slack_web_client.chat_postEphemeral(
                user=user_id,
                attachments=language_selecter["attachments"],
                channel=channel_id,
                text=f"Hello {user_name}")
            return
        except SlackApiError:
            logger.info("Failed to send message", exc_info=True)
    # ENDS HERE

    if 'files' in event:
        files = event["files"]
        audio_url = files[0].get("url_private_download")
        user_preferred_language = USER_LANGUAGE_MAPPINGS.get(channel_id).get(
            user_id)
        file_name = get_audio_file(audio_url, user_id)
        logger.info(f"File name of audio received is :{file_name}")
        text = speech.speech_to_text(file_name, user_preferred_language)
        logger.info(f"Text from audio {file_name} is :  {text}")

    if text:
        text = text.replace("'", "\\'")
    source_language = translate_api.detect_language(GOOGLE_TRANSLATE_API_KEY,
                                                    text)
    logger.info(
        f"Detected language of the message is {get_language_from_iso_code(source_language)}"
    )

    # When a message is posted, translate it for all the users in the channel
    for target_user_id, target_language in USER_LANGUAGE_MAPPINGS.get(
            channel_id).items():
        if target_user_id != user_id:
            logger.info(
                f'Target user is {user_name} and target language is {get_language_from_iso_code(target_language)} '
            )
            start = time.time()
            translated_text = get_translated_message(text, source_language,
                                                     target_language)
            logger.info(
                f'Translated text in {get_language_from_iso_code(target_language)} is {translated_text}. Completed in {time.time()-start} seconds'
            )
            try:
                slack_web_client.chat_postEphemeral(
                    user=target_user_id,
                    channel=channel_id,
                    text=f"*{user_name}* :\n{translated_text} ")
            except SlackApiError:
                logger.error("Failed to send message", exc_info=True)
コード例 #11
0
# Initialize a Flask app to host the events adapter
app = Flask(__name__)
# Create an events adapter and register it to an endpoint in the slack app for event injestion.
slack_events_adapter = SlackEventAdapter(SLACK_SIGNING_SECRET, "/slack/events",
                                         app)

# Initialize a Web API client
slack_web_client = WebClient(token=SLACK_BOT_ACCESS_TOKEN)

try:
    with open(f'{Path(__file__).parent}/user_language_mapping.json') as f:
        USER_LANGUAGE_MAPPINGS = json.load(f)
except FileNotFoundError:
    USER_LANGUAGE_MAPPINGS = {}
    logger.info("First run?")

# when the app starts, load the language_mappings.json file and create a json for /change_language command. Any changes to language list to just be done
# in language_mappings.json file
with open(f'{Path(__file__).parent}/language_mapping.json') as language:
    LANGUAGE_ISO_MAPPING = json.load(language)

language_selecter = {
    "text":
    "Please choose your preferred language",
    "response_type":
    "ephemeral",
    "attachments": [{
        "text":
        "Select a language",
        "fallback":
コード例 #12
0
ファイル: chat.py プロジェクト: odty101/PyCryptoChat
 def connect(self, user, server):
     self.manager.user = user
     logger.info('Connecting to: {} as {}'.format(server, user))
コード例 #13
0
ファイル: chat.py プロジェクト: odty101/PyCryptoChat
 def disconnect(self):
     logger.info('Disconnecting')