1
0
Fork 0

Better separed nemubot

This commit is contained in:
Némunaire 2012-03-21 23:12:16 +01:00
parent 3a30b482ab
commit 992ecaa59c
5 changed files with 371 additions and 14 deletions

130
birthday.py Normal file
View File

@ -0,0 +1,130 @@
# coding=utf-8
import counter
from datetime import datetime
BIRTHDAYS = list()
def xmlparse(node):
for item in node.getElementsByTagName("item"):
if (item.hasAttribute("year")):
year = int(item.getAttribute("year"))
else:
year = 0
if (item.hasAttribute("month")):
month = int(item.getAttribute("month"))
else:
month = 0
if (item.hasAttribute("day")):
day = int(item.getAttribute("day"))
else:
day = 0
if (item.hasAttribute("hour")):
hour = int(item.getAttribute("hour"))
else:
hour = 0
if (item.hasAttribute("minute")):
minute = int(item.getAttribute("minute"))
else:
minute = 0
second = 1
BIRTHDAYS.append((item.getAttribute("name"), datetime(year, month, day, hour, minute, second)))
def xmlsave(doc):
top = doc.createTextNode("birthday")
for brth in BIRTHDAYS:
item = doc.createTextNode("item")
item.setAttribute("", "")
top.appendChild(item);
def parseanswer(s, channel, sender, cmd):
if len(cmd) < 2 or cmd[1].lower() == "moi":
name = sender.lower()
else:
name = cmd[1].lower()
matches = []
if name in birthdays:
matches.append(name)
else:
for k in birthdays.keys():
if k.find(name) == 0:
matches.append(k)
if len(matches) == 1:
(n, d) = (matches[0], birthdays[matches[0]])
tyd = d
tyd = datetime(date.today().year, tyd.month, tyd.day)
if tyd.day == datetime.today().day and tyd.month == datetime.today().month:
newyear.launch (s, info[2], d, ["", "C'est aujourd'hui l'anniversaire de %s ! Il a%s. Joyeux anniversaire :)" % (n, "%s")], cmd)
else:
if tyd < datetime.today():
tyd = datetime(date.today().year + 1, tyd.month, tyd.day)
newyear.launch (s, info[2], tyd, ["Il reste%s avant l'anniversaire de %s !" % ("%s", n), ""], cmd)
else:
s.send("PRIVMSG %s :%s: désolé, je ne connais pas la date d'anniversaire de %s. Quand est-il né ?\r\n"%(info[2], sender[0], name))
def parseask(s, channel, sender, msgl):
if re.match(".*(date de naissance|birthday|geburtstag|née?|nee? le|born on).*", msgl) is not None:
result = re.match("[^0-9]+(([0-9]{1,4})[^0-9]+([0-9]{1,2}|janvier|january|fevrier|février|february|mars|march|avril|april|mai|maï|may|juin|juni|juillet|july|jully|august|aout|août|septembre|september|october|obtobre|novembre|november|decembre|décembre|december)([^0-9]+([0-9]{1,4}))?)[^0-9]+(([0-9]{1,2})[^0-9]*[h':][^0-9]*([0-9]{1,2}))?.*", msgl)
if result is None:
s.send("PRIVMSG %s :%s: je ne reconnais pas le format de ta date de naissance :(\r\n"%(channel, sender))
else:
day = result.group(2)
if len(day) == 4:
year = day
day = 0
month = result.group(3)
if month == "janvier" or month == "january" or month == "januar":
month = 1
elif month == "fevrier" or month == "février" or month == "february":
month = 2
elif month == "mars" or month == "march":
month = 3
elif month == "avril" or month == "april":
month = 4
elif month == "mai" or month == "may" or month == "maï":
month = 5
elif month == "juin" or month == "juni" or month == "junni":
month = 6
elif month == "juillet" or month == "jully" or month == "july":
month = 7
elif month == "aout" or month == "août" or month == "august":
month = 8
elif month == "september" or month == "septembre":
month = 9
elif month == "october" or month == "october" or month == "oktober":
month = 10
elif month == "november" or month == "novembre":
month = 11
elif month == "december" or month == "decembre" or month == "décembre":
month = 12
if day == 0:
day = result.group(5)
else:
year = result.group(5)
hour = result.group(7)
minute = result.group(8)
print "Chaîne reconnue : %s/%s/%s %s:%s"%(day, month, year, hour, minute)
if year == None:
year = date.today().year
if hour == None:
hour = 0
if minute == None:
minute = 0
try:
newdate = datetime(int(year), int(month), int(day), int(hour), int(minute))
birthdays[sender[0].lower()] = newdate
s.send("PRIVMSG %s :%s: ok, c'est noté, ta date de naissance est le %s\r\n"%(channel, sender, newdate.strftime("%A %d %B %Y à %H:%M")))
except ValueError:
s.send("PRIVMSG %s :%s: ta date de naissance me paraît peu probable...\r\n"%(channel, sender))
return True
return False

View File

@ -16,6 +16,7 @@ import norme
import newyear
import ontime
import watchWebsite
import qd
if len(sys.argv) > 1:
sys.exit(0)
@ -29,7 +30,7 @@ IDENT='nemubot'
REALNAME='nemubot'
OWNER='nemunaire' #The bot owner's nick
#CHANLIST='#nemutest'
CHANLIST='#42sh #nemutest #tc'
CHANLIST='#42sh #nemutest #tc #epitagueule'
readbuffer='' #Here we store all the messages from server
birthdays = {"maxence23": datetime(1991, 8, 11),
@ -39,6 +40,13 @@ birthdays = {"maxence23": datetime(1991, 8, 11),
"test": datetime(1991, 1, 25),
"colona": datetime(1991, 7, 16)}
#score42 = {"bob": (datetime.now(), 10, 3, 1, 0, 0, 5),
# "benf": (datetime.now(), 3, 4, 0, 0, 0, 0),
# "colona": (datetime.now(), 10, 0, 4, 0, 1, 1),
# "maxence23": (datetime.now(), 16, 2, 4, 0, 0, 11),
# "nemunaire": (datetime.now(), 15, 3, 4, 0, 1, 2),
# "xetal": (datetime.now(), 6, 0, 0, 0, 0, 0)}
s = socket.socket( ) #Create the socket
s.connect((HOST, PORT)) #Connect to server
s.send("PASS %s\r\n" % "McsuapTesbuf")
@ -49,7 +57,7 @@ s.send("USER %s %s bla :%s\r\n" % (IDENT, HOST, REALNAME))
print("Welcome on Nemubot. I operate on %s. My PID is %i" % (CHANLIST, os.getpid()))
def parsemsg(msg):
global birthdays
global birthdays, score42
complete = msg[1:].split(':',1) #Parse the message into useful data
info = complete[0].split(' ')
msgpart = complete[1]
@ -58,6 +66,8 @@ def parsemsg(msg):
if len(msgpart) <= 0:
return
qd.go (s, sender, msgpart, info[2])
if CHANLIST.find(info[2]) != -1 and re.match(".*(norme|coding style).*", msgpart) is not None and re.match(".*(please|give|obtenir|now|plz|stp|svp|s'il (te|vous) pla.t|check).*", msgpart) is not None:
norme.launch (s, sender, msgpart)
@ -69,6 +79,18 @@ def parsemsg(msg):
elif re.match(".*di[st] (a|à) ([a-zA-Z0-9_]+) (.+)$", msgpart) is not None:
result = re.match(".*di[st] (a|à) ([a-zA-Z0-9_]+) (qu(e |'))?(.+)$", msgpart)
s.send("PRIVMSG %s :%s: %s\r\n"%(info[2], result.group(2), result.group(5)))
elif re.match(".*di[st] sur (#[a-zA-Z0-9]+) (.+)$", msgpart) is not None:
result = re.match(".*di[st] sur (#[a-zA-Z0-9]+) (.+)$", msgpart)
if CHANLIST.find(result.group(1)):
s.send("PRIVMSG %s :%s\r\n"%(result.group(1), result.group(2)))
else:
print "Channel non autorisé"
elif re.match(".*di[st] (.+) sur (#[a-zA-Z0-9]+)$", msgpart) is not None:
result = re.match(".*di[st] (.+) sur (#[a-zA-Z0-9]+)$", msgpart)
if CHANLIST.find(result.group(2)):
s.send("PRIVMSG %s :%s\r\n"%(result.group(2), result.group(1)))
else:
print "Channel non autorisé"
elif re.match(".*di[st] (.+) (a|à) ([a-zA-Z0-9_]+)$", msgpart) is not None:
result = re.match(".*di[st] (.+) (à|a) ([a-zA-Z0-9_]+)$", msgpart)
s.send("PRIVMSG %s :%s: %s\r\n"%(info[2], result.group(3), result.group(1)))
@ -132,7 +154,7 @@ def parsemsg(msg):
birthdays[sender[0].lower()] = newdate
s.send("PRIVMSG %s :%s: ok, c'est noté, ta date de naissance est le %s\r\n"%(info[2], sender[0], newdate.strftime("%A %d %B %Y à %H:%M")))
except ValueError:
s.send("PRIVMSG %s :%s: ta date de naissance me paraît peu probable...\r\n"%(info[2], sender[0]))
s.send("PRIVMSG %s :%s: ta date de naissance me paraît peu probable...\r\n"%(info[2], sender[0]))
elif CHANLIST.find(info[2]) != -1 and msgpart[0] == '!': #Treat all messages starting with '!' as command
cmd = msgpart[1:].split(' ')
@ -144,6 +166,13 @@ def parsemsg(msg):
s.send("PRIVMSG %s : - !partiels : Affiche le temps restant avant les prochains partiels\r\n"%(sender[0]))
s.send("PRIVMSG %s : - !vacs !vacances !holidays !free-time : Affiche le temps restant avant les prochaines vacances\r\n"%(sender[0]))
s.send("PRIVMSG %s : - !jpo !next-jpo : Affiche le temps restant avant la prochaine JPO\r\n"%(sender[0]))
s.send("PRIVMSG %s : - !42 !scores : Affiche les scores des gens\r\n"%(sender[0]))
if cmd[0] == 'score' or cmd[0] == 'scores' or cmd[0] == '42':
qd.scores(s, cmd, info[2])
if cmd[0] == 'chronos' or cmd[0] == 'edt' or cmd[0] == 'cours':
s.send("PRIVMSG %s :chronos\r\n"%(info[2]))
if cmd[0] == 'new-year' or cmd[0] == 'newyear' or cmd[0] == 'ny':
#What is the next year?
@ -177,7 +206,7 @@ def parsemsg(msg):
if cmd[0] == 'katy' or cmd[0] == 'album':
ndate = datetime(2012, 3, 26, 8, 0, 0)
newyear.launch (s, info[2], ndate, ["Il reste%s avant la sortie du prochain album de Katy Perry :)", "Vite, courrons s'acheter le nouvel album de Katy Perry, il est sorti depuis%s"], cmd)
if cmd[0] == 'anniv':
if cmd[0] == 'anniv' or cmd[0] == 'age':
if len(cmd) < 2 or cmd[1].lower() == "moi":
name = sender[0].lower()
else:
@ -203,7 +232,10 @@ def parsemsg(msg):
if tyd < datetime.today():
tyd = datetime(date.today().year + 1, tyd.month, tyd.day)
newyear.launch (s, info[2], tyd, ["Il reste%s avant l'anniversaire de %s !" % ("%s", n), ""], cmd)
if cmd[0] == 'age':
newyear.launch (s, info[2], d, ["", "%s a%s aujourd'hui !" % (n, "%s")], cmd)
else:
newyear.launch (s, info[2], tyd, ["Il reste%s avant l'anniversaire de %s !" % ("%s", n), ""], cmd)
else:
s.send("PRIVMSG %s :%s: désolé, je ne connais pas la date d'anniversaire de %s. Quand est-il né ?\r\n"%(info[2], sender[0], name))
@ -214,8 +246,8 @@ def parsemsg(msg):
#ndate = datetime(2012, 2, 4, 8, 30, 1)
newyear.launch (s, info[2], ndate, ["Il reste%s avant la prochaine JPO... We want you!", "Nous somme en pleine JPO depuis%s"], cmd)
if cmd[0] == 'professional-project' or cmd[0] == 'project-professionnel' or cmd[0] == 'projet-professionnel' or cmd[0] == 'project-professionel' or cmd[0] == 'tc' or cmd[0] == 'next-rendu' or cmd[0] == 'rendu':
ndate = datetime(2012, 3, 4, 23, 42, 1)
newyear.launch (s, info[2], ndate, ["Il reste%s avant la fermeture du rendu de TC-4, vite au boulot !", "À %s près, il aurait encore été possible de rendre"], cmd)
ndate = datetime(2012, 3, 18, 23, 42, 1)
newyear.launch (s, info[2], ndate, ["Il reste%s avant la fermeture du rendu de TC-5 et de corewar, vite au boulot !", "À %s près, il aurait encore été possible de rendre"], cmd)
elif msgpart[0] == '`' and sender[0] == OWNER and CHANLIST.find(info[2]) != -1: #Treat all messages starting with '`' as command
@ -252,7 +284,6 @@ def read():
#signal.signal(signal.SIGHUP, onSignal)
for line in temp:
print line
line = line.rstrip() #remove trailing 'rn'
if line.find('PRIVMSG') != -1: #Call a parsing function
@ -265,7 +296,8 @@ def read():
def launch(s):
# thread.start_new_thread(ontime.startThread, (s,datetime(2012, 1, 18, 6, 0, 1),["Il reste%s avant la fin de Wikipédia", "C'est fini, Wikipédia a sombrée depuis%s"],CHANLIST))
thread.start_new_thread(watchWebsite.startThread, (s, "you.p0m.fr", "", "#42sh", "Oh, quelle est cette nouvelle image sur http://you.p0m.fr/ ? :p"))
# thread.start_new_thread(ontime.startThread, (s,datetime(2012, 2, 23, 0, 0, 1),[],CHANLIST))
thread.start_new_thread(watchWebsite.startThread, (s, "you.p0m.fr", "", "#42sh #epitaguele", "Oh, quelle est cette nouvelle image sur http://you.p0m.fr/ ? :p"))
thread.start_new_thread(watchWebsite.startThread, (s, "intra.nbr23.com", "", "#42sh", "Oh, quel est ce nouveau film sur http://intra.nbr23.com/ ? :p"))
print "Launched successfuly"

View File

@ -29,11 +29,22 @@ def launch(s, chan, ndate, sentences, msgpart):
force = 0
if force or delta.days > 0:
force = 1
sentence += " %i jour"%(delta.days)
if delta.days > 366:
year = delta.days / 365
days = delta.days % 365 - year / 4
sentence += " %i an"%(year)
if year > 1:
sentence += "s"
sentence += ","
sentence += " %i jour"%(days)
if days > 1:
sentence += "s"
else:
sentence += " %i jour"%(delta.days)
if delta.days > 1:
sentence += "s"
if delta.days > 1:
sentence += "s"
force = 1
sentence += ","
if force or hours > 0:
@ -63,4 +74,5 @@ def launch(s, chan, ndate, sentences, msgpart):
def special(s, chan):
# s.send("PRIVMSG %s :Bonne année %i !\r\n"%(chan, datetime.today().year))
s.send("PRIVMSG %s :Wikipédia vient de sombrer :(\r\n"%(chan))
# s.send("PRIVMSG %s :Wikipédia vient de sombrer :(\r\n"%(chan))
s.send("PRIVMSG %s :Joyeux anniversaire Xetal !\r\n"%(chan))

View File

@ -32,6 +32,11 @@ def startThread(s, ndate, sentences, CHANLIST):
for chan in CHANLIST.split():
newyear.special (s, chan)
elif minute == 0 and datetime.now ().hour == 0 and datetime.now ().day == 23 and datetime.now ().month == 2:
print("Anniv Xetal!")
for chan in CHANLIST.split():
newyear.special (s, chan)
if minute == 18:
for chan in CHANLIST.split():
newyear.launch (s, chan, datetime(2012, 1, 18, 6, 0, 1), sentences, 0)

178
qd.py Normal file
View File

@ -0,0 +1,178 @@
# coding=utf-8
from datetime import date
from datetime import datetime
from datetime import timedelta
channels = "#nemutest #42sh #epitagueule"
manche = (2, 'maxence23', datetime(2012, 3, 7, 22, 23, 0, 0), "colona", 193)
#score42 = {'nemunaire': (46, 5, 19, 1, 1, 27), 'cocacompany': (1, 0, 0, 0, 0, 0), 'nelson': (5, 5, 0, 0, 0, 1), 'xetal': (10, 2, 0, 0, 0, 2), 'colona': (31, 4, 32, 0, 1, 13), 'bob': (47, 4, 19, 0, 1, 27), 'benf': (12, 8, 0, 0, 1, 2), 'maxence23': (46, 18, 42, 1, 1, 45)}
score42 = {'nemunaire': (49, 1, 40, 2, 2, 42, 2), 'xetal': (1, 0, 0, 0, 0, 0, 0), 'benf': (3, 0, 0, 0, 0, 0, 0), 'colona': (23, 0, 9, 0, 1, 18, 0), 'nelson': (7, 0, 0, 0, 0, 3, 0), 'maxence23': (43, -4, 25, 1, 1, 37, 0), 'bob': (39, 1, 14, 1, 0, 26, 0), 'cccompany': (1, 0, 0, 0, 0, 1, 0)}
temps = dict()
def scores(s, cmd, where):
global score42
if len(cmd) > 1 and (cmd[1] == "help" or cmd[1] == "aide"):
s.send("PRIVMSG %s :Formule : normal * 2 - bad * 10 + great * 5 + leet * 3 + pi * 3.1415 + dt + not_found * 4.04\r\n"%(where))
elif len(cmd) > 1 and (cmd[1] == "manche"):
txt = "Nous sommes dans la %de manche, commencée par %s le %s et gagnée par %s avec %d points"%manche
s.send("PRIVMSG %s :%s\r\n"%(where, txt))
#elif where == "#nemutest":
else:
phrase = ""
if where == "#42sh":
players = ["Bob", "colona", "maxence23", "nemunaire", "Xetal"]
elif where == "#tc":
players = ["benf", "Bob", "maxence23", "nemunaire", "Xetal"]
elif where == "#epitagueule":
players = ["benf", "Bob", "colona", "cccompany", "maxence23", "nelson", "nemunaire", "Xetal"]
else:
players = score42.keys()
if len(cmd) > 1:
if cmd[1].lower() in score42:
(normal, bad, great, leet, pi, dt, nf) = user(cmd[1])
phrase += " %s: 42: %d, 23: %d, bad: %d, great: %d, leet: %d, pi: %d, 404: %d = %d."%(cmd[1], normal, dt, bad, great, leet, pi, nf, normal * 2 - bad * 10 + great * 5 + leet * 3 + pi * 3.1415 + dt + nf * 4.04)
else:
phrase = " %s n'a encore jamais joué,"%(cmd[1])
else:
joueurs = dict()
# for player in players:
for player in score42.keys():
if player in score42:
joueurs[player] = score(player)
for nom, scr in sorted(joueurs.iteritems(), key=lambda (k,v): (v,k), reverse=True):
if phrase == "":
phrase = " *%s: %d*,"%(nom, scr)
else:
phrase += " %s: %d,"%(nom, scr)
s.send("PRIVMSG %s :Scores :%s\r\n"%(where, phrase[0:len(phrase)-1]))
def score(who):
(normal, bad, great, leet, pi, dt, nf) = user(who)
# return (normal * 2 + leet * 3 + pi * 3.1415 + dt + nf * 4.04) * (10000 * great / (1 + bad * 2.5))
return (normal * 2 - bad * 10 + great * 5 + leet * 3 + pi * 3.1415 + dt + nf * 4.04)
def win(s, who):
global score42, manche
who = who.lower()
(num_manche, whosef, dayte, winner, nb_points) = manche
maxi_scor = 0
maxi_name = None
for player in score42.keys():
scr = score(player)
if scr > maxi_scor:
maxi_scor = scr
maxi_name = player
#Reset !
score42 = dict()
# score42[maxi_name] = (-10, 0, -4, 0, 0, -2, 0)
score42[maxi_name] = (0, 0, 0, 0, 0, 0, 0)
score42[who] = (0, -4, -1, 1, 1, 1, 0)
for chan in channels.split(' '):
if who != maxi_name:
s.send("PRIVMSG %s :Félicitations %s, tu remportes cette manche terminée par %s, avec un score de %d !\r\n"%(chan, maxi_name, who, maxi_scor))
else:
s.send("PRIVMSG %s :Félicitations %s, tu remportes cette manche avec %d points !\r\n"%(chan, maxi_name, maxi_scor))
manche = (num_manche + 1, who, datetime.now(), maxi_name, maxi_scor)
print "Nouvelle manche :", manche
print datetime.now(), score42
def user(who):
who = who.lower()
if who in score42:
return score42[who]
else:
return (0, 0, 0, 0, 0, 0, 0)
def canPlay(who):
who = who.lower()
if not who in temps or (temps[who].minute != datetime.now().minute or temps[who].hour != datetime.now().hour or temps[who].day != datetime.now().day):
temps[who] = datetime.now()
return True
else:
return False
def go(s, sender, msgpart, where):
if where != "#nemutest":
great = 0
if (msgpart.strip().startswith("42") and len (msgpart) < 5) or ((msgpart.strip().lower().startswith("quarante-deux") or msgpart.strip().lower().startswith("quarante deux")) and len (msgpart) < 17):
(normal, bad, great, leet, pi, dt, nf) = user(sender[0])
if canPlay(sender[0]):
if datetime.now().minute == 42:
if datetime.now().second == 0:
great += 1
normal += 1
else:
bad += 1
score42[sender[0].lower()] = (normal, bad, great, leet, pi, dt, nf)
print datetime.now(), score42
if (msgpart.strip().startswith("23") and len (msgpart) < 5) or ((msgpart.strip().lower().startswith("vingt-trois") or msgpart.strip().lower().startswith("vingt trois")) and len (msgpart) < 14):
(normal, bad, great, leet, pi, dt, nf) = user(sender[0])
if canPlay(sender[0]):
if datetime.now().minute == 23:
if datetime.now().second == 0:
great += 1
dt += 1
else:
bad += 1
score42[sender[0].lower()] = (normal, bad, great, leet, pi, dt, nf)
print datetime.now(), score42
if len (msgpart) < 12 and (msgpart.strip().lower().startswith("leet time") or msgpart.strip().lower().startswith("leettime") or msgpart.strip().lower().startswith("l33t time") or msgpart.strip().lower().startswith("1337")):
(normal, bad, great, leet, pi, dt, nf) = user(sender[0])
if canPlay(sender[0]):
if datetime.now().hour == 13 and datetime.now().minute == 37:
if datetime.now().second == 0:
great += 1
leet += 1
else:
bad += 1
score42[sender[0].lower()] = (normal, bad, great, leet, pi, dt, nf)
print datetime.now(), score42
if len (msgpart) < 11 and (msgpart.strip().lower().startswith("pi time") or msgpart.strip().lower().startswith("pitime") or msgpart.strip().lower().startswith("3.14 time")):
(normal, bad, great, leet, pi, dt, nf) = user(sender[0])
if canPlay(sender[0]):
if datetime.now().hour == 3 and datetime.now().minute == 14:
if datetime.now().second == 15 or datetime.now().second == 16:
great += 1
pi += 1
else:
bad += 1
score42[sender[0].lower()] = (normal, bad, great, leet, pi, dt, nf)
print datetime.now(), score42
if len (msgpart) < 16 and (msgpart.strip().lower().startswith("time not found") or msgpart.strip().lower().startswith("timenotfound") or msgpart.strip().lower().startswith("404 time")) or (len (msgpart) < 6 and msgpart.strip().lower().startswith("404")):
(normal, bad, great, leet, pi, dt, nf) = user(sender[0])
if canPlay(sender[0]):
if datetime.now().hour == 4 and datetime.now().minute == 04:
if datetime.now().second == 0 or datetime.now().second == 4:
great += 1
nf += 1
else:
bad += 1
score42[sender[0].lower()] = (normal, bad, great, leet, pi, dt, nf)
print datetime.now(), score42
if great >= 42:
print "Nous avons un vainqueur ! Nouvelle manche :p"
win(s, sender[0])