<commit_before>from __future__ import absolute_import
import sys
import os
import time
import signal
import traceback
import logging
import inspect
import cwbot.util.DebugThreading as threading
from cwbot.processArgv import processArgv
from cwbot.sys.BotSystem import BotSystem
from cwbot.common.exceptions import ManualException, ManualRestartException, \
                                    FatalError
from cwbot.kolextra.manager.ChatManager import ChatManager
from cwbot.kolextra.request.SendMessageRequest import SendMessageRequest
from cwbot.kolextra.manager.InventoryManager import InventoryManager
from cwbot.util.tryRequest import tryRequest
from cwbot.database import database
from kol.Session import Session
import kol.Error
from cwbot.sys.database import Database

exitEvent = threading.Event()
databaseName = 'data/cwbot.db'


def openSession(props):
    """ Log in to the KoL servers. """
    log = logging.getLogger()
    s = Session()
    s.login(props.userName, props.password)
    log.info("Logged in.")
    return s


def createChatManager(s):
    """ Open a new chat manager. """
    log = logging.getLogger()
    log.debug("Opening chat...")    
    c = ChatManager(s)
    log.info("Logged in to chat.")
    return c

    
def createInventoryManager(s, db):
    """ Create a new inventory manager. """
    inv = InventoryManager(s, db)
    return inv


def notifyAdmins(s, props, log, etype, value, tb):
    # kmail the administrators
    if props.debug:
        return
    if s is not None and s.isConnected:
        for uid in props.getAdmins('crash_notify'):
            errorText = ''.join(traceback.format_exception(
                                                    etype, value, tb))
            if len(errorText) > 1800:
                errorText = "..." + errorText[-1800:]
                                                    
            alert1 = SendMessageRequest(
                    s, {'userId': uid, 
                        'text': "NOTICE: CWbot encountered an "
                                "unknown error: {}".format(errorText)})
            try:
                log.info("Sending notice to {}".format(uid))
                tryRequest(alert1)
            except Exception:
                log.exception("Exception sending error notice.")


def loginLoop(myDb, props):
    """ Main part of the login loop. """
    global exitEvent
    log = logging.getLogger()
    s = None
    onlineTime = time.time()
    successfulShutdown = False
    fastCrash = False
    cman = None
    try:
        loginWait = 60
        s = openSession(props)
        inv = createInventoryManager(s, myDb)
        cman = createChatManager(s)
        database.flush()
        bsys = BotSystem(s, cman, props, inv, 'modules.ini', myDb, exitEvent)
        
        # run the bot main loop. If this function returns, then we are logging
        # out for rollover. If it throws an exception, then we are either
        # shutting down manually or crashing.
        bsys.loop()

        loginWait = props.rolloverWait<commit_msg>Set default socket timeout to 60 seconds.<commit_after>from __future__ import absolute_import
import sys
import os
import time
import signal
import traceback
import logging
import inspect
import socket
import cwbot.util.DebugThreading as threading
from cwbot.processArgv import processArgv
from cwbot.sys.BotSystem import BotSystem
from cwbot.common.exceptions import ManualException, ManualRestartException, \
                                    FatalError
from cwbot.kolextra.manager.ChatManager import ChatManager
from cwbot.kolextra.request.SendMessageRequest import SendMessageRequest
from cwbot.kolextra.manager.InventoryManager import InventoryManager
from cwbot.util.tryRequest import tryRequest
from cwbot.database import database
from kol.Session import Session
import kol.Error
from cwbot.sys.database import Database

exitEvent = threading.Event()
databaseName = 'data/cwbot.db'


def openSession(props):
    """ Log in to the KoL servers. """
    log = logging.getLogger()
    s = Session()
    s.login(props.userName, props.password)
    log.info("Logged in.")
    return s


def createChatManager(s):
    """ Open a new chat manager. """
    log = logging.getLogger()
    log.debug("Opening chat...")    
    c = ChatManager(s)
    log.info("Logged in to chat.")
    return c

    
def createInventoryManager(s, db):
    """ Create a new inventory manager. """
    inv = InventoryManager(s, db)
    return inv


def notifyAdmins(s, props, log, etype, value, tb):
    # kmail the administrators
    if props.debug:
        return
    if s is not None and s.isConnected:
        for uid in props.getAdmins('crash_notify'):
            errorText = ''.join(traceback.format_exception(
                                                    etype, value, tb))
            if len(errorText) > 1800:
                errorText = "..." + errorText[-1800:]
                                                    
            alert1 = SendMessageRequest(
                    s, {'userId': uid, 
                        'text': "NOTICE: CWbot encountered an "
                                "unknown error: {}".format(errorText)})
            try:
                log.info("Sending notice to {}".format(uid))
                tryRequest(alert1)
            except Exception:
                log.exception("Exception sending error notice.")


def loginLoop(myDb, props):
    """ Main part of the login loop. """
    global exitEvent
    log = logging.getLogger()
    s = None
    onlineTime = time.time()
    successfulShutdown = False
    fastCrash = False
    cman = None
    try:
        loginWait = 60
        s = openSession(props)
        inv = createInventoryManager(s, myDb)
        cman = createChatManager(s)
        database.flush()
        socket.setdefaulttimeout(60)
        bsys = BotSystem(s, cman, props, inv, 'modules.ini', myDb, exitEvent)
        
        # run the bot main loop. If this function returns, then we are logging
        # out for rollover. If it throws an exception, then we are either
        # shutting down manually or crashing.
        bsys.loop()

        loginWait = props.rolloverWait
{'fraction_non_alphanumeric': 0.08661800486618004, 'fraction_numerical': 0.004541768045417681, 'mean_word_length': 2.2384453781512605, 'pattern_counts': {'":': 0, '<': 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': 10, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '564479', 'n_tokens_mistral': 1723, 'n_tokens_neox': 1651, 'n_words': 516}