]> jfr.im git - z_archive/twitter.git/commitdiff
Ran 2to3.
authorMike Verdone <redacted>
Wed, 2 Mar 2011 20:49:41 +0000 (21:49 +0100)
committerMike Verdone <redacted>
Wed, 2 Mar 2011 20:49:41 +0000 (21:49 +0100)
twitter/__init__.py
twitter/ansi.py
twitter/api.py
twitter/auth.py
twitter/cmdline.py
twitter/ircbot.py
twitter/oauth.py
twitter/oauth_dance.py
twitter/util.py

index 1343a41d6262a370dfba71351468a608303aadd0..77bc02bdd0accd49687deb06828716c070302ec7 100644 (file)
@@ -4,6 +4,6 @@ The minimalist yet fully featured Twitter API and Python toolset.
 For building your own applications, look at the `Twitter` class.
 """
 
-from api import Twitter, TwitterError, TwitterHTTPError, TwitterResponse
-from auth import NoAuth
-from oauth import OAuth, read_token_file, write_token_file
+from .api import Twitter, TwitterError, TwitterHTTPError, TwitterResponse
+from .auth import NoAuth
+from .oauth import OAuth, read_token_file, write_token_file
index 0a8456444987783b817e99efa44974f3ad0a541e..1537000ec8c4208a57fee9cbadd6cb1f981d07da 100644 (file)
@@ -20,12 +20,12 @@ import sys
 ESC = chr(0x1B)
 RESET = "0"
 
-COLOURS_NAMED = dict(zip(
+COLOURS_NAMED = dict(list(zip(
     ['black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white'],
     [str(x) for x in range(30, 38)]
-))
+)))
 COLOURS_MIDS = [
-    colour for name, colour in COLOURS_NAMED.items()
+    colour for name, colour in list(COLOURS_NAMED.items())
     if name not in ('black', 'white')
 ]
 
@@ -47,8 +47,8 @@ class ColourMap(object):
         Returns an ansi colour value given a `string`.
         The same ansi colour value is always returned for the same string
         '''
-        if not self._cmap.has_key(string):
-            self._cmap[string] = self._colourIter.next()
+        if string not in self._cmap:
+            self._cmap[string] = next(self._colourIter)
         return self._cmap[string]
 
 def cmdReset():
index 6927f51b81302b9da14a1e9edff73f9b3514adbd..9803c4b103cc4d6466193b0a7d83cf89ccaa2565 100644 (file)
@@ -1,4 +1,4 @@
-import urllib2
+import urllib.request, urllib.error, urllib.parse
 
 from twitter.twitter_globals import POST_ACTIONS
 from twitter.auth import NoAuth
@@ -110,8 +110,8 @@ class TwitterCall(object):
         for uripart in self.uriparts:
             # If this part matches a keyword argument, use the
             # supplied value otherwise, just use the part.
-            uriparts.append(unicode(kwargs.pop(uripart, uripart)))
-        uri = u'/'.join(uriparts)
+            uriparts.append(str(kwargs.pop(uripart, uripart)))
+        uri = '/'.join(uriparts)
 
         method = "GET"
         for action in POST_ACTIONS:
@@ -144,16 +144,16 @@ class TwitterCall(object):
             else:
                 body = arg_data
 
-        req = urllib2.Request(uriBase, body, headers)
+        req = urllib.request.Request(uriBase, body, headers)
 
         try:
-            handle = urllib2.urlopen(req)
+            handle = urllib.request.urlopen(req)
             if "json" == self.format:
                 res = json.loads(handle.read())
                 return wrap_response(res, handle.headers)
             else:
                 return wrap_response(str(handle.read()), handle.headers)
-        except urllib2.HTTPError, e:
+        except urllib.error.HTTPError as e:
             if (e.code == 304):
                 return []
             else:
index d92b9183ae3552f1a3f08a3a861675f372b28815..9aad691711439a2c964e1bf8c85e7e1b39a9d005 100644 (file)
@@ -1,4 +1,4 @@
-import urllib
+import urllib.request, urllib.parse, urllib.error
 from base64 import encodestring
 
 class Auth(object):
@@ -26,7 +26,7 @@ class NoAuth(Auth):
         pass
 
     def encode_params(self, base_url, method, params):
-        return urllib.urlencode(params)
+        return urllib.parse.urlencode(params)
 
     def generate_headers(self):
         return {}
index f86900e6ecf2ed8176418dbe51a13d14638df921..e6f04b0fde4fd1a57331ddedfa82479d38759cd0 100644 (file)
@@ -68,15 +68,15 @@ from getopt import gnu_getopt as getopt, GetoptError
 from getpass import getpass
 import re
 import os.path
-from ConfigParser import SafeConfigParser
+from configparser import SafeConfigParser
 import datetime
-from urllib import quote
+from urllib.parse import quote
 import webbrowser
 
-from api import Twitter, TwitterError
-from oauth import OAuth, write_token_file, read_token_file
-from oauth_dance import oauth_dance
-import ansi
+from .api import Twitter, TwitterError
+from .oauth import OAuth, write_token_file, read_token_file
+from .oauth_dance import oauth_dance
+from . import ansi
 
 OPTIONS = {
     'action': 'friends',
@@ -146,7 +146,7 @@ def get_time_string(status, options, format="%a %b %d %H:%M:%S +0000 %Y"):
 
 class StatusFormatter(object):
     def __call__(self, status, options):
-        return (u"%s%s %s" %(
+        return ("%s%s %s" %(
             get_time_string(status, options),
             status['user']['screen_name'], status['text']))
 
@@ -156,14 +156,14 @@ class AnsiStatusFormatter(object):
 
     def __call__(self, status, options):
         colour = self._colourMap.colourFor(status['user']['screen_name'])
-        return (u"%s%s%s%s %s" %(
+        return ("%s%s%s%s %s" %(
             get_time_string(status, options),
             ansi.cmdColour(colour), status['user']['screen_name'],
             ansi.cmdReset(), status['text']))
 
 class VerboseStatusFormatter(object):
     def __call__(self, status, options):
-        return (u"-- %s (%s) on %s\n%s\n" %(
+        return ("-- %s (%s) on %s\n%s\n" %(
             status['user']['screen_name'],
             status['user']['location'],
             status['created_at'],
@@ -173,20 +173,20 @@ class URLStatusFormatter(object):
     urlmatch = re.compile(r'https?://\S+')
     def __call__(self, status, options):
         urls = self.urlmatch.findall(status['text'])
-        return u'\n'.join(urls) if urls else ""
+        return '\n'.join(urls) if urls else ""
 
 
 class ListsFormatter(object):
     def __call__(self, list):
         if list['description']:
-            list_str = u"%-30s (%s)" % (list['name'], list['description'])
+            list_str = "%-30s (%s)" % (list['name'], list['description'])
         else:
-            list_str = u"%-30s" % (list['name'])
-        return u"%s\n" % list_str
+            list_str = "%-30s" % (list['name'])
+        return "%s\n" % list_str
 
 class ListsVerboseFormatter(object):
     def __call__(self, list):
-        list_str = u"%-30s\n description: %s\n members: %s\n mode:%s\n" % (list['name'], list['description'], list['member_count'], list['mode'])
+        list_str = "%-30s\n description: %s\n members: %s\n mode:%s\n" % (list['name'], list['description'], list['member_count'], list['mode'])
         return list_str
 
 class AnsiListsFormatter(object):
@@ -195,22 +195,22 @@ class AnsiListsFormatter(object):
 
     def __call__(self, list):
         colour = self._colourMap.colourFor(list['name'])
-        return (u"%s%-15s%s %s" %(
+        return ("%s%-15s%s %s" %(
             ansi.cmdColour(colour), list['name'],
             ansi.cmdReset(), list['description']))
 
 
 class AdminFormatter(object):
     def __call__(self, action, user):
-        user_str = u"%s (%s)" %(user['screen_name'], user['name'])
+        user_str = "%s (%s)" %(user['screen_name'], user['name'])
         if action == "follow":
-            return u"You are now following %s.\n" %(user_str)
+            return "You are now following %s.\n" %(user_str)
         else:
-            return u"You are no longer following %s.\n" %(user_str)
+            return "You are no longer following %s.\n" %(user_str)
 
 class VerboseAdminFormatter(object):
     def __call__(self, action, user):
-        return(u"-- %s: %s (%s): %s" % (
+        return("-- %s: %s (%s): %s" % (
             "Following" if action == "follow" else "Leaving",
             user['screen_name'],
             user['name'],
@@ -218,7 +218,7 @@ class VerboseAdminFormatter(object):
 
 class SearchFormatter(object):
     def __call__(self, result, options):
-        return(u"%s%s %s" %(
+        return("%s%s %s" %(
             get_time_string(result, options, "%a, %d %b %Y %H:%M:%S +0000"),
             result['from_user'], result['text']))
 
@@ -229,7 +229,7 @@ class URLSearchFormatter(object):
     urlmatch = re.compile(r'https?://\S+')
     def __call__(self, result, options):
         urls = self.urlmatch.findall(result['text'])
-        return u'\n'.join(urls) if urls else ""
+        return '\n'.join(urls) if urls else ""
 
 class AnsiSearchFormatter(object):
     def __init__(self):
@@ -237,7 +237,7 @@ class AnsiSearchFormatter(object):
 
     def __call__(self, result, options):
         colour = self._colourMap.colourFor(result['from_user'])
-        return (u"%s%s%s%s %s" %(
+        return ("%s%s%s%s %s" %(
             get_time_string(result, options, "%a, %d %b %Y %H:%M:%S +0000"),
             ansi.cmdColour(colour), result['from_user'],
             ansi.cmdReset(), result['text']))
@@ -312,13 +312,13 @@ class Action(object):
 
         prompt = 'You really want to %s %s? ' %(subject, sample)
         try:
-            answer = raw_input(prompt).lower()
+            answer = input(prompt).lower()
             if careful:
                 return answer in ('yes', 'y')
             else:
                 return answer not in ('no', 'n')
         except EOFError:
-            print >>sys.stderr # Put Newline since Enter was never pressed
+            print(file=sys.stderr) # Put Newline since Enter was never pressed
             # TODO:
                 #   Figure out why on OS X the raw_input keeps raising
                 #   EOFError and is never able to reset and get more input
@@ -339,7 +339,7 @@ class Action(object):
             else:
                 doAction()
         except KeyboardInterrupt:
-            print >>sys.stderr, '\n[Keyboard Interrupt]'
+            print('\n[Keyboard Interrupt]', file=sys.stderr)
             pass
 
 class NoSuchActionError(Exception):
@@ -351,9 +351,9 @@ class NoSuchAction(Action):
 
 def printNicely(string):
     if sys.stdout.encoding:
-        print string.encode(sys.stdout.encoding, 'replace')
+        print(string.encode(sys.stdout.encoding, 'replace'))
     else:
-        print string.encode('utf-8')
+        print(string.encode('utf-8'))
 
 class StatusAction(Action):
     def __call__(self, twitter, options):
@@ -390,14 +390,14 @@ class AdminAction(Action):
         af = get_formatter('admin', options)
         try:
             user = self.getUser(twitter, options['extra_args'][0])
-        except TwitterError, e:
-            print "There was a problem following or leaving the specified user."
-            print "You may be trying to follow a user you are already following;"
-            print "Leaving a user you are not currently following;"
-            print "Or the user may not exist."
-            print "Sorry."
-            print
-            print e
+        except TwitterError as e:
+            print("There was a problem following or leaving the specified user.")
+            print("You may be trying to follow a user you are already following;")
+            print("Leaving a user you are not currently following;")
+            print("Or the user may not exist.")
+            print("Sorry.")
+            print()
+            print(e)
         else:
             printNicely(af(options['action'], user))
 
@@ -452,7 +452,7 @@ class SetStatusAction(Action):
     def __call__(self, twitter, options):
         statusTxt = (" ".join(options['extra_args']).decode(get_term_encoding())
                      if options['extra_args']
-                     else unicode(raw_input("message: ")))
+                     else str(input("message: ")))
         status = (statusTxt.encode('utf8', 'replace'))
         twitter.statuses.update(status=status)
 
@@ -473,39 +473,39 @@ class TwitterShell(Action):
         while True:
             options['action'] = ""
             try:
-                args = raw_input(prompt).split()
+                args = input(prompt).split()
                 parse_args(args, options)
                 if not options['action']:
                     continue
                 elif options['action'] == 'exit':
                     raise SystemExit(0)
                 elif options['action'] == 'shell':
-                    print >>sys.stderr, 'Sorry Xzibit does not work here!'
+                    print('Sorry Xzibit does not work here!', file=sys.stderr)
                     continue
                 elif options['action'] == 'help':
-                    print >>sys.stderr, '''\ntwitter> `action`\n
+                    print('''\ntwitter> `action`\n
                           The Shell Accepts all the command line actions along with:
 
                           exit    Leave the twitter shell (^D may also be used)
 
-                          Full CMD Line help is appended below for your convinience.'''
+                          Full CMD Line help is appended below for your convinience.''', file=sys.stderr)
                 Action()(twitter, options)
                 options['action'] = ''
-            except NoSuchActionError, e:
-                print >>sys.stderr, e
+            except NoSuchActionError as e:
+                print(e, file=sys.stderr)
             except KeyboardInterrupt:
-                print >>sys.stderr, '\n[Keyboard Interrupt]'
+                print('\n[Keyboard Interrupt]', file=sys.stderr)
             except EOFError:
-                print >>sys.stderr
+                print(file=sys.stderr)
                 leaving = self.ask(subject='Leave')
                 if not leaving:
-                    print >>sys.stderr, 'Excellent!'
+                    print('Excellent!', file=sys.stderr)
                 else:
                     raise SystemExit(0)
 
 class HelpAction(Action):
     def __call__(self, twitter, options):
-        print __doc__
+        print(__doc__)
 
 class DoNothingAction(Action):
     def __call__(self, twitter, options):
@@ -540,9 +540,9 @@ def main(args=sys.argv[1:]):
     arg_options = {}
     try:
         parse_args(args, arg_options)
-    except GetoptError, e:
-        print >> sys.stderr, "I can't do that, %s." %(e)
-        print >> sys.stderr
+    except GetoptError as e:
+        print("I can't do that, %s." %(e), file=sys.stderr)
+        print(file=sys.stderr)
         raise SystemExit(1)
 
     config_path = os.path.expanduser(
@@ -554,13 +554,13 @@ def main(args=sys.argv[1:]):
     # arguments.
     options = dict(OPTIONS)
     for d in config_options, arg_options:
-        for k,v in d.items():
+        for k,v in list(d.items()):
             if v: options[k] = v
 
     if options['refresh'] and options['action'] not in (
         'friends', 'public', 'replies'):
-        print >> sys.stderr, "You can only refresh the friends, public, or replies actions."
-        print >> sys.stderr, "Use 'twitter -h' for help."
+        print("You can only refresh the friends, public, or replies actions.", file=sys.stderr)
+        print("Use 'twitter -h' for help.", file=sys.stderr)
         return 1
 
     oauth_filename = os.path.expanduser(options['oauth_filename'])
@@ -582,10 +582,10 @@ def main(args=sys.argv[1:]):
 
     try:
         Action()(twitter, options)
-    except NoSuchActionError, e:
-        print >>sys.stderr, e
+    except NoSuchActionError as e:
+        print(e, file=sys.stderr)
         raise SystemExit(1)
-    except TwitterError, e:
-        print >> sys.stderr, str(e)
-        print >> sys.stderr, "Use 'twitter -h' for help."
+    except TwitterError as e:
+        print(str(e), file=sys.stderr)
+        print("Use 'twitter -h' for help.", file=sys.stderr)
         raise SystemExit(1)
index bfac05086445e1257275d68f7a07a811c46bce2a..7804da2f5dd392807ea2ef70ab4d0e0b2f107eff 100644 (file)
@@ -44,16 +44,16 @@ IRC_REGULAR = chr(0x0f)
 import sys
 import time
 from dateutil.parser import parse
-from ConfigParser import SafeConfigParser
+from configparser import SafeConfigParser
 from heapq import heappop, heappush
 import traceback
 import os
 import os.path
 
-from api import Twitter, TwitterError
-from oauth import OAuth, read_token_file
-from oauth_dance import oauth_dance
-from util import htmlentitydecode
+from .api import Twitter, TwitterError
+from .oauth import OAuth, read_token_file
+from .oauth_dance import oauth_dance
+from .util import htmlentitydecode
 
 try:
     import irclib
@@ -77,10 +77,10 @@ class SchedTask(object):
 
     def __repr__(self):
         return "<SchedTask %s next:%i delta:%i>" %(
-            self.task.__name__, self.next, self.delta)
+            self.task.__name__, self.__next__, self.delta)
 
     def __cmp__(self, other):
-        return cmp(self.next, other.next)
+        return cmp(self.__next__, other.__next__)
 
     def __call__(self):
         return self.task()
@@ -94,7 +94,7 @@ class Scheduler(object):
     def next_task(self):
         now = time.time()
         task = heappop(self.task_heap)
-        wait = task.next - now
+        wait = task.__next__ - now
         task.next = now + task.delta
         heappush(self.task_heap, task)
         if (wait > 0):
@@ -137,8 +137,8 @@ class TwitterBot(object):
         debug("In check_statuses")
         try:
             updates = self.twitter.statuses.friends_timeline()
-        except Exception, e:
-            print >> sys.stderr, "Exception while querying twitter:"
+        except Exception as e:
+            print("Exception while querying twitter:", file=sys.stderr)
             traceback.print_exc(file=sys.stderr)
             return
 
@@ -155,7 +155,7 @@ class TwitterBot(object):
                 #   to people who are not on our following list.
                 if not text.startswith("@"):
                     self.privmsg_channels(
-                        u"=^_^=  %s%s%s %s" %(
+                        "=^_^=  %s%s%s %s" %(
                             IRC_BOLD, update['user']['screen_name'],
                             IRC_BOLD, text.decode('utf-8')))
 
@@ -304,11 +304,11 @@ def main():
         if not os.path.exists(configFilename):
             raise Exception()
         load_config(configFilename)
-    except Exception, e:
-        print >> sys.stderr, "Error while loading ini file %s" %(
-            configFilename)
-        print >> sys.stderr, e
-        print >> sys.stderr, __doc__
+    except Exception as e:
+        print("Error while loading ini file %s" %(
+            configFilename), file=sys.stderr)
+        print(e, file=sys.stderr)
+        print(__doc__, file=sys.stderr)
         sys.exit(1)
 
     bot = TwitterBot(configFilename)
index ed15492ac576a9a0b3529f9db8070175b72203a3..dcbd8d2e0f4007b90ca9b0f24db8b19d54f664b4 100644 (file)
@@ -3,7 +3,7 @@ from twitter.auth import Auth
 from time import time
 from random import getrandbits
 from time import time
-import urllib
+import urllib.request, urllib.parse, urllib.error
 import hashlib
 import hmac
 
@@ -13,8 +13,8 @@ def write_token_file(filename, oauth_token, oauth_token_secret):
     Write a token file to hold the oauth token and oauth token secret.
     """
     oauth_file = open(filename, 'w')
-    print >> oauth_file, oauth_token
-    print >> oauth_file, oauth_token_secret
+    print(oauth_token, file=oauth_file)
+    print(oauth_token_secret, file=oauth_file)
     oauth_file.close()
 
 def read_token_file(filename):
@@ -52,16 +52,16 @@ class OAuth(Auth):
         params['oauth_timestamp'] = str(int(time()))
         params['oauth_nonce'] = str(getrandbits(64))
 
-        enc_params = urlencode_noplus(sorted(params.iteritems()))
+        enc_params = urlencode_noplus(sorted(params.items()))
 
-        key = self.consumer_secret + "&" + urllib.quote(self.token_secret, '')
+        key = self.consumer_secret + "&" + urllib.parse.quote(self.token_secret, '')
 
         message = '&'.join(
-            urllib.quote(i, '') for i in [method.upper(), base_url, enc_params])
+            urllib.parse.quote(i, '') for i in [method.upper(), base_url, enc_params])
 
         signature = hmac.new(
             key, message, hashlib.sha1).digest().encode('base64')[:-1]
-        return enc_params + "&" + "oauth_signature=" + urllib.quote(signature, '')
+        return enc_params + "&" + "oauth_signature=" + urllib.parse.quote(signature, '')
 
     def generate_headers(self):
         return {}
@@ -73,18 +73,18 @@ class OAuth(Auth):
 def urlencode_noplus(query):
     if hasattr(query,"items"):
         # mapping objects
-        query = query.items()
+        query = list(query.items())
 
     encoded_bits = []
     for n, v in query:
         # and do unicode here while we are at it...
-        if isinstance(n, unicode):
+        if isinstance(n, str):
             n = n.encode('utf-8')
         else:
             n = str(n)
-        if isinstance(v, unicode):
+        if isinstance(v, str):
             v = v.encode('utf-8')
         else:
             v = str(v)
-        encoded_bits.append("%s=%s" % (urllib.quote(n, ""), urllib.quote(v, "")))
+        encoded_bits.append("%s=%s" % (urllib.parse.quote(n, ""), urllib.parse.quote(v, "")))
     return "&".join(encoded_bits)
index a89bdd26d658f825c328c62becd577730b36bc4c..dace720ae3603d168ff19c638730ddc3d833db02 100644 (file)
@@ -2,8 +2,8 @@
 import webbrowser
 import time
 
-from api import Twitter
-from oauth import OAuth, write_token_file
+from .api import Twitter
+from .oauth import OAuth, write_token_file
 
 def oauth_dance(app_name, consumer_key, consumer_secret, token_filename=None):
     """
@@ -18,20 +18,20 @@ def oauth_dance(app_name, consumer_key, consumer_secret, token_filename=None):
     If a token_filename is given, the oauth tokens will be written to
     the file.
     """
-    print ("Hi there! We're gonna get you all set up to use %s." % app_name)
+    print(("Hi there! We're gonna get you all set up to use %s." % app_name))
     twitter = Twitter(
         auth=OAuth('', '', consumer_key, consumer_secret),
         format='')
     oauth_token, oauth_token_secret = parse_oauth_tokens(
         twitter.oauth.request_token())
-    print """
+    print("""
 In the web browser window that opens please choose to Allow
 access. Copy the PIN number that appears on the next page and paste or
 type it here:
-"""
+""")
     oauth_url = ('http://api.twitter.com/oauth/authorize?oauth_token=' +
                  oauth_token)
-    print "Opening: %s\n" % oauth_url
+    print("Opening: %s\n" % oauth_url)
 
     try:
         r = webbrowser.open(oauth_url)
@@ -41,12 +41,12 @@ type it here:
         if not r:
             raise Exception()
     except:
-        print """
+        print("""
 Uh, I couldn't open a browser on your computer. Please go here to get
 your PIN:
 
-""" + oauth_url
-    oauth_verifier = raw_input("Please enter the PIN: ").strip()
+""" + oauth_url)
+    oauth_verifier = input("Please enter the PIN: ").strip()
     twitter = Twitter(
         auth=OAuth(
             oauth_token, oauth_token_secret, consumer_key, consumer_secret),
@@ -56,9 +56,9 @@ your PIN:
     if token_filename:
         write_token_file(
             token_filename, oauth_token, oauth_token_secret)
-        print
-        print "That's it! Your authorization keys have been written to %s." % (
-            token_filename)
+        print()
+        print("That's it! Your authorization keys have been written to %s." % (
+            token_filename))
     return oauth_token, oauth_token_secret
 
 def parse_oauth_tokens(result):
index 70ff7a5f0b5b7541341e28723a576450bb9a28fb..76283cdeafe0cb0003769d8ef775cae4f6b577a3 100644 (file)
@@ -7,11 +7,11 @@ Internal utility functions.
 
 
 import re
-from htmlentitydefs import name2codepoint
+from html.entities import name2codepoint
 
 def htmlentitydecode(s):
     return re.sub(
         '&(%s);' % '|'.join(name2codepoint), 
-        lambda m: unichr(name2codepoint[m.group(1)]), s)
+        lambda m: chr(name2codepoint[m.group(1)]), s)
 
 __all__ = ["htmlentitydecode"]