ccccnbo2 / ccc.py
coollsd's picture
Update ccc.py
ae2fb85 verified
raw
history blame
8.27 kB
import requests
import discord
from discord.ext import commands
import asyncio
import re
import os
TOKEN = os.environ['TOKEN']
CHANNEL_ID = 1298830206387228682
PETS_API = 'https://petsapi.deno.dev/'
EXISTS_API = 'https://existsapi.deno.dev/'
RAP_API = 'https://rapapi.deno.dev/'
intents = discord.Intents.default()
bot = commands.Bot(command_prefix='!', intents=intents)
pet_images = {}
pet_difficulties = {}
pet_raps = {}
async def update_rap_values():
try:
response = requests.get(RAP_API)
if response.status_code == 200:
data = response.json()
if data['status'] == 'ok':
# Clear existing RAP values
pet_raps.clear()
# Process each pet in the list
for pet_data in data['data']:
config_data = pet_data['configData']
pet_id = config_data['id']
value = pet_data['value']
# Check if it's a shiny pet
is_shiny = config_data.get('sh', False)
if is_shiny:
pet_raps[f"Shiny {pet_id}"] = value
else:
pet_raps[pet_id] = value
print(f"Updated RAP values for {len(data['data'])} pets")
except Exception as e:
print(f"Error fetching RAP values: {e}")
async def get_huge_secret_pets():
try:
response = requests.get(PETS_API)
if response.status_code == 200:
data = response.json()
if data['status'] == 'ok':
huge_secret_pets = []
for pet in data['data']:
config_data = pet['configData']
if config_data.get('huge') or config_data.get('secret'):
pet_name = config_data['name']
huge_secret_pets.append(pet_name)
huge_secret_pets.append(f"Shiny {pet_name}")
# Store difficulty value
difficulty = config_data.get('difficulty', 'Unknown')
pet_difficulties[pet_name] = difficulty
# Shiny pets are 100x harder
pet_difficulties[f"Shiny {pet_name}"] = difficulty * 100
if 'thumbnail' in config_data:
pet_images[pet_name] = config_data['thumbnail']
pet_images[f"Shiny {pet_name}"] = config_data['thumbnail']
print(f"Stored image URL for {pet_name}: {config_data['thumbnail']}")
print(f"Found {len(huge_secret_pets)} pets to track (including shiny versions)")
return huge_secret_pets
else:
print("API response status not OK")
return [] # Return empty list instead of None
except Exception as e:
print(f"Error fetching pets list: {e}")
return [] # Return empty list instead of None
except Exception as e:
print(f"Error fetching pets list: {e}")
return []
async def send_embed_message(channel, pet_name, previous_value, current_value, is_change=False):
pet_image_url = pet_images.get(pet_name, None)
difficulty = pet_difficulties.get(pet_name, "Unknown")
rap_value = pet_raps.get(pet_name, "No RAP")
# Format RAP value with commas
if isinstance(rap_value, (int, float)):
rap_display = f"{rap_value:,}"
else:
rap_display = rap_value
# Format difficulty with commas
if isinstance(difficulty, (int, float)):
difficulty_display = f"{difficulty:,}"
else:
difficulty_display = difficulty
# Format exist counts with commas
if isinstance(current_value, (int, float)):
current_display = f"{current_value:,}"
else:
current_display = current_value
if isinstance(previous_value, (int, float)):
previous_display = f"{previous_value:,}"
else:
previous_display = previous_value
embed = discord.Embed(
title=f"🎲 A {pet_name} was rolled! 🎲",
description=f"{pet_name} exists: **{current_display}**\nDifficulty: **1 in {difficulty_display}**\nRAP Value: **{rap_display}**",
color=discord.Color.blue() if not is_change else discord.Color.orange(),
)
if pet_image_url:
if isinstance(pet_image_url, str):
if pet_image_url.startswith('rbxassetid://'):
asset_id = pet_image_url.replace('rbxassetid://', '')
asset_id = re.search(r'^\d+', asset_id).group(0)
pet_image_url = f"https://rbxgleaks.pythonanywhere.com/asset/{asset_id}"
print(f"Using image URL for {pet_name}: {pet_image_url}")
embed.set_thumbnail(url=pet_image_url)
try:
await channel.send(embed=embed)
except discord.HTTPException as e:
print(f"Failed to send embed for {pet_name}: {e}")
await channel.send(f"🎲 A {pet_name} was rolled! Exists: {current_display} (Previous: {previous_display})")
async def petdata(tracked_pets):
try:
response = requests.get(EXISTS_API)
if response.status_code == 200:
data = response.json()
if data['status'] == 'ok':
pet_values = {pet: 0 for pet in tracked_pets}
for pet in data['data']:
pet_id = pet['configData']['id']
is_shiny = pet['configData'].get('sh', False)
value = pet['value']
pet_name = f"Shiny {pet_id}" if is_shiny else pet_id
if pet_name in pet_values:
print(f"Found pet: {pet_name} with exist count {value}")
pet_values[pet_name] = value
return pet_values
print(f"Error code: {response.status_code}")
except Exception as e:
print(f"Error: {e}")
return None
async def main_loop():
channel = bot.get_channel(CHANNEL_ID)
if channel is None:
print("Invalid channel ID. Please check your channel ID.")
return
tracked_pets = await get_huge_secret_pets()
if not tracked_pets: # If we get an empty list, wait and retry
print("No pets fetched, retrying in 60 seconds...")
await asyncio.sleep(60)
return
lastknown = {pet: None for pet in tracked_pets}
print(f"Initially tracking {len(tracked_pets)} pets")
while True:
try:
if not tracked_pets:
tracked_pets = await get_huge_secret_pets() or [] # Ensure we always have a list
lastknown.update({pet: None for pet in tracked_pets if pet not in lastknown})
# Update RAP values periodically
await update_rap_values()
vvalues = await petdata(tracked_pets)
if vvalues is not None:
for pet, value in vvalues.items():
if lastknown[pet] is None:
print(f"Initial value for {pet}: {value}")
elif value != lastknown[pet]:
await send_embed_message(channel, pet, lastknown[pet], value, is_change=True)
lastknown[pet] = value
else:
print("Broken check")
new_pets = await get_huge_secret_pets() or [] # Ensure we always have a list
if new_pets and set(new_pets) != set(tracked_pets): # Only compare if new_pets is not empty
print("Pet list updated!")
tracked_pets = new_pets
lastknown.update({pet: None for pet in tracked_pets if pet not in lastknown})
await asyncio.sleep(60)
except Exception as e:
print(f"Error in main loop: {e}")
await asyncio.sleep(60) # Wait before retrying if there's an error
@bot.event
async def on_ready():
print(f'Logged in as {bot.user.name}')
bot.loop.create_task(main_loop())
bot.run(TOKEN)