#!/usr/bin/python
# -*- coding: UTF8 -*-

"""
    Tux Droid - Trasform your Tux Droid into a irc bot
    Copyright (C) 2007 Francesco Frassinelli <frafra _at_ autistici _dot_ org>

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2, or (at your option)
    any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.
"""

__author__  = 'Francesco Frassinelli <frafra _at_ autistici _dot_ org>'
__appname__ = 'tuxdroid in irc'
__version__ = '0.0.1'
__date__    = '2007/12/25'
__license__ = 'GPL'

from sys import path
path.append('/opt/tuxdroid/api/python/')
from tux import *
import socket
from os import getuid
from pwd import getpwuid
from time import sleep

server = "irc.freenode.net"
channel = "#tuxdroid" # This is optional. If you don't want do join, comment it
botname = getpwuid(getuid())[0]+"_tuxdroid"

def say(text, mouthOpenAndClose=True):
    if mouthOpenAndClose: tux.cmd.mouth_open()
    tux.tts.speak(text)
    if mouthOpenAndClose: tux.cmd.mouth_close()

def destroy():
    global switch
    switch = 0
    irc.send("TIME\n")
tux.event.on_remote_bt[K_STANDBY] = destroy

irc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
irc.connect((server, 6667))
irc.send("USER %s %s %s %s\n" % ((botname,)*4))
irc.send("NICK %s\n" % botname)
if channel:
    irc.send("JOIN %s\n" % channel)

global switch
switch = 1
while switch:
    sleep(.1)
    msg = irc.recv(1024).split()
    if len(msg) > 1:
        if msg[0] == "PING":
            irc.send("PONG %s\n" % msg[1])
        elif len(msg) > 3:
            if msg[1] == "PRIVMSG":
                nick, msg[3] = (msg[0])[1:].split("!", 1)[0], msg[3][1:]
                if msg[3][-6:] != "ACTION":
                    say(nick+", ha detto: "+" ".join(msg[3:]))
                else:
                    say(nick+", "+(" ".join(msg[4:])[:-1]))
irc.close()
tux.destroy()
