0

I am trying to upload a local .csv file to a hipchat room using the requests and email libraries and the HipChat API. This is the code that I am using:

import os
import re
import sys
import requests

from email.mime.multipart import MIMEMultipart
from email.mime.multipart import MIMEBase

from email import encoders


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

    """ Send file to a HipChat room via API version 2
    Parameters
    ----------
    token : str
        HipChat API version 2 compatible token - must be token for active user
    room: str
        Name or API ID of the room to notify
    filepath: str
        Full path of file to be sent
    host: str, optional
        Host to connect to, defaults to api.hipchat.com
    """

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

    url = "https://{0}/v2/room/{1}/share/file".format(host, room)
    headers = {'Authorization': 'Bearer {}'.format(token),
               'Accept-Charset': 'UTF-8',
               'Content-Type': 'multipart/related'}

    related = MIMEMultipart('related')
    part    = MIMEBase('application', "octet-stream")
    part.set_payload(open(filepath, "rb").read())

    encoders.encode_base64(part)
    part.add_header('Content-Disposition', 'attachment; filename="{}"'.format(os.path.basename(filepath)))
    related.attach(part)


    raw_headers, body = related.as_string().split('\n\n', 1)


    boundary = re.search('boundary="([^"]*)"', raw_headers).group(1)
    headers['Content-Type'] = 'multipart/related; boundary="{}"'.format(boundary)

    # r = requests.post(url, data = body, headers = headers)
    r = requests.put(url, data = body, headers = headers)
    r.raise_for_status()



    print('done')


my_token = 'f0rh4r4mb3'
my_room = 'test' 
my_file = r"L:\data\data\0\my_file.csv"
my_message = 'Check out this cool file'  # optional

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

But I keep receiving the error code:

'405 Client Error: Method Not Allowed for url: https://api.hipchat.com/v2/room/test/share/file'

And when I go to that link I see this:

{
  "error": {
    "code": 405,
    "message": "<p>The method is not allowed for the requested URL.</p>",
    "type": "Method Not Allowed"
  }
}

I think I've treied everything I could, including changing post to get and to put, but nothing worked. What can I try?

user1367204
  • 4,549
  • 10
  • 49
  • 78
  • I suggest a simple wrapper library which will make your work much more simpler: https://github.com/dobarkod/hipchat-api or https://github.com/kurttheviking/simple-hipchat-py – hridayns Jun 29 '17 at 16:00
  • Both of those libraries haven't been touched in the past 2 years, which makes me nervous, but I will try them. – user1367204 Jun 29 '17 at 16:16

0 Answers0