Esempio n. 1
0
File: server.py Progetto: weary/piet
def checkmessages(channel_):
  global nicks;
  where="WHERE lower(nick) IN ("+','.join(['"'+x.lower()+'"' for x in nicks])+")";
  msgs=piet.db("SELECT nick,msg FROM notes "+where);
  if (msgs!=None and len(msgs)>=2):
    piet.db("DELETE FROM notes "+where);
    msgs=[n+": "+m for n,m in msgs[1:]];
    piet.send(channel_, '\n'.join(msgs));
Esempio n. 2
0
File: server.py Progetto: weary/piet
def checkmessages(channel_):
    global nicks
    where = "WHERE lower(nick) IN (" + ','.join(
        ['"' + x.lower() + '"' for x in nicks]) + ")"
    msgs = piet.db("SELECT nick,msg FROM notes " + where)
    if (msgs != None and len(msgs) >= 2):
        piet.db("DELETE FROM notes " + where)
        msgs = [n + ": " + m for n, m in msgs[1:]]
        piet.send(channel_, '\n'.join(msgs))
Esempio n. 3
0
def check_pagina(channel, nick, paginas):
    try:
        paginas = int(paginas)
        nu = int(time.time())
        piet.db("INSERT INTO paginas VALUES(" + str(nu) + ", \"" + nick +
                "\", " + str(paginas) + ");")
        first = piet.db("SELECT tijd,paginas FROM paginas WHERE nick=\"" +
                        nick + "\" ORDER BY tijd LIMIT 1")[1]
        first = [int(a) for a in first]
        prev = int(
            piet.db("SELECT paginas FROM paginas WHERE nick=\"" + nick +
                    "\" ORDER BY tijd DESC LIMIT 2")[2][0])

        # sinds vorige keer
        mutatie = paginas - prev
        r = ""
        if mutatie > 1:
            r = "dat zijn er weer " + str(mutatie)
        elif mutatie > 0:
            r = "weer eentje dus"
        elif mutatie < -1:
            r = "hee, dat zijn er " + str(-mutatie) + " minder"
        elif mutatie < 0:
            r = "pagina'tje minder, altijd goed"
        else:
            r = "echt opschieten doet't niet"

        # sinds begin
        dpag = paginas - int(first[1])
        dtijd = nu - int(first[0])
        d = float(dpag) / dtijd
        d = d * 60
        eenheid = "minuut"
        if abs(d) < 0.5:
            d = d * (24 * 60)
            eenheid = "dag"
        if abs(d) < 0.5:
            d = d * 7
            eenheid = "week"
        if abs(d) < 0.5:
            d = d * 52
            eenheid = "jaar"
        d = round(d, 2)

        r = r + " (ongeveer " + str(d) + " per " + eenheid + ")"
        piet.send(channel, r)
    except:
        traceback.print_exc()
Esempio n. 4
0
File: react.py Progetto: weary/piet
def check_pagina(channel, nick, paginas):
  try:
    paginas=int(paginas);
    nu=int(time.time());
    piet.db("INSERT INTO paginas VALUES("+str(nu)+", \""+nick+"\", "+str(paginas)+");");
    first=piet.db("SELECT tijd,paginas FROM paginas WHERE nick=\""+nick+"\" ORDER BY tijd LIMIT 1")[1];
    first=[int(a) for a in first]
    prev=int(piet.db("SELECT paginas FROM paginas WHERE nick=\""+nick+"\" ORDER BY tijd DESC LIMIT 2")[2][0]);

    # sinds vorige keer
    mutatie=paginas-prev;
    r="";
    if mutatie>1:
        r="dat zijn er weer "+str(mutatie);
    elif mutatie>0:
        r="weer eentje dus";
    elif mutatie<-1:
        r="hee, dat zijn er "+str(-mutatie)+" minder"
    elif mutatie<0:
        r="pagina'tje minder, altijd goed"
    else:
        r="echt opschieten doet't niet"
    
    # sinds begin
    dpag=paginas-int(first[1]);
    dtijd=nu-int(first[0]);
    d=float(dpag)/dtijd;
    d=d*60; eenheid="minuut";
    if abs(d)<0.5:
        d=d*(24*60);
        eenheid="dag";
    if abs(d)<0.5:
        d=d*7;
        eenheid="week";
    if abs(d)<0.5:
        d=d*52;
        eenheid="jaar";
    d=round(d,2);
    
    r=r+" (ongeveer "+str(d)+" per "+eenheid+")";
    piet.send(channel, r)
  except:
    traceback.print_exc();
Esempio n. 5
0
File: react.py Progetto: weary/piet
def do_search_replace(channel, nick, regmatchobj, lastchat):
	try:
		matchstring = regmatchobj.group();
		matchresult = matchstring.split('/');

		fromstring = matchresult[1];
		tostring = matchresult[2];

		if(lastchat[0:7] == "\001ACTION"):
			lastchat = "* " + nick + lastchat[7:len(lastchat)-1];

		replaceresult = lastchat.replace(fromstring, tostring);
		if(replaceresult != lastchat):
			piet.send(channel, "Volgens mij bedoelde " + nick + " dit: " + replaceresult);
			return replaceresult;
		else:
			return False;
	except:
		traceback.print_exc();
		return False;
Esempio n. 6
0
File: server.py Progetto: weary/piet
def check_names(nick_, channel_, msg_):
  global nicks
  print("check_names("+nick_+", "+channel_+", "+msg_+")\n")
  msg_nicks=msg_[msg_.find(':')+1:].split(' ')
  nicks={}
  for x in msg_nicks:
    if (x[0]=='@'):
      nicks[x[1:]]=True
    else:
      nicks[x]=False
  pietnick=piet.nick()
  if nicks[pietnick]: # piet heeft ops
    noop = [k for (k,v) in nicks.iteritems() if not v]
    op_basenames = set(k.strip('_') for k,v in nicks.iteritems() if v)
    if noop:
      qry = ("SELECT name FROM auth WHERE auth>=500 AND name IN (" +
           ','.join(['"'+x+'"' for x in noop])+")")
      dbres=piet.db(qry)
      if dbres and len(dbres)>=2:
        authusers = [x[0] for x in dbres[1:]]
        newnicks = set(n for n in authusers if n.strip('_') not in op_basenames) # only print message if user not already joined
        if len(newnicks) == 1:
          piet.send(channel_, "hup, een apenstaart voor "+list(newnicks)[0]+"\n")
        elif len(newnicks) > 1:
          piet.send(channel_, "ho, hier moet even wat gefixed worden.\n")
        piet.op(channel_, authusers)
  else: # piet niet operator
    ops=[x for (x,o) in nicks.iteritems() if o]
    if ops:
      myop=random.choice(ops)
      msg=random.choice(["mag ik een @?", "toe, doe eens een @?",
          "ik wil graag je operatortje zijn, mag ik?",
          "kijk, ik heb geen @. fix's?", "een @, ah toe?"])
      piet.send(channel_, myop+": "+msg+"\n")
  checkmessages(channel_)
Esempio n. 7
0
File: react.py Progetto: weary/piet
def get_url_title(channel, url):
	if url[0:4].lower()!="http": url="http://"+url;
	if len(url)>0 and url[-1]=='?': url=url[0:-1];
	try:
		url_input=pietlib.get_url(url);
	except:
		piet.send(channel, "nou, dat lijkt misschien wel wat op een url, maar 't bestaat niet hoor\n");
		traceback.print_exc();
		return;
	
	tinyurl="dat ding";
	if len(url)>60:
		apiurl = "http://tinyurl.com/api-create.php?url=";
		tinyurl = urllib.urlopen(apiurl + url).read();

	try:
		soup = BeautifulSoup.BeautifulSoup(url_input)
		title = soup.html.title.string
		title = ''.join(title.split('\n')[:10])
		title = re.sub('[ \t]+', ' ', title).strip()
		piet.send(channel, "de titel van "+tinyurl+" is: "+title+"\n")
		if url.find('divx.com'):
			value = dict(soup.input.attrs)['value']
			value = urllib.unquote(value)
			value = value.replace("&lt;", "<").replace("&gt;", ">").replace("&quot;", '"')
			print repr(value)
			soup2 = BeautifulSoup.BeautifulSoup(value)
			movieurl = dict(soup2.embed.attrs)['src']
			piet.send(channel, "maar eigenlijk is dit het filmpje: " + movieurl + "\n")
	except:
		traceback.print_exc()
Esempio n. 8
0
def print_kookgeschiedenis(channel, nrecords):
  try:
    records = piet.db("SELECT tijdstip,koker,eters,kosten,commentaar FROM kookbalans_mutaties ORDER BY tijdstip DESC LIMIT %d" % nrecords)

  except:
    return format_exception("probleem met database")

  if records == None or len(records) < 2:
    return "geen informatie"

  del records[0]

  for rec in records:
    tijdstip = rec[0]
    koker = rec[1]
    eters = rec[2].strip().split(" ")
    kosten = float(rec[3])
    commentaar = rec[4]

    piet.send(channel, "%s: %s" % (tijdstip, kookmelding(koker, eters, kosten, commentaar)))

  return ""
Esempio n. 9
0
File: server.py Progetto: weary/piet
def nickchange(nick_, auth_, channel_, newnick):
    global nicks
    print("nickchange(" + nick_ + ", " + str(auth_) + ", " + channel_ + ", " +
          newnick + "):\n")
    if (newnick[0] == ':'): newnick = newnick[1:]
    if (nick_ == piet.nick()):
        piet.nick(newnick)
        piet.send(
            channel_, "wat een prutnaam, dat " + nick_ +
            ", ik heet veel liever " + newnick + "\n")
    else:
        try:
            otherauth = piet.db(
                "SELECT name,auth,timezone FROM auth where name=\"" + newnick +
                "\"")[1]
        except:
            otherauth = [newnick, -5, pietlib.LOCALTIMEZONE]

        try:
            auth = piet.db(
                "SELECT name,auth,timezone FROM auth where name=\"" + nick_ +
                "\"")[1]
        except:
            auth = [nick_, -5, pietlib.LOCALTIMEZONE]

        print("nickswap: " + repr(auth) + " en " + repr(otherauth) + "\n")
        piet.db("REPLACE INTO auth VALUES(\"" + auth[0] + "\", " +
                str(otherauth[1]) + ", \"" + otherauth[2] + "\")")
        piet.db("REPLACE INTO auth VALUES(\"" + otherauth[0] + "\", " +
                str(auth[1]) + ", \"" + auth[2] + "\")")

        if (auth[1] > otherauth[1]):
            piet.send(channel_, "authenticatie "+str(auth[1])+" nu naar "+newnick+" overgezet, "+\
                nick_+" heeft 't niet meer nodig lijkt me\n")
        elif auth[1] == otherauth[1] and auth[1] > 0:
            if nick.strip('_') != nick:
                piet.send(
                    channel_, "authenticatie van " + str(nick_) + " en " +
                    newnick + " zijn gelijk, niks veranderd\n")
        elif (auth[1] < otherauth[1] and auth[1] > 0):
            piet.send(
                channel_,
                "authenticatie " + str(auth[1]) + " nu naar " + newnick +
                " overgezet, niet nickchangen om hogere auth te krijgen\n")

    if nicks.has_key(nick_):
        nicks[newnick] = nicks[nick_]
        del nicks[nick_]
    check_names_delayed(channel_)
Esempio n. 10
0
def do_search_replace(channel, nick, regmatchobj, lastchat):
    try:
        matchstring = regmatchobj.group()
        matchresult = matchstring.split('/')

        fromstring = matchresult[1]
        tostring = matchresult[2]

        if (lastchat[0:7] == "\001ACTION"):
            lastchat = "* " + nick + lastchat[7:len(lastchat) - 1]

        replaceresult = lastchat.replace(fromstring, tostring)
        if (replaceresult != lastchat):
            piet.send(
                channel,
                "Volgens mij bedoelde " + nick + " dit: " + replaceresult)
            return replaceresult
        else:
            return False
    except:
        traceback.print_exc()
        return False
Esempio n. 11
0
File: server.py Progetto: weary/piet
def check_sleep_time(nick_, auth_, channel_, command_, msg_):
    print("check_sleep_time(" + nick_ + ", " + str(auth_) + ", " + channel_ +
          ", " + command_ + ", " + msg_ + ")\n")
    # CREATE TABLE logout(
    #    channel string, nick string, tijd int, reason string,
    #    primary key (channel,nick));

    chan = channel_.replace('"', '""').lower()
    nick = nick_.replace('"', '""').lower()
    if (command_ in ["PART", "QUIT", "KICK"]):
        tijd = str(int(time.time() + 0.5))
        reason = msg_[5:].replace('"', '""')
        query = 'REPLACE INTO logout VALUES("' + chan + '", "' + nick + '", ' + tijd + ', "' + reason + '")'
        piet.db(query)
    elif (command_ in ["JOIN"]):
        try:
            where = 'WHERE channel="' + chan + '" and nick="' + nick + '"'
            dbtijd = piet.db('SELECT tijd FROM logout ' + where)
            piet.db('DELETE FROM logout ' + where)
            if dbtijd and len(dbtijd) >= 2:
                tu = int(time.time() + 0.5) - int(dbtijd[1][0])
            else:
                tu = -1

            titel = random.choice(
                ("heer", "meester", "prins", "gast", "joker", "orgelspeler",
                 "held", "bedwinger", "plaag", "buitenlander", "mastermind",
                 "heerser", "samensteller"))
            subtitel = random.choice(
                ("des duisternis", "van het licht", "des ubers", "des modders",
                 "des oordeels", "van de knaagdieren", "overste", "ongezien",
                 "enzo", "extraordinaire", "(gevallen)", "in rust",
                 "ten strijde", "(onverschrokken)", "van iedereen",
                 "van deze wereld", "in de dop", "(te jong)"))

            reply = "ACTION presenteert: %s, %s %s" % (nick, titel, subtitel)

            nicks_stripped = set(n.strip('_') for n in nicks.keys())
            if nick.strip('_') in nicks_stripped:
                print "user %s was al gejoined, geen groet" % nick
            elif tu > 0:
                reply = reply + ", weer terug na " + pietlib.format_tijdsduur(
                    tu, 2)
                try:
                    gemiddeld = doe_gemiddelde_offlinetijd(channel_, nick_, tu)
                    reply += ", gemiddeld %s nu" % pietlib.format_tijdsduur(
                        gemiddeld, 2)
                except:
                    traceback.print_exc()
                    reply += ", geen gemiddelde"
                piet.send(channel_, reply + ".\n")
            elif tu == 0:
                piet.send(channel_,
                          "blijkbaar is " + nick_ + " aan het fietsen\n")
        except:
            traceback.print_exc()
            piet.send(channel_, "Hee " + nick_ + "!\n")
Esempio n. 12
0
File: server.py Progetto: weary/piet
def check_sleep_time(nick_, auth_, channel_, command_, msg_):
  print("check_sleep_time("+nick_+", "+str(auth_)+", "+channel_+", "+command_+", "+msg_+")\n");
  # CREATE TABLE logout(
  #    channel string, nick string, tijd int, reason string,
  #    primary key (channel,nick));

  chan=channel_.replace('"', '""').lower();
  nick=nick_.replace('"', '""').lower();
  if (command_ in ["PART", "QUIT", "KICK"]):
    tijd=str(int(time.time()+0.5));
    reason=msg_[5:].replace('"', '""');
    query='REPLACE INTO logout VALUES("'+chan+'", "'+nick+'", '+tijd+', "'+reason+'")';
    piet.db(query);
  elif (command_ in ["JOIN"]):
    try:
      where='WHERE channel="' + chan + '" and nick="' + nick + '"'
      dbtijd = piet.db('SELECT tijd FROM logout ' + where)
      piet.db('DELETE FROM logout ' + where)
      if dbtijd and len(dbtijd) >= 2:
        tu = int(time.time()+0.5) - int(dbtijd[1][0])
      else:
        tu = -1

      titel=random.choice(("heer", "meester", "prins", "gast", "joker",
        "orgelspeler", "held", "bedwinger", "plaag", "buitenlander", "mastermind",
        "heerser", "samensteller"))
      subtitel=random.choice(("des duisternis", "van het licht", "des ubers",
        "des modders", "des oordeels", "van de knaagdieren", "overste",
        "ongezien", "enzo", "extraordinaire", "(gevallen)",
        "in rust", "ten strijde", "(onverschrokken)", "van iedereen", "van deze wereld",
        "in de dop", "(te jong)"))
        
      reply = "ACTION presenteert: %s, %s %s" % (nick, titel, subtitel)

      nicks_stripped = set(n.strip('_') for n in nicks.keys())
      if nick.strip('_') in nicks_stripped:
        print "user %s was al gejoined, geen groet" % nick
      elif tu>0:
        reply = reply + ", weer terug na " + pietlib.format_tijdsduur(tu, 2)
        try:
          gemiddeld = doe_gemiddelde_offlinetijd(channel_, nick_, tu)
          reply += ", gemiddeld %s nu" % pietlib.format_tijdsduur(gemiddeld, 2)
        except:
          traceback.print_exc()
          reply += ", geen gemiddelde"
        piet.send(channel_, reply+".\n")
      elif tu==0:
        piet.send(channel_, "blijkbaar is "+nick_+" aan het fietsen\n")
    except:
      traceback.print_exc()
      piet.send(channel_, "Hee "+nick_+"!\n")
Esempio n. 13
0
File: server.py Progetto: weary/piet
def nickchange(nick_, auth_, channel_, newnick):
  global nicks;
  print("nickchange("+nick_+", "+str(auth_)+", "+channel_+", "+newnick+"):\n");
  if (newnick[0]==':'): newnick=newnick[1:];
  if (nick_==piet.nick()):
    piet.nick(newnick);
    piet.send(channel_, "wat een prutnaam, dat "+nick_+", ik heet veel liever "+newnick+"\n");
  else:
    try:
      otherauth=piet.db("SELECT name,auth,timezone FROM auth where name=\""+newnick+"\"")[1];
    except:
      otherauth=[newnick, -5, pietlib.LOCALTIMEZONE];

    try:
      auth=piet.db("SELECT name,auth,timezone FROM auth where name=\""+nick_+"\"")[1];
    except:
      auth=[nick_, -5, pietlib.LOCALTIMEZONE];

    print("nickswap: "+repr(auth)+" en "+repr(otherauth)+"\n");
    piet.db("REPLACE INTO auth VALUES(\""+auth[0]+"\", "+str(otherauth[1])+", \""+otherauth[2]+"\")");
    piet.db("REPLACE INTO auth VALUES(\""+otherauth[0]+"\", "+str(auth[1])+", \""+auth[2]+"\")");

    if (auth[1]>otherauth[1]):
      piet.send(channel_, "authenticatie "+str(auth[1])+" nu naar "+newnick+" overgezet, "+\
          nick_+" heeft 't niet meer nodig lijkt me\n")
    elif auth[1] == otherauth[1] and auth[1]>0:
      if nick.strip('_') != nick:
        piet.send(channel_, "authenticatie van "+str(nick_)+" en "+newnick+ " zijn gelijk, niks veranderd\n")
    elif (auth[1]<otherauth[1] and auth[1]>0):
      piet.send(channel_, "authenticatie "+str(auth[1])+" nu naar "+newnick+
          " overgezet, niet nickchangen om hogere auth te krijgen\n")
  
  if nicks.has_key(nick_):
    nicks[newnick]=nicks[nick_];
    del nicks[nick_];
  check_names_delayed(channel_);
Esempio n. 14
0
File: server.py Progetto: weary/piet
def check_names(nick_, channel_, msg_):
    global nicks
    print("check_names(" + nick_ + ", " + channel_ + ", " + msg_ + ")\n")
    msg_nicks = msg_[msg_.find(':') + 1:].split(' ')
    nicks = {}
    for x in msg_nicks:
        if (x[0] == '@'):
            nicks[x[1:]] = True
        else:
            nicks[x] = False
    pietnick = piet.nick()
    if nicks[pietnick]:  # piet heeft ops
        noop = [k for (k, v) in nicks.iteritems() if not v]
        op_basenames = set(k.strip('_') for k, v in nicks.iteritems() if v)
        if noop:
            qry = ("SELECT name FROM auth WHERE auth>=500 AND name IN (" +
                   ','.join(['"' + x + '"' for x in noop]) + ")")
            dbres = piet.db(qry)
            if dbres and len(dbres) >= 2:
                authusers = [x[0] for x in dbres[1:]]
                newnicks = set(
                    n for n in authusers if n.strip('_') not in op_basenames
                )  # only print message if user not already joined
                if len(newnicks) == 1:
                    piet.send(
                        channel_,
                        "hup, een apenstaart voor " + list(newnicks)[0] + "\n")
                elif len(newnicks) > 1:
                    piet.send(channel_,
                              "ho, hier moet even wat gefixed worden.\n")
                piet.op(channel_, authusers)
    else:  # piet niet operator
        ops = [x for (x, o) in nicks.iteritems() if o]
        if ops:
            myop = random.choice(ops)
            msg = random.choice([
                "mag ik een @?", "toe, doe eens een @?",
                "ik wil graag je operatortje zijn, mag ik?",
                "kijk, ik heb geen @. fix's?", "een @, ah toe?"
            ])
            piet.send(channel_, myop + ": " + msg + "\n")
    checkmessages(channel_)
Esempio n. 15
0
def get_url_title(channel, url):
    if url[0:4].lower() != "http": url = "http://" + url
    if len(url) > 0 and url[-1] == '?': url = url[0:-1]
    try:
        url_input = pietlib.get_url(url)
    except:
        piet.send(
            channel,
            "nou, dat lijkt misschien wel wat op een url, maar 't bestaat niet hoor\n"
        )
        traceback.print_exc()
        return

    tinyurl = "dat ding"
    if len(url) > 60:
        apiurl = "http://tinyurl.com/api-create.php?url="
        tinyurl = urllib.urlopen(apiurl + url).read()

    try:
        soup = BeautifulSoup.BeautifulSoup(url_input)
        title = soup.html.title.string
        title = ''.join(title.split('\n')[:10])
        title = re.sub('[ \t]+', ' ', title).strip()
        piet.send(channel, "de titel van " + tinyurl + " is: " + title + "\n")
        if url.find('divx.com'):
            value = dict(soup.input.attrs)['value']
            value = urllib.unquote(value)
            value = value.replace("&lt;",
                                  "<").replace("&gt;",
                                               ">").replace("&quot;", '"')
            print repr(value)
            soup2 = BeautifulSoup.BeautifulSoup(value)
            movieurl = dict(soup2.embed.attrs)['src']
            piet.send(channel,
                      "maar eigenlijk is dit het filmpje: " + movieurl + "\n")
    except:
        traceback.print_exc()
Esempio n. 16
0
File: ns.py Progetto: weary/piet
def ns(regel, channel):
	def format_station(x_org, opmerkingen):
		x = {  # common typo's
			'rtc': 'rtd',
			'utc': 'ut'
		}.get(x_org, x_org)
		if x != x_org:
			opmerkingen.append((x, x_org))
		if (x[0]=='"' and x[-1]=='"') or (x[0]=="'" and x[-1]=="'"):
			x = x[1:-1]
		y = stations.to_short(x)
		if not y:
			return x
		if x!=y:
			opmerkingen.append((y,stations.to_long(y)))
		return y

	pietlib.timezone_reset()

	if regel == "?":
		result = pietlib.get_url_soup("http://mobiel.ns.nl/storingen.action")
		storingen = [ str(i.contents[0]) for i in result.body.findAll('h4') ]
		storingen = [ i for i in storingen if i !='Disruptions (in Dutch)' ]
		if len(storingen) > 8:
			return "het is weer's helemaal stuk, met %d gemelde storingen: %s" % (
					len(storingen), pietlib.make_list(storingen))
		elif storingen:
			return "er zijn %d storingen op:\n  %s" % (
					len(storinger) + "\n  ".join(storingen))
		else:
			return "er zijn geen storingen"

	if regel.lower().startswith("afk") or regel.lower().startswith("accr"):
		naam = regel.split(' ', 1)[1:]
		if not naam:
			return "ja, ik wil je best afkortingen geven, ook wel van stations"
		s = stations.to_short(naam[0])
		if not s:
			return "beter dan '%s' wordt het niet, daar is geen afkorting voor" % naam[0]
		return '%s (%s)' % (s, stations.to_long(s))

	qs = """\s*((?:["][^"]*["])|(?:['][^']*['])|(?:[^'"]\S*))\s*"""
	full = (
		"(?:van)?"+qs+
		"(?:naar)?"+qs+
		"(?:via"+qs+")?"+
		"(om|v\S*|a\S*)?\s*(\d+:\d{2})?\s*(hsl)?")

	r = re.match(full, regel)
	if not(r):
		return "uh, dus je wilt met de trein. verder snapte ik het allemaal niet"
	(van, naar, via, tijdtype, tijd, hsl) = r.groups()
	opmerkingen = []
	van = format_station(van, opmerkingen)
	naar = format_station(naar, opmerkingen)
	via = via and format_station(via, opmerkingen) or ""
	datum = time.strftime("%d-%m-%Y")
	tijdtype = not(tijdtype) or tijdtype=="om" or tijdtype[0]=="v"

	if opmerkingen:
		opm = [ "\002%s\002 voor %s" % (s,l) for s,l in opmerkingen ]
		piet.send(channel, "%s was korter geweest" % pietlib.make_list(opm))

	print "NS: van %s naar %s via %s %stijd %s" % (repr(van), repr(naar), repr(via), tijdtype and "vertrek" or "aankomst", repr(tijd))

	# test ns site en haal cookies
	cookies = []
	pietlib.get_url("http://mobiel.ns.nl/planner.action?lang=nl", outcookies=cookies, headers=[('Accept','text/html')])
	cookies = [ re.sub(';.*', '', c) for c in cookies ]

	postdata = {
		'from':van, 'to':naar, 'via':via,
		'date':datum, 'time':tijd, 'departure':(tijdtype and 'true' or 'false'),
		'planroute':'Reisadvies',
		'hsl':(hsl and 'true' or 'false')}

	for retrycount in range(1): # try max 5 times to get a correct page
		page = pietlib.get_url("http://mobiel.ns.nl/planner.action", postdata, incookies=cookies, headers=[('Accept','text/html')])
		open("nsresult.html", "w").write(page)
		reisadvies, page, errors = ns_format_page(page)
		if reisadvies or errors:
			break
	if errors:
		return '\n'.join(errors)
	return page
Esempio n. 17
0
File: server.py Progetto: weary/piet
def do_server(channel_, nick_, auth_, msg_):
  global nicks,topic;
  print("do_server("+nick_+", "+str(auth_)+", "+channel_+", "+msg_+")\n");
  command=msg_.split(' ')[0].upper();
  netsplit=False;
  if command in ["JOIN", "PART", "QUIT", "KICK"]:
    if auth_>0:
      print("check_netsplit("+nick_+", "+channel_+", "+command+", "+msg_+"): ");
      netsplit=check_netsplit(nick_, channel_, command, msg_);
      print(repr(netsplit)+"\n");
      if not(netsplit):
        check_sleep_time(nick_, auth_, channel_, command, msg_);
    check_names_delayed(channel_);
  if command in ["PART", "QUIT"]:
    try:
      del nicks[nick_];
    except:
      piet.send(channel_, "voor jullie informatie: het schijnt dat er hier een "+nick_+" was, maar ik heb 'm niet gezien\n");
  if command in ["KICK"] and auth_>0:
    kicknick=msg_.split(' ')[2];
    piet.send(channel_, "en waag het niet om weer te komen, jij vuile "+kicknick+"!\n");
    try:
      del nicks[nick_];
    except:
      piet.send(channel_, "niet dat je er was, maar toch\n");
  if command in ["NICK"]:
    nickchange(nick_, auth_, channel_, msg_[5:]);
  if command in ["437"] and auth_>0:
    piet.send(channel_, "bah, die nick is even niet beschikbaar\n");
  if command in ["353"]:
    check_names(nick_, channel_, msg_);
  if command in ["TOPIC"]:
    nu = time.time()
    newtopic = msg_.split(' ', 1)[1]
    if newtopic.find(':')>=0:
      newtopic = newtopic[newtopic.find(':')+1:]
    if topic:
      delay = nu-topic[-1][0]
      if delay>3*60*60 and topic[-1][1]!=newtopic:
        piet.send(channel_, "\002oude\002 topic van \002%s\002 geleden: %s" % (pietlib.format_tijdsduur(delay,1), topic[-1][1]));
    topic.append((nu, newtopic))
    print "topic lijst bevat nu:", repr(topic)
  if command in ["MODE"] and auth_>0:
    if ((msg_.find(' +o')>=0) or (msg_.find(' -o')>=0)):
      check_names_delayed(channel_);
    else:
      if not(netsplit):
        piet.send(channel_, 'server riep "'+msg_+'", maar dat interesseert echt helemaal niemand\n');
Esempio n. 18
0
def do_react(channel, nick, auth_, line):
    reactfile = "react.txt"
    loosfile = "loos.txt"
    logfile = "log.txt"

    pietnick = piet.nick()
    line = line.replace(pietnick, "piet")

    # ok, alles in een file
    lines = open(reactfile).read().split('\n')

    # laatste regel even in een logfile
    open(logfile, "a+").write(line + "\n")

    ready = False

    if lastnicklog.has_key(nick) and lastnicklog[nick] == line:
        r = random.choice([
            "ja, zeg het vooral nog's", "spannend hoor, zo'n herhaling",
            "gave opmerking, zeg", "blij dat je dat nog's zegt", line,
            "ah, ja, dat. verstond je niet de 1e keer", "s/" + line + "//"
        ])
        piet.send(channel, r + "\n")
        ready = True

    if line[:1] == '\x01' and line[-1:] == '\x01':
        line = line[1:-1]

    # check for url's in the input
    urlmatch = re.search("((https?://|www\.)[^ \t,]*)", line)
    if (urlmatch):
        get_url_title(channel, urlmatch.group(0))
        ready = True

    paginamatch = re.search("([0-9]{2,3})[ ]*pagina", line)
    if (paginamatch):
        check_pagina(channel, nick, paginamatch.group(1))
        ready = True

    nicklogset = False
    if not (ready):
        try:
            srmatch = re.match("^(s[/][A-Za-z0-9 ]+[/][A-Za-z0-9 ]*[/]?)$",
                               line)
            if srmatch:
                sr_result = do_search_replace(channel, nick, srmatch,
                                              lastnicklog[nick])
                if sr_result:
                    lastnicklog[nick] = sr_result
                    nicklogset = True
                    ready = True
        except:
            # Not gonna happen
            traceback.print_exc()

    if not (nicklogset):
        lastnicklog[nick] = line

    random.seed()
    i = 0
    result = ""
    while (i < len(lines)) and not (ready):
        try:
            excludethis = False
            if (lines[i].count('#') == 2):
                (keyw, chance, reactline) = lines[i].split('#')
                exclude = ""
            else:
                (keyw, chance, reactline, exclude) = lines[i].split('#', 3)
                if (exclude.count('#') == 0):
                    excludethis = (line.find(exclude) != -1)
                else:
                    for excludeword in exclude.split('#'):
                        if (line.find(excludeword) != -1):
                            excludethis = True
            r = random.random()

            if not (excludethis):
                if (line.find(keyw) != -1) and (random.random() <=
                                                float(chance)):
                    ready = True
                    result = reactline
        except:
            result = ""
        i = i + 1

    if not (ready):
        r = random.random()
        if (r <= 0.06):
            if globals().has_key("geordi") and (random.random() < 0.08):
                n = random.randint(1, 4000)
                time.sleep(n)
                result = geordi("bla")
            else:
                inf = open(loosfile)
                lines = inf.read().split('\n')
                inf.close()
                result = random.choice(lines)

    if result[:6] == "ACTION":
        result = "\001" + result + "\001"
    if (len(result) > 0):
        result = result.replace("NICK", nick)
        result = result.replace("piet", pietnick)
        piet.send(channel, result + "\n")
Esempio n. 19
0
def ns(regel, channel):
    def format_station(x_org, opmerkingen):
        x = {  # common typo's
            'rtc': 'rtd',
            'utc': 'ut'
        }.get(x_org, x_org)
        if x != x_org:
            opmerkingen.append((x, x_org))
        if (x[0] == '"' and x[-1] == '"') or (x[0] == "'" and x[-1] == "'"):
            x = x[1:-1]
        y = stations.to_short(x)
        if not y:
            return x
        if x != y:
            opmerkingen.append((y, stations.to_long(y)))
        return y

    pietlib.timezone_reset()

    if regel == "?":
        result = pietlib.get_url_soup("http://mobiel.ns.nl/storingen.action")
        storingen = [str(i.contents[0]) for i in result.body.findAll('h4')]
        storingen = [i for i in storingen if i != 'Disruptions (in Dutch)']
        if len(storingen) > 8:
            return "het is weer's helemaal stuk, met %d gemelde storingen: %s" % (
                len(storingen), pietlib.make_list(storingen))
        elif storingen:
            return "er zijn %d storingen op:\n  %s" % (len(storinger) +
                                                       "\n  ".join(storingen))
        else:
            return "er zijn geen storingen"

    if regel.lower().startswith("afk") or regel.lower().startswith("accr"):
        naam = regel.split(' ', 1)[1:]
        if not naam:
            return "ja, ik wil je best afkortingen geven, ook wel van stations"
        s = stations.to_short(naam[0])
        if not s:
            return "beter dan '%s' wordt het niet, daar is geen afkorting voor" % naam[
                0]
        return '%s (%s)' % (s, stations.to_long(s))

    qs = """\s*((?:["][^"]*["])|(?:['][^']*['])|(?:[^'"]\S*))\s*"""
    full = ("(?:van)?" + qs + "(?:naar)?" + qs + "(?:via" + qs + ")?" +
            "(om|v\S*|a\S*)?\s*(\d+:\d{2})?\s*(hsl)?")

    r = re.match(full, regel)
    if not (r):
        return "uh, dus je wilt met de trein. verder snapte ik het allemaal niet"
    (van, naar, via, tijdtype, tijd, hsl) = r.groups()
    opmerkingen = []
    van = format_station(van, opmerkingen)
    naar = format_station(naar, opmerkingen)
    via = via and format_station(via, opmerkingen) or ""
    datum = time.strftime("%d-%m-%Y")
    tijdtype = not (tijdtype) or tijdtype == "om" or tijdtype[0] == "v"

    if opmerkingen:
        opm = ["\002%s\002 voor %s" % (s, l) for s, l in opmerkingen]
        piet.send(channel, "%s was korter geweest" % pietlib.make_list(opm))

    print "NS: van %s naar %s via %s %stijd %s" % (repr(van), repr(
        naar), repr(via), tijdtype and "vertrek" or "aankomst", repr(tijd))

    # test ns site en haal cookies
    cookies = []
    pietlib.get_url("http://mobiel.ns.nl/planner.action?lang=nl",
                    outcookies=cookies,
                    headers=[('Accept', 'text/html')])
    cookies = [re.sub(';.*', '', c) for c in cookies]

    postdata = {
        'from': van,
        'to': naar,
        'via': via,
        'date': datum,
        'time': tijd,
        'departure': (tijdtype and 'true' or 'false'),
        'planroute': 'Reisadvies',
        'hsl': (hsl and 'true' or 'false')
    }

    for retrycount in range(1):  # try max 5 times to get a correct page
        page = pietlib.get_url("http://mobiel.ns.nl/planner.action",
                               postdata,
                               incookies=cookies,
                               headers=[('Accept', 'text/html')])
        open("nsresult.html", "w").write(page)
        reisadvies, page, errors = ns_format_page(page)
        if reisadvies or errors:
            break
    if errors:
        return '\n'.join(errors)
    return page
Esempio n. 20
0
File: server.py Progetto: weary/piet
def do_server(channel_, nick_, auth_, msg_):
    global nicks, topic
    print("do_server(" + nick_ + ", " + str(auth_) + ", " + channel_ + ", " +
          msg_ + ")\n")
    command = msg_.split(' ')[0].upper()
    netsplit = False
    if command in ["JOIN", "PART", "QUIT", "KICK"]:
        if auth_ > 0:
            print("check_netsplit(" + nick_ + ", " + channel_ + ", " +
                  command + ", " + msg_ + "): ")
            netsplit = check_netsplit(nick_, channel_, command, msg_)
            print(repr(netsplit) + "\n")
            if not (netsplit):
                check_sleep_time(nick_, auth_, channel_, command, msg_)
        check_names_delayed(channel_)
    if command in ["PART", "QUIT"]:
        try:
            del nicks[nick_]
        except:
            piet.send(
                channel_,
                "voor jullie informatie: het schijnt dat er hier een " +
                nick_ + " was, maar ik heb 'm niet gezien\n")
    if command in ["KICK"] and auth_ > 0:
        kicknick = msg_.split(' ')[2]
        piet.send(
            channel_,
            "en waag het niet om weer te komen, jij vuile " + kicknick + "!\n")
        try:
            del nicks[nick_]
        except:
            piet.send(channel_, "niet dat je er was, maar toch\n")
    if command in ["NICK"]:
        nickchange(nick_, auth_, channel_, msg_[5:])
    if command in ["437"] and auth_ > 0:
        piet.send(channel_, "bah, die nick is even niet beschikbaar\n")
    if command in ["353"]:
        check_names(nick_, channel_, msg_)
    if command in ["TOPIC"]:
        nu = time.time()
        newtopic = msg_.split(' ', 1)[1]
        if newtopic.find(':') >= 0:
            newtopic = newtopic[newtopic.find(':') + 1:]
        if topic:
            delay = nu - topic[-1][0]
            if delay > 3 * 60 * 60 and topic[-1][1] != newtopic:
                piet.send(
                    channel_, "\002oude\002 topic van \002%s\002 geleden: %s" %
                    (pietlib.format_tijdsduur(delay, 1), topic[-1][1]))
        topic.append((nu, newtopic))
        print "topic lijst bevat nu:", repr(topic)
    if command in ["MODE"] and auth_ > 0:
        if ((msg_.find(' +o') >= 0) or (msg_.find(' -o') >= 0)):
            check_names_delayed(channel_)
        else:
            if not (netsplit):
                piet.send(
                    channel_, 'server riep "' + msg_ +
                    '", maar dat interesseert echt helemaal niemand\n')
Esempio n. 21
0
File: ov9292.py Progetto: weary/piet
def ov9292(param,nick,channel):
    print("ov start");
    par=re.match("[ ]*(optie|keuze)?[ ]*([abcdefABCDEF123456])[ ]*$", param)
    if par:
        # probeer oude resultaten op te halen
        nr=par.group(2);
        if nr.isdigit():
            nr=int(nr)-1;
        elif nr>='a' and nr<='z':
            nr=ord(nr)-ord('a');
        else:
            nr=ord(nr)-ord('A');
        
        if not(ovresults.has_key(nick)):
            return "maar ik heb helemaal geen reizen opgeslagen voor jou, "+nick;
        results=ovresults[nick];
        if nr>=len(results):
            return "d'r is vast een resultaat zoekgeraakt ofzo, kan nr "+str(nr+1)+" niet vinden";
        return results[nr];            
   
    print("ov zoektocht");
    # nieuwe zoekopdracht
    tz=pietlib.tijdzone_nick(nick);
    regex=\
    '(["]([^"]*)["]|([^"][^ ]*))[ ]+(["]([^"]*)["]|([^"][^ ]*))[ ]*'+\
    '(vertrek|aankomst)?[ ]*(.*)';
    par=re.match(regex, param);
    if not(par):
        return 'ik snap d\'r geen hout van, parameters moeten zijn: '\
        '"<van>" "<naar>" vertrek|aankomst datum tijd'
    van=par.group(2) or par.group(3);
    naar=par.group(5) or par.group(6);
    vertrek='D';
    if par.group(7) and par.group(7).strip()=="aankomst":
        vertrek='A';
    tijd=time.time()+10*60; # geen tijd opgegeven -> over 10 minuten
    tijdstr=par.group(8).strip();
    if len(tijdstr)>0:
        try:
            tijd=pietlib.parse_tijd(tijdstr,tz);
        except:
            return 'De datum+tijd '+tijdstr+' snap ik niet, sorry';
   
    print("ov van \""+van+"\" naar \""+naar+"\" om "+str(tijd));

    # get frontpage
    print("ov 1");
    action,actionpath,q,form=do_fetch("", "", {});

    print("ov 2");
    # get from-radiobuttons
    action,actionpath,q,form=do_fetch(action, actionpath, q);

    print("ov 3");
    if van.find(',')>=0:
        action,actionpath,q,form=do_plaats(van, action, actionpath, q, channel);
    else:
        action,actionpath,q,form=do_station(van, action, actionpath, q, channel);

    print("ov 4");
    if naar.find(',')>=0:
        action,actionpath,q,form=do_plaats(naar, action, actionpath, q, channel);
    else:
        action,actionpath,q,form=do_station(naar, action, actionpath, q, channel);
    
    print("ov 5");
    # tijd/datum
    os.environ['TZ']="Europe/Amsterdam";
    time.tzset();
    tijdstruct=time.localtime(tijd);
    q["d"]=time.strftime("%Y-%m-%d", tijdstruct);
    q["u"]=time.strftime("%H", tijdstruct);
    q["m"]=time.strftime("%M", tijdstruct);
    q["v"]=vertrek; # D=vertrek, A=aankomst
    pietlib.timezone_reset();

    action,actionpath,q,form=do_fetch(action, actionpath, q);

    regex=\
    "<tr><td>(Ver[^&]*)[^<]*<[/]td><td[^>]*>([^<]*)<[/]td><[/]tr>[^<]*"+\
    "<tr><td>([^&]*)[^<]*<[/]td><td[^>]*>([^<]*)<[/]td><[/]tr>[^<]*"+\
    "<tr><td>([^&]*)[^<]*<[/]td><td[^>]*>([^<]*)<[/]td><[/]tr>[^<]*"+\
    "<tr><td>([^&]*)[^<]*<[/]td><td[^>]*>([^<]*)<[/]td><[/]tr>[^<]*"+\
    "<tr><td [^>]*><a (href)=\"([^>]*)\">[^>]*><[/]td><[/]tr>"+\
    "";
    results=re.findall(regex, form, re.DOTALL|re.IGNORECASE);
    print("ov 6 (done, fetching individual results)");
    if len(results)==0:
      piet.send(channel, "9292mobiel site is weer stuk, blijkbaar. ik heb een leeg lijstje gekregen.");

    r=[];
    for i in results:
        piet.send(channel, i[0]+": "+i[1]+", "+i[2]+": "+i[3]+", "+i[4]+": "+i[5]+", "+i[6]+\
        ": "+i[7]+" (zeg \""+piet.nick()+": ov "+("ABCDEF"[len(r)])+"\")");
        qs=i[9];
        url=ov9292url+actionpath+qs.replace("&amp;", "&");
        raw=pietlib.get_url(url);
        res=re.findall(\
        "<tr><td><span class='kop'>([^<]*)<[/]span>"+\
        "<span class='kopn'>([^<]*)<[/]span>"\
        "</td></tr><tr><td class='kopn'>([^<]*)</td></tr>", raw, re.DOTALL|re.IGNORECASE);
        r.append('\n'.join([' '.join(i) for i in res]));
        print("ov got an individual result");
    ovresults[nick]=r;
    print("ov done\n");
    return "";
Esempio n. 22
0
File: ov9292.py Progetto: weary/piet
def niet_herkent(channel, what, choice, choices):
  choices.remove(choice);
  msg=what+" niet herkend, ik pak "+choice;
  if len(choices)>0:
    msg=msg+" (en niet "+pietlib.make_list(choices, "of")+")";
  piet.send(channel,msg);
Esempio n. 23
0
File: ov9292.py Progetto: weary/piet
def niet_herkent(channel, what, choice, choices):
    choices.remove(choice)
    msg = what + " niet herkend, ik pak " + choice
    if len(choices) > 0:
        msg = msg + " (en niet " + pietlib.make_list(choices, "of") + ")"
    piet.send(channel, msg)
Esempio n. 24
0
File: ov9292.py Progetto: weary/piet
def ov9292(param, nick, channel):
    print("ov start")
    par = re.match("[ ]*(optie|keuze)?[ ]*([abcdefABCDEF123456])[ ]*$", param)
    if par:
        # probeer oude resultaten op te halen
        nr = par.group(2)
        if nr.isdigit():
            nr = int(nr) - 1
        elif nr >= 'a' and nr <= 'z':
            nr = ord(nr) - ord('a')
        else:
            nr = ord(nr) - ord('A')

        if not (ovresults.has_key(nick)):
            return "maar ik heb helemaal geen reizen opgeslagen voor jou, " + nick
        results = ovresults[nick]
        if nr >= len(results):
            return "d'r is vast een resultaat zoekgeraakt ofzo, kan nr " + str(
                nr + 1) + " niet vinden"
        return results[nr]

    print("ov zoektocht")
    # nieuwe zoekopdracht
    tz = pietlib.tijdzone_nick(nick)
    regex=\
    '(["]([^"]*)["]|([^"][^ ]*))[ ]+(["]([^"]*)["]|([^"][^ ]*))[ ]*'+\
    '(vertrek|aankomst)?[ ]*(.*)'
    par = re.match(regex, param)
    if not (par):
        return 'ik snap d\'r geen hout van, parameters moeten zijn: '\
        '"<van>" "<naar>" vertrek|aankomst datum tijd'
    van = par.group(2) or par.group(3)
    naar = par.group(5) or par.group(6)
    vertrek = 'D'
    if par.group(7) and par.group(7).strip() == "aankomst":
        vertrek = 'A'
    tijd = time.time() + 10 * 60
    # geen tijd opgegeven -> over 10 minuten
    tijdstr = par.group(8).strip()
    if len(tijdstr) > 0:
        try:
            tijd = pietlib.parse_tijd(tijdstr, tz)
        except:
            return 'De datum+tijd ' + tijdstr + ' snap ik niet, sorry'

    print("ov van \"" + van + "\" naar \"" + naar + "\" om " + str(tijd))

    # get frontpage
    print("ov 1")
    action, actionpath, q, form = do_fetch("", "", {})

    print("ov 2")
    # get from-radiobuttons
    action, actionpath, q, form = do_fetch(action, actionpath, q)

    print("ov 3")
    if van.find(',') >= 0:
        action, actionpath, q, form = do_plaats(van, action, actionpath, q,
                                                channel)
    else:
        action, actionpath, q, form = do_station(van, action, actionpath, q,
                                                 channel)

    print("ov 4")
    if naar.find(',') >= 0:
        action, actionpath, q, form = do_plaats(naar, action, actionpath, q,
                                                channel)
    else:
        action, actionpath, q, form = do_station(naar, action, actionpath, q,
                                                 channel)

    print("ov 5")
    # tijd/datum
    os.environ['TZ'] = "Europe/Amsterdam"
    time.tzset()
    tijdstruct = time.localtime(tijd)
    q["d"] = time.strftime("%Y-%m-%d", tijdstruct)
    q["u"] = time.strftime("%H", tijdstruct)
    q["m"] = time.strftime("%M", tijdstruct)
    q["v"] = vertrek
    # D=vertrek, A=aankomst
    pietlib.timezone_reset()

    action, actionpath, q, form = do_fetch(action, actionpath, q)

    regex=\
    "<tr><td>(Ver[^&]*)[^<]*<[/]td><td[^>]*>([^<]*)<[/]td><[/]tr>[^<]*"+\
    "<tr><td>([^&]*)[^<]*<[/]td><td[^>]*>([^<]*)<[/]td><[/]tr>[^<]*"+\
    "<tr><td>([^&]*)[^<]*<[/]td><td[^>]*>([^<]*)<[/]td><[/]tr>[^<]*"+\
    "<tr><td>([^&]*)[^<]*<[/]td><td[^>]*>([^<]*)<[/]td><[/]tr>[^<]*"+\
    "<tr><td [^>]*><a (href)=\"([^>]*)\">[^>]*><[/]td><[/]tr>"+\
    ""
    results = re.findall(regex, form, re.DOTALL | re.IGNORECASE)
    print("ov 6 (done, fetching individual results)")
    if len(results) == 0:
        piet.send(
            channel,
            "9292mobiel site is weer stuk, blijkbaar. ik heb een leeg lijstje gekregen."
        )

    r = []
    for i in results:
        piet.send(channel, i[0]+": "+i[1]+", "+i[2]+": "+i[3]+", "+i[4]+": "+i[5]+", "+i[6]+\
        ": "+i[7]+" (zeg \""+piet.nick()+": ov "+("ABCDEF"[len(r)])+"\")")
        qs = i[9]
        url = ov9292url + actionpath + qs.replace("&amp;", "&")
        raw = pietlib.get_url(url)
        res=re.findall(\
        "<tr><td><span class='kop'>([^<]*)<[/]span>"+\
        "<span class='kopn'>([^<]*)<[/]span>"\
        "</td></tr><tr><td class='kopn'>([^<]*)</td></tr>", raw, re.DOTALL|re.IGNORECASE)
        r.append('\n'.join([' '.join(i) for i in res]))
        print("ov got an individual result")
    ovresults[nick] = r
    print("ov done\n")
    return ""
Esempio n. 25
0
File: react.py Progetto: weary/piet
def do_react(channel, nick, auth_, line):
	reactfile = "react.txt"
	loosfile = "loos.txt"
	logfile = "log.txt"

	pietnick = piet.nick()
	line = line.replace(pietnick, "piet");

	# ok, alles in een file
	lines = open(reactfile).read().split('\n')

	# laatste regel even in een logfile
	open(logfile, "a+").write(line+"\n")

	ready=False;

	if lastnicklog.has_key(nick) and lastnicklog[nick]==line:
		r=random.choice([
				"ja, zeg het vooral nog's",
				"spannend hoor, zo'n herhaling",
				"gave opmerking, zeg",
				"blij dat je dat nog's zegt",
				line,
				"ah, ja, dat. verstond je niet de 1e keer",
				"s/"+line+"//"]);
		piet.send(channel, r+"\n");
		ready=True;
	
	if line[:1] == '\x01' and line[-1:] == '\x01':
		line = line[1:-1]

	# check for url's in the input
	urlmatch=re.search("((https?://|www\.)[^ \t,]*)", line);
	if (urlmatch):
		get_url_title(channel, urlmatch.group(0));
		ready=True;

	paginamatch=re.search("([0-9]{2,3})[ ]*pagina", line);
	if (paginamatch):
		check_pagina(channel, nick, paginamatch.group(1));
		ready=True;

	nicklogset = False;
	if not(ready):
		try:
			srmatch = re.match("^(s[/][A-Za-z0-9 ]+[/][A-Za-z0-9 ]*[/]?)$", line);
			if srmatch:
				sr_result = do_search_replace(channel, nick, srmatch, lastnicklog[nick]);
				if sr_result:
					lastnicklog[nick] = sr_result;
					nicklogset = True;
					ready=True;
		except:
			# Not gonna happen
			traceback.print_exc();

	if not(nicklogset):
		lastnicklog[nick] = line;

	random.seed();
	i=0;
	result="";
	while (i<len(lines)) and not(ready):
		try:
			excludethis=False;
			if (lines[i].count('#')==2):
				(keyw, chance, reactline) = lines[i].split('#');
				exclude="";
			else:
				(keyw, chance, reactline,exclude) = lines[i].split('#',3);
				if (exclude.count('#')==0):
					excludethis=(line.find(exclude)!=-1);
				else:
					for excludeword in exclude.split('#'):
						if (line.find(excludeword)!=-1):
							excludethis=True;
			r=random.random();
			
			if not(excludethis):
				if (line.find(keyw)!=-1) and (random.random()<=float(chance)):
					ready=True;
					result=reactline;
		except:
			result="";
		i=i+1;

	if not(ready):
		r=random.random();
		if (r<=0.06):
			if globals().has_key("geordi") and (random.random()<0.08):
				n=random.randint(1,4000);
				time.sleep(n);
				result=geordi("bla");
			else:
				inf = open(loosfile);
				lines = inf.read().split('\n');
				inf.close();
				result=random.choice(lines);

	if result[:6]=="ACTION":
		result = "\001"+result+"\001";
	if (len(result)>0):
		result=result.replace("NICK", nick);
		result=result.replace("piet", pietnick);
		piet.send(channel, result+"\n");