A Python robot that edits Wikipedia and interacts with people over IRC https://en.wikipedia.org/wiki/User:EarwigBot

76 rivejä
2.3 KiB

  1. # -*- coding: utf-8 -*-
  2. # A class to interface with IRC.
  3. import socket
  4. import threading
  5. class BrokenSocketException(Exception):
  6. """A socket has broken, because it is not sending data."""
  7. pass
  8. class Connection(object):
  9. def __init__(self, host=None, port=None, nick=None, ident=None, realname=None):
  10. """a class to interface with IRC"""
  11. self.host = host
  12. self.port = port
  13. self.nick = nick
  14. self.ident = ident
  15. self.realname = realname
  16. def connect(self):
  17. """connect to IRC"""
  18. self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  19. self.sock.connect((self.host, self.port))
  20. self.send("NICK %s" % self.nick)
  21. self.send("USER %s %s * :%s" % (self.ident, self.host, self.realname))
  22. def close(self):
  23. """close our connection with IRC"""
  24. try:
  25. self.sock.shutdown(socket.SHUT_RDWR) # shut down connection first
  26. except socket.error:
  27. pass # ignore if the socket is already down
  28. self.sock.close()
  29. def get(self, size=4096):
  30. """receive (get) data from the server"""
  31. data = self.sock.recv(4096)
  32. if not data: # socket giving us no data, so it is dead/broken
  33. raise BrokenSocketException()
  34. return data
  35. def send(self, msg):
  36. """send data to the server"""
  37. lock = threading.Lock()
  38. lock.acquire() # ensure that we only send one message at a time (blocking)
  39. try:
  40. self.sock.sendall(msg + "\r\n")
  41. print " %s" % msg
  42. finally:
  43. lock.release()
  44. def say(self, target, msg):
  45. """send a message"""
  46. self.send("PRIVMSG %s :%s" % (target, msg))
  47. def reply(self, data, msg):
  48. """send a message as a reply"""
  49. self.say(data.chan, "%s%s%s: %s" % (chr(2), data.nick, chr(0x0f), msg))
  50. def action(self, target, msg):
  51. """send a message as an action"""
  52. self.say(target,"%sACTION %s%s" % (chr(1), msg, chr(1)))
  53. def notice(self, target, msg):
  54. """send a notice"""
  55. self.send("NOTICE %s :%s" % (target, msg))
  56. def join(self, chan):
  57. """join a channel"""
  58. self.send("JOIN %s" % chan)
  59. def mode(self, chan, level, msg):
  60. """send a mode message"""
  61. self.send("MODE %s %s %s" % (chan, level, msg))