Skip to content

Instantly share code, notes, and snippets.

@llk23r
Created October 14, 2022 09:09
Show Gist options
  • Save llk23r/3e9fd449997dde8796af22e4ddde3b84 to your computer and use it in GitHub Desktop.
Save llk23r/3e9fd449997dde8796af22e4ddde3b84 to your computer and use it in GitHub Desktop.
Upload file to slack using the slack files.upload API.
import requests
from decouple import (
config,
) # decouple is a library that allows you to store your secrets in a .env file
SLACK_FILE_UPLOAD_URL = "https://slack.com/api/files.upload"
def upload_file_to_slack(file_path) -> dict:
"""Uploads a file to slack using the slack api
Read more about the slack api here: https://api.slack.com/methods/files.upload
Args:
file_path (str): The path to the file you want to upload
Returns:
dict: The 'file' response from the slack API.
"""
payload = {
"filename": "filename.html",
"filetype": "html",
"initial_comment": "Initial comment",
"title": "File title",
"channels": "Comma, separated, list, of, channels", # Optional
}
files = {"file": (file_path, open(file_path, "rb"), "html")}
bot_token = config(
"SLACK_BOT_TOKEN"
) # value from https://api.slack.com/apps/<APP_ID>/oauth
headers = {"Authorization": f"Bearer {bot_token}"}
response = requests.request(
"POST",
SLACK_FILE_UPLOAD_URL,
headers=headers,
data=payload,
files=files,
)
try:
return response.json().get("file")
except Exception as e:
return {"error": str(e), "status_code": response.status_code}
if __name__ == "__main__":
file_path = "path/to/file.html"
print(upload_file_to_slack(file_path))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment