from pypresence import Presence, ActivityType import os from dotenv import load_dotenv import icalendar import pytz import requests from datetime import datetime, timezone import time load_dotenv() # Initialize PyPresence with your application ID client_id = os.getenv('DISCORD_APPLICATION_ID') ics_url = os.getenv('ICS_URL') if not client_id or not ics_url: raise ValueError("issue in .env file") RPC = Presence(client_id) try: RPC.connect() except Exception as e: print(f"Failed to connect to Discord: {e}") exit(1) def fetch_ics(url): response = requests.get(url) if response.status_code == 200: return response.content else: raise Exception("Failed to fetch the .ics file") def parse_ics(ics_content): cal = icalendar.Calendar.from_ical(ics_content) events = [] for component in cal.walk(): if component.name == 'VEVENT': summary = component.get('summary') dtstart = component.get('dtstart').dt dtend = component.get('dtend').dt # Convert datetime to timezone-aware if necessary if isinstance(dtstart, datetime) and dtstart.tzinfo is None: dtstart = pytz.utc.localize(dtstart) if isinstance(dtend, datetime) and dtend.tzinfo is None: dtend = pytz.utc.localize(dtend) events.append({ 'summary': str(summary), 'start': dtstart, 'end': dtend }) return events def update_presence(event): now = datetime.now(timezone.utc) if event['start'] <= now <= event['end']: parts = event['summary'].split(' - ') if len(parts) == 2: state_part, details_part = parts else: state_part = event['summary'] details_part = 'Event' RPC.update( activity_type=ActivityType.WATCHING, details=details_part, state=state_part, large_image="favicon", # Replace with your image key large_text="Bangers incomming", start=int(event['start'].timestamp()), end=int(event['end'].timestamp()) ) else: RPC.clear() print("Rich Presence is running. Press Ctrl+C to stop.") try: while True: try: ics_content = fetch_ics(ics_url) events = parse_ics(ics_content) for event in events: update_presence(event) except Exception as e: print(f"An error occurred: {e}") time.sleep(60) # Update every minute except KeyboardInterrupt: print("Stopping Rich Presence...") finally: RPC.close()