
from threading import Thread
from pickle import dump, load
from random import randrange, choice, random
from re import match, search
from socket import socket
from time import sleep, time




DICT = {
    7: {'suicide', 'enculer', 'couille', 'trucide', 'connard', 'putains',
        'salauds', 'salopes', 'chattes', 'vaginal', 'sodomie', 'sucerai'},
    8: {'suicides', 'enculera', 'enculees', 'couilles', 'trucider', 'connasse',
        'salopard', 'sodomise', 'suicider'}
}

with open('dict.data', 'rb') as file:
    DICT = load(file)

NICK, FD = 'plopitude', socket()


FD.connect(('irc', 6667))

send = lambda x: FD.send(x.encode() + b'\r\n')
def recv():
    for line in FD.recv(65536).split(b'\r\n'):
        if pong(line):
            continue
        print('\033[35m« %s\033[0m' % line.decode())
        yield line.decode().strip()

def pong(line):
    if line.startswith(b'PING'):
        FD.send(b'PONG ' + line.rsplit(b':', maxsplit=1)[-1] + b'\r\n')
        return True
    return False


send('NICK {x}\r\nUSER {x} {x} {x} :{x}'.format(x=NICK))
list(recv()); sleep(1); list(recv())

send('JOIN #motus')
print(DICT)
length, seen, stop, pause, last = 0, set(), True, 0, 0

def submit():
    print('flan')
    while True:
        sleep(2 + random() / 3. + random() + last / 30.)
        if not stop and length in DICT and DICT[length] - seen:
            word = choice(list(DICT[length] - seen))
            send('PRIVMSG #motus :%s' % word)
            seen.add(word)
            last = len(word)
#Thread(target=submit).start()

while True:
    for line in recv():
        found = search(r'\((\d+) lettres?', line)
        if found:
            seen = set()
            length = int(found.group(1))
            stop = False
        if 'Bravo' in line or 'Le temps est écoulé' in line:
            stop = True
        found = search(r'PRIVMSG #motus :([a-z]+)$', line)
        if found:
            word = found.group(1)
            seen.add(word)
            if len(word) not in DICT:
                DICT[len(word)] = set()
            DICT[len(word)].add(word)
            print('\033[1;32m+ Added %s\033[0m' % word.upper())
            with open('dict.data', 'wb') as file:
                dump(DICT, file)
            continue
        found = search(r'Le mot.+?([A-Z]+).+?est invalide.', line)
        if found:
            word = found.group(1).lower()
            if len(word) in DICT and word in DICT[len(word)]:
                DICT[len(word)].remove(word)
                print('\033[1;31m- Removed %s\033[0m' % word.upper())
        if not stop and pause < time() and length in DICT and DICT[length] - seen:
            word = choice(list(DICT[length] - seen))
            #pause = time() + (2 + random() / 3. + random() + last / 30.)
            sleep(2 + random() / 3. + random() + last / 30.)
            send('PRIVMSG #motus :%s' % word)
            seen.add(word)
            last = len(word)
