the yampy yammer package for python allows you get the url to images in messages. However these images are only viewable if you are logged in.
I have access to message content via the api with an access token, but how do I download the images?
import yampy
import pprint
from werkzeug.wrappers import Request, Response
from datetime import datetime
import textwrap
import os,webbrowser
from flask import Flask
from flask import jsonify
pp = pprint.PrettyPrinter(indent=4)
authenticator = yampy.Authenticator(client_id="asdfadsfasdfsdf",
client_secret="asdfasdfasdf")
app = Flask(__name__)
redirect_uri = "https://localhost:8000/yammerasdf/api/v1/redirect"
# auth_url = authenticator.authorization_url(redirect_uri=redirect_uri)
# access_token = authenticator.fetch_access_token(code)
# access_data = authenticator.fetch_access_data(code)
# access_token = access_data.access_token.token
# user_info = access_data.user
# network_info = access_data.network
yammer = yampy.Yammer(access_token="asdfasdfasdfsd-asdfasdfadsf")
@app.route("/")
def hello():
messages = yammer.messages.from_user(2323423432, older_than=None, newer_than=None, limit=3, threaded=1)
# asdfmessages = yammer.messages.from_user(1663406272)
allposts = ''
messagesdata= []
for message in messages.messages:
post= '<div class="chat-body clearfix"><div class="header"><strong class="primary-font">asdfasdfdsf</strong>'
d1= message.created_at.split()[0]
d = datetime.strptime(d1, '%Y/%m/%d')
day_string = d.strftime('%A, %B %d')
post+= '<small class="pull-right text-muted">' + day_string + '</small></div>'
post+='<p style="margin-top:10px"><a href="' + message.web_url + '" target="_blank" style="font-size:13px;padding:15px" class="thumbnail">'
messageimages = []
for image in message.attachments:
webbrowser.open(image.image.url)
# urllib.request.urlretrieve(image.image.url)
# urllib.urlretrieve(image.image.url, "local-filename.jpg")
post+='<img src="' + image.image.url + '">'
messageimages.append(image.image.url)
post+= textwrap.wrap(message.content_excerpt, 120)[0] + '...</a></p></div><hr>'
allposts += post
messagedict = {'date':day_string, 'url':message.web_url, 'images':messageimages, 'content':textwrap.wrap(message.content_excerpt, 120)[0]}
messagesdata.append(messagedict.copy())
# messagesdata=['html',allposts]
return jsonify(messagesdata)
if __name__ == '__main__':
from werkzeug.serving import run_simple
port = int(os.environ.get('PORT', 5000))
app.run(host='0.0.0.0', port=port)
# run_simple('localhost', port, app)
Yampy only delivers back data as json format. To download the image you need the raw response and a stream. To do this you can use requests and shutil instead:
import requests
import shutil
headers = {"Authorization": "Bearer " + access_token}
response = requests.get("yammer_image_url", headers=headers, stream=True)
with open("path_to_new_image.jpg", "wb") as f:
response.raw.decode_content = True
shutil.copyfileobj(response.raw, f)