class ClumsyRobot(discord.Client):
    def __init__(self):
        # load the markov chain data
        print('*** Loading markov data from {}...'.format(
            MARKOV_DATA_SAVE_LOCATION))
        try:
            with open(MARKOV_DATA_SAVE_LOCATION, 'rb') as markov_file:
                self._markov = Markov(pickle.load(markov_file))
                markov_file.close()
        except IOError:
            print('*** Unable to load file!')
            self._markov = Markov()

        self._messages_since_last_autosave = 0
        super().__init__()

    # Connected as a discord client
    async def on_ready(self):
        print('*** Connected as {}.'.format(self.user))

    # Message received
    async def on_message(self, message):
        # don't respond to or learn from our own messages
        if message.author == self.user:
            return

        # learn and occasionally engage in discussion
        content = message.content.lower()
        self._markov.DigestInput(content)

        if random() < RESPONSE_FREQUENCY:
            response = self._markov.GenerateChain(content)
            await message.channel.send(response)

        # save the markov data sometimes
        self._messages_since_last_autosave += 1
        if self._messages_since_last_autosave == MESSAGES_PER_AUTOSAVE:
            print('*** Saving markov data to {}...'.format(
                MARKOV_DATA_SAVE_LOCATION))
            try:
                with open(MARKOV_DATA_SAVE_LOCATION, 'wb') as markov_file:
                    pickle.dump(self._markov.GetData(), markov_file)
                    markov_file.close()
                self._messages_since_last_autosave = 0
            except IOError:
                print('*** Unable to save file!')
RAW_CHAT_LOG_LOCATION     = 'lines.txt'
MARKOV_DATA_SAVE_LOCATION = 'markov_data.pkl'

print('opening raw chat logs...')
try:
    log_file = open(RAW_CHAT_LOG_LOCATION, 'r', encoding='utf-8', errors='replace')
except IOError as e:
    print('could not open file. ({})'.format(str(e)))
    exit()

messages = log_file.readlines()
log_file.close()

markov = Markov()
num_msgs = len(messages)
count = 0
print('found {} messages in log. digesting... '.format(num_msgs))
for message in messages:
    message = message.strip().lower()
    markov.DigestInput(message)
    count += 1
    print('\r... {} / {}'.format(count, num_msgs), end='')

print('\nsaving pickle...')
try:
    with open(MARKOV_DATA_SAVE_LOCATION, 'wb') as pickle_file:
        pickle.dump(markov.GetData(), pickle_file)
        pickle_file.close()
except IOError as e:
    print('could not save file. ({})'.format(str(e)))