#!/usr/bin/python
# -*- coding:Utf-8 -*-

##########################################################
# nomsn - Bot jabber à utiliser avec une passerelle msn  #
# Version 0.2.0                                          #
# Basé sur l'exemple de script pour xmpppy :             #
# http://xmpppy.sourceforge.net/examples/bot.py          #
# Copyright Florian Birée, 2006                          #
# http://filyb.info/                                     #
# Sous licence GNU GPL                                   #
##########################################################

#/Personalisation du bot : \_________________________________________________________________________________
#############################################################################################################
#URL d'explication sur l'utilisation de jabber
explicurl = "http://thesa.serveurperso.com/dotclear/index.php/2006/01/28/211-comment-me-parler-avec-jabber"
#Texte affiché par le bot par la commande contact (le %s ajoute l'url d'explication sur jabber)
contactText = """
Florian Biree
Messagerie instantanee Jabber : florian.biree@laposte.net (explications : %s )
Mail : florian.biree@laposte.net
Site web et blog : http://filyb.info/
"""%explicurl
#JID du propriétaire du bot (le seul qui peut fermer le bot / JID affiché dans le message par défaut
jidOwner = 'florian.biree@jabber.fr'
#____________________________________________________________________________________________________________
#############################################################################################################

__author__ = "Florian Birée"
__version__ = "0.2.0"
copyright = "Florian Birée, 2006, sous licence GNU/GPL"

###Changlog :
#version 0.2.0 :
#   o enregistrement des messages de l'extérieur dans ~/.nomsnlog
#   o déplacement des variables de contexte en haut du script

###Importation des modules
import sys
import xmpp
import os
import time

commands={}
i18n={'fr':{},'en':{}}
########################### Commandes ##################################
i18n['fr']['AIDE']="Robot d'informations sur jabber.\nCommandes disponibles : %s"
i18n['en']['AIDE']="Jabber info bot.\nAvailable commands: %s"
def aideHandler(user,command,args,mess):
    lst=commands.keys()
    lst.sort()
    return "AIDE",', '.join(lst)

i18n['en']['EMPTY']="%s"
i18n['fr']['CONTACT']='Contact : %s'
i18n['en']['CONTACT']='Contact : %s'
def contactHandler(user,command,args,mess):
    return "CONTACT",contactText

i18n['fr']['APROPOS']='A propos de : %s'
def aproposHandler(user,command,args,mess):
    return "APROPOS","ce robot jabber a ete programme en python avec xmpppy. Copyright %s. Les citations sont fournies par le programme Fortune"%copyright

i18n['fr']['CITATION']='Citation :\n%s'
def citationHandler(user,command,args,mess):
    import commands
    cit = commands.getoutput('fortune')
    #cit = cit.encode("ascii","replace")
    return "CITATION", cit

i18n['fr']['FERMER']='Fermer : %s'
def fermerHandler(user,command,args,mess):
    if str(user)[:23] == jidOwner :
        sys.exit()
    ret = "Cette commande est réservée à %s. Pour quitter cette discussion, fermez simplement votre fenetre ;-)"%jidOwner
    return "FERMER",ret
########################### user handlers stop ###################################
############################ bot logic start #####################################
i18n['en']["UNKNOWN COMMAND"]='Unknown command "%s". Try "help"'
i18n['fr']["UNKNOWN COMMAND"]='Bonjour !\nJ\'ai decide d\'arreter d\'utiliser MSN Messenger. Si vous voulez me parler par messagerie instantanee, vous pouvez le faire en utilisant le reseau Jabber (mon identifiant jabber est : ' + jidOwner + '). Pour plus de details, voyez cette page web : ' + explicurl + ' Merci !\nCe message est un message automatique. La commande que vous avez envoye a ce robot ("%s") est inconnue. Entrez "Aide" pour connaitre les commandes possibles.'
i18n['fr']["UNKNOWN USER"]="Je ne vous connait pas. Enregistrez-vous s'il vous plait."
i18n['en']["UNKNOWN USER"]="I do not know you. Register first."

def messageCB(conn,mess):
    text=mess.getBody()
    user=mess.getFrom()
    user.lang='fr'      # dup
    if text.find(' ')+1: command,args=text.split(' ',1)
    else: command,args=text,''
    cmd=command.lower()

    #ajouter au log
    log = open(os.getenv("HOME") + "/.nomsnlog","a")
    log.write(time.asctime(time.localtime()) + " :: " + str(user) + " :: " + cmd + "\n")
    log.close
    #fin log
    if commands.has_key(cmd): reply=commands[cmd](user,command,args,mess)
    else: reply=("UNKNOWN COMMAND",cmd)

    if type(reply)==type(()):
        key,args=reply
        if i18n[user.lang].has_key(key): pat=i18n[user.lang][key]
        elif i18n['en'].has_key(key): pat=i18n['en'][key]
        else: pat="%s"
        if type(pat)==type(''): reply=pat%args
        else: reply=pat(**args)
    else:
        try: reply=i18n[user.lang][reply]
        except KeyError:
            try: reply=i18n['en'][reply]
            except KeyError: pass
    if reply: conn.send(xmpp.Message(mess.getFrom(),reply))

for i in globals().keys():
    if i[-7:]=='Handler' and i[:-7].lower()==i[:-7]: commands[i[:-7]]=globals()[i]

############################# bot logic stop #####################################

def StepOn(conn):
    try:
        conn.Process(1)
    except KeyboardInterrupt: return 0
    return 1

def GoOn(conn):
    while StepOn(conn): pass

if len(sys.argv)<3:
    print "Usage: bot.py username@server.net password"
else:
    jid=xmpp.JID(sys.argv[1])
    user,server,password=jid.getNode(),jid.getDomain(),sys.argv[2]

    conn=xmpp.Client(server)#,debug=[])
    conres=conn.connect()
    if not conres:
        print "Unable to connect to server %s!"%server
        sys.exit(1)
    if conres<>'tls':
        print "Warning: unable to estabilish secure connection - TLS failed!"
    authres=conn.auth(user,password)
    if not authres:
        print "Unable to authorize on %s - check login/password."%server
        sys.exit(1)
    if authres<>'sasl':
        print "Warning: unable to perform SASL auth os %s. Old authentication method used!"%server
    conn.RegisterHandler('message',messageCB)
    conn.sendInitPresence()
    print "Bot started."
    GoOn(conn)
