slack_send_message.py 861 B

1234567891011121314151617181920212223242526272829
  1. import os
  2. import pickle
  3. from slack_sdk import WebClient
  4. from slack_sdk.errors import SlackApiError
  5. def slack_send_message(channel_id, text):
  6. # Load Slack credentials
  7. credentials_path = './credentials/slack/token.pickle'
  8. if os.path.exists(credentials_path):
  9. with open(credentials_path, 'rb') as token_file:
  10. slack_token = pickle.load(token_file)
  11. else:
  12. raise FileNotFoundError("Slack token file not found.")
  13. client = WebClient(token=slack_token)
  14. try:
  15. # Call the chat.postMessage method using the WebClient
  16. result = client.chat_postMessage(
  17. channel=channel_id,
  18. text=text
  19. )
  20. print("Message sent successfully.", result)
  21. except SlackApiError as e:
  22. # Print the error
  23. print(f"Error sending message: {e.response['error']}")
  24. raise