Search code examples
pythonslackslack-api

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


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?


Solution

  • You have to send the file using a Bot User Token of a bot-user. You can find more info at the official documentation https://api.slack.com/bot-users