Sharing files via HipChat is a very useful feature. However, it’s on my opinion, one of the hardest APIs to use. Here’s an example of how to do it in python:

#!/bin/python

import argparse
import json
import os.path
import re
import requests
import sys
from email.mime.multipart import MIMEMultipart
from email.mime.nonmultipart import MIMENonMultipart

requests.packages.urllib3.disable_warnings()

def post_file(token, url, msg_body, file_path):
    headers = {"Content-Type": "application/json", "Authorization": "Bearer {}".format(token)}

    related = MIMEMultipart("related")

    part_body = MIMENonMultipart("application", "json", charset="utf8")
    part_body.add_header("Content-Disposition", 'attachment; name="body"')
    part_body.set_payload(json.dumps(msg_body))
    related.attach(part_body)

    file_name = os.path.basename(file_path)
    with open(file_path, 'rb') as f:
        file_data = f.read()

    part_file = MIMENonMultipart('application', "octet-stream")
    part_file.set_payload(file_data, "utf-8")
    part_file.add_header("Content-Disposition", 'attachment; name="file"; filename="{}"'.format(file_name))
    related.attach(part_file)
    body = related.as_string().split('\n\n', 1)[1]

    headers.update(dict(list(related.items())))

    resp = requests.post(url, data=body, headers=headers, verify=False)
    resp.raise_for_status()

def share_file_with_room(api_url, room_id, token, file_path, message):
    url = "{}/room/{}/share/file".format(api_url, room_id)
    post_file(token, url, {"message": message}, file_path)    

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='Share a file with a room')

    parser.add_argument('-r', '--room', dest='room', type=str, help='The room id', required=True)
    parser.add_argument('-t', '--token', dest='token', type=str, help='The HipChat authorization token', required=True)
    parser.add_argument('-f', '--file', dest='file_path', type=str, help='The path to the file', required=True)
    parser.add_argument('-m', '--message', dest='message', type=str, help='The message to include with the file', required=False, default='')
    parser.add_argument('--api-url', dest='api_url', type=str, help='The HipChat API url', required=False, default="https://hipchat.com/v2")
    user_options = parser.parse_args()

    share_file_with_room(user_options.api_url, user_options.room, user_options.token, user_options.file_path, user_options.message)

Hope it helps!

Build a stride bot in seconds with glitch

After a few months on beta, Stride's developer API is finally open [to the world](https://blog.stride.com/custom-apps-all-aboard-strides-...… Continue reading

Change email in your commit history

Published on July 16, 2017

Automate your lights with openHAB and Alexa

Published on December 10, 2016