1

Slack offers a method to upload files through their api. The documentation is found here:

Slack files.upload method

On this page it gives an example of how to post a file:

curl -F file=@dramacat.gif -F "initial_comment=Shakes the cat" -F channels=C024BE91L,D032AC32T -H "Authorization: Bearer xoxa-xxxxxxxxx-xxxx" https://slack.com/api/files.upload

I am trying to translate how to execute this line of code using the httr package in R, with a file in my R working directory. I'm having trouble translating the different parts of the command. Here is what I have so far.

api_token='******'
f_path='c:/mark/consulting/dreamcloud' #this is also my working directory
f_name='alert_picture.png'

res<-httr::POST(url='https://slack.com/api/files.upload', httr::add_headers(`Content-Type` = "multipart/form-data"), 
      body = list(token=api_token, channels='CCJL7TMC7', title='test', file = httr::upload_file(f_path), filename=f_name))

When I run this I get the following error:

Error in curl::curl_fetch_memory(url, handle = handle) : 
  read function returned funny value

I tried to find better examples to use but so far no luck. Any suggestions are appreciated!

Adil B
  • 14,635
  • 11
  • 60
  • 78
Mark
  • 172
  • 1
  • 10

1 Answers1

1

There's an example in slackr's own gg_slackr method, which creates an image of a GGPlot and uploads it to Slack:

  res <- POST(url="https://slack.com/api/files.upload",
              add_headers(`Content-Type`="multipart/form-data"),
              body=list(file=upload_file(ftmp),
                        token=api_token, channels=modchan))

Your code seems to be passing a path to a directory rather than a file as the file parameter - consider changing that parameter to file=upload_file(paste(f_path, f_name, sep="/") and see if that fixes your error.

Adil B
  • 14,635
  • 11
  • 60
  • 78
  • 1
    You are a genius! Initially it didn't work because the 'modchan' parameter is actually a function to transform the channel name to the channel ID. Not sure why that wasn't working, but when I replaced it with the actual channel ID it posted the image. You are a lifesaver! – Mark Sep 07 '18 at 22:54
  • Glad I could help! – Adil B Sep 07 '18 at 23:40