Skip to content

Instantly share code, notes, and snippets.

@ateska
Last active April 21, 2023 12:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ateska/46d1a87bf0d38cf0a3c2311a7caad065 to your computer and use it in GitHub Desktop.
Save ateska/46d1a87bf0d38cf0a3c2311a7caad065 to your computer and use it in GitHub Desktop.
import os
from slack_sdk import WebClient
from slack_sdk.errors import SlackApiError
# Initialize a Web API client with your bot token
slack_bot_token = 'xoxb-your-bot-token'
client = WebClient(token=slack_bot_token)
# Define the message text
message_text = 'Hello, this is a message with a PDF attachment'
# Upload the PDF file
file_path = 'path/to/your/file.pdf'
file_name = os.path.basename(file_path)
try:
upload_response = client.files_upload(
channels='#your-channel-name',
file=file_path,
filename=file_name,
title='My PDF File'
)
file_id = upload_response['file']['id']
print(f"File uploaded: {file_id}")
except SlackApiError as e:
print(f"Error uploading file: {e}")
# Attach the uploaded PDF file to the message
attachments = [
{
"fallback": "Required plain-text summary of the attachment.",
"color": "#2eb886",
"pretext": "Optional text that appears above the attachment block",
"title": "My PDF File",
"title_link": f"https://app.slack.com/files/{file_id}", # URL to view the uploaded file
"text": "Optional text that appears within the attachment",
}
]
# Send the message with attachments
try:
response = client.chat_postMessage(
channel='#your-channel-name',
text=message_text,
attachments=attachments
)
print('Message sent: ', response['ts'])
except SlackApiError as e:
print(f"Error sending message: {e}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment