Home > Enterprise >  Send messages to Slack with attachments using Python
Send messages to Slack with attachments using Python

Time:03-31

I'm trying to send messages to Slack using Python. It's working for the normal messages but I need it with attaching files.

In this example, I'm trying to send an image located on my local device. Within the following piece of code:

import os
import slack
from slack_sdk import WebClient
from pathlib import Path
from dotenv import load_dotenv
from slack_sdk.errors import SlackApiError

env_path = Path('.') / '.env'
load_dotenv(dotenv_path=env_path)
client = slack.WebClient(token=os.environ['SLACK_TOKEN'])

try:
    filepath = "./ccc.jpg"
    response = client.files_upload(channels='#test', file=filepath)
    assert response["file"]  # the uploaded file
except SlackApiError as e:
    assert e.response["ok"] is False
    assert e.response["error"]
    print(f"Got an error: {e.response['error']}")

When I try to run the code it shows this type of error/warning:

C:\ProgramData\Anaconda3\envs\practice\lib\site-packages\slack\deprecation.py:16: UserWarning: slack package is deprecated. Please use slack_sdk.web/webhook/rtm package instead. For more info, go to https://slack.dev/python-slack-sdk/v3-migration/
  warnings.warn(message)
Got an error: missing_scope

Any way to solve this kind of problem?

CodePudding user response:

The error missing_scope means the application with this token doesn't have enough permissions, meaning 'scope' is the terminology for permission in Slack.

To solve this check the Required Scopes section here https://api.slack.com/methods/files.upload

you will find you need to give your application the following permissions 'files:write', you can do that by going to https://api.slack.com -> your apps on the top right -> pick your application and go to 'OAuth & Permissions' tab, scroll down and you will find scopes sections, from there you can add the required scope.

you will get a notification (banner) at the top of the page that you need to reinstall your app, do that then invite your bot/application to your channel and run your code again.

Just make sure to use the latest slack_sdk, not the deprecated one.

This script should run with no errors:

import os
from slack_sdk import WebClient
from pathlib import Path
from dotenv import load_dotenv
from slack_sdk.errors import SlackApiError

env_path = Path('.') / '.env'
load_dotenv(dotenv_path=env_path)
client = WebClient(token=os.environ['SLACK_TOKEN'])

try:
    filepath = "./ccc.jpg"
    response = client.files_upload(channels='#test', file=filepath)
    assert response["file"]  # the uploaded file
except SlackApiError as e:
    assert e.response["ok"] is False
    assert e.response["error"]
    print(f"Got an error: {e.response['error']}")
  • Related