1

How can I send a file from my local computer to hipchat using a python API? I am currently using Hypchat but it is not well documented.

Here is my code so far:

import hypchat

hc = hypchat.HypChat("myKey")

room = hc.get_room('bigRoom')

I'm not sure how to proceed. I tried other methods such as this one but I keep getting the error:

[ERROR] HipChat file failed: '405 Client Error: Method Not Allowed for url: https://api.hipchat.com/v2/room/bigRoom/share/file'
user1367204
  • 4,549
  • 10
  • 49
  • 78
  • dumb question - but can you perform this task without the use of Python? If not, then it could be permissions issue. Have you supplied/are there any authorization tokens that are required? – MattR Jul 05 '17 at 16:50
  • Hi, yes I can perform it without Python. – user1367204 Jul 05 '17 at 16:53

1 Answers1

2

This code allows me to send any file to a hipchat room:

# do this:
#     pip install requests_toolbelt

from os                import path
from sys               import exit, stderr
from requests          import post
from requests_toolbelt import MultipartEncoder


class MultipartRelatedEncoder(MultipartEncoder):
    """A multipart/related encoder"""
    @property
    def content_type(self):
        return str('multipart/related; boundary={0}'.format(self.boundary_value))

    def _iter_fields(self):
        # change content-disposition from form-data to attachment
        for field in super(MultipartRelatedEncoder, self)._iter_fields():
            content_type = field.headers['Content-Type']
            field.make_multipart(content_disposition = 'attachment',
                                 content_type        = content_type)
            yield field




def hipchat_file(token, room, filepath, host='api.hipchat.com'):

    if not path.isfile(filepath):
        raise ValueError("File '{0}' does not exist".format(filepath))


    url                      = "https://{0}/v2/room/{1}/share/file".format(host, room)
    headers                  = {'Content-type': 'multipart/related; boundary=boundary123456'}
    headers['Authorization'] = "Bearer " + token



    m = MultipartRelatedEncoder(fields={'metadata' : (None, '', 'application/json; charset=UTF-8'),
                                        'file'     : (path.basename(filepath), open(filepath, 'rb'), 'text/csv')})

    headers['Content-type'] = m.content_type

    r = post(url, data=m, headers=headers)

if __name__ == '__main__:

    my_token = <my token>   
    my_room  = <room name>    
    my_file  = <filepath>

    try:
        hipchat_file(my_token, my_room, my_file)
    except Exception as e:
        msg = "[ERROR] HipChat file failed: '{0}'".format(e)
        print(msg, file=stderr)
        exit(1)

Shout out to @Martijn Pieters

user1367204
  • 4,549
  • 10
  • 49
  • 78