A Python robot that edits Wikipedia and interacts with people over IRC https://en.wikipedia.org/wiki/User:EarwigBot
Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.

connection.py 2.0 KiB

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