Skip to content

Instantly share code, notes, and snippets.

@wodim
Created September 19, 2014 12:41
Show Gist options
  • Select an option

  • Save wodim/95f4b414468e5a10af16 to your computer and use it in GitHub Desktop.

Select an option

Save wodim/95f4b414468e5a10af16 to your computer and use it in GitHub Desktop.
Python script to post images to Twitter. (Needs tweepy)
# -*- coding: utf-8 -*-
import re
import requests
import sys
import md5
import magic
import os
from tweepy.streaming import StreamListener
from tweepy import OAuthHandler
from tweepy import Stream
from tweepy import API
consumer_key=""
consumer_secret=""
access_token=""
access_token_secret=""
auth = OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = API(auth)
if len(sys.argv) < 2:
print("Usage: %s <file/url> [text]" % (sys.argv[0]),)
sys.exit(1)
if re.match(r'^https?://', sys.argv[1]):
# it's an url, so we need to download it
image_url = sys.argv[1]
session = requests.session()
response = session.get(image_url)
if response.status_code != requests.codes.ok:
raise Exception('Not 200.')
filename = 'poster_%s.jpeg' % md5.new(image_url).hexdigest()
with open(filename, 'wb') as handle:
for block in response.iter_content(1048576):
if not block:
break
handle.write(block)
handle.close()
mimetype = magic.from_file(filename, mime=True)
if not mimetype.startswith('image/'):
raise Exception('Not an image: ' + mimetype)
if os.stat(filename).st_size > 3072 * 1024: # 3MB? unsure
raise Exception('Bigger than 3MB')
else:
filename = sys.argv[1]
try:
api.update_with_media(filename, status=sys.argv[2])
except IndexError:
api.update_with_media(filename)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment