def post_tweet(text, image_path=None,
user_token=None, user_secret=None,
consumer_key=None, consumer_secret=None):
"""
Post a tweet, optionally with an image attached.
"""
if len(text) > 140:
raise ValueError('tweet is too long')
auth = twitter.OAuth(
user_token or os.environ['TWITTER_USER_TOKEN'],
user_secret or os.environ['TWITTER_USER_SECRET'],
consumer_key or os.environ['TWITTER_CONSUMER_KEY'],
consumer_secret or os.environ['TWITTER_CONSUMER_SECRET'])
image_data, image_id = None, None
if image_path:
with open(image_path, 'rb') as image_file:
image_data = image_file.read()
t_up = twitter.Twitter(domain='upload.twitter.com', auth=auth)
image_id = t_up.media.upload(media=image_data)['media_id_string']
if not (text.strip() or image_id):
raise ValueError('no text or images to tweet')
t_api = twitter.Twitter(auth=auth)
params = {
'status': text,
'trim_user': True,
}
if image_id:
params.update({
'media[]': base64.b64encode(image_data),
'_base64': True,
})
return t_api.statuses.update_with_media(**params)
else:
return t_api.statuses.update(**params)
评论列表
文章目录