]> gitweb.pimeys.fr Git - bots/hung.git/blobdiff - hung.py
C'est cool d'être daemonizable
[bots/hung.git] / hung.py
diff --git a/hung.py b/hung.py
index 30278ea1043c28d517ddc71ac34768fd208aecce..49371f1caa81b6534fc54cb8a0d0431ee2c7b902 100755 (executable)
--- a/hung.py
+++ b/hung.py
@@ -5,8 +5,6 @@
 
 # Un test de bot irc, parce que c'est cool
 
-import irclib
-import ircbot
 import threading
 import random
 import time
@@ -14,15 +12,22 @@ import socket, ssl, json
 import pickle
 import re
 import os
+import signal
+import sys
 from commands import getstatusoutput as ex
 
+# Oui, j'ai recodé ma version d'irclib pour pouvoir rattrapper les SIGHUP
+sys.path.insert(0, "/home/vincent/scripts/python-myirclib")
+import irclib
+import ircbot
+
 import sys
 config_debug_stdout=True
 if "--quiet" in sys.argv:
     config_debug_stdout=False
 
 config_irc_password="I'mAHungMan"
-config_irc_pseudo="Hung"
+config_irc_pseudo="hung"
 config_chanlist=["#bot","#flood"]
 config_stay_channels=["#bot","#flood"]
 config_play_channels=["#flood"]
@@ -122,7 +127,7 @@ class Hung(ircbot.SingleServerIRCBot):
         self.chanlist=config_chanlist
         self.stay_channels=config_stay_channels
         self.play_channels=config_play_channels
-        self.play_status={}
+        self.play_status={i:[None,None,None] for i in self.play_channels}
         self.quiet_channels=config_quiet_channels
 
 
@@ -405,7 +410,7 @@ class Hung(ircbot.SingleServerIRCBot):
                         serv.privmsg(canal,"%s: %s"%(auteur,ligne.encode("utf8")))
             # on essaye de voir si le mot fourni matche la partie en cours
             mot = cmd
-            if is_mot(mot, self.play_status[canal][0]):
+            if self.play_status[canal][0]!=None and is_mot(mot, self.play_status[canal][0]):
                 # on a trouvé le mot
                 # on regarde combien de lettre il manquait
                 manquait = sum([not lettre[1] for lettre in self.play_status[canal][0]])
@@ -430,6 +435,28 @@ class Hung(ircbot.SingleServerIRCBot):
               "%s : Euh, tu fais de la merde avec ton encodage là, j'ai failli crasher…"%(auteur))
             return
         mypseudo=serv.get_nickname()
+
+    def on_kick(self,serv,ev):
+        auteur = irclib.nm_to_n(ev.source())
+        channel = ev.target()
+        victime = ev.arguments()[0]
+        raison = ev.arguments()[1]
+        if victime==self.nick:
+            log(self.serveur,"%s kické de %s par %s (raison : %s)" %(victime,channel,auteur,raison))
+            time.sleep(5)
+            serv.join(channel)
+            # on ne dit rien au rejoin
+            #l1,l2=config_kick_answers,config_kick_actions
+            #n1,n2=len(l1),len(l2)
+            #i=random.randrange(n1+n2)
+            #if i>=n1:
+            #    serv.action(channel,l2[i-n1].format(auteur).encode("utf8"))
+            #else:
+            #    serv.privmsg(channel,l1[i].format(auteur).encode("utf8"))
+    
+    def _getnick(self):
+        return self.serv.get_nickname()
+    nick = property(_getnick)
     
     def quitter(self,chan,leave_message=None):
         if leave_message==None:
@@ -478,17 +505,47 @@ class Hung(ircbot.SingleServerIRCBot):
         serv.privmsg(canal,"Contributions : %s"%("  ".join(contribs)) )
         self.play_status[canal]=[None,None,None]
 
+    def start_as_daemon(self, outfile):
+        sys.stderr = Logger(outfile)
+        self.start()
+
+
+class Logger(object):
+    """Pour écrire ailleurs que sur stdout"""
+    def __init__(self, filename="hung.full.log"):
+        self.filename = filename
+
+    def write(self, message):
+        f = open(self.filename, "a")
+        f.write(message)
+        f.close()
+
 
 if __name__=="__main__":
     import sys
     if len(sys.argv)==1:
-        print "Usage : hung.py <serveur> [--debug]"
+        print "Usage : hung.py <serveur> [--debug] [--no-output] [--daemon [--pidfile]] [--outfile]"
+        print "        --outfile sans --no-output ni --daemon n'a aucun effet"
         exit(1)
     serveur=sys.argv[1]
+    if "--daemon" in sys.argv:
+        thisfile = os.path.realpath(__file__)
+        thisdirectory = thisfile.rsplit("/", 1)[0]
+        os.chdir(thisdirectory)
+        daemon = True
+    else:
+        daemon = False
     if "debug" in sys.argv or "--debug" in sys.argv:
         debug=True
     else:
         debug=False
+    if "--no-output" in sys.argv or "--daemon" in sys.argv:
+        outfile = "/var/log/bots/hung.full.log"
+        for arg in sys.argv:
+            arg = arg.split("=")
+            if arg[0].strip('-') in ["out", "outfile", "logfile"]:
+                outfile = arg[1]
+        sys.stdout = Logger(outfile)
     serveurs={"a♡":"acoeur.crans.org","acoeur":"acoeur.crans.org","acoeur.crans.org":"acoeur.crans.org",
               "irc":"irc.crans.org","crans":"irc.crans.org","irc.crans.org":"irc.crans.org",
               "localhost":"localhost"}
@@ -498,4 +555,21 @@ if __name__=="__main__":
         print "Server Unknown : %s"%(serveur)
         exit(404)
     hung=Hung(serveur,debug)
-    hung.start()
+    if daemon:
+        child_pid = os.fork()
+        if child_pid == 0:
+            os.setsid()
+            hung.start_as_daemon(outfile)
+        else:
+            # on enregistre le pid de hung
+            pidfile = "/var/run/bots/hung.pid"
+            for arg in sys.argv:
+                arg = arg.split("=")
+                if arg[0].strip('-') in ["pidfile"]:
+                    pidfile = arg[1]
+            f = open(pidfile, "w")
+            f.write("%s\n" % child_pid)
+            f.close()
+    else:
+        hung.start()
+