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

dccsend 2.5KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  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 DCCSend(irclib.SimpleIRCClient):
  14. def __init__(self, receiver, filename):
  15. irclib.SimpleIRCClient.__init__(self)
  16. self.receiver = receiver
  17. self.filename = filename
  18. self.filesize = os.path.getsize(self.filename)
  19. self.file = open(filename)
  20. self.sent_bytes = 0
  21. def on_welcome(self, connection, event):
  22. self.dcc = self.dcc_listen("raw")
  23. self.connection.ctcp("DCC", self.receiver, "SEND %s %s %d %d" % (
  24. os.path.basename(self.filename),
  25. irclib.ip_quad_to_numstr(self.dcc.localaddress),
  26. self.dcc.localport,
  27. self.filesize))
  28. def on_dcc_connect(self, connection, event):
  29. if self.filesize == 0:
  30. self.dcc.disconnect()
  31. return
  32. self.send_chunk()
  33. def on_dcc_disconnect(self, connection, event):
  34. print "Sent file %s (%d bytes)." % (self.filename, self.filesize)
  35. self.connection.quit()
  36. def on_dccmsg(self, connection, event):
  37. acked = struct.unpack("!I", event.arguments()[0])[0]
  38. if acked == self.filesize:
  39. self.dcc.disconnect()
  40. self.connection.quit()
  41. elif acked == self.sent_bytes:
  42. self.send_chunk()
  43. def on_disconnect(self, connection, event):
  44. sys.exit(0)
  45. def on_nosuchnick(self, connection, event):
  46. print "No such nickname:", event.arguments()[0]
  47. self.connection.quit()
  48. def send_chunk(self):
  49. data = self.file.read(1024)
  50. self.dcc.privmsg(data)
  51. self.sent_bytes = self.sent_bytes + len(data)
  52. def main():
  53. if len(sys.argv) != 5:
  54. print "Usage: dccsend <server[:port]> <nickname> <receiver nickname> <filename>"
  55. print "\nSends <filename> to <receiver nickname> via DCC and then exits."
  56. sys.exit(1)
  57. s = sys.argv[1].split(":", 1)
  58. server = s[0]
  59. if len(s) == 2:
  60. try:
  61. port = int(s[1])
  62. except ValueError:
  63. print "Error: Erroneous port."
  64. sys.exit(1)
  65. else:
  66. port = 6667
  67. nickname = sys.argv[2]
  68. receiver = sys.argv[3]
  69. filename = sys.argv[4]
  70. c = DCCSend(receiver, filename)
  71. try:
  72. c.connect(server, port, nickname)
  73. except irclib.ServerConnectionError, x:
  74. print x
  75. sys.exit(1)
  76. c.start()
  77. if __name__ == "__main__":
  78. main()