import random import json import pypokedex import json import datetime import requests from huggingface_hub import login, HfApi import os hf_token = os.environ["HF_TOKEN"] login(hf_token) hfapi = HfApi() metadata_url = "https://huggingface.co/spaces/panda1835/pokemon-data/raw/main/metadata.json" def read_json_from_url(url): try: response = requests.get(url) response.raise_for_status() # Will raise an HTTPError if the HTTP request returned an unsuccessful status code json_data = response.json() return json_data except requests.RequestException as e: print(f"Error occurred: {e}") return None def read_metadata(): # Open the JSON file and read its contents # with open("metadata.json", "r") as json_file: # metadata = json.load(json_file) metadata = read_json_from_url(metadata_url) # Access the JSON data return metadata def save_metadata(metadata): with open("metadata.json", "w") as json_file: json.dump(metadata, json_file, indent=4) try: hfapi.upload_file( path_or_fileobj="metadata.json", path_in_repo="metadata.json", repo_id="panda1835/pokemon-data", repo_type="space", ) return "### Data updated βœ…" except Exception as e: return "❌ " + str(e) def get_all_pokemon_dex(): metadata = read_metadata() return list(metadata["pokemon"].keys()) def get_streak(): metadata = read_metadata() return metadata["streak"] def get_total_minifigure(): metadata = read_metadata() return metadata["total_minifigure"] def get_money(): metadata = read_metadata() return metadata["money"] def get_pokemon(): metadata = read_metadata() return metadata["pokemon"] def get_pokemon_by_dex(dex): metadata = read_metadata() return metadata["pokemon"][dex] def get_donation(): metadata = read_metadata() return metadata["donation"] def get_wishlist(): metadata = read_metadata() return metadata["wishlist"] def get_poke_energy(dex): metadata = read_metadata() return metadata["pokemon"][dex]["energy"] def get_pokemon_info(dex): pokemon = pypokedex.get(dex=dex) description = pokemon.get_descriptions() try: description = description[list(description.keys())[0]].replace('\n', ' ') except: description = "Not yet understood" name = pokemon.name.capitalize() image = list(pokemon.other_sprites.values())[2].front['default'] try: sprite = pokemon.sprites.front['default'] except: sprite = None return name, description, image, sprite def get_evolution_chain(dex): # Fetch the PokΓ©mon species data for Ivysaur pokemon = pypokedex.get(dex=dex) name = pokemon.name species_url = f"https://pokeapi.co/api/v2/pokemon-species/{name}" species_response = requests.get(species_url) species_data = json.loads(species_response.text) # Extract the evolution chain URL evolution_chain_url = species_data['evolution_chain']['url'] # Fetch the evolution chain data evolution_chain_response = requests.get(evolution_chain_url) evolution_chain_data = json.loads(evolution_chain_response.text) # Parse the evolution chain data and get the full list of evolutions evolution_list = [] chain = evolution_chain_data['chain'] while chain: species_name = chain['species']['name'] evolution_list.append(pypokedex.get(name=species_name).dex) if chain.get('evolves_to') != []: chain = chain.get('evolves_to')[0] else: break return evolution_list def can_evolve(dex, energy): metadata = read_metadata() if metadata["pokemon"][dex]["max_energy"] <= energy: return True else: return False def evolve_to(dex): evolution_chain = get_evolution_chain(dex) print(evolution_chain) # If fully evolved if dex == evolution_chain[-1]: return None else: evolve_dex = evolution_chain[evolution_chain.index(dex) + 1] name, description, image, sprite = get_pokemon_info(evolve_dex) return { evolve_dex: { "name": name, "image": image, "sprite": sprite, "description": description, "energy": 0, "max_energy": 100 + 20*(evolution_chain.index(dex) + 1), "visible": True } } def random_pokemon(): min_dex = 1 max_dex = 1017 all_dex = get_all_pokemon_dex() while True: dex = random.randint(min_dex, max_dex) # if not in the team and the first level if (dex not in all_dex) and (dex == get_evolution_chain(dex)[0]): name, description, image, sprite = get_pokemon_info(dex) break random_pokemon = { dex: { "name": name, "image": image, "sprite": sprite, "description": description, "energy": 0, "max_energy": 100, "visible": True } } return random_pokemon def add_new_pokemon(new_pokemon): metadata = read_metadata() metadata["pokemon"].update(new_pokemon) return metadata def is_lucky(streak): p = (-0.0274 * streak + 30) / 100 # Generate a random number from the Bernoulli distribution random_number = random.choices([0, 1], weights=[1-p, p])[0] return random_number == 1 def lucky_draw(): """Placeholder 0 = 50 energy 1 = a new pokemon 2 = money 3 = minifigure """ metadata = read_metadata() gifts = ['energy', 'pokemon', 'money', 'minifigure'] random_number = random.choices([0, 1, 2, 3], weights=[0.3, 0.3, 0.3, 0.1])[0] gift = gifts[random_number] if gift == 'money': money = random.choices([20000, 50000, 100000], weights=[0.4, 0.4, 0.4])[0] metadata["money"] += money save_metadata(metadata) return ('money', money) elif gift == 'pokemon': new_pokemon = random_pokemon() metadata = add_new_pokemon(new_pokemon) save_metadata(metadata) return ("pokemon", new_pokemon) elif gift == 'energy': all_dex = get_all_pokemon_dex() random_dex = random.choice(all_dex) metadata["pokemon"][random_dex]["energy"] += 50 save_metadata(metadata) return ('energy', random_dex, 50) else: metadata["total_minifigure"] += 1 save_metadata(metadata) return ('minifigure', 'https://u6wdnj9wggobj.vcdn.cloud/media/catalog/product/cache/a237138a07ed0dd2cc8a6fa440635ea6/7/1/71034_3_.jpg') def poke_energy(streak, intensity): return round(7 + streak/60 + intensity) def new_streak(intensity): metadata = read_metadata() metadata["streak"] += 1 streak = metadata["streak"] reward = "" date1 = datetime.datetime.today() date2 = datetime.datetime.strptime(metadata["last_streak_day"], "%d/%m/%Y") delta = date1 - date2 distance = delta.days if (distance >= 2): metadata = { "streak": 0, "total_minifigure": 0, "donation": [ { "wildact": { "donation_link": "https://www.wildact-vn.org/en/support-us/donate/", "image": "https://a-us.storyblok.com/f/1014782/567x567/7338612d04/wa_logo-2023-vn.png" } } ], "last_streak_day": datetime.datetime.today().strftime("%d/%m/%Y"), "money": 0, "pokemon": { "4": { "name": "Charmander", "image": "https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/other/official-artwork/4.png", "sprite": "https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/4.png", "description": "Obviously prefers hot places. When it rains, steam is said to spout from the tip of its tail.", "energy": 0, "max_energy": 100, "visible": True } }, "wishlist": [ "https://u6wdnj9wggobj.vcdn.cloud/media/catalog/product/cache/a237138a07ed0dd2cc8a6fa440635ea6/7/6/76414_copy_0.jpg", "https://u6wdnj9wggobj.vcdn.cloud/media/catalog/product/cache/a237138a07ed0dd2cc8a6fa440635ea6/6/0/60302_7_.jpg" ] } save_metadata(metadata) return "# πŸ”₯πŸ”₯πŸ”₯ YOU SKIP 1 DAYYYYYY. EVERYTHING IS BURNTTTTTT. ALL YOUR FRIENDS ARE VANISHINGGGGG πŸ”₯πŸ”₯πŸ”₯" if is_lucky(streak): gift = lucky_draw() if gift[0] == 'money': gift_str = f"{gift[1]} VND" if gift[0] == 'pokemon': new_pokemon = gift[1] dex = list(new_pokemon.keys())[0] gift_str = f"**{new_pokemon[dex]['name']}**" if gift[0] == 'minifigure': gift_str = "a minifigure" if gift[0] == 'energy': gift_str = f"{gift[2]} energy point to **{get_pokemon_by_dex(gift[1])['name']}**" reward += f"**Lucky!!!** You are awarded {gift_str} 🎁.\n\n \n\n" # Update new reward metadata = read_metadata() all_dex = get_all_pokemon_dex() while True: random_dex = random.choice(all_dex) if metadata["pokemon"][random_dex]["visible"] == True: energy = poke_energy(streak, intensity) metadata["pokemon"][random_dex]["energy"] += energy if can_evolve(random_dex, metadata["pokemon"][random_dex]["energy"]): metadata["pokemon"][random_dex]["visible"] = False evolve_pokemon = evolve_to(int(random_dex)) evolve_dex = list(evolve_pokemon.keys())[0] metadata["pokemon"].update(evolve_pokemon) reward += f"Your **{metadata['pokemon'][random_dex]['name']}** has just evolved into **{metadata['pokemon'][evolve_dex]['name']}**. Hoorayyyyy!!! πŸ₯³.\n\n \n\n" reward += f"Your **{metadata['pokemon'][random_dex]['name']}** has just got **{energy} EXP** β˜€οΈ.\n\n \n\n" break metadata["last_streak_day"] = datetime.datetime.today().strftime("%d/%m/%Y") save_metadata(metadata) is_first_day_of_week = datetime.date.today().weekday() == 0 if is_first_day_of_week: new_pokemon = random_pokemon() add_new_pokemon(new_pokemon) dex = list(new_pokemon.keys())[0] reward += f"**{new_pokemon[dex]['name']}** has joined with your family!!!" return reward