from telethon import events, Button
from datetime import datetime, timedelta
import pytz
import requests
# Replace 'YOUR_API_ID' and 'YOUR_API_HASH' with your actual values
api_id = 'YOUR_API_ID'
api_hash = 'YOUR_API_HASH'
# Replace 'YOUR_BOT_TOKEN' with your actual bot token
bot_token = 'YOUR_BOT_TOKEN'
# Function to get the SubsPlease schedule for a specific day
def get_subsplease_schedule(date_param):
# SubsPlease API endpoint for schedule
api_url = f'https://subsplease.org/api/?f=schedule&h=true&tz=$&date={date_param}'
# Make the API request
try:
response = requests.get(api_url)
response.raise_for_status() # Raise an HTTPError for bad responses
return response.json()
except requests.exceptions.RequestException as e:
print(f"Error fetching SubsPlease schedule: {e}")
return None
# Function to convert UTC time to Indian Standard Time (IST)
def convert_utc_to_ist(utc_time_str):
# Parse the UTC time string
utc_time = datetime.strptime(utc_time_str, '%H:%M')
# Set the time zone to Indian Standard Time (IST)
ist_timezone = pytz.timezone('Asia/Kolkata')
# Get today's date in IST
today_ist = datetime.now(ist_timezone).date()
# Combine today's date with the parsed time
ist_time = datetime.combine(today_ist, utc_time.time()).astimezone(ist_timezone)
# Format the IST time and date
formatted_ist_time = ist_time.strftime('%Y-%m-%d %H:%M:%S IST')
return formatted_ist_time
# Function to get the date of the next occurrence of a specified day
def get_next_occurrence_of_day(day):
today = datetime.utcnow()
days_until_target_day = (today.weekday() - day) % 7
next_occurrence = today + timedelta(days=(7 - days_until_target_day))
return next_occurrence.strftime('%Y-%m-%d')
# Function to print a tick or cross based on the aired status
def print_status(aired_status):
return '✅' if aired_status else '❌'
# Function to get the schedule for a specific day
async def get_schedule_for_day(event, day):
try:
# Get the schedule for the specified day
target_day_index = day
target_day_date = get_next_occurrence_of_day(target_day_index)
# Get the SubsPlease schedule for the specified day
response_data = get_subsplease_schedule(target_day_date)
if response_data:
# Extract anime titles, airing times, and aired status
schedule = response_data.get('schedule', [])
# Prepare the response message
response_msg = "✅ Aired | ❌ Not Aired\n\n"
# Append anime details with status
for entry in schedule:
anime_title = entry.get('title', '')
airing_time_utc = entry.get('time', '')
aired_status = entry.get('aired', False)
# Convert UTC time to IST
airing_time_ist = convert_utc_to_ist(airing_time_utc)
response_msg += f"{anime_title} - {airing_time_ist} | Status: {print_status(aired_status)}\n"
# Send the response message
await event.edit(response_msg)
else:
await event.edit("Error fetching SubsPlease schedule. Please try again later.")
except Exception as e:
print(f"Error in get_schedule_for_day: {e}")
await event.edit("An error occurred. Please try again later.")
# Define the Telethon event handler for the /subsplease command
@events.register(events.NewMessage(pattern='/subsplease'))
async def subsplease_handler(event):
try:
# Define the button rows for each day
button_rows = []
for day_index, day_name in enumerate(["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"], start=1):
button_rows.append([Button.inline(day_name, data=f'schedule_{day_index}')])
# Build the response message
response_msg = "Today's currently airing animes:\n"
response_msg += "Press a button to view the schedule for a specific day.\n"
# Send the initial response message with inline buttons
await event.respond(response_msg, buttons=button_rows)
except Exception as e:
print(f"Error in subsplease_handler: {e}")
# Define the Telethon event handler for button clicks
@events.register(events.CallbackQuery(pattern=b'schedule_(\d+)'))
async def button_click_handler(event):
try:
# Extract the day index from the button data
day_index = int(event.pattern_match.group(1))
# Get the schedule for the specified day and edit the response
await get_schedule_for_day(event, day_index)
except Exception as e:
print(f"Error in button_click_handler: {e}")
# Start the Telethon client
from telethon import TelegramClient
with TelegramClient('session_name', api_id, api_hash) as client:
client.run_until_disconnected()