Update Slack Message files: modify requirements.txt and slack_poster.py

This commit is contained in:
reethu2703 2025-10-04 23:22:52 +05:30
parent 5622378a52
commit e0e4885d23
2 changed files with 26 additions and 16 deletions

View File

@ -1,2 +1,3 @@
slack_sdk>=3.21.0 slack_sdk>=3.21.0
requests>=2.28.0 requests>=2.28.0
python-dotenv>=1.0.0

View File

@ -6,6 +6,7 @@ A command-line tool that posts messages to Slack channels using the Slack Web AP
""" """
import argparse import argparse
import os
import sys import sys
from datetime import datetime from datetime import datetime
from typing import Optional from typing import Optional
@ -17,6 +18,14 @@ except ImportError:
print("Error: slack_sdk not installed. Run: pip install slack_sdk") print("Error: slack_sdk not installed. Run: pip install slack_sdk")
sys.exit(1) sys.exit(1)
# Try to load environment variables from .env file
try:
from dotenv import load_dotenv
load_dotenv()
except ImportError:
# dotenv not installed, continue without it
pass
class SlackPoster: class SlackPoster:
"""Main class for posting messages to Slack.""" """Main class for posting messages to Slack."""
@ -47,9 +56,9 @@ class SlackPoster:
) )
return response return response
except SlackApiError as e: except SlackApiError as e:
raise SlackApiError(f"Slack API Error: {e.response['error']}") raise e
except SlackClientError as e: except SlackClientError as e:
raise SlackClientError(f"Slack Client Error: {e}") raise e
def get_user_input(prompt: str, required: bool = True) -> str: def get_user_input(prompt: str, required: bool = True) -> str:
@ -138,8 +147,8 @@ Examples:
args = parser.parse_args() args = parser.parse_args()
# Get token # Get token (try environment variable first, then command line, then interactive)
token = args.token token = args.token or os.getenv('SLACK_BOT_TOKEN')
if not token: if not token:
print("Slack Token not provided. Please enter it interactively:") print("Slack Token not provided. Please enter it interactively:")
token = get_user_input("Enter your Slack token: ") token = get_user_input("Enter your Slack token: ")
@ -149,8 +158,8 @@ Examples:
print("Error: Invalid token format. Slack tokens typically start with 'xoxb-', 'xoxp-', 'xoxa-', or 'xoxr-'") print("Error: Invalid token format. Slack tokens typically start with 'xoxb-', 'xoxp-', 'xoxa-', or 'xoxr-'")
sys.exit(1) sys.exit(1)
# Get channel # Get channel (try environment variable first, then command line, then interactive)
channel = args.channel channel = args.channel or os.getenv('SLACK_CHANNEL_ID')
if not channel: if not channel:
print("Channel ID not provided. Please enter it interactively:") print("Channel ID not provided. Please enter it interactively:")
channel = get_user_input("Enter Slack channel ID (e.g., C04ABC123): ") channel = get_user_input("Enter Slack channel ID (e.g., C04ABC123): ")
@ -187,30 +196,30 @@ Examples:
except (ValueError, TypeError): except (ValueError, TypeError):
formatted_time = timestamp formatted_time = timestamp
print(f"✅ Success! Message posted to channel {channel_name}") print(f"[SUCCESS] Message posted to channel {channel_name}")
print(f"📅 Timestamp: {formatted_time}") print(f"[TIMESTAMP] {formatted_time}")
print(f"💬 Message: {message}") print(f"[MESSAGE] {message}")
except SlackApiError as e: except SlackApiError as e:
error_msg = str(e) error_msg = str(e)
if "invalid_auth" in error_msg.lower(): if "invalid_auth" in error_msg.lower():
print("❌ Error: Invalid token. Please check your Slack token.") print("[ERROR] Invalid token. Please check your Slack token.")
elif "channel_not_found" in error_msg.lower(): elif "channel_not_found" in error_msg.lower():
print(f"❌ Error: Channel '{channel}' not found. Please check the channel ID.") print(f"[ERROR] Channel '{channel}' not found. Please check the channel ID.")
elif "not_in_channel" in error_msg.lower(): elif "not_in_channel" in error_msg.lower():
print(f"❌ Error: Bot is not a member of channel '{channel}'. Please add the bot to the channel.") print(f"[ERROR] Bot is not a member of channel '{channel}'. Please add the bot to the channel.")
elif "rate_limited" in error_msg.lower(): elif "rate_limited" in error_msg.lower():
print("❌ Error: Rate limited. Please wait before trying again.") print("[ERROR] Rate limited. Please wait before trying again.")
else: else:
print(f" Slack API Error: {error_msg}") print(f"[ERROR] Slack API Error: {error_msg}")
sys.exit(1) sys.exit(1)
except SlackClientError as e: except SlackClientError as e:
print(f" Slack Client Error: {e}") print(f"[ERROR] Slack Client Error: {e}")
sys.exit(1) sys.exit(1)
except Exception as e: except Exception as e:
print(f" Unexpected error: {e}") print(f"[ERROR] Unexpected error: {e}")
sys.exit(1) sys.exit(1)