Skip to content

Commit 53f2e31

Browse files
author
brucIDM
committed
modified the code of the function _Encode(self,s) at line 4373 in twitter/api.py to fix the TypeError discribed in issure 327, after modified, the TypeError doesn't apear
1 parent 4480ea9 commit 53f2e31

3 files changed

Lines changed: 243 additions & 1 deletion

File tree

tweet.py

Lines changed: 149 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,149 @@
1+
#!/usr/bin/env python
2+
3+
'''Post a message to twitter'''
4+
5+
__author__ = 'dewitt@google.com'
6+
7+
import ConfigParser
8+
import getopt
9+
import os
10+
import sys
11+
import twitter
12+
13+
14+
USAGE = '''Usage: tweet [options] message
15+
16+
This script posts a message to Twitter.
17+
18+
Options:
19+
20+
-h --help : print this help
21+
--consumer-key : the twitter consumer key
22+
--consumer-secret : the twitter consumer secret
23+
--access-key : the twitter access token key
24+
--access-secret : the twitter access token secret
25+
--encoding : the character set encoding used in input strings, e.g. "utf-8". [optional]
26+
27+
Documentation:
28+
29+
If either of the command line flags are not present, the environment
30+
variables TWEETUSERNAME and TWEETPASSWORD will then be checked for your
31+
consumer_key or consumer_secret, respectively.
32+
33+
If neither the command line flags nor the environment variables are
34+
present, the .tweetrc file, if it exists, can be used to set the
35+
default consumer_key and consumer_secret. The file should contain the
36+
following three lines, replacing *consumer_key* with your consumer key, and
37+
*consumer_secret* with your consumer secret:
38+
39+
A skeletal .tweetrc file:
40+
41+
[Tweet]
42+
consumer_key: *consumer_key*
43+
consumer_secret: *consumer_password*
44+
access_key: *access_key*
45+
access_secret: *access_password*
46+
47+
'''
48+
49+
50+
def PrintUsageAndExit():
51+
print USAGE
52+
sys.exit(2)
53+
54+
55+
def GetConsumerKeyEnv():
56+
return os.environ.get("TWEETUSERNAME", None)
57+
58+
59+
def GetConsumerSecretEnv():
60+
return os.environ.get("TWEETPASSWORD", None)
61+
62+
63+
def GetAccessKeyEnv():
64+
return os.environ.get("TWEETACCESSKEY", None)
65+
66+
67+
def GetAccessSecretEnv():
68+
return os.environ.get("TWEETACCESSSECRET", None)
69+
70+
71+
class TweetRc(object):
72+
def __init__(self):
73+
self._config = None
74+
75+
def GetConsumerKey(self):
76+
return self._GetOption('consumer_key')
77+
78+
def GetConsumerSecret(self):
79+
return self._GetOption('consumer_secret')
80+
81+
def GetAccessKey(self):
82+
return self._GetOption('access_key')
83+
84+
def GetAccessSecret(self):
85+
return self._GetOption('access_secret')
86+
87+
def _GetOption(self, option):
88+
try:
89+
return self._GetConfig().get('Tweet', option)
90+
except:
91+
return None
92+
93+
def _GetConfig(self):
94+
if not self._config:
95+
self._config = ConfigParser.ConfigParser()
96+
self._config.read(os.path.expanduser('~/.tweetrc'))
97+
return self._config
98+
99+
100+
def main():
101+
try:
102+
shortflags = 'h'
103+
longflags = ['help', 'consumer-key=', 'consumer-secret=',
104+
'access-key=', 'access-secret=', 'encoding=']
105+
opts, args = getopt.gnu_getopt(sys.argv[1:], shortflags, longflags)
106+
except getopt.GetoptError:
107+
PrintUsageAndExit()
108+
consumer_keyflag = None
109+
consumer_secretflag = None
110+
access_keyflag = None
111+
access_secretflag = None
112+
encoding = None
113+
for o, a in opts:
114+
if o in ("-h", "--help"):
115+
PrintUsageAndExit()
116+
if o in ("--consumer-key"):
117+
consumer_keyflag = a
118+
if o in ("--consumer-secret"):
119+
consumer_secretflag = a
120+
if o in ("--access-key"):
121+
access_keyflag = a
122+
if o in ("--access-secret"):
123+
access_secretflag = a
124+
if o in ("--encoding"):
125+
encoding = a
126+
message = ' '.join(args)
127+
if not message:
128+
PrintUsageAndExit()
129+
rc = TweetRc()
130+
consumer_key = consumer_keyflag or GetConsumerKeyEnv() or rc.GetConsumerKey()
131+
consumer_secret = consumer_secretflag or GetConsumerSecretEnv() or rc.GetConsumerSecret()
132+
access_key = access_keyflag or GetAccessKeyEnv() or rc.GetAccessKey()
133+
access_secret = access_secretflag or GetAccessSecretEnv() or rc.GetAccessSecret()
134+
if not consumer_key or not consumer_secret or not access_key or not access_secret:
135+
PrintUsageAndExit()
136+
api = twitter.Api(consumer_key=consumer_key, consumer_secret=consumer_secret,
137+
access_token_key=access_key, access_token_secret=access_secret,
138+
input_encoding=encoding)
139+
try:
140+
status = api.PostUpdate(message)
141+
except UnicodeDecodeError:
142+
print "Your message could not be encoded. Perhaps it contains non-ASCII characters? "
143+
print "Try explicitly specifying the encoding with the --encoding flag"
144+
sys.exit(2)
145+
print "%s just posted: %s" % (status.user.name, status.text)
146+
147+
148+
if __name__ == "__main__":
149+
main()

twitter-to-xhtml.py

Lines changed: 93 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,93 @@
1+
#!/usr/bin/env python
2+
# -*- coding: utf-8 -*-
3+
# ===================================================================
4+
# FileName: twitter-to-xhtml.py
5+
# Email: brucvv@gmail.com
6+
# CreateTime: 2016-04-29 18:45
7+
# ===================================================================
8+
9+
10+
'''Load the latest update for a Twitter user and leave it in an XHTML fragment'''
11+
12+
__author__ = 'dewitt@google.com'
13+
14+
import codecs
15+
import getopt
16+
import sys
17+
import twitter
18+
19+
TEMPLATE = """
20+
<div class="twitter">
21+
<span class="twitter-user"><a href="http://twitter.com/%s">Twitter</a>: </span>
22+
<span class="twitter-text">%s</span>
23+
<span class="twitter-relative-created-at"><a href="http://twitter.com/%s/statuses/%s">Posted %s</a></span>
24+
</div>
25+
"""
26+
27+
28+
def Usage():
29+
print 'Usage: %s [options] twitterid' % __file__
30+
print
31+
print ' This script fetches a users latest twitter update and stores'
32+
print ' the result in a file as an XHTML fragment'
33+
print
34+
print ' Options:'
35+
print ' --help -h : print this help'
36+
print ' --output : the output file [default: stdout]'
37+
38+
39+
def FetchTwitter(user, output):
40+
assert user
41+
encoding = 'utf-8'
42+
import tweet
43+
rc = tweet.TweetRc()
44+
consumer_key = rc.GetConsumerKey()
45+
consumer_secret = rc.GetConsumerSecret()
46+
access_key = rc.GetAccessKey()
47+
access_secret = rc.GetAccessSecret()
48+
if not consumer_key or not consumer_secret or not access_key or not access_secret:
49+
print("mising oAuth key or secret")
50+
api = twitter.Api(consumer_key=consumer_key, consumer_secret=consumer_secret,
51+
access_token_key=access_key, access_token_secret=access_secret,
52+
input_encoding=encoding)
53+
54+
statuses = api.GetUserTimeline(user_id=user, count=1)
55+
s = statuses[0]
56+
print(statuses)
57+
xhtml = TEMPLATE % (s.user.screen_name, s.text, s.user.screen_name, s.id, s.relative_created_at)
58+
if output:
59+
Save(xhtml, output)
60+
else:
61+
print xhtml
62+
63+
64+
def Save(xhtml, output):
65+
out = codecs.open(output, mode='w', encoding='ascii',
66+
errors='xmlcharrefreplace')
67+
out.write(xhtml)
68+
out.close()
69+
70+
71+
def main():
72+
try:
73+
opts, args = getopt.gnu_getopt(sys.argv[1:], 'ho', ['help', 'output='])
74+
except getopt.GetoptError:
75+
Usage()
76+
sys.exit(2)
77+
try:
78+
user = args[0]
79+
except:
80+
Usage()
81+
sys.exit(2)
82+
output = None
83+
for o, a in opts:
84+
if o in ("-h", "--help"):
85+
Usage()
86+
sys.exit(2)
87+
if o in ("-o", "--output"):
88+
output = a
89+
FetchTwitter(user, output)
90+
91+
92+
if __name__ == "__main__":
93+
main()

twitter/api.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4370,7 +4370,7 @@ def _DecompressGzippedResponse(self, response):
43704370

43714371
def _Encode(self, s):
43724372
if self._input_encoding:
4373-
return str(s, self._input_encoding).encode('utf-8')
4373+
return str(s).encode(self._input_encoding)
43744374
else:
43754375
return str(s).encode('utf-8')
43764376

0 commit comments

Comments
 (0)