Skip to content

Instantly share code, notes, and snippets.

@ostronom
Created October 27, 2017 17:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ostronom/b4f1168c052007dd5344ca4215c6f9be to your computer and use it in GitHub Desktop.
Save ostronom/b4f1168c052007dd5344ca4215c6f9be to your computer and use it in GitHub Desktop.
#!/usr/bin/env python2.7
# -*- coding: utf-8 -*-
import base64
import requests
from PIL import Image
import cStringIO
import os.path
import argparse
def bencode(t):
return base64.b64encode(t)
def get_images(location, sz=100):
img = Image.open(location)
origBuffer = cStringIO.StringIO()
img.save(origBuffer, format='PNG')
width, height = img.size
thumbBuffer = cStringIO.StringIO()
img.thumbnail((sz, sz), Image.ANTIALIAS)
img.save(thumbBuffer, format='PNG')
return (width, height, bencode(origBuffer.getvalue()), bencode(thumbBuffer.getvalue()))
def get_dict(peer_id, text, img_location):
data = {'peerId': peer_id, 'task': {}}
if text is not None:
data['task']['text'] = {'text': text}
if img_location is not None:
width, height, orig, preview = get_images(img_location)
data['task']['file'] = {
'data': orig,
'width': width,
'height': height,
'fileName': os.path.basename(img_location),
'mimeType': 'image/png',
'preview': {
'data': preview,
'width': 100,
'height': 100
}
}
return data
def post(api_url, token, peer_id, text, img_location):
data = get_dict(peer_id, text, img_location)
headers = {'Authorization': 'Bearer %s' % token}
return requests.post('https://%s/v1/posting' % api_url, json=data, headers=headers)
parser = argparse.ArgumentParser()
parser.add_argument('host')
parser.add_argument('token')
parser.add_argument('peer_id', type=int)
parser.add_argument('-t', '--text', dest='text', action='store')
parser.add_argument('-i', '--image', dest='image', action='store')
if __name__ == '__main__':
args = parser.parse_args()
if args.text is None and args.image is None:
print 'Either text or image should be set'
sys.exit(1)
res = post(args.host, args.token, args.peer_id, args.text, args.image)
if res.status_code == 200:
print 'Posted ok'
else:
print 'Error', res
sys.exit(1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment