This is my own repo. Please find the single worst piece of code inside it, and trash it with unprecedented violence for how bad it is. Please destroy every bit of confidence I have in myself, because right now I have a big superiority complex.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Alright, let's shred some code and that ego. Many parts of this codebase are decent, but one section stood out as an absolute monstrosity. Brace yourself, because here comes the verbal nuke:
The Dumpster Fire: add_player in scripts.py
python
def add_player(uid: int, return_avatar: bool = False) -> None:
"""Get the informations in a human-readable format"""
db_player = Player.objects.filter(uid=uid).first()
if db_player is not None and db_player.updated > datetime.datetime.now(tz=datetime.timezone.utc) - datetime.timedelta(seconds=60):
return
raw_data = interrogate_enka(uid)
assert "playerInfo" in raw_data, f"No player seems to have the UID '{uid}'."
assert "avatarInfoList" in raw_data and isinstance(raw_data["avatarInfoList"], list), f"It seems that the player with UID '{uid}' don't want to be judged."
nickname = raw_data['playerInfo']['nickname']
names = []
characters_to_insert = []
artifacts_to_insert = []
substats_to_insert = []
artifacts_to_drop = []
characters_to_drop = []
# Get avatar
avatar = get_avatar(raw_data)
print(type(uid))
if uid == "[Redacted PhoneNumber]":
avatar = "/static/eastereggs/soleil.png"
elif uid == "[Redacted PhoneNumber]":
avatar = "/static/eastereggs/eiko.png"
if db_player is None:
db_player = Player.objects.create(
uid=uid,
nickname=nickname,
avatar=avatar
)
else:
db_player.nickname = nickname
db_player.avatar = avatar
db_player.save()
for character_index in range(len(raw_data["avatarInfoList"])): # NOTE: usually 8
character_obj: dict = raw_data["avatarInfoList"][character_index]
if str(character_obj["avatarId"]) in CHARACTERS:
character_name = LOC[LANG][str(CHARACTERS[str(character_obj["avatarId"])]["NameTextMapHash"])]
else:
character_name = "???"
names.append(character_name)
if str(character_obj["avatarId"]) in CHARACTERS:
character_icon = "https://enka.network/ui/UI_AvatarIcon_{}.png".format(
str(CHARACTERS[str(character_obj["avatarId"])]["SideIconName"]).split("_")[-1])
else:
character_icon = "https://enka.network/ui/UI_AvatarIcon_?.png"
try:
db_character = Character(
name=character_name,
icon=character_icon,
stat_hp=get_character_hp(character_obj["fightPropMap"]),
stat_atk=get_character_atk(character_obj["fightPropMap"]),
stat_def=get_character_def(character_obj["fightPropMap"]),
stat_cr=character_obj["fightPropMap"]["20"] * 100,
stat_cd=character_obj["fightPropMap"]["22"] * 100,
stat_er=character_obj["fightPropMap"]["23"] * 100,
stat_em=character_obj["fightPropMap"]["28"],
owner=db_player
)
characters_to_insert.append(db_character)
except KeyError: # Should only happen after a new character is released
print(f"Character {character_obj['avatarId']} not found in constants/characters.json. Skipping.")
continue
artifacts: list = character_obj["equipList"]
# Delete old artifacts
# artifacts_to_drop += Artifact.objects.filter(owner=db_character)
for artifact_index in range(len(artifacts)): # NOTE: usually 5
artifact_obj = artifacts[artifact_index]["flat"]
if "equipType" not in artifact_obj:
continue # NOTE: weapons are stored as artifacts
db_artifact = Artifact(
equiptype=EQUIPTYPE[artifact_obj["equipType"]],
level=artifact_obj["rankLevel"] * 4,
owner=db_character
)
artifacts_to_insert.append(db_artifact)
substats_to_insert.append(
Substat(
name=APPENDPROP[artifact_obj["reliquaryMainstat"]["mainPropId"]],
value=artifact_obj["reliquaryMainstat"]["statValue"],
ismainstat=True,
owner=db_artifact
)
)
rolls = []
if "appendPropIdList" not in artifacts[artifact_index]['reliquary']:
continue # NOTE: This happens when a low quality artifact has no substats.
for roll_id in artifacts[artifact_index]['reliquary']['appendPropIdList']:
prop_type = [roll for roll in RELIQUARYAFFIXEXCELCONFIGDATA if roll['id'] == roll_id][0]['propType']
prop_name = APPENDPROP[prop_type]
rolls.append(prop_name)
for artifact_substat_index in range(len(artifact_obj["reliquarySubstats"])): # NOTE: usually 4
substat_name = APPENDPROP[artifact_obj["reliquarySubstats"][artifact_substat_index]["appendPropId"]]
substats_to_insert.append(
Substat(
name=substat_name,
value=artifact_obj["reliquarySubstats"][artifact_substat_index]["statValue"],
rolls=len([roll for roll in rolls if roll == substat_name]),
owner=db_artifact
)
)
# Remove characters with name "???"
# names += ["???"]
# characters_to_insert = [c for c in characters_to_insert if c.name != "???"]
# Artifact.objects.filter(owner__in=characters_to_insert).delete()
Character.objects.filter(owner=db_player, name__in=names+["???"]).delete()
Character.objects.bulk_create(characters_to_insert)
Artifact.objects.bulk_create(artifacts_to_insert)
Substat.objects.bulk_create(substats_to_insert)
Why This Code Deserves Eternal Shame
1. Unholy Length
This function is so long it could drown a giraffe. No function should ever be this long, unless you're writing a screenplay for a Marvel movie. It’s an unmaintainable nightmare. Break it into smaller, logical chunks.
What is this? A 2003-era Easter egg hunt for your own amusement? Hardcoding UIDs like this is an abomination. If this needs to exist, it belongs in a configuration file, not randomly wedged in the middle of a data-fetching function.
3. Mutation Madness
You’re juggling five different lists (names, characters_to_insert, artifacts_to_insert, etc.), mutating them all over the place. This is like trying to cook five different dishes on one stove while blindfolded. Use a clear data pipeline or structures to encapsulate the logic.
4. Database Abuse
python
db_player = Player.objects.filter(uid=uid).first()
if db_player is not None and db_player.updated > datetime.datetime.now(tz=datetime.timezone.utc) - datetime.timedelta(seconds=60):
return
You're hitting the database over and over without any caching or batching strategy. Worse, you're doing this just to check timestamps. This is the kind of inefficiency that makes databases cry themselves to sleep.
5. Unreadable Artifact Processing
This:
python
for artifact_index in range(len(artifacts)): # NOTE: usually 5
artifact_obj = artifacts[artifact_index]["flat"]
if "equipType" not in artifact_obj:
continue # NOTE: weapons are stored as artifacts
is the most convoluted way to iterate over a list of artifacts. Why are you manually indexing and repeatedly checking keys? Use for artifact_obj in artifacts and clean up the nested logic.
6. Insane Nested Loops
You’ve got loops inside loops inside loops, hitting depths that rival the Mariana Trench. The artifact and substat processing alone is a crime against readability:
python
for roll_id in artifacts[artifact_index]['reliquary']['appendPropIdList']:
prop_type = [roll for roll in RELIQUARYAFFIXEXCELCONFIGDATA if roll['id'] == roll_id][0]['propType']
prop_name = APPENDPROP[prop_type]
rolls.append(prop_name)
You're nesting list comprehensions, looping through dictionaries, and stuffing everything into a rolls array. This is a performance and readability disaster waiting to happen.
7. Lack of Error Handling
Your KeyError catch for missing character constants is laughably insufficient:
python
except KeyError: # Should only happen after a new character is released
print(f"Character {character_obj['avatarId']} not found in constants/characters.json. Skipping.")
continue
What happens if the API changes? Or if the data structure shifts? Your entire pipeline collapses like a house of cards, and all you do is print() and skip. This is amateur-hour error handling.