irclib -- Internet Relay Chat (IRC) protocol client library

dccreceive 2.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. #! /usr/bin/env python
  2. #
  3. # Example program using irclib.py.
  4. #
  5. # This program is free without restrictions; do anything you like with
  6. # it.
  7. #
  8. # Joel Rosdahl <joel@rosdahl.net>
  9. import irclib
  10. import os
  11. import struct
  12. import sys
  13. class DCCReceive(irclib.SimpleIRCClient):
  14. def __init__(self):
  15. irclib.SimpleIRCClient.__init__(self)
  16. self.received_bytes = 0
  17. def on_ctcp(self, connection, event):
  18. args = event.arguments()[1].split()
  19. if args[0] != "SEND":
  20. return
  21. self.filename = os.path.basename(args[1])
  22. if os.path.exists(self.filename):
  23. print "A file named", self.filename,
  24. print "already exists. Refusing to save it."
  25. self.connection.quit()
  26. self.file = open(self.filename, "w")
  27. peeraddress = irclib.ip_numstr_to_quad(args[2])
  28. peerport = int(args[3])
  29. self.dcc = self.dcc_connect(peeraddress, peerport, "raw")
  30. def on_dccmsg(self, connection, event):
  31. data = event.arguments()[0]
  32. self.file.write(data)
  33. self.received_bytes = self.received_bytes + len(data)
  34. self.dcc.privmsg(struct.pack("!I", self.received_bytes))
  35. def on_dcc_disconnect(self, connection, event):
  36. self.file.close()
  37. print "Received file %s (%d bytes)." % (self.filename,
  38. self.received_bytes)
  39. self.connection.quit()
  40. def on_disconnect(self, connection, event):
  41. sys.exit(0)
  42. def main():
  43. if len(sys.argv) != 3:
  44. print "Usage: dccreceive <server[:port]> <nickname>"
  45. print "\nReceives one file via DCC and then exits. The file is stored in the"
  46. print "current directory."
  47. sys.exit(1)
  48. s = sys.argv[1].split(":", 1)
  49. server = s[0]
  50. if len(s) == 2:
  51. try:
  52. port = int(s[1])
  53. except ValueError:
  54. print "Error: Erroneous port."
  55. sys.exit(1)
  56. else:
  57. port = 6667
  58. nickname = sys.argv[2]
  59. c = DCCReceive()
  60. try:
  61. c.connect(server, port, nickname)
  62. except irclib.ServerConnectionError, x:
  63. print x
  64. sys.exit(1)
  65. c.start()
  66. if __name__ == "__main__":
  67. main()