Anonymous avatar Anonymous committed 64a345b

* dccsend:
* dccreceive:
* irclib.py:
* ircbot.py:
* irccat:
* irccat2:
* servermap:
* testbot.py:
Code modernization - String methods used instead of deprecated string functions, keyword 'in' used for membership testing instead of 'has_key' method, etc.

Comments (0)

Files changed (10)

+2005-12-23  Keltus <keltus@users.sourceforge.net>
+	* dccsend:
+	* dccreceive:
+	* irclib.py:
+	* ircbot.py:
+	* irccat:
+	* irccat2:
+	* servermap:
+	* testbot.py:
+	Code modernization - String methods used instead of deprecated
+	string functions, keyword 'in' used for membership testing instead
+	of 'has_key' method, etc.
+
 2005-12-06  Keltus <keltus@users.sourceforge.net>
 	* irclib.py (ServerConnection.process_data): Reversed fix from
 	2005-05-28. This is strange because there was a bug before and
 
 Enjoy.
 
-Current Maintainer:
+Maintainer:
 keltus <keltus@users.sourceforge.net>
 
 Original Founder:
 
 import irclib
 import os
-import string
 import struct
 import sys
 
         self.received_bytes = 0
 
     def on_ctcp(self, connection, event):
-        args = string.split(event.arguments()[1])
+        args = event.arguments()[1].split()
         if args[0] != "SEND":
             return
         self.filename = os.path.basename(args[1])
         print "current directory."
         sys.exit(1)
 
-    s = string.split(sys.argv[1], ":", 1)
+    s = sys.argv[1].split(":", 1)
     server = s[0]
     if len(s) == 2:
         try:
 
 import irclib
 import os
-import string
 import struct
 import sys
 
         print "\nSends <filename> to <receiver nickname> via DCC and then exits."
         sys.exit(1)
 
-    s = string.split(sys.argv[1], ":", 1)
+    s = sys.argv[1].split(":", 1)
     server = s[0]
     if len(s) == 2:
         try:
 """
 
 import sys
-import string
 from UserDict import UserDict
 
 from irclib import SimpleIRCClient
 
     def _on_mode(self, c, e):
         """[Internal]"""
-        modes = parse_channel_modes(string.join(e.arguments()))
+        modes = parse_channel_modes(" ".join(e.arguments()))
         t = e.target()
         if is_channel(t):
             ch = self.channels[t]
         # e.arguments()[2] == nick list
 
         ch = e.arguments()[1]
-        for nick in string.split(e.arguments()[2]):
+        for nick in e.arguments()[2].split():
             if nick[0] == "@":
                 nick = nick[1:]
                 self.channels[ch].set_mode("o", nick)
             if len(e.arguments()) > 1:
                 c.ctcp_reply(nm_to_n(e.source()),
                              "PING " + e.arguments()[1])
-        elif e.arguments()[0] == "DCC" and string.split(e.arguments()[1],
-                                                        " ", 1)[0] == "CHAT":
+        elif e.arguments()[0] == "DCC" and e.arguments()[1].split(" ", 1)[0] == "CHAT":
             self.on_dccchat(c, e)
 
     def on_dccchat(self, c, e):
     def __getitem__(self, key):
         return self.data[self.canon_keys[irc_lower(key)]]
     def __setitem__(self, key, item):
-        if self.has_key(key):
+        if key in self:
             del self[key]
         self.data[key] = item
         self.canon_keys[irc_lower(key)] = key
     def values(self):
         return self.data.values()
     def has_key(self, key):
-        return self.canon_keys.has_key(irc_lower(key))
+        return irc_lower(key) in self.canon_keys
     def update(self, dict):
         for k, v in dict.items():
             self.data[k] = v
 
     def has_user(self, nick):
         """Check whether the channel has a user."""
-        return self.userdict.has_key(nick)
+        return nick in self.userdict
 
     def is_oper(self, nick):
         """Check whether a user has operator status in the channel."""
-        return self.operdict.has_key(nick)
+        return nick in self.operdict
 
     def is_voiced(self, nick):
         """Check whether a user has voice mode set in the channel."""
-        return self.voiceddict.has_key(nick)
+        return nick in self.voiceddict
 
     def add_user(self, nick):
         self.userdict[nick] = 1
 
     def remove_user(self, nick):
         for d in self.userdict, self.operdict, self.voiceddict:
-            if d.has_key(nick):
+            if nick in d:
                 del d[nick]
 
     def change_nick(self, before, after):
         self.userdict[after] = 1
         del self.userdict[before]
-        if self.operdict.has_key(before):
+        if before in self.operdict:
             self.operdict[after] = 1
             del self.operdict[before]
-        if self.voiceddict.has_key(before):
+        if before in self.voiceddict:
             self.voiceddict[after] = 1
             del self.voiceddict[before]
 
 # Joel Rosdahl <joel@rosdahl.net>
 
 import irclib
-import string
 import sys
 
 def on_connect(connection, event):
 def on_disconnect(connection, event):
     sys.exit(0)
 
-s = string.split(sys.argv[1], ":", 1)
+s = sys.argv[1].split(":", 1)
 server = s[0]
 if len(s) == 2:
     try:
 # Joel Rosdahl <joel@rosdahl.net>
 
 import irclib
-import string
 import sys
 
 class IRCCat(irclib.SimpleIRCClient):
         print "\ntarget is a nickname or a channel."
         sys.exit(1)
 
-    s = string.split(sys.argv[1], ":", 1)
+    s = sys.argv[1].split(":", 1)
     server = s[0]
     if len(s) == 2:
         try:
 This library is intended to encapsulate the IRC protocol at a quite
 low level.  It provides an event-driven IRC client framework.  It has
 a fairly thorough support for the basic IRC protocol, CTCP, DCC chat,
-but DCC send is not yet supported.
+but DCC file transfers is not yet supported.
 
 In order to understand how to make an IRC client, I'm afraid you more
 or less must understand the IRC specifications.  They are available
   * The IRC protocol shines through the abstraction a bit too much.
   * Data is not written asynchronously to the server, i.e. the write()
     may block if the TCP buffers are stuffed.
-  * There are no support for DCC sends.
+  * There are no support for DCC file transfers.
   * The author haven't even read RFC 2810, 2811, 2812 and 2813.
   * Like most projects, documentation is lacking...
 
         \"NO MORE\", no more handlers will be called.
         """
 
-        if not self.handlers.has_key(event):
+        if not event in self.handlers:
             self.handlers[event] = []
         bisect.insort(self.handlers[event], ((priority, handler)))
 
 
         Returns 1 on success, otherwise 0.
         """
-        if not self.handlers.has_key(event):
+        if not event in self.handlers:
             return 0
         for h in self.handlers[event]:
             if handler == h[1]:
                     self.real_server_name = prefix
 
             if m.group("command"):
-                command = string.lower(m.group("command"))
+                command = m.group("command").lower()
 
             if m.group("argument"):
-                a = string.split(m.group("argument"), " :", 1)
-                arguments = string.split(a[0])
+                a = m.group("argument").split(" :", 1)
+                arguments = a[0].split()
                 if len(a) == 2:
                     arguments.append(a[1])
 
             # Translate numerics into more readable strings.
-            if numeric_events.has_key(command):
+            if command in numeric_events:
                 command = numeric_events[command]
 
             if command == "nick":
     def _handle_event(self, event):
         """[Internal]"""
         self.irclibobj._handle_event(self, event)
-        if self.handlers.has_key(event.eventtype()):
+        if event.eventtype() in self.handlers:
             for fn in self.handlers[event.eventtype()]:
                 fn(self, event)
 
 
     def admin(self, server=""):
         """Send an ADMIN command."""
-        self.send_raw(string.strip(string.join(["ADMIN", server])))
+        self.send_raw(" ".join(["ADMIN", server]).strip())
 
     def ctcp(self, ctcptype, target, parameter=""):
         """Send a CTCP command."""
-        ctcptype = string.upper(ctcptype)
+        ctcptype = ctcptype.upper()
         self.privmsg(target, "\001%s%s\001" % (ctcptype, parameter and (" " + parameter) or ""))
 
     def ctcp_reply(self, target, parameter):
 
     def info(self, server=""):
         """Send an INFO command."""
-        self.send_raw(string.strip(string.join(["INFO", server])))
+        self.send_raw(" ".join(["INFO", server]).strip())
 
     def invite(self, nick, channel):
         """Send an INVITE command."""
-        self.send_raw(string.strip(string.join(["INVITE", nick, channel])))
+        self.send_raw(" ".join(["INVITE", nick, channel]).strip())
 
     def ison(self, nicks):
         """Send an ISON command.
 
             nicks -- List of nicks.
         """
-        self.send_raw("ISON " + string.join(nicks, " "))
+        self.send_raw("ISON " + " ".join(nicks))
 
     def join(self, channel, key=""):
         """Send a JOIN command."""
         """Send a LIST command."""
         command = "LIST"
         if channels:
-            command = command + " " + string.join(channels, ",")
+            command = command + " " + ",".join(channels)
         if server:
             command = command + " " + server
         self.send_raw(command)
 
     def names(self, channels=None):
         """Send a NAMES command."""
-        self.send_raw("NAMES" + (channels and (" " + string.join(channels, ",")) or ""))
+        self.send_raw("NAMES" + (channels and (" " + ",".join(channels)) or ""))
 
     def nick(self, newnick):
         """Send a NICK command."""
         if type(channels) == types.StringType:
             self.send_raw("PART " + channels + (message and (" " + message)))
         else:
-            self.send_raw("PART " + string.join(channels, ",") + (message and (" " + message)))
+            self.send_raw("PART " + ",".join(channels) + (message and (" " + message)))
 
     def pass_(self, password):
         """Send a PASS command."""
     def privmsg_many(self, targets, text):
         """Send a PRIVMSG command to multiple targets."""
         # Should limit len(text) here!
-        self.send_raw("PRIVMSG %s :%s" % (string.join(targets, ","), text))
+        self.send_raw("PRIVMSG %s :%s" % (",".join(targets), text))
 
     def quit(self, message=""):
         """Send a QUIT command."""
 
     def topic(self, channel, new_topic=None):
         """Send a TOPIC command."""
-        if new_topic == None:
+        if new_topic is None:
             self.send_raw("TOPIC " + channel)
         else:
             self.send_raw("TOPIC %s :%s" % (channel, new_topic))
 
     def userhost(self, nicks):
         """Send a USERHOST command."""
-        self.send_raw("USERHOST " + string.join(nicks, ","))
+        self.send_raw("USERHOST " + ",".join(nicks))
 
     def users(self, server=""):
         """Send a USERS command."""
 
     def whois(self, targets):
         """Send a WHOIS command."""
-        self.send_raw("WHOIS " + string.join(targets, ","))
+        self.send_raw("WHOIS " + ",".join(targets))
 
     def whowas(self, nick, max="", server=""):
         """Send a WHOWAS command."""
     """
     nick = irc_lower(nick)
     mask = irc_lower(mask)
-    mask = string.replace(mask, "\\", "\\\\")
+    mask = mask.replace("\\", "\\\\")
     for ch in ".$|[](){}+":
-        mask = string.replace(mask, ch, "\\" + ch)
-    mask = string.replace(mask, "?", ".")
-    mask = string.replace(mask, "*", ".*")
+        mask = mask.replace(ch, "\\" + ch)
+    mask = mask.replace("?", ".")
+    mask = mask.replace("*", ".*")
     r = re.compile(mask, re.IGNORECASE)
     return r.match(nick)
 
-_alpha = "abcdefghijklmnopqrstuvwxyz"
 _special = "-[]\\`^{}"
-nick_characters = _alpha + string.upper(_alpha) + string.digits + _special
-_ircstring_translation = string.maketrans(string.upper(_alpha) + "[]\\^",
-                                          _alpha + "{}|~")
+nick_characters = string.ascii_letters + string.digits + _special
+_ircstring_translation = string.maketrans(string.ascii_uppercase + "[]\\^",
+                                          string.ascii_lowercase + "{}|~")
 
 def irc_lower(s):
     """Returns a lowercased string.
     The definition of lowercased comes from the IRC specification (RFC
     1459).
     """
-    return string.translate(s, _ircstring_translation)
+    return s.translate(_ircstring_translation)
 
 def _ctcp_dequote(message):
     """[Internal] Dequote a message according to CTCP specifications.
     else:
         # Split it into parts.  (Does any IRC client actually *use*
         # CTCP stacking like this?)
-        chunks = string.split(message, _CTCP_DELIMITER)
+        chunks = message.split(_CTCP_DELIMITER)
 
         messages = []
         i = 0
 
             if i < len(chunks)-2:
                 # Aye!  CTCP tagged data ahead!
-                messages.append(tuple(string.split(chunks[i+1], " ", 1)))
+                messages.append(tuple(chunks[i+1].split(" ", 1)))
 
             i = i + 2
 
     n = long(num)
     p = map(str, map(int, [n >> 24 & 0xFF, n >> 16 & 0xFF,
                            n >> 8 & 0xFF, n & 0xFF]))
-    return string.join(p, ".")
+    return ".".join(p)
 
 def ip_quad_to_numstr(quad):
     """Convert an IP address string (e.g. '192.168.0.1') to an IP
     number as an integer given in ASCII representation
     (e.g. '3232235521')."""
-    p = map(long, string.split(quad, "."))
+    p = map(long, quad.split("."))
     s = str((p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3])
     if s[-1] == "L":
         s = s[:-1]
 
     (The source of an Event is a nickmask.)
     """
-    return string.split(s, "!")[0]
+    return s.split("!")[0]
 
 def nm_to_uh(s):
     """Get the userhost part of a nickmask.
 
     (The source of an Event is a nickmask.)
     """
-    return string.split(s, "!")[1]
+    return s.split("!")[1]
 
 def nm_to_h(s):
     """Get the host part of a nickmask.
 
     (The source of an Event is a nickmask.)
     """
-    return string.split(s, "@")[1]
+    return s.split("@")[1]
 
 def nm_to_u(s):
     """Get the user part of a nickmask.
 
     (The source of an Event is a nickmask.)
     """
-    s = string.split(s, "!")[1]
-    return string.split(s, "@")[0]
+    s = s.split("!")[1]
+    return s.split("@")[0]
 
 def parse_nick_modes(mode_string):
     """Parse a nick mode string.
     # State variable.
     sign = ""
 
-    a = string.split(mode_string)
+    a = mode_string.split()
     if len(a) == 0:
         return []
     else:
 #     `-omega.ca.us.dal.net
 
 import irclib
-import string
 import sys
 
 if len(sys.argv) != 3:
         if from_node != to_node:
             m[from_node] = m.get(from_node, []) + [to_node]
 
-    if m.has_key(connection.get_server_name()):
+    if connection.get_server_name() in m:
         if len(m[connection.get_server_name()]) == 1:
             hubs = len(m) - 1
         else:
 def print_tree(level, active_levels, root, map, last=0):
     sys.stdout.write(indent_string(level, active_levels, last)
                      + root + "\n")
-    if map.has_key(root):
+    if root in map:
         list = map[root]
         for r in list[:-1]:
             print_tree(level+1, active_levels[:]+[level], r, map)
         print_tree(level+1, active_levels[:], list[-1], map, 1)
 
-s = string.split(sys.argv[1], ":", 1)
+s = sys.argv[1].split(":", 1)
 server = s[0]
 if len(s) == 2:
     try:
     dcc -- Let the bot invite you to a DCC CHAT connection.
 """
 
-import string
 from ircbot import SingleServerIRCBot
 from irclib import nm_to_n, nm_to_h, irc_lower, ip_numstr_to_quad, ip_quad_to_numstr
 
         self.do_command(e, e.arguments()[0])
 
     def on_pubmsg(self, c, e):
-        a = string.split(e.arguments()[0], ":", 1)
+        a = e.arguments()[0].split(":", 1)
         if len(a) > 1 and irc_lower(a[0]) == irc_lower(self.connection.get_nickname()):
-            self.do_command(e, string.strip(a[1]))
+            self.do_command(e, a[1].strip())
         return
 
     def on_dccmsg(self, c, e):
     def on_dccchat(self, c, e):
         if len(e.arguments()) != 2:
             return
-        args = string.split(e.arguments()[1])
+        args = e.arguments()[1].split()
         if len(args) == 4:
             try:
                 address = ip_numstr_to_quad(args[2])
                 c.notice(nick, "Channel: " + chname)
                 users = chobj.users()
                 users.sort()
-                c.notice(nick, "Users: " + string.join(users, ", "))
+                c.notice(nick, "Users: " + ", ".join(users))
                 opers = chobj.opers()
                 opers.sort()
-                c.notice(nick, "Opers: " + string.join(opers, ", "))
+                c.notice(nick, "Opers: " + ", ".join(opers))
                 voiced = chobj.voiced()
                 voiced.sort()
-                c.notice(nick, "Voiced: " + string.join(voiced, ", "))
+                c.notice(nick, "Voiced: " + ", ".join(voiced))
         elif cmd == "dcc":
             dcc = self.dcc_listen()
             c.ctcp("DCC", nick, "CHAT chat %s %d" % (
         print "Usage: testbot <server[:port]> <channel> <nickname>"
         sys.exit(1)
 
-    s = string.split(sys.argv[1], ":", 1)
+    s = sys.argv[1].split(":", 1)
     server = s[0]
     if len(s) == 2:
         try:
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.