Advertisement
Guest User

Bot code

a guest
May 26th, 2015
577
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.69 KB | None | 0 0
  1. import telnetlib as tn
  2. import re, urllib.request, urllib.parse
  3.  
  4. def smart_truncate(content, length=100, suffix='...'):
  5.     if len(content) <= length:
  6.         return content
  7.     else:
  8.         return ' '.join(content[:length+1].split(' ')[0:-1]) + suffix
  9.  
  10. def getwiki(qstr):
  11.     qstr = urllib.parse.quote(qstr,':/')
  12.     url = "http://en.wikipedia.org/w/api.php?action=query&titles={}&prop=extracts&exintro=True&format=json".format(qstr)
  13.     try:
  14.         wintro = urllib.request.urlopen(url).read().decode()
  15.     except:
  16.         return "\"Sorry, I couldn't connect to Wikipedia."
  17.     if re.search(r"\"pages\":\{\"-1\"", wintro) != None:
  18.         return "\"Sorry, Wikipedia doesn't have a page that matches {}.".format(re.sub(r"%","%%",qstr))
  19.     wintro = re.search(r"\"extract\":\"([^\}]+)",wintro).group(1)[:-1]
  20.     wintro = re.sub(r"\\u2013","-",wintro)
  21.     wintro = re.sub(r"<[^>]+>","",wintro)
  22.     wintro = re.sub("\\\\n","",wintro)
  23.     wintro = re.sub("\\\\u.{4}","",wintro)
  24.     wintro = re.sub("\\\\\"","\"",wintro)
  25.     wintro = re.sub("\/[^\/]+\/","",wintro)
  26.     wintro = re.sub("\[[^\]]+\]","",wintro)
  27.     wintrosm = smart_truncate(wintro, 1000)
  28.     return "quote {}".format(wintrosm)
  29.  
  30. wikir = re.compile(b"\[to Elbot\]: wiki (.+)")
  31.  
  32. t = tn.Telnet(<host>,<port>)
  33. t.read_until(b"\"news\"")
  34. t.write(<connection string>)
  35. while True:
  36.     try:
  37.         g = t.expect([wikir])
  38.         if g[0] == 0:
  39.             t.write(bytes("\"You asked for {}. Hang on a second.\n".format(g[1].group(1).decode()),"UTF-8"))
  40.             o = getwiki(g[1].group(1))
  41.             out = bytes("{}\n".format(o),"UTF-8")
  42.         t.write(out)
  43.         print("Sent text.")
  44.     except KeyboardInterrupt:
  45.         break
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement