Spaces:
Running
on
CPU Upgrade
Running
on
CPU Upgrade
import os | |
import praw | |
import threading | |
import gradio as gr | |
from slack_sdk import WebClient | |
from slack_sdk.errors import SlackApiError | |
SLACK_BOT_TOKEN = os.getenv('BOT_USER_OAUTH_TOKEN_HF') | |
SLACK_CHANNEL_ID = 'C079VG7D03V' | |
SLACK_CHANNEL_ID_TEST = 'C07B4KNU5BQ' | |
slack_client = WebClient(token=SLACK_BOT_TOKEN) | |
print("Initializing Reddit instance...") | |
client_id = os.getenv('CLIENT_ID') | |
client_secret = os.getenv('CLIENT_SECRET') | |
user_agent = os.getenv('USER_AGENT') | |
username = os.getenv('REDDIT_USERNAME') | |
password = os.getenv('REDDIT_PASSWORD') | |
print(f"Client ID: {client_id}") | |
print(f"Client Secret is set: {'Yes' if client_secret else 'No'}") | |
print(f"User Agent: {user_agent}") | |
print(f"Username: {username}") | |
print(f"Password is set: {'Yes' if password else 'No'}") | |
# Check if all credentials are retrieved successfully | |
if not all([client_id, client_secret, user_agent, username, password]): | |
print("Error: One or more environment variables are missing.") | |
exit(1) | |
try: | |
reddit = praw.Reddit( | |
client_id=client_id, | |
client_secret=client_secret, | |
user_agent=user_agent, | |
username=username, | |
password=password | |
) | |
print("Reddit instance created successfully.") | |
except Exception as e: | |
print(f"Error creating Reddit instance: {e}") | |
exit(1) | |
def monitor_new_posts(): | |
try: | |
print("Attempting to access subreddit...") | |
subreddit_name = 'huggingface' # test | |
subreddit = reddit.subreddit(subreddit_name) | |
print(f"Successfully accessed subreddit: {subreddit.display_name}") | |
except Exception as e: | |
print(f"Error accessing subreddit: {e}") | |
return | |
print("Starting to monitor new posts...") | |
try: | |
for submission in subreddit.stream.submissions(skip_existing=True): | |
print(f"New post detected in r/{subreddit.display_name}:") | |
print(f"Title: {submission.title}") | |
print(f"Author: {submission.author}") | |
print(f"URL: {submission.url}") | |
print(f"Content: {submission.selftext}\n") | |
text_content = f"*{submission.title}*" | |
if submission.selftext: | |
text_content += f"\n{submission.selftext}" | |
else: | |
text_content += "\n_No content available (may be a link or image post)_" | |
text_content += f"{submission.url}" | |
response = slack_client.chat_postMessage( | |
channel=SLACK_CHANNEL_ID, | |
text=text_content, | |
thread_ts=None, | |
unfurl_links=False, | |
unfurl_media=False | |
) | |
except Exception as e: | |
print(f"Error during streaming submissions: {e}") | |
REPORT = "" | |
def log(msg): | |
global REPORT | |
REPORT += "\n\n" + msg | |
with gr.Blocks() as demo: | |
gr.Markdown("Background job running to check for access requests...") | |
report = gr.Markdown() | |
report.attach_load_event(lambda: REPORT, every=1) | |
threading.Thread(target=monitor_new_posts, daemon=True).start() | |
demo.launch() | |