How to send Image to Slack as slack bot via slackclient?

Viewed 10067

I'm building a simple bot to periodically generate charts as images and post to slack via the python slackclient package.

I've managed to send a bot message with the code below:

def post_message_to_channel(self, channel_id, message=DEFAULT_TEST_MESSAGE):
    sc = SlackClient(TOKEN)
    sc.api_call(
        "chat.postMessage",
        channel=channel_id,
        username='mybot',
        text='test text message'
    )

But when I try to do the same with a file upload, the image is sent correctly, but it shows my name, and not the specified bot name:

def post_image_to_channel(self, channel_name, filepath, tile='Test Upload'):
    sc = SlackClient(TOKEN)
    with open(filepath, 'rb') as file_content:
        sc.api_call(
                "files.upload",
                channels=channel_id,
                file=file_content,
                title=tile,
                username='mybot',               
            )

Looking at the slack API documentation for files.upload, it appears that the username is not available.

How can I send the files.upload image using the bot name?

3 Answers

Another approach is to send your images as part of a message attachments. That way you can also include some context information around the chart. And since you are sending a message you have still full control over username etc.

import slack
import json
import os

def pureimg(data1):
        data1 = '[{"text": "", "image_url": "'+data1+'"}]'
        data1 = [json.loads(data1[1:-1])]
        return data1

#This function will make the image url to correct format.

slacker = slack.WebClient(token='your-token-here')

payoff=os.path.join(os.path.dirname(os.path.realpath(__file__)), 'filename.png')
#It gives cross OS compatibility on filepath.

response=slacker.files_upload(channel='#theta',file=payoff)
payoff=response['file']['permalink']

#First We upload the local file to Slack and fetch permalink.
#If you do not have any local file just put the external image URL in the payoff.

response=slacker.chat_postMessage(channel='#channel_name', text="Sample Text", username='Bot name', attachments=pureimg(payoff), icon_emoji=':emoji:')

#Then, We post to Slack Channel as a bot!
Related