bot.py 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  1. #!/usr/bin/env python3
  2. import asyncore
  3. import threading
  4. import re
  5. import socket
  6. import sys
  7. from unzipper import unar
  8. class IRCClient(asyncore.dispatcher):
  9. HOST="irc.irchighway.net"
  10. PORT=6667
  11. NICK="booksbot3321321"
  12. IDENT="booksbot"
  13. REALNAME="NotABot"
  14. IGNORE=["NOTICE","PART","QUIT", "332","333", "372", "353","366", "251", "252", "254", "255","265","266","396"]
  15. LOOKING_FOR="cryptonomicon"
  16. CHANNEL="#ebooks"
  17. EXTENSION="epub"
  18. STATUS=""
  19. OUT_DIR="/tmp"
  20. OUTPUT_VALUE=""
  21. buffer = []
  22. readbuffer=b''
  23. joined=False
  24. connected=False
  25. def __init__(self,book,extension):
  26. asyncore.dispatcher.__init__(self)
  27. self.EXTENSION=extension
  28. self.LOOKING_FOR=book
  29. self.create_socket()
  30. self.connect( (self.HOST, self.PORT) )
  31. nickstr="NICK %s" % self.NICK
  32. userstr="USER %s %s bla :%s" % (self.IDENT, self.HOST, self.REALNAME)
  33. self.send_queue(nickstr)
  34. self.send_queue(userstr)
  35. def handle_connect(self):
  36. print("connected")
  37. self.STATUS="CONNECTED"
  38. self.connected=True
  39. pass
  40. def handle_close(self):
  41. print("closed")
  42. self.STATUS="DISCONNECTED"
  43. self.connected=False
  44. self.close()
  45. def handle_read(self):
  46. data=self.recv(1024)
  47. if not (data[-1]==10 and data[-2]==13):
  48. self.readbuffer+=data
  49. return
  50. data=self.readbuffer+data
  51. data=data.replace(b'\x95', b'').replace(b'0xc2',b'').decode('utf-8','ignore') #purge mojibake
  52. self.readbuffer=b''
  53. lines=data.splitlines()
  54. for line in lines:
  55. words=line.split(' ')
  56. if len(words)<2:
  57. continue
  58. msg_from=words[0]
  59. comm=words[1]
  60. if comm in self.IGNORE:
  61. continue
  62. if comm=="JOIN":
  63. if self.NICK not in msg_from:
  64. continue
  65. self.STATUS="JOINED"
  66. print("Joined channel %s" % self.CHANNEL)
  67. self.search(self.LOOKING_FOR)
  68. self.joined=True
  69. if comm=="PRIVMSG":
  70. if words[2] != self.NICK:
  71. continue
  72. self.parse_msg(line);
  73. if comm=="PING" or msg_from=="PING":
  74. self.pong(line)
  75. continue
  76. if comm=="376": #END MOTD
  77. self.join(self.CHANNEL)
  78. continue
  79. if not self.joined:
  80. continue
  81. def parse_msg(self,msg):
  82. msg=msg.split(':')[2]
  83. msg=msg.replace("\x01","")
  84. args=msg.replace("DCC SEND ","").split(" ")
  85. size=int(args.pop())
  86. port=int(args.pop())
  87. ip=self.ip_from_decimal(int(args.pop()))
  88. filename="_".join(args)
  89. self.STATUS="RECEIVING"
  90. n=self.netcat(ip,port,size,filename)
  91. files=unar(n,"/tmp/")
  92. self.OUTPUT_VALUE=[]
  93. for f in files:
  94. if "searchbot" in f.lower():
  95. self.list_books(f)
  96. def list_books(self,f):
  97. f=open(f,"r")
  98. lines=f.readlines()
  99. lines=[l.strip() for l in lines if self.EXTENSION in l.lower() ]
  100. # for l in lines:
  101. # print(l)
  102. return lines
  103. def netcat(self,ip,port,size,filename):
  104. s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  105. s.connect((ip,port))
  106. #s.shutdown(socket.SHUT_WR)
  107. sizelen=len(str(size))
  108. fname='%s/%s' % (self.OUT_DIR,filename)
  109. f=open(fname, 'wb')
  110. count=0
  111. while True:
  112. data = s.recv(1024)
  113. if len(data)==0:
  114. print("empty")
  115. break
  116. count+=len(data)
  117. f.write(data)
  118. #sys.stdout.write("\r%s/%d" % (str(count).zfill(sizelen),size)) #progress
  119. if count >= size:
  120. break
  121. s.close()
  122. f.close()
  123. return fname
  124. def search(self,book):
  125. print("searching for %s" % book)
  126. self.send_queue("PRIVMSG %s :@search %s " % (self.CHANNEL,book))
  127. def pong(self,data):
  128. msg=data.replace("PING ","")
  129. self.send_queue("PONG %s" % msg)
  130. def join(self,channel):
  131. self.send_queue("JOIN %s" % channel)
  132. def writable(self):
  133. return (len(self.buffer) > 0 and self.connected)
  134. def handle_write(self):
  135. out=self.buffer.pop()
  136. self.send(out)
  137. def send_queue(self,msg):
  138. add=bytes(str(msg),"utf-8")+bytes([13,10])
  139. self.buffer.append(add)
  140. def book(self,book):
  141. print("asking for %s" % book)
  142. self.send_queue("PRIVMSG %s :%s " % (self.CHANNEL,book))
  143. def who(self):
  144. self.send_queue("WHO %s" % self.CHANNEL)
  145. def ip_from_decimal(self,dec):
  146. return ".".join([ str(int(b,2)) for b in self.b_octets(bin(dec)[2:]) ])
  147. def b_octets(self,l):
  148. l=l.zfill(32)
  149. return [l[0:8],l[8:16],l[16:24],l[24:32]]
  150. def stop(self):
  151. self.close()
  152. if __name__ == "__main__":
  153. if len(sys.argv)!=3:
  154. print("USAGE: %s <BOOK> <FORMAT>" % sys.argv[0])
  155. sys.exit(1)
  156. print("Looking for %s in format %s" % (sys.argv[1],sys.argv[2]))
  157. client = IRCClient(sys.argv[1],sys.argv[2])
  158. loop_thread = threading.Thread(target=asyncore.loop)
  159. loop_thread.start()