dust.py 文件源码

python
阅读 22 收藏 0 点赞 0 评论 0

项目:dust 作者: ljcooke 项目源码 文件源码
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)
评论列表
文章目录


问题


面经


文章

微信
公众号

扫码关注公众号