Files
ValueList/discord_trade_parser.py
T
2026-11-19 17:23:16 +01:00

1934 lines
80 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
"""Parse messy, manually copied Discord trading messages into a deduplicated CSV.
No Discord API, account automation, or scraping is used. Requires Python 3.10+.
Windows PowerShell:
Get-Clipboard -Raw | py discord_trade_parser.py
py discord_trade_parser.py trades.txt
py discord_trade_parser.py pastes --detailed
Recognized message boundaries:
[\n11:46\n]\nUsername (@handle) [Role],\n:\nTrading ...
[11:46]\nUsername\n:\nTrading ...
### 11:33Username (@handle)*:*\nTrading ...
Default CSV has the original two columns: offer, looking_for.
Use --detailed to additionally export LF / MLF / NLF, hashed authors,
repost counts, and update counts. An SQLite database preserves the latest
observed listing across multiple processing runs. Process older files first.
Reported scam warnings with named accounts go to scammer_warnings.csv.
"""
from __future__ import annotations
import argparse
from collections import Counter
import csv
from dataclasses import dataclass
from difflib import SequenceMatcher
import glob
import hashlib
import html
import json
from pathlib import Path
import re
import sqlite3
import sys
import unicodedata
import uuid
from typing import Iterable, Iterator
TIME = re.compile(r"(?:[01]?\d|2[0-3]):[0-5]\d")
BRACKETED_TIME = re.compile(r"\[\s*((?:[01]?\d|2[0-3]):[0-5]\d)\s*\]")
INLINE_HEADER = re.compile(r"^(?P<time>(?:[01]?\d|2[0-3]):[0-5]\d)\s*(?P<rest>\S.*)$")
HANDLE = re.compile(r"\(@([^\)]+)\)")
WORD = re.compile(r"[\w]+", re.UNICODE)
EMOJI_CODE = re.compile(r"<a?:[A-Za-z0-9_~+-]+:\d+>|:[A-Za-z][A-Za-z0-9_~+-]*:")
KEYCAP_EMOJI = re.compile(r"[#*0-9]\ufe0f?\u20e3")
EMOJI_PUNCTUATION = {"\u203c", "\u2049"}
# Earlier parsing stripped the colons from these decorative server emoji names.
LEGACY_BARE_EMOJI = re.compile(r"(?<!\w)(?:CH_[A-Za-z0-9_]+|tlw[A-Z][A-Za-z0-9_]*)(?!\w)")
DECORATIVE_MARKS = re.compile(r"-+>+|<{2,}|>{2,}")
FODDER_NAME = re.compile(
r"\b(?:FODDERS?|FOODDERS?|FOODERS?|FODERS?)(?:\s+UNITS?)?\b|"
r"\bFOLDER\s+UNITS?\b", re.I,
)
FODDER_MYTHICS = re.compile(
r"\b(?:FODDERS?|FOODDERS?|FOODERS?|FODERS?)\s+MYTHICS?\b", re.I,
)
FODDER_ALIAS_NAMES = re.compile(
r"\b(?:TRASH\s+(?:MYTHICS?|UNITS?)|BUM\s+UNITS?)\b", re.I,
)
FODDER_ALIAS_PAIR = re.compile(
r"(?<!\w)(?P<left>Fodder Units|Trash (?:Mythics?|Units?)|Bum Units?)"
r"(?P<status1>\s+(?:Evo|Unevo))?\s*/\s*"
r"(?P<right>Fodder Units|Trash (?:Mythics?|Units?)|Bum Units?)"
r"(?P<status2>\s+(?:Evo|Unevo))?(?!\w)", re.I,
)
UNIT_NAME_RULES = tuple(
(re.compile(pattern, re.I), canonical)
for pattern, canonical in (
(r"\bSHINNY\b", "Shiny"),
(r"\bFRIREN\b", "Frieren"),
(r"\bUMBRA\b", "Cid"),
(r"\bZABUZA\b", "Mist Ninja"),
(r"\bDAZAI\b", "Inhuman"),
(r"\bILLUSIONIST\b", "Aizen"),
(r"\bFRIEREN\b", "Elf Mage"),
(r"\bLORD\s+ALIEN\s+(?:EVO\s+)?KING\b", "Boros"),
(r"\bLORD\s+ALIEN\b", "Boros"),
(r"\bALIEN\s+KING\b", "Boros"),
(r"\bLORD\s+BOROS\b", "Boros"),
(r"\bBORON\b", "Boros"),
(r"\bBOROS\b", "Boros"),
(r"\bSHISUI\b", "Shizo"),
(r"\bDOFFY\b", "Doflamingo"),
(r"\bDOFLAMINGO\b", "Doflamingo"),
(r"\bRIONY\b", "Rias"),
(r"\bRIAS\b", "Rias"),
(r"\bMILLIE\b", "Mamy"),
(r"\bMAMI\b", "Mamy"),
(r"\bMAMY\b", "Mamy"),
(r"\bJUDAR\b", "Dark Mage"),
(r"\bCHIHIRO\b", "Vengeful Swordsman"),
(r"\bHAMMER\s*HEAD\b", "Harribel"),
(r"\bHARRIBEL\b", "Harribel"),
(r"\bHARIBELL\b", "Harribel"),
(r"\bMITSUKAI\b", "Violentine"),
(r"\bINUYASHU\b", "Dog Demon"),
(r"\bDOG\s+DEMON\b", "Dog Demon"),
(r"\bCRUSADER\b", "Heathcliff"),
(r"\bHEATHCLIFF\b", "Heathcliff"),
(r"\bBLACK\s*DOG\b", "Black Dog"),
(r"\bSEA\s+GOD\b", "Poseidon"),
(r"\b(?:ENLIGHTENED|ENLIGTHENED|ELIGHTEND)\b", "Buddha"),
(r"\bGOLDEN\s+KING\b", "Gilgamesh"),
(r"\bDRACULA\b", "Alucard"),
(r"\bVIKING\b", "Thorfinn"),
(r"\bSHADOWGIRL\b", "Homura"),
(r"\bLEGENDARY\s+ASSASSIN\b", "Sakamoto"),
(r"\bPRIME\s+ASSASSIN\b", "Sakamoto"),
(r"\bSK\s*/\s*SKULL\s*/\s*SKELETON\s+KNIGHT\b", "Skull Knight"),
(r"\bSHINY\s+SK\b", "Shiny Skull Knight"),
(r"\bSK\b", "Skull Knight"),
(r"\bDM\b(?!\s+(?:ME|US|YOUR|IF|FOR|OFFERS?|PLEASE|PLS|TO)\b)", "Dark Mage"),
(r"\bBPS\b", "Battlepasses"),
(r"\bBP\b", "Battlepass"),
(r"\bOPS\b", "Overpays"),
(r"\bOP\b", "Overpay"),
(r"\b(?:BATLLEPASS|BATTLE\s*PASS|BATTLEPASS)\b", "Battlepass"),
(r"\bVENG(?:E)?FULL?\s+SWORD\s*S?MAN\b", "Vengeful Swordsman"),
(r"\bVENG(?:E)?FULL?\s+SWORD\b", "Vengeful Swordsman"),
(r"\bVENG(?:E)?FULL?\b(?!\s+SWORD)", "Vengeful Swordsman"),
(r"\b(?:FRIEND|FIEND)\s+GIRL\b", "Fiend Girl"),
(r"\bSKULL\s*(?:NIGHT|KNIGHT)\b", "Skull Knight"),
(r"\bSWITCH\s*BLADES?\b", "Nagumo"),
(r"\bSWITH\s*BLADES?\b", "Nagumo"),
(r"\bNAGOMO\b", "Nagumo"),
(r"\bNAGUMO\b", "Nagumo"),
(r"\bDARK\s*(?:MAGES?|MAE)\b", "Dark Mage"),
(r"\bELF\s+MAGE\b", "Elf Mage"),
(r"\bSLIVER\s+KING\b", "Silver King"),
(r"\bERZA\s+LIGHTING\b", "Erza Lightning"),
(r"\bMIST\s+NINJA\b", "Mist Ninja"),
(r"\b(?:HOMURU|HOMURA|HOMURUS)\b", "Homura"),
(r"\b(?:VIOLETINE|VIOLENTINE)\b", "Violentine"),
(r"\b(?:SOMBRE|SOMBER)\b", "Somber"),
(r"\b(?:POSIDON|POSIEDON|POSSEIDON|POSEIDON)\b", "Poseidon"),
(r"\b(?:CHUNI|CHUNNI|CHUNII|CHUUNI|CHUUNIS)\b", "Chuuni"),
(r"\bBUDDHAS\b", "Buddha"),
(r"\bNAGUMOS\b", "Nagumo"),
(r"\bDAKR\s+MAGE\b", "Dark Mage"),
(r"\bGLIGAMESH\b", "Gilgamesh"),
(r"\b(?:KILL\s*STREAK|KILLSTEAK|KILSTREAK|KILLSTRIKE)\b", "Killstreak"),
(r"\bMAMMY\b", "Mamy"),
(r"\bAIZENS\b", "Aizen"),
(r"\bALUCARDS\b", "Alucard"),
(r"\bBUDDA\b", "Buddha"),
(r"\b(?:GILGA|GILG)\b", "Gilgamesh"),
(r"\bJIRAYA\b", "Jiraiya"),
(r"\bHEALTCLIFF\b", "Heathcliff"),
(r"\bHEATCLIFF\b", "Heathcliff"),
(r"\bDEER[- ]?TAN\b", "Deer Tan"),
(r"\b(?:ANDROID\s+21|A21)\b", "Android 21"),
(r"\bSHINY\b", "Shiny"),
(r"\b(?:YNEVO|UN[- ]?EVO|UNEVOLV(?:E|ED))\b", "Unevo"),
(r"\bEHO\b", "Evo"),
(r"\bEVOLVED\b", "Evo"),
(r"\bEVO\b", "Evo"),
*((rf"\b{name}\b", name.title()) for name in (
"AIZEN", "ALUCARD", "CHUUNI", "GILGAMESH", "BUDDHA", "DAZAI",
"CID", "HIDAN", "KANSAI", "CREAM", "SAKAMOTO", "SHARKFIN",
"INHUMAN", "EMILIA", "NAMI", "KOBENI", "HIMENO", "TENGEN",
"JIRAIYA", "AKI", "BOROS", "MADOKA", "YOSHINA", "DIO",
)),
)
)
KNOWN_UNIT_NAMES = tuple(sorted(
{name for _, name in UNIT_NAME_RULES if isinstance(name, str)}
- {"Shiny", "Shiny Skull Knight", "Battlepass", "Battlepasses",
"Overpay", "Overpays", "Evo", "Unevo"}
| {
"Nagumo", "Siren", "Frieren", "Rias", "Roger", "Avdol", "Unohana",
"Thorfinn", "Heathcliff", "Deer Tan", "Black Dog", "Golden King",
"Toad Sensei", "Gravity Mage", "Puppet Girl", "Ghost Lady",
"Death Ninja", "Ice Lily", "Illusionist", "Doflamingo", "Doffy",
"Viking", "Gohan", "Issei", "Mami", "Mamy", "Millie", "Merlin",
"Yamamoto", "Scarlet Slayer", "Flash Ninja", "Heart Princess",
"Angel Devil", "Esdeath", "Erza", "Lucy", "Zabuza", "Kagura Bachi",
"Saki", "Gaku", "Rukia", "Hinami", "Julias", "Umbra", "Rohan",
"Daki", "Caesar", "Lelouch", "Flamingo", "Veko", "Ichigo",
"Mangaka", "Oshy", "Akeno", "Akena", "Bomb Angel", "Kisame",
"Karma", "Kaori", "Stitches", "Ghosty", "Icy Dragon",
"Lord Alien", "Lord Boros", "Dio OH", "Harribel", "Perona", "Power",
"Pain", "Robot", "Gas", "Doll", "Lulu", "Shizo", "Denji",
"Sea God", "Snake Princess", "Turtle Master", "Hammerhead",
"Isagi", "Kisuke", "Ging", "Ace", "Saikiki", "Blue Devil",
"Shade Hunter", "Android AAA", "Scarlet", "Shidou", "Emily",
"Ice Queen", "Enlightened", "Time Savior", "Toshiro", "Idol",
"Tiger", "Gin", "Ippo", "Boxer", "Dracula", "Sombra",
"Harribu", "Jio", "Messi", "Buggy", "Bunny", "Psychic Princess",
"Piccolo", "Weather Girl", "Flamefeather", "Blade Beast",
"Bubblegum", "Jelly",
},
key=lambda name: (-len(name.split()), -len(name), name),
))
UNIT_MENTION = re.compile(
r"(?<!\w)(?:" + "|".join(re.escape(name).replace(r"\ ", r"\s+")
for name in KNOWN_UNIT_NAMES) + r")(?!\w)",
re.I,
)
ALIASED_UNITS = ("Cid", "Mist Ninja", "Inhuman", "Aizen", "Elf Mage",
"Boros", "Poseidon", "Buddha", "Gilgamesh", "Alucard",
"Thorfinn", "Homura", "Sakamoto", "Shizo", "Doflamingo",
"Nagumo", "Rias", "Mamy", "Dark Mage", "Vengeful Swordsman",
"Harribel", "Violentine", "Dog Demon", "Heathcliff")
_ALIAS_NAMES = "|".join(re.escape(name).replace(r"\ ", r"\s+")
for name in sorted(ALIASED_UNITS, key=len, reverse=True))
ALIAS_PAIR = re.compile(
r"(?<!\w)(?P<shiny1>Shiny\s+)?(?P<unit>" + _ALIAS_NAMES + r")"
r"(?P<status1>\s+(?:Evo|Unevo))?\s*(?P<sep>[/\-])\s*"
r"(?P<shiny2>Shiny\s+)?(?P=unit)"
r"(?P<status2>\s+(?:Evo|Unevo)|\s*\(\s*(?:Evo|Unevo)\s*\))?(?!\w)",
re.I,
)
ALIAS_PARENS = re.compile(
r"(?<!\w)(?P<shiny>Shiny\s+)?(?P<unit>" + _ALIAS_NAMES + r")"
r"(?P<status1>\s+(?:Evo|Unevo))?\s*\(\s*(?P<shiny2>Shiny\s+)?"
r"(?P=unit)(?P<status2>\s+(?:Evo|Unevo))?\s*\)",
re.I,
)
MAMY_ALIAS_CHAIN = re.compile(
r"(?<!\w)Shiny\s+(?:Mamy|Millie|Mami|Mammy)\s+(?:Evo|Unevo)"
r"(?:\s*/\s*|\s+)(?:Mamy|Millie|Mami|Mammy)\s+(?:Evo|Unevo)"
r"(?:(?:\s*/\s*|\s+)(?:Mamy|Millie|Mami|Mammy)\s+(?:Evo|Unevo))*",
re.I,
)
SHINY_NAMED_ALIAS = re.compile(
r"(?<!\w)Shiny\s+(?P<first>Hammerhead|Harribel|Mitsukai|Violentine|Inuyashu|Dog\s+Demon|Crusader|Heathcliff)"
r"(?P<status1>\s+(?:Evo|Unevo))?(?P<note>\s*\([^|()]{1,80}\))?\s*/\s*"
r"(?P<second>Hammerhead|Harribel|Mitsukai|Violentine|Inuyashu|Dog\s+Demon|Crusader|Heathcliff)"
r"(?P<status2>\s+(?:Evo|Unevo))?(?!\w)",
re.I,
)
JUDAR_PREFIX_ALIAS = re.compile(
r"(?<!\w)(?P<status>Evo|Unevo)\s+Dark\s+Mage\s*/\s*Judar"
r"(?:\s+(?P<other>Evo|Unevo))?(?!\w)",
re.I,
)
JUDAR_NOTE_ALIAS = re.compile(
r"(?<!\w)Dark\s+Mage\s+(?P<status>Evo|Unevo)"
r"(?P<note>\s*\([^|()]{1,80}\))\s*/\s*Judar"
r"(?:\s+(?P<other>Evo|Unevo))?(?!\w)",
re.I,
)
HEATHCLIFF_ADMIN_ALIAS = re.compile(
r"(?<!\w)(?P<shiny>Shiny\s+)?Heathcliff"
r"(?P<status>\s+(?:Evo|Unevo))?\s*\(\s*Admin\s*\)",
re.I,
)
DARK_MAGE_FALLEN_STAR_ALIAS = re.compile(
r"(?<!\w)(?P<shiny>Shiny\s+)?Dark\s+Mage"
r"(?P<status>\s+(?:Evo|Unevo))?\s*(?:[-–—]\s*)?"
r"(?:\(\s*Fallen\s+Star\s*\)|\bFallen\s+Star\b)",
re.I,
)
BUDDHA_NIRVANA_ALIAS = re.compile(
r"(?<!\w)(?P<shiny>Shiny\s+)?Buddha"
r"(?P<status>\s+(?:Evo|Unevo))?\s*(?:[-–—]\s*)?"
r"(?:\(\s*(?:Buddha\s+)?Nirvana\s*\)|(?:Buddha\s+)?Nirvana\b)",
re.I,
)
ALUCARD_UNHOLY_ALIAS = re.compile(
r"\s*\(\s*(?:Alucard\s+(?:Evo\s+)?)?Unholy\s+King\s*\)",
re.I,
)
SAKAMOTO_REDUNDANT_ALIAS = re.compile(
r"\s*\(\s*(?:Sakamoto(?:\s+Evo)?(?:\s+Prime)?|Prime)\s*\)",
re.I,
)
SAKAMOTO_PRIME_BARE = re.compile(
r"(?<!\w)(?P<shiny>Shiny\s+)?Sakamoto"
r"(?P<status>\s+(?:Evo|Unevo))?"
r"(?:\s*[-–—]\s*|\s+)Prime\b",
re.I,
)
AIZEN_TRANSCENDED_ALIAS = re.compile(
r"\s*\(\s*(?:Aizen\s+(?:Evo\s+)?)?Transcended\s*\)",
re.I,
)
AIZEN_TRANSCENDED_BARE = re.compile(
r"(?<!\w)(?P<shiny>Shiny\s+)?Aizen"
r"(?P<status>\s+(?:Evo|Unevo))?"
r"(?:\s*[-–—]\s*|\s+)Transcended\b",
re.I,
)
CID_NUCLEAR_ALIAS = re.compile(
r"\s*\(\s*(?:Cid\s+(?:Evo\s+)?)?Nuclear\s*\)",
re.I,
)
CID_NUCLEAR_BARE = re.compile(
r"(?<!\w)(?P<shiny>Shiny\s+)?Cid"
r"(?P<status>\s+(?:Evo|Unevo))?"
r"(?:\s*[-–—]\s*|\s+)Nuclear\b",
re.I,
)
GILGAMESH_HEROES_ALIAS = re.compile(
r"\s*\(\s*(?:Gilgamesh\s+(?:Evo\s+)?)?Lord\s+of\s+Heroes\s*\)",
re.I,
)
GILGAMESH_HEROES_BARE = re.compile(
r"(?<!\w)(?P<shiny>Shiny\s+)?Gilgamesh"
r"(?P<status>\s+(?:Evo|Unevo))?"
r"(?:\s*[-–—]\s*|\s+)Lord\s+of\s+Heroes\b",
re.I,
)
INHUMAN_NULLIFIER_ALIAS = re.compile(
r"\s*\(\s*(?:Inhuman\s+(?:Evo\s+)?)?Nullifier\s*\)",
re.I,
)
INHUMAN_NULLIFIER_BARE = re.compile(
r"(?<!\w)(?P<shiny>Shiny\s+)?Inhuman"
r"(?P<status>\s+(?:Evo|Unevo))?"
r"(?:\s*[-–—]\s*|\s+)Nullifier\b",
re.I,
)
POSEIDON_TYRANT_ALIAS = re.compile(
r"\s*\(\s*(?:Poseidon\s+(?:Evo\s+)?)?Tyrant\s+of\s+the\s+Seas\s*\)",
re.I,
)
POSEIDON_TYRANT_BARE = re.compile(
r"(?<!\w)(?P<shiny>Shiny\s+)?Poseidon"
r"(?P<status>\s+(?:Evo|Unevo))?"
r"(?:\s*[-–—]\s*|\s+)Tyrant\s+of\s+the\s+Seas\b",
re.I,
)
BLACK_DOG_HELLHOUND_ALIAS = re.compile(
r"\s*\(\s*(?:Black\s+Dog\s+(?:Evo\s+)?)?Hellhound\s*\)",
re.I,
)
BLACK_DOG_HELLHOUND_BARE = re.compile(
r"(?<!\w)(?P<shiny>Shiny\s+)?Black\s+Dog"
r"(?P<status>\s+(?:Evo|Unevo))?"
r"(?:\s*[-–—]\s*|\s+)Hellhound\b",
re.I,
)
BLACK_DOG_POSTFIX_SHINY = re.compile(
r"(?<!\w)Black\s+Dog(?P<status>\s+(?:Evo|Unevo))?\s+Shiny\b",
re.I,
)
ELF_MAGE_AURA_ALIAS = re.compile(
r"\s*\(\s*(?:Elf\s+Mage\s+(?:Evo\s+)?)?Aura\s*\)",
re.I,
)
ELF_MAGE_AURA_BARE = re.compile(
r"(?<!\w)(?P<shiny>Shiny\s+)?Elf\s+Mage"
r"(?P<status>\s+(?:Evo|Unevo))?"
r"(?:\s*[-–—]\s*|\s+)Aura\b",
re.I,
)
ELF_MAGE_POSTFIX_SHINY = re.compile(
r"(?<!\w)Elf\s+Mage(?P<status>\s+(?:Evo|Unevo))?\s+Shiny\b",
re.I,
)
KNOWN_SHINY_UNITS = tuple(tuple(name.casefold().split()) for name in KNOWN_UNIT_NAMES)
EVO_STATUS = re.compile(r"\b(?:Evo|Unevo)\b", re.I)
CONTACT_ADDRESS = re.compile(
r"(?:\b(?:delivered\s+with|sent\s+via)\s+)?"
r"(?:https?://[^\s|]+|[\w.+-]+@[\w.-]+\.[A-Za-z]{2,}|"
r"[A-Za-z0-9_-]+(?:\{dot\}|\.)[A-Za-z]{2,})",
re.IGNORECASE,
)
CONTACT_REQUEST = re.compile(
r"\b(?:SEND\s+FRIENDS?\s+REQ(?:UEST)?\s+IF\s+U\s+CANT\s+DMS|DM\s+OFFERS?)\b",
re.I,
)
OFFER_HEADING = re.compile(r"(?:^|(?<=\|))\s*(?:/\s*)?(?:TRADING|FLIPPING|IN\s+STOCK)\s*[:=]?\s*", re.I)
FRIEND_BOUNDARY = re.compile(
r"(?:^|(?<=\|))\s*friends?\s*:?(?=\s*\||\s*$)|"
r"(?:^|(?<=\|))\s*friends?\s*:\s*(?=\S)",
re.I,
)
FRIEND_FIELD = re.compile(r"(?:^|(?<=\|))\s*friends?\s*(?=\||$)", re.I)
NFL_LABEL = re.compile(r"(?<!\w)NFL\s*[:=\-]?\s*", re.I)
CHALLENGE_NOTE = re.compile(
r"\(?\s*\bup\s+from\s+[^|)\n]{1,100}?\s+to\s+[^|)\n]{1,100}\)?",
re.I,
)
REPORT_HANDLE = re.compile(r"(?<![\w@])@[A-Za-z0-9_.-]{2,32}")
SCAM_WARNING_START = re.compile(
r"\bscamm?er\s+@[A-Za-z0-9_.-]{2,32}|"
r"['\"`]?@[A-Za-z0-9_.-]{2,32}['\"`]?"
r"(?:\s+\(@[A-Za-z0-9_.-]{2,32}\))?"
r"\s+(?:is|was)\s+(?:a\s+)?scamm?er\b",
re.I,
)
NON_TRADE_NOTICES = re.compile(
r"\(?\s*(?:NO\s+(?:ANSWER|REPLY)\s*=\s*(?:AFK|ASLEEP)|"
r"WILL\s+REPLY\s+AS\s+SOON\s+AS\s+POSSIBLE\s+BUT\s+MAY\s+BE\s+ASLEEP|"
r"ANY\s+OFFERS\s+I\s+REPLY\s+TO\s+ALL,?\s+"
r"YOU\s+DONT\s+HAVE\s+TO\s+COME\s+WITH\s+ONE\s+BUT\s+ITS\s+PREFERRED|"
r"I(?:['’]?LL|\s+WILL)?\s+ALWAYS\s+(?:RESPOND|REPLY)|"
r"I\s+REPLY\s+TO\s+ALL(?:\s+OFFERS?)?|"
r"(?:OFFER\s*:\s*|DROP\s+OFFER\s*/\s*)?"
r"I\s+(?:DO\s+NOT|DON['’]?T)\s+OFFER|"
r"I(?:['’]?M|\s+AM)\s+REALLY\s+FRIENDLY|"
r"(?:ALL|ANY)\s+OFFERS?(?:\s+ALL)?\s+(?:(?:ARE|IS)\s+)?WELCOME"
r"(?:\s+WILL\s+RESPOND\s+TO\s+ALL)?|"
r"(?:I\s+|WILL\s+)?RESPOND\s+TO\s+ALL\s+OFFERS?|"
r"(?:PLS+\s+)?DM\s+ME\s+(?:IF\s+U\s+HAVE\s+(?:AN?\s+)?OFFER|"
r"FOR\s+TRADE|YOUR\s+OFFERS)|"
r"SCC?AMM?ERS?/BEGGARS\s+DONT\s+BOR?THER|"
r"DONT\s+COME\s+WITH\s+SHIT\s+OFFERS|"
r"I\s+AM\s+NOT\s+A\s+LINK\s+SENDER)\s*[.!?]*\s*\)?",
re.IGNORECASE,
)
INPUT_EXTENSIONS = {".txt", ".md", ".log"}
# Order matters: MLF/NLF must never be interpreted as simple LF.
LABEL = re.compile(
r"(?<![\w])(?P<label>mostly\s+looking\s+for|not\s+looking\s+for|"
r"looking\s+for|trading|flipping|in\s+stock|mlf|nlf|nfl|lf)(?![\w])\s*[:=\-]?\s*",
re.IGNORECASE,
)
TRADE_AT_LINE_START = re.compile(r"^(?:[\s|*~\-]*)(?:trade)\b\s*[:=\-]?\s*", re.I)
LOOKING_AT_LINE_START = re.compile(r"^looking\b(?!\s+for\b)\s*[:=\-]?\s*", re.I)
INLINE_FOR = re.compile(r"\bfor\b", re.I)
INLINE_OFFER_ITEM = re.compile(
r"\b(?:Fodder Units|battlepass(?:es)?|bundles?|gamepass(?:es)?|"
r"display\s+\d+\s+units?|rrs?|rerolls?|sss|stats?|skins?|"
r"relics?|items?|limit\s+break\s+unit|hunter)\b|\b\d+\s*rrs?\b", re.I,
)
INLINE_REQUEST = re.compile(
r"\b(?:offers?|upgrades?|downgrades?|overpays?|battlepass(?:es)?|"
r"bundles?|gamepass(?:es)?|gp|rrs?|rerolls?|sss|ss\+?|stats?|"
r"spa|dmg|damage|range|rng|skins?|relics?|items?|units?|"
r"adds?|anything|hunter|grand\s+return)\b", re.I,
)
INLINE_FOR_PURPOSE = re.compile(
r"^(?:sacrifice|limit\s+break|moderators?|server\s+boosters?|"
r"content\s+creators?|fair\s+trade|trading\b)", re.I,
)
GENERIC_REQUEST = re.compile(
r"^(?:any\s+)?(?:offers?|upgrades?|overpays?|downgrades?)"
r"(?:\s*[/,&+]\s*(?:offers?|upgrades?|overpays?|downgrades?))*\s*[!?.]*$",
re.I,
)
BOILERPLATE = re.compile(
r"^(?:weitergeleitet|forwarded|feel free to offer.*|dm me.*|"
r"i'?m not offering.*|open to all offers.*|dm if .*|send offers?.*|"
r"\(?come with an offer.*|units?|inv|inventory|unit \(all evo\))$",
re.I,
)
@dataclass(frozen=True)
class Message:
author: str
body: str
@dataclass(frozen=True)
class ScamWarning:
reported_handles: str
warning_text: str
reporter_hash: str
@dataclass(frozen=True)
class Listing:
author: str
offer: str
lf: str = ""
mlf: str = ""
nlf: str = ""
@property
def looking_for(self) -> str:
# Compatibility with the original offer,looking_for CSV.
# Label MLF so it is not confused with ordinary LF requests.
if self.lf and self.mlf:
return f"{self.lf} | MLF: {self.mlf}"
if self.mlf:
return f"MLF: {self.mlf}"
return self.lf
def tidy_line(raw: str) -> str:
line = "".join(
ch for ch in html.unescape(raw) if unicodedata.category(ch) != "Cf"
)
line = re.sub(r"^\s*#{1,6}\s+", "", line)
# Clear markdown formatting without damaging stats such as S-/S+/SSS.
line = line.replace("**", "").replace("__", "").replace("`", "")
line = line.replace("*:*", ":")
return line.strip()
def author_from_header(value: str) -> tuple[str, str]:
"""Return a stable author identity and any inline text after header colon."""
value = tidy_line(value).strip(" ,")
inline = ""
# With handle: a colon after role / handle can precede text on same line.
match = re.search(r":\s+(?=\S)", value)
if match:
inline = value[match.end():].strip()
value = value[:match.start()]
value = re.sub(r"\s*\[[^\]\n]{0,70}\]\s*$", "", value).strip(" :*,")
handle = HANDLE.search(value)
if handle:
return "handle:" + handle.group(1).strip().casefold(), inline
return "display:" + value.casefold(), inline
def legacy_header(line: str) -> tuple[str, str] | None:
match = INLINE_HEADER.fullmatch(line)
if not match:
return None
rest = match.group("rest")
if rest.casefold().startswith(("trading ", "lf ", "mlf ", "nlf ")):
return None
return author_from_header(rest)
def iter_messages(lines: Iterable[str]) -> Iterator[Message]:
"""Stream user messages using either Discord's split or compact headers.
Only a few lines of lookahead are buffered; entire files aren't loaded.
"""
source = iter(tidy_line(line) for line in lines)
buffered: list[str] = []
author: str | None = None
body: list[str] = []
def peek(index: int) -> str | None:
while len(buffered) <= index:
try:
buffered.append(next(source))
except StopIteration:
return None
return buffered[index]
def take() -> str | None:
if peek(0) is None:
return None
return buffered.pop(0)
def finish() -> Message | None:
text = "\n".join(body).strip()
if not text:
return None
return Message(author or "unknown:" + uuid.uuid4().hex, text)
while peek(0) is not None:
p0 = peek(0)
assert p0 is not None
split_timestamp = (
p0 == "[" and (peek(1) is not None and bool(TIME.fullmatch(peek(1) or "")))
and peek(2) == "]"
)
full_timestamp = bool(BRACKETED_TIME.fullmatch(p0))
header = legacy_header(p0) if not split_timestamp and not full_timestamp else None
if split_timestamp or full_timestamp or header:
prior = finish()
if prior:
yield prior
body = []
author = None
if split_timestamp:
take(); take(); take()
elif full_timestamp:
take()
if header is not None:
take()
author, inline = header
if inline:
body.append(inline)
else:
while peek(0) == "":
take()
next_line = take()
if next_line is not None:
author, inline = author_from_header(next_line)
if inline:
body.append(inline)
if peek(0) == ":":
take()
continue
body.append(take() or "")
last = finish()
if last:
yield last
def extract_scam_warnings(msg: Message) -> tuple[Message, list[ScamWarning]]:
"""Keep reported allegations separate from the surrounding trade text."""
kept_lines: list[str] = []
warnings: list[ScamWarning] = []
for raw in msg.body.splitlines():
fragments = raw.split("|")
kept_fragments: list[str] = []
found = False
for fragment in fragments:
match = SCAM_WARNING_START.search(fragment)
if not match:
kept_fragments.append(fragment)
continue
warning_text = tidy_line(fragment[match.start():])
handles = list(dict.fromkeys(
handle.group()[1:].rstrip(".,;:")
for handle in REPORT_HANDLE.finditer(warning_text)
))
if not handles:
kept_fragments.append(fragment)
continue
warnings.append(ScamWarning(" | ".join(handles), warning_text,
hash_author(msg.author)))
prefix = fragment[:match.start()].strip()
if prefix:
kept_fragments.append(prefix)
found = True
if found:
line = " | ".join(part.strip() for part in kept_fragments if part.strip())
if line:
kept_lines.append(line)
else:
kept_lines.append(raw)
return Message(msg.author, "\n".join(kept_lines)), warnings
def remove_emoji_codes(value: str) -> str:
return LEGACY_BARE_EMOJI.sub(" ", EMOJI_CODE.sub(" ", value))
def remove_unicode_emoji(value: str) -> str:
value = KEYCAP_EMOJI.sub(" ", value)
return "".join(
ch for ch in value
if unicodedata.category(ch) not in {"So", "Sk", "Cf"}
and ch not in EMOJI_PUNCTUATION
and ord(ch) not in {0xFE0E, 0xFE0F, 0x20E3}
and not 0xE0100 <= ord(ch) <= 0xE01EF
)
def remove_decorative_marks(value: str) -> str:
return DECORATIVE_MARKS.sub(" ", value)
def remove_non_trade_notices(value: str) -> str:
value = CHALLENGE_NOTE.sub(" ", value)
value = NON_TRADE_NOTICES.sub(" ", value)
value = CONTACT_REQUEST.sub(" ", value)
return CONTACT_ADDRESS.sub(" ", value)
def normalize_fodder_units(value: str) -> str:
"""Keep fodders as an item class without assuming an evolution status."""
value = re.sub(
rf"\b(?P<count>(?:x\d+|\d+x|\d+))\s+Unevo\s+units?\s*/\s*"
rf"(?:{FODDER_NAME.pattern})",
lambda match: match.group("count") + " Fodder Units Unevo",
value, flags=re.I,
)
value = FODDER_MYTHICS.sub("Fodder Units", value)
value = FODDER_NAME.sub("Fodder Units", value)
def collapse_fodder_alias(match: re.Match[str]) -> str:
if not (FODDER_ALIAS_NAMES.fullmatch(match.group("left")) or
FODDER_ALIAS_NAMES.fullmatch(match.group("right"))):
return match.group()
status1 = (match.group("status1") or "").strip().capitalize()
status2 = (match.group("status2") or "").strip().capitalize()
if status1 and status2 and status1 != status2:
return match.group() # Keep distinct variants.
return "Fodder Units" + (" " + (status1 or status2) if status1 or status2 else "")
value = FODDER_ALIAS_PAIR.sub(collapse_fodder_alias, value)
value = FODDER_ALIAS_NAMES.sub("Fodder Units", value)
def move_status(match: re.Match[str]) -> str:
if re.search(r"\bFodder Units\s*$", value[:match.start()], re.I):
return match.group() # The status belongs to the first variant.
previous = list(UNIT_MENTION.finditer(value, 0, match.start()))
if previous and not value[previous[-1].end():match.start()].strip():
return match.group() # The status may belong to that unit.
return "Fodder Units " + match.group("status").capitalize()
value = re.sub(
r"\b(?P<status>Evo|Unevo)\s*/?\s*Fodder Units\b",
move_status,
value, flags=re.I,
)
value = re.sub(
r"\bFodder Units\s*\(\s*(?P<status>Evo|Unevo)\s*\)",
lambda match: "Fodder Units " + match.group("status").capitalize(),
value, flags=re.I,
)
value = re.sub(
r"\bFodder Units\s+(?P<count>\d+\+?)\s+(?P<status>Evo|Unevo)\b",
lambda match: match.group("count") + " Fodder Units " +
match.group("status").capitalize(),
value, flags=re.I,
)
value = re.sub(
r"\bFodder Units\s*\(\s*(\d+)\s+(Evo|Unevo)\s+(\d+)\s+(Evo|Unevo)\s*\)",
lambda match: "Fodder Units (" + match.group(1) + " " +
match.group(2).capitalize() + ", " + match.group(3) + " " +
match.group(4).capitalize() + ")",
value, flags=re.I,
)
return value
def normalize_unit_names(value: str) -> str:
def collapse_shiny_named_alias(match: re.Match[str]) -> str:
if match.group("first").casefold() == match.group("second").casefold():
return match.group()
canonical_names = {
"hammerhead": "Harribel", "harribel": "Harribel",
"mitsukai": "Violentine", "violentine": "Violentine",
"inuyashu": "Dog Demon", "dog demon": "Dog Demon",
"crusader": "Heathcliff", "heathcliff": "Heathcliff",
}
first = canonical_names[match.group("first").casefold()]
second = canonical_names[match.group("second").casefold()]
if first != second:
return match.group()
status1 = (match.group("status1") or "").strip().capitalize()
status2 = (match.group("status2") or "").strip().capitalize()
if status1 and status2 and status1 != status2:
return match.group()
status = status1 or status2
return "Shiny " + first + (" " + status if status else "") + (match.group("note") or "")
def collapse_judar_alias(match: re.Match[str]) -> str:
status = match.group("status").capitalize()
other = match.group("other")
if other and other.casefold() != status.casefold():
return match.group()
if "note" in match.groupdict():
return "Dark Mage " + status + match.group("note")
return status + " Dark Mage"
def collapse_mamy_aliases(match: re.Match[str]) -> str:
names = re.findall(r"\b(?:Mamy|Millie|Mami|Mammy)\b", match.group(), re.I)
statuses = re.findall(r"\b(?:Evo|Unevo)\b", match.group(), re.I)
if (len({name.casefold() for name in names}) == 1 or
len({status.casefold() for status in statuses}) != 1):
return match.group()
return "Shiny Mamy " + statuses[0].capitalize()
value = SHINY_NAMED_ALIAS.sub(collapse_shiny_named_alias, value)
value = JUDAR_PREFIX_ALIAS.sub(collapse_judar_alias, value)
value = JUDAR_NOTE_ALIAS.sub(collapse_judar_alias, value)
value = MAMY_ALIAS_CHAIN.sub(collapse_mamy_aliases, value)
for pattern, canonical in UNIT_NAME_RULES:
value = pattern.sub(canonical, value)
def drop_admin_alias(match: re.Match[str]) -> str:
status = (match.group("status") or "").strip().capitalize()
if status == "Unevo" or re.search(r"\bUnevo\s+$", value[:match.start()], re.I):
return match.group()
return ("Shiny " if match.group("shiny") else "") + "Heathcliff" + (
" " + status if status else ""
)
value = HEATHCLIFF_ADMIN_ALIAS.sub(drop_admin_alias, value)
def drop_fallen_star_alias(match: re.Match[str]) -> str:
status = (match.group("status") or "").strip().capitalize()
if status == "Unevo" or re.search(r"\bUnevo\s+$", value[:match.start()], re.I):
return match.group()
return ("Shiny " if match.group("shiny") else "") + "Dark Mage Evo"
value = DARK_MAGE_FALLEN_STAR_ALIAS.sub(drop_fallen_star_alias, value)
def drop_nirvana_alias(match: re.Match[str]) -> str:
status = (match.group("status") or "").strip().capitalize()
if status == "Unevo" or re.search(r"\bUnevo\s+$", value[:match.start()], re.I):
return match.group()
return ("Shiny " if match.group("shiny") else "") + "Buddha Evo"
value = BUDDHA_NIRVANA_ALIAS.sub(drop_nirvana_alias, value)
parts = value.split("|")
for index, part in enumerate(parts):
without_alias = ALUCARD_UNHOLY_ALIAS.sub("", part)
if (without_alias != part and re.search(r"\bAlucard\b", without_alias, re.I)
and not re.search(r"\bUnevo\s+Alucard\b|\bAlucard\s+Unevo\b",
without_alias, re.I)):
parts[index] = without_alias
value = "|".join(parts)
def drop_sakamoto_prime(match: re.Match[str]) -> str:
status = (match.group("status") or "").strip().capitalize()
if status == "Unevo" or re.search(r"\bUnevo\s+$", value[:match.start()], re.I):
return match.group()
return ("Shiny " if match.group("shiny") else "") + "Sakamoto Evo"
parts = value.split("|")
for index, part in enumerate(parts):
without_alias = SAKAMOTO_REDUNDANT_ALIAS.sub("", part)
if (without_alias != part and re.search(r"\bSakamoto\b", without_alias, re.I)
and not re.search(r"\bUnevo\s+Sakamoto\b|\bSakamoto\s+Unevo\b",
without_alias, re.I)):
parts[index] = without_alias
value = "|".join(parts)
value = SAKAMOTO_PRIME_BARE.sub(drop_sakamoto_prime, value)
parts = value.split("|")
for index, part in enumerate(parts):
without_alias = AIZEN_TRANSCENDED_ALIAS.sub("", part)
if (without_alias != part and re.search(r"\bAizen\b", without_alias, re.I)
and not re.search(r"\bUnevo\s+Aizen\b|\bAizen\s+Unevo\b",
without_alias, re.I)):
parts[index] = without_alias
value = "|".join(parts)
def drop_aizen_transcended(match: re.Match[str]) -> str:
status = (match.group("status") or "").strip().capitalize()
if status == "Unevo" or re.search(r"\bUnevo\s+$", value[:match.start()], re.I):
return match.group()
return ("Shiny " if match.group("shiny") else "") + "Aizen Evo"
value = AIZEN_TRANSCENDED_BARE.sub(drop_aizen_transcended, value)
parts = value.split("|")
for index, part in enumerate(parts):
without_alias = CID_NUCLEAR_ALIAS.sub("", part)
if (without_alias != part and re.search(r"\bCid\b", without_alias, re.I)
and not re.search(r"\bUnevo\s+Cid\b|\bCid\s+Unevo\b",
without_alias, re.I)):
parts[index] = without_alias
value = "|".join(parts)
def drop_cid_nuclear(match: re.Match[str]) -> str:
status = (match.group("status") or "").strip().capitalize()
if status == "Unevo" or re.search(r"\bUnevo\s+$", value[:match.start()], re.I):
return match.group()
return ("Shiny " if match.group("shiny") else "") + "Cid Evo"
value = CID_NUCLEAR_BARE.sub(drop_cid_nuclear, value)
parts = value.split("|")
for index, part in enumerate(parts):
without_alias = GILGAMESH_HEROES_ALIAS.sub("", part)
if (without_alias != part and re.search(r"\bGilgamesh\b", without_alias, re.I)
and not re.search(r"\bUnevo\s+Gilgamesh\b|\bGilgamesh\s+Unevo\b",
without_alias, re.I)):
parts[index] = without_alias
value = "|".join(parts)
def drop_gilgamesh_heroes(match: re.Match[str]) -> str:
status = (match.group("status") or "").strip().capitalize()
if status == "Unevo" or re.search(r"\bUnevo\s+$", value[:match.start()], re.I):
return match.group()
return ("Shiny " if match.group("shiny") else "") + "Gilgamesh Evo"
value = GILGAMESH_HEROES_BARE.sub(drop_gilgamesh_heroes, value)
parts = value.split("|")
for index, part in enumerate(parts):
without_alias = INHUMAN_NULLIFIER_ALIAS.sub("", part)
if (without_alias != part and re.search(r"\bInhuman\b", without_alias, re.I)
and not re.search(r"\bUnevo\s+Inhuman\b|\bInhuman\s+Unevo\b",
without_alias, re.I)):
parts[index] = without_alias
value = "|".join(parts)
def drop_inhuman_nullifier(match: re.Match[str]) -> str:
status = (match.group("status") or "").strip().capitalize()
if status == "Unevo" or re.search(r"\bUnevo\s+$", value[:match.start()], re.I):
return match.group()
return ("Shiny " if match.group("shiny") else "") + "Inhuman Evo"
value = INHUMAN_NULLIFIER_BARE.sub(drop_inhuman_nullifier, value)
parts = value.split("|")
for index, part in enumerate(parts):
without_alias = POSEIDON_TYRANT_ALIAS.sub("", part)
if (without_alias != part and re.search(r"\bPoseidon\b", without_alias, re.I)
and not re.search(r"\bUnevo\s+Poseidon\b|\bPoseidon\s+Unevo\b",
without_alias, re.I)):
parts[index] = without_alias
value = "|".join(parts)
def drop_poseidon_tyrant(match: re.Match[str]) -> str:
status = (match.group("status") or "").strip().capitalize()
if status == "Unevo" or re.search(r"\bUnevo\s+$", value[:match.start()], re.I):
return match.group()
return ("Shiny " if match.group("shiny") else "") + "Poseidon Evo"
value = POSEIDON_TYRANT_BARE.sub(drop_poseidon_tyrant, value)
parts = value.split("|")
for index, part in enumerate(parts):
without_alias = BLACK_DOG_HELLHOUND_ALIAS.sub("", part)
if (without_alias != part and re.search(r"\bBlack\s+Dog\b", without_alias, re.I)
and not re.search(r"\bUnevo\s+Black\s+Dog\b|\bBlack\s+Dog\s+Unevo\b",
without_alias, re.I)):
parts[index] = without_alias
value = "|".join(parts)
def drop_black_dog_hellhound(match: re.Match[str]) -> str:
status = (match.group("status") or "").strip().capitalize()
if status == "Unevo" or re.search(r"\bUnevo\s+$", value[:match.start()], re.I):
return match.group()
return ("Shiny " if match.group("shiny") else "") + "Black Dog Evo"
value = BLACK_DOG_HELLHOUND_BARE.sub(drop_black_dog_hellhound, value)
def move_black_dog_shiny(match: re.Match[str]) -> str:
prefix = "" if re.search(r"\bShiny\s+$", value[:match.start()], re.I) else "Shiny "
return prefix + "Black Dog" + (match.group("status") or "")
value = BLACK_DOG_POSTFIX_SHINY.sub(move_black_dog_shiny, value)
parts = value.split("|")
for index, part in enumerate(parts):
without_alias = ELF_MAGE_AURA_ALIAS.sub("", part)
if (without_alias != part and re.search(r"\bElf\s+Mage\b", without_alias, re.I)
and not re.search(r"\bUnevo\s+Elf\s+Mage\b|\bElf\s+Mage\s+Unevo\b",
without_alias, re.I)):
parts[index] = without_alias
value = "|".join(parts)
def drop_elf_mage_aura(match: re.Match[str]) -> str:
status = (match.group("status") or "").strip().capitalize()
if status == "Unevo" or re.search(r"\bUnevo\s+$", value[:match.start()], re.I):
return match.group()
return ("Shiny " if match.group("shiny") else "") + "Elf Mage Evo"
value = ELF_MAGE_AURA_BARE.sub(drop_elf_mage_aura, value)
def move_elf_mage_shiny(match: re.Match[str]) -> str:
prefix = "" if re.search(r"\bShiny\s+$", value[:match.start()], re.I) else "Shiny "
return prefix + "Elf Mage" + (match.group("status") or "")
value = ELF_MAGE_POSTFIX_SHINY.sub(move_elf_mage_shiny, value)
return normalize_fodder_units(value)
def collapse_alias_pairs(value: str) -> str:
def status(raw: str | None) -> str:
match = EVO_STATUS.search(raw or "")
return match.group().capitalize() if match else ""
def replace_parentheses(match: re.Match[str]) -> str:
status1, status2 = status(match.group("status1")), status(match.group("status2"))
if status1 and status2 and status1 != status2:
return match.group()
return (("Shiny " if match.group("shiny") or match.group("shiny2") else "") +
match.group("unit") + (" " + (status1 or status2) if status1 or status2 else ""))
value = ALIAS_PARENS.sub(replace_parentheses, value)
def replace(match: re.Match[str]) -> str:
shiny1, shiny2 = bool(match.group("shiny1")), bool(match.group("shiny2"))
if shiny1 != shiny2 and not (match.group("sep") == "-" and shiny1):
return match.group()
if re.match(r"\s*\[[^]]+\]", value[match.end():]):
return match.group() # The second copy has its own stats.
# A leading status belongs to the first unit, e.g. Unevo Alucard / Alucard Evo.
if re.search(r"\b(?:Evo|Unevo)\s+$", value[:match.start()], re.I):
return match.group()
status1 = status(match.group("status1"))
status2 = status(match.group("status2"))
if (status1 == "Unevo" and not status2) or (status2 == "Unevo" and not status1):
return match.group() # An unspecified variant defaults to Evo.
if status1 and status2 and status1 != status2:
return match.group()
resolved_status = status1 or status2
return (("Shiny " if shiny1 or shiny2 else "") + match.group("unit") +
(" " + resolved_status if resolved_status else ""))
while True:
updated = ALIAS_PAIR.sub(replace, value)
if updated == value:
return value
value = updated
CATEGORY_HEADING = re.compile(
r"(?:LIST|FRIENDS?\s*:?|STATS?\s*:?|SSS\s+STATS?\s*:?|"
r"(?:NORMAL|REGULAR)\s+UNITS?\s*/\s*"
r"(?:FODDERS?|FOODERS?|FODDER\s+UNITS?)\s*:?|"
r"(?:FODDERS?|FOODERS?|FODDER\s+UNITS?)\s*:|"
r"UNEVO\s+UNITS?\s*:?|SSS\s*/\s*SKINS?\s*:?|"
r"UNIT\s*\(\s*THAT\s+HAVE\s+GOOD\s+STAT\s*\)\s*:?|"
r"ITEMS?\s*:|GAMEPASS(?:ES)?\s*:|GP\s*:|ALL\s+EVO\s*:?|"
r"KEYWORD\s*:?|"
r"(?:SHINY\s+)?UNITS?(?:\s+AVAILABLE)?\s*:|"
r"(?:SHINY|SHINIES|SHINY\s+UNITS?|EVO|UNEVO|NORMAL|NORMAL\s+UNITS?|"
r"REGULAR\s+UNITS?(?:\s+FOR\s+TRADE)?|NON[- ]SHINY(?:\s+UNITS?)?|"
r"OTHER\s+UNITS?|SECRET\s+UNITS?|SSS\s+UNITS?|VALUE\s+UNITS?|"
r"SKINS?|MISC|EXTRAS?|OTHER|GAMEPASSES|"
r"HIGH\s+A\s+TIER/A\+|MID\s+A\s+TIER/A|A\s+TIER\s+UNITS?|"
r"HIGH\s+TIER\s+UNITS?\s*&\s*SHINIES|"
r"SECRET/NORMAL\s+UNITS?\s*&\s*RARE\s+MYTHICAL\s+SKINS?|"
r"THESE\s+UNITS?/SKINS?|TOURNEY\s*&\s*INF\s+CASTLE\s+UNITS?)\s*:?)",
re.I,
)
SHINY_HEADING = re.compile(r"(?:SHINY|SHINIES|SHINY\s+EVO|SHINY\s+UNITS?(?:\s+ALL\s+BELOW\s+ARE\s+SHINY)?)\s*:?$", re.I)
INLINE_CATEGORY_HEADING = re.compile(
r"^\s*(?P<label>SHINY(?:\s+EVO|\s+UNITS?)?|SHINIES|EVO|UNEVO|"
r"NORMAL(?:\s+UNITS?)?|REGULAR\s+UNITS?|NON[- ]SHINY(?:\s+UNITS?)?|"
r"UNITS?|ITEMS?|GAMEPASS(?:ES)?|GP)"
r"\s*:\s*(?=\S)", re.I,
)
UNEVO_HEADING = re.compile(r"UNEVO\s+UNITS?\s*:?$", re.I)
STATUS_HEADING = re.compile(
r"(?:\(?ALL\s+UNITS?\s+(?:BELOW\s+ARE\s+)?EVO\)?|"
r"UNITS?\s*(?:&\s*BULK\s+SSS\s*)?\(?\s*ALL\s+EVOS?\s*\)?|"
r"\(?ALL\s+EVO\)?(?:\s+COME\s+WITH\s+AN\s+OFFER)?)", re.I,
)
def strip_category_headings(value: str) -> str:
"""Remove standalone labels while retaining the Shiny variant they imply."""
parts = value.split("|")
if len(parts) == 1:
return "" if re.fullmatch(r"THESE\s+UNITS?/SKINS?\s*:?", value.strip(), re.I) else value
output: list[str] = []
shiny_section = False
unevo_section = False
for part in parts:
inline = INLINE_CATEGORY_HEADING.match(part)
if inline:
shiny_section = bool(re.match(r"SHINY|SHINIES", inline.group("label"), re.I))
unevo_section = False
part = part[inline.end():]
label = part.strip()
if SHINY_HEADING.fullmatch(label):
shiny_section = True
unevo_section = False
continue
if UNEVO_HEADING.fullmatch(label):
shiny_section = False
unevo_section = True
continue
if CATEGORY_HEADING.fullmatch(label) or STATUS_HEADING.fullmatch(label):
shiny_section = False
unevo_section = False
continue
part = re.sub(r"^\s*-\s*(?=[A-Za-z])", "", part)
if unevo_section:
for match in reversed(list(UNIT_MENTION.finditer(part))):
suffix = part[match.end():]
status = re.match(r"\s+(?:Evo|Unevo)\b|\s*\(\s*(?:Evo|Unevo)\s*\)", suffix, re.I)
end = match.end() + (status.end() if status else 0)
part = part[:match.end()] + " Unevo" + part[end:]
if shiny_section and label:
matches = list(UNIT_MENTION.finditer(part))
if matches:
for match in reversed(matches):
before = part[:match.start()]
if not re.search(r"\bShiny(?:\s+Evo)?\s+$", before, re.I):
part = part[:match.start()] + "Shiny " + part[match.start():]
elif not re.search(r"\bShiny\b", part, re.I):
part = re.sub(r"^(\s*(?:(?:x?\d+x?)\s+)?)", r"\1Shiny ", part, count=1, flags=re.I)
fragments = re.split(r"(\s+/\s+)", part)
for index in range(0, len(fragments), 2):
fragment = fragments[index]
if (index and re.search(r"\b[A-Za-z]{3,}\b", fragment) and
not re.search(r"\bShiny\b", fragment, re.I) and
not UNIT_MENTION.search(fragment)):
fragments[index] = re.sub(
r"^(\s*(?:(?:x?\d+x?)\s+)?)", r"\1Shiny ",
fragment, count=1, flags=re.I,
)
part = "".join(fragments)
output.append(part)
return "|".join(output)
def normalize_shiny_evo_order(value: str) -> str:
"""Keep one Evo and put Shiny immediately before the unit."""
unit = UNIT_MENTION.pattern
def split_variants(match: re.Match[str]) -> str:
first, second = match.group("first").capitalize(), match.group("second").capitalize()
if first == second:
return match.group()
name = ("Shiny " if match.group("shiny") else "") + match.group("unit")
variants = name + " " + first + " | " + name + " " + second
quantity = match.group("quantity")
if not quantity:
return variants
count = int(re.search(r"\d+", quantity).group())
if count == 2:
return variants # Two units, one of each variant.
if count == 1:
return match.group() # Two variants cannot be assigned to one unit.
return str(count) + " total across variants: " + variants
quantity = r"(?P<quantity>(?:x\d+|\d+\s*x|\d+)\s+)?"
name = rf"(?P<shiny>Shiny\s+)?(?P<unit>{unit})"
statuses = r"(?P<first>Evo|Unevo)\s*(?:and|&|/|\+)\s*(?P<second>Evo|Unevo)"
value = re.sub(
rf"(?<!\w){quantity}{name}\s*\(\s*{statuses}\s*\)",
split_variants, value, flags=re.I,
)
value = re.sub(
rf"(?<!\w){quantity}{name}\s+{statuses}\b(?!\s+Items?\b)",
split_variants, value, flags=re.I,
)
value = re.sub(r"\b(Evo|Unevo)\s*<\s*\1\s*>", r"\1", value, flags=re.I)
value = re.sub(
rf"(?P<unit>{unit})\s*\(\s*(?P<status>Evo|Unevo)\s*\)",
lambda m: m.group("unit") + " " + m.group("status").capitalize(),
value, flags=re.I,
)
value = re.sub(
rf"\bShiny\s+Unevo\s+(?P<unit>{unit})(?:\s+Unevo)?(?!\s+Evo\b)",
lambda m: "Shiny " + m.group("unit") + " Unevo", value, flags=re.I,
)
value = re.sub(
rf"(?P<lead>^|[|/,~+;]|\b(?:and|or|for|with)\b)\s*"
rf"Unevo\s+Shiny\s+(?P<unit>{unit}|elf\b)(?:\s+Unevo)?(?!\s+Evo\b)",
lambda m: m.group("lead") + " Shiny " +
("Elf Mage" if m.group("unit").casefold() == "elf" else m.group("unit")) +
" Unevo", value, flags=re.I,
)
def move_unevo(match: re.Match[str]) -> str:
previous = list(UNIT_MENTION.finditer(value, 0, match.start()))
if previous and not value[previous[-1].end():match.start()].strip():
return match.group() # Unevo may belong to the preceding unit.
return match.group("unit") + " Unevo"
value = re.sub(
rf"\bUnevo\s+(?P<unit>{unit})(?:\s+Unevo)?"
rf"(?!\s*(?:Evo\b|\(\s*Evo\s*\)))",
move_unevo, value, flags=re.I,
)
def move_evo(match: re.Match[str]) -> str:
previous = list(UNIT_MENTION.finditer(value, 0, match.start()))
if previous and not value[previous[-1].end():match.start()].strip():
return match.group() # Evo may belong to the preceding unit.
return match.group("unit") + " Evo"
value = re.sub(
rf"\bEvo\s+(?P<unit>{unit})(?:\s+Evo)?"
rf"(?!\s*(?:Unevo\b|\(\s*Unevo\s*\)))",
move_evo, value, flags=re.I,
)
value = re.sub(
rf"(?:\[\s*Shiny\s*\]|\(\s*Shiny\s*\))\s*(?={unit})",
"Shiny ", value, flags=re.I,
)
value = re.sub(
rf"(?P<unit>{unit})\s*\(\s*Shiny\s+(?P<status>Evo|Unevo)\s*\)",
lambda m: "Shiny " + m.group("unit") + " " + m.group("status"),
value, flags=re.I,
)
value = re.sub(
rf"(?P<unit>{unit})\s*\(\s*Shiny\s+(?P<note>(?:Evo|Unevo)\b[^)]*)\)",
lambda m: "Shiny " + m.group("unit") + " (" + m.group("note") + ")",
value, flags=re.I,
)
value = re.sub(
rf"(?P<unit>{unit})(?:\s+(?P<status>Evo|Unevo))?\s+"
rf"(?:\[\s*Shiny\s*\]|Shiny)"
rf"(?:\s*\(\s*(?P<status2>Evo|Unevo)\s*\))?"
rf"(?=\s*(?:\||$|[,;/)]|x\d+\b|\d+x\b))",
lambda m: "Shiny " + m.group("unit") + " " +
(m.group("status") or m.group("status2") or "Evo"),
value, flags=re.I,
)
value = re.sub(r"\bShiny\s+Shiny\b", "Shiny", value, flags=re.I)
value = re.sub(
rf"\bShiny\s+Evo\s+(?P<unit>{unit})(?:\s+Evo)?",
lambda m: "Shiny " + m.group("unit") + " Evo", value, flags=re.I,
)
value = re.sub(
rf"(?P<unit>{unit})\s+Evo\s+Shiny\s*(?:Evo\b|\(\s*Evo\s*\))",
lambda m: "Shiny " + m.group("unit") + " Evo", value, flags=re.I,
)
value = re.sub(
rf"(?P<unit>{unit})\s+Evo\s+Shiny(?=\s*(?:\||$|[,;/)]))",
lambda m: "Shiny " + m.group("unit") + " Evo", value, flags=re.I,
)
parts = value.split("|")
for i, part in enumerate(parts):
part = re.sub(
rf"\b(?P<my>my)\s+Evo\s+Shiny\s+(?P<unit>{unit})(?:\s+Evo)?",
lambda m: m.group("my") + " Shiny " + m.group("unit") + " Evo",
part, flags=re.I,
)
parts[i] = re.sub(
rf"^(\s*(?:(?:x?\d+x?)\s+)?)Evo\s+Shiny\s+(?P<unit>{unit})(?:\s+Evo)?",
lambda m: m.group(1) + "Shiny " + m.group("unit") + " Evo",
part, count=1, flags=re.I,
)
return collapse_alias_pairs("|".join(parts))
def normalize_evo_status(value: str) -> str:
"""Add the default Evo status to recognized units without a local status."""
matches = list(UNIT_MENTION.finditer(value))
insertions: list[int] = []
for index, match in enumerate(matches):
prefix = value[:match.start()]
opening = value.rfind("(", 0, match.start())
if opening > value.rfind(")", 0, match.start()) and index:
previous = matches[index - 1]
if re.fullmatch(r"\s*(?:Evo|Unevo)?\s*", value[previous.end():opening], re.I):
continue # An alternate name in parentheses is the same unit.
if re.search(r"\bEvo\s+Items?\s*:\s*$", prefix, re.I):
continue
before = re.search(
r"\b(?:Evo|Unevo)\b(?:\s+(?:Shiny|x\d+|\d+x))*\s*$",
prefix, re.I,
)
if before and index:
between = value[matches[index - 1].end():match.start()]
if re.fullmatch(r"\s*(?:\([^)]*\)\s*)?(?:Evo|Unevo)\s*(?:Shiny\s*)?", between, re.I):
before = None # The status belongs to the preceding unit.
if before:
continue
suffix = value[match.end():]
direct = re.match(r"\s*(?:(?:x\d+|\d+x|\d+)\s+)?(?:Evo|Unevo)\b", suffix, re.I)
if direct:
continue
if suffix.lstrip().startswith("("):
bracket = suffix.find(")")
if 0 < bracket < 100:
if EVO_STATUS.search(suffix[:bracket + 1]):
continue
if re.match(r"\s*(?:Evo|Unevo)\b", suffix[bracket + 1:], re.I):
continue
insertions.append(match.end())
for position in reversed(insertions):
value = value[:position] + " Evo" + value[position:]
return value
def normalize_body_line(raw: str) -> str:
value = tidy_line(raw)
value = remove_unicode_emoji(value)
value = normalize_shiny_evo_order(normalize_unit_names(
remove_non_trade_notices(remove_decorative_marks(remove_emoji_codes(value)))
))
value = value.replace("!", "")
value = normalize_shiny_evo_order(normalize_evo_status(normalize_shiny_evo_order(value)))
value = re.sub(r"^\s*[-•]+\s+", "", value)
value = re.sub(r"(?:\s*\|\s*){2,}", " | ", value)
value = re.sub(r"\s+", " ", value).strip(" |")
return value
def category_for_label(value: str) -> str:
label = re.sub(r"\s+", " ", value.casefold())
if label in {"trading", "flipping", "trade", "in stock"}:
return "offer"
if label in {"mlf", "mostly looking for"}:
return "mlf"
if label in {"nlf", "nfl", "not looking for"}:
return "nlf"
return "lf"
def is_boilerplate(line: str) -> bool:
simple = line.strip().strip("|").strip()
return bool(BOILERPLATE.fullmatch(simple) or BOILERPLATE.fullmatch(simple.strip(" ()[]")))
def normalized_chunk(lines: list[str]) -> str:
cleaned: list[str] = []
for raw in lines:
line = normalize_body_line(raw)
if not line or is_boilerplate(line):
continue
# Decorative token-only lines (not real item entries).
if re.fullmatch(r"(?:\||[-=~* ])+", line):
continue
cleaned.append(line.strip(" |"))
return " | ".join(line for line in cleaned if line)
def distinct_chunks(chunks: list[list[str]]) -> str:
seen: set[str] = set()
unique: list[str] = []
for section in chunks:
cleaned = normalized_chunk(section)
key = canon(cleaned)
if not cleaned or not key or key in seen:
continue
seen.add(key)
unique.append(cleaned)
return " | ".join(unique)
def looks_like_variant_item(value: str) -> bool:
return bool(
2 <= len(value.split()) <= 6 and
re.fullmatch(r"[\w #+.'-]+", value) and
re.search(r"\b(?:evo|unevo|shiny)\b", value, re.I)
)
def split_inline_offer_for(offer: str, lf: str = "") -> tuple[str, str]:
"""Move clear 'Trading X for Y' requests out of the offered inventory."""
offered: list[str] = []
requested: list[str] = []
for segment in offer.split("|"):
segment = segment.strip()
if not segment:
continue
split: tuple[str, str] | None = None
for match in INLINE_FOR.finditer(segment):
before = segment[:match.start()]
if before.count("(") > before.count(")"):
continue
left = before.strip(" .,:;/-")
right = segment[match.end():].strip(" .,:;/-")
if (not right or INLINE_FOR_PURPOSE.match(right) or
re.search(r"\b(?:or|and|for)$", right, re.I)):
continue
normalized_left = normalize_unit_names(left)
normalized_right = normalize_unit_names(right)
right_is_unit = bool(UNIT_MENTION.search(normalized_right) or
looks_like_variant_item(normalized_right))
right_is_request = right_is_unit or bool(INLINE_REQUEST.search(normalized_right))
left_is_item = bool(UNIT_MENTION.search(normalized_left) or
INLINE_OFFER_ITEM.search(normalized_left) or
looks_like_variant_item(normalized_left))
short_unknown_item = bool(
right_is_unit and 1 <= len(left.split()) <= 5 and
re.fullmatch(r"[\w #+.'-]+", left) and
not re.match(r"(?:channel|i\s+can|you\s+can)\b", left, re.I)
)
if not right_is_request:
continue
if left.casefold() in {"", "all", "both"}:
if offered:
split = ("", right)
break
continue
if left_is_item or short_unknown_item:
split = (left, right)
break
if split is None:
offered.append(segment)
continue
if split[0]:
offered.append(split[0])
requested.append(split[1])
if not offered or not requested:
return offer, lf
existing = lf.strip(" |")
merged = [existing] if existing else []
seen = canon(existing) if existing else ""
for request in requested:
key = canon(request)
if not key or key in seen or any(canon(part) == key for part in merged):
continue
merged.append(request)
seen = canon(" | ".join(merged))
return " | ".join(offered), " | ".join(merged)
def parse_listing(msg: Message) -> Listing | None:
"""One CSV row per Discord message, not per 'TRADING' word.
LF without a concrete offer is excluded. Handles multiple TRADING labels,
repeated paragraphs within one message, MLF and NLF, and a conservative
LF-first inventory variant (LF OFFERS/UPGRADES followed by item lines).
"""
groups: dict[str, list[list[str]]] = {"offer": [], "lf": [], "mlf": [], "nlf": []}
current = "preface"
seen_offer_marker = False
for raw in msg.body.splitlines():
line = normalize_body_line(raw)
if not line:
continue
if is_boilerplate(line):
continue
# Explicit 'TRADE ...' is also common in trading channels.
short_trade = TRADE_AT_LINE_START.match(line)
# A few servers use a separate 'LOOKING' heading without 'FOR'.
short_looking = LOOKING_AT_LINE_START.match(line)
markers: list[tuple[int, int, str]] = [
(match.start(), match.end(), category_for_label(match.group("label")))
for match in LABEL.finditer(line)
if not (category_for_label(match.group("label")) != "offer"
and line[:match.start()].count("(") > line[:match.start()].count(")"))
]
if short_trade and not any(start == short_trade.start() for start, _, _ in markers):
markers.append((short_trade.start(), short_trade.end(), "offer"))
if short_looking and not any(start == short_looking.start() for start, _, _ in markers):
markers.append((short_looking.start(), short_looking.end(), "lf"))
markers.sort(key=lambda item: item[0])
if not markers:
if current != "preface":
groups[current][-1].append(line)
continue
first = markers[0][0]
prefix = line[:first].strip(" :|-")
if prefix and current != "preface" and prefix.casefold() not in {"i am mainly", "im mainly"}:
groups[current][-1].append(prefix)
for i, (start, end, category) in enumerate(markers):
current = category
if category == "offer":
seen_offer_marker = True
groups[category].append([])
end_of_text = markers[i + 1][0] if i + 1 < len(markers) else len(line)
fragment = line[end:end_of_text].strip(" :|-")
if fragment:
groups[category][-1].append(fragment)
if not seen_offer_marker:
# Specific salvage case: 'LF OFFERS/UPGRADES' on first line, followed
# by a multiline inventory. This is not an LF-only request.
if len(groups["lf"]) == 1:
section = groups["lf"][0]
if (len(section) >= 3 and GENERIC_REQUEST.fullmatch(section[0])
and len([s for s in section[1:] if not BOILERPLATE.fullmatch(s)]) >= 2):
groups["offer"].append(section[1:])
groups["lf"] = [[section[0]]]
else:
return None
else:
return None
offer = distinct_chunks(groups["offer"])
if not offer:
return None
lf = distinct_chunks(groups["lf"])
offer, lf = split_inline_offer_for(offer, lf)
return Listing(
author=msg.author, offer=offer,
lf=lf,
mlf=distinct_chunks(groups["mlf"]),
nlf=distinct_chunks(groups["nlf"]),
)
def parse_listings(msg: Message) -> list[Listing]:
"""Split explicit Friend(s) sections into trades with a separate identity."""
if not any(FRIEND_BOUNDARY.search(line) for line in msg.body.splitlines()):
listing = parse_listing(msg)
return [listing] if listing else []
parts: list[str] = []
sections: list[Message] = []
author = msg.author
friend_number = 0
for raw in msg.body.splitlines():
rest = raw
while match := FRIEND_BOUNDARY.search(rest):
before = rest[:match.start()].strip(" |")
if before:
parts.append(before)
if parts:
sections.append(Message(author, "\n".join(parts)))
friend_number += 1
author = f"friend:{hash_author(msg.author)}:{friend_number}"
parts = ["Trading:"]
rest = rest[match.end():]
if rest.strip(" |"):
parts.append(rest.strip(" |") if friend_number else rest)
if parts:
sections.append(Message(author, "\n".join(parts)))
listings: list[Listing] = []
parsed_sections: list[Message] = []
for section in sections:
listing = parse_listing(section)
if listing:
listings.append(listing)
parsed_sections.append(section)
elif listings and section.author.startswith("friend:"):
# A Friend marker can occur only in LF/MLF text. Keep those terms
# with the preceding trade when no friend offer follows it.
remainder = section.body.removeprefix("Trading:").strip()
if remainder:
prior = parsed_sections[-1]
combined = Message(prior.author, prior.body + "\n" + remainder)
merged = parse_listing(combined)
if merged:
listings[-1] = merged
parsed_sections[-1] = combined
return listings
def canon(value: str) -> str:
value = clean_export_text(html.unescape(value)).casefold()
value = re.sub(r"(\d+)\s*[×x]\b", r"\1x", value)
return " ".join(WORD.findall(value))
def shiny_signature(value: str) -> Counter[str]:
words = WORD.findall(normalize_unit_names(value).casefold())
signature: Counter[str] = Counter()
for i, word in enumerate(words):
if word != "shiny":
continue
j = i + 1
while j < len(words) and (words[j] in {"evo", "unevo"} or
re.fullmatch(r"(?:x\d+|\d+x)", words[j])):
j += 1
unit = next((" ".join(name) for name in KNOWN_SHINY_UNITS
if tuple(words[j:j + len(name)]) == name),
words[j] if j < len(words) else "")
signature[unit] += 1
return signature
def token_overlap(a: str, b: str) -> float:
ta, tb = Counter(WORD.findall(a)), Counter(WORD.findall(b))
denom = sum(ta.values()) + sum(tb.values())
return 2 * sum((ta & tb).values()) / denom if denom else 1.0
def similar_update(old_offer: str, old_lf: str, new_offer: str, new_lf: str, threshold: float) -> bool:
if old_offer == new_offer and old_lf == new_lf:
return True
if shiny_signature(old_offer) != shiny_signature(new_offer):
return False
if shiny_signature(old_lf) != shiny_signature(new_lf):
return False
if min(len(old_offer.split()), len(new_offer.split())) < 5:
return False
if bool(old_lf) != bool(new_lf):
return False
if old_lf and SequenceMatcher(None, old_lf, new_lf).ratio() < 0.75:
return False
return (
SequenceMatcher(None, old_offer, new_offer).ratio() >= threshold
and token_overlap(old_offer, new_offer) >= max(0.77, threshold - 0.08)
)
def hash_author(author: str) -> str:
return hashlib.sha256(author.encode("utf-8")).hexdigest()[:24]
def clean_export_text(value: str) -> str:
# Existing database rows may still contain emoji and formatting marks.
original = value
value = remove_unicode_emoji(value)
# Remove an Excel escape added by an earlier export before an arrow.
value = re.sub(r"^'(?=-+>+|-[A-Za-z])", "", value)
cleaned = OFFER_HEADING.sub("", remove_non_trade_notices(remove_decorative_marks(remove_emoji_codes(value))))
cleaned = normalize_shiny_evo_order(normalize_unit_names(cleaned))
cleaned = collapse_alias_pairs(strip_category_headings(cleaned))
cleaned = normalize_shiny_evo_order(normalize_evo_status(cleaned.replace("!", "")))
if cleaned != original or re.search(r"^\s*\||\|\s*$|\|\s*\|", cleaned):
parts = (re.sub(r"\s+", " ", part).strip() for part in cleaned.split("|"))
value = " | ".join(part for part in parts if part and not re.fullmatch(r"[-—–~*]+", part))
return value
def csv_safe(value: str) -> str:
value = clean_export_text(value)
return excel_safe(value)
def excel_safe(value: str) -> str:
# Prevent formula injection if opening arbitrary user text in Excel.
return "'" + value if value and value.lstrip().startswith(("=", "+", "-", "@")) else value
def record_scam_warning(conn: sqlite3.Connection, warning: ScamWarning) -> None:
conn.execute(
"""INSERT INTO scam_warnings (reported_handles,warning_text,reporter_hash)
VALUES (?,?,?)
ON CONFLICT(reported_handles,warning_text,reporter_hash)
DO UPDATE SET reports_seen=reports_seen+1""",
(warning.reported_handles, warning.warning_text, warning.reporter_hash),
)
def migrate_friend_trades(conn: sqlite3.Connection) -> None:
"""Split legacy Friend(s) sections already stored as one trade."""
rows = list(conn.execute(
"SELECT id,author_hash,offer,lf,mlf,nlf,seen_count,update_count,last_seen FROM trades"
))
for row_id, author_hash, offer, lf, mlf, nlf, seen, updates, last_seen in rows:
if not any(FRIEND_FIELD.search(value) for value in (offer, lf, mlf, nlf)):
continue
offers = [clean_export_text(part.strip(" |")) for part in FRIEND_FIELD.split(offer)]
lf, mlf, nlf = (
clean_export_text(" | ".join(part.strip() for part in FRIEND_FIELD.split(value) if part.strip(" |")))
for value in (lf, mlf, nlf)
)
main = Listing("", offers[0], lf, mlf, nlf)
conn.execute(
"""UPDATE trades SET offer=?,looking_for=?,lf=?,mlf=?,nlf=?,
canon_offer=?,canon_lf=? WHERE id=?""",
(main.offer, main.looking_for, main.lf, main.mlf, main.nlf,
canon(main.offer), canon(main.looking_for), row_id),
)
for friend_number, friend_offer in enumerate(offers[1:], 1):
if not friend_offer:
continue
friend = Listing("", friend_offer, lf, mlf, nlf)
friend_hash = hash_author(f"friend:{author_hash}:{friend_number}")
conn.execute(
"""INSERT INTO trades (author_hash,offer,looking_for,canon_offer,canon_lf,
seen_count,update_count,last_seen,lf,mlf,nlf)
VALUES (?,?,?,?,?,?,?,?,?,?,?)""",
(friend_hash, friend.offer, friend.looking_for,
canon(friend.offer), canon(friend.looking_for), seen, updates,
last_seen, friend.lf, friend.mlf, friend.nlf),
)
def migrate_nfl_labels(conn: sqlite3.Connection) -> None:
"""Move legacy NFL text from LF to the not-looking-for field."""
for row_id, offer, lf, mlf, nlf in conn.execute(
"SELECT id,offer,lf,mlf,nlf FROM trades WHERE lf LIKE '%NFL%'"
):
match = NFL_LABEL.search(lf)
if not match:
continue
moved = lf[match.end():].strip(" |")
lf = lf[:match.start()].strip(" |")
nlf = " | ".join(part for part in (nlf, moved) if part)
listing = Listing("", offer, lf, mlf, nlf)
conn.execute(
"""UPDATE trades SET looking_for=?,lf=?,nlf=?,canon_lf=? WHERE id=?""",
(listing.looking_for, listing.lf, listing.nlf,
canon(listing.looking_for), row_id),
)
def migrate_inline_for_trades(conn: sqlite3.Connection) -> int:
"""Move requests in stored 'Trading X for Y' offers into LF."""
changed = 0
rows = list(conn.execute("SELECT id,offer,lf,mlf,nlf FROM trades"))
for row_id, offer, lf, mlf, nlf in rows:
new_offer, new_lf = split_inline_offer_for(offer, lf)
if (new_offer, new_lf) == (offer, lf):
continue
listing = Listing("", new_offer, new_lf, mlf, nlf)
conn.execute(
"""UPDATE trades SET offer=?,looking_for=?,lf=?,canon_offer=?,canon_lf=?
WHERE id=?""",
(new_offer, listing.looking_for, new_lf, canon(new_offer),
canon(listing.looking_for), row_id),
)
changed += 1
return changed
def open_database(path: Path) -> sqlite3.Connection:
path.parent.mkdir(parents=True, exist_ok=True)
conn = sqlite3.connect(path)
conn.execute("PRAGMA busy_timeout=10000")
conn.execute("PRAGMA journal_mode=WAL")
conn.execute(
"""CREATE TABLE IF NOT EXISTS trades (
id INTEGER PRIMARY KEY,
author_hash TEXT NOT NULL,
offer TEXT NOT NULL,
looking_for TEXT NOT NULL,
canon_offer TEXT NOT NULL,
canon_lf TEXT NOT NULL,
seen_count INTEGER NOT NULL DEFAULT 1,
update_count INTEGER NOT NULL DEFAULT 0,
last_seen INTEGER NOT NULL,
lf TEXT NOT NULL DEFAULT '',
mlf TEXT NOT NULL DEFAULT '',
nlf TEXT NOT NULL DEFAULT ''
)"""
)
conn.execute(
"""CREATE TABLE IF NOT EXISTS scam_warnings (
id INTEGER PRIMARY KEY,
reported_handles TEXT NOT NULL,
warning_text TEXT NOT NULL,
reporter_hash TEXT NOT NULL,
reports_seen INTEGER NOT NULL DEFAULT 1,
UNIQUE(reported_handles,warning_text,reporter_hash)
)"""
)
# Schema migration from the old parser's existing SQLite state.
columns = {row[1] for row in conn.execute("PRAGMA table_info(trades)")}
migrated = "lf" not in columns
for column in ("lf", "mlf", "nlf"):
if column not in columns:
conn.execute(f"ALTER TABLE trades ADD COLUMN {column} TEXT NOT NULL DEFAULT ''")
if migrated:
conn.execute("UPDATE trades SET lf=looking_for")
conn.execute("CREATE INDEX IF NOT EXISTS trades_exact ON trades(author_hash, canon_offer, canon_lf)")
conn.execute("CREATE INDEX IF NOT EXISTS trades_author_recent ON trades(author_hash, last_seen DESC)")
migrate_friend_trades(conn)
if conn.execute("PRAGMA user_version").fetchone()[0] < 1:
for row_id, offer, looking_for in conn.execute("SELECT id,offer,looking_for FROM trades"):
conn.execute(
"UPDATE trades SET canon_offer=?,canon_lf=? WHERE id=?",
(canon(offer), canon(looking_for), row_id),
)
conn.execute("PRAGMA user_version=1")
if conn.execute("PRAGMA user_version").fetchone()[0] < 2:
migrate_nfl_labels(conn)
conn.execute("PRAGMA user_version=2")
if conn.execute("PRAGMA user_version").fetchone()[0] < 56:
for row_id, offer, looking_for in conn.execute("SELECT id,offer,looking_for FROM trades"):
conn.execute(
"UPDATE trades SET canon_offer=?,canon_lf=? WHERE id=?",
(canon(offer), canon(looking_for), row_id),
)
conn.execute("PRAGMA user_version=56")
if conn.execute("PRAGMA user_version").fetchone()[0] < 57:
migrate_inline_for_trades(conn)
conn.execute("PRAGMA user_version=57")
conn.commit()
return conn
def import_previous_state(conn: sqlite3.Connection, path: Path) -> int:
old = json.loads(path.read_text(encoding="utf-8-sig"))
if not isinstance(old, list):
raise ValueError("legacy JSON state must be a list")
for i, item in enumerate(old, start=1):
offer, lf = item["offer"], item["looking_for"]
conn.execute(
"""INSERT INTO trades
(author_hash, offer, looking_for, canon_offer, canon_lf,
seen_count, update_count, last_seen, lf)
VALUES(?,?,?,?,?,?,?,?,?)""",
(item["author_hash"], offer, lf, canon(offer), canon(lf),
int(item.get("seen_count", 1)), int(item.get("update_count", 0)), i, lf),
)
return len(old)
class TradeStore:
def __init__(self, conn: sqlite3.Connection, threshold: float, no_fuzzy: bool):
self.conn = conn
self.threshold = threshold
self.no_fuzzy = no_fuzzy
self.sequence = int(conn.execute("SELECT COALESCE(MAX(last_seen),0) FROM trades").fetchone()[0])
self.added = 0
self.exact = 0
self.updated = 0
def add(self, listing: Listing) -> None:
self.sequence += 1
ah = hash_author(listing.author)
co, cl = canon(listing.offer), canon(listing.looking_for)
exact = self.conn.execute(
"""SELECT id FROM trades WHERE author_hash=? AND canon_offer=? AND canon_lf=?
ORDER BY last_seen DESC LIMIT 1""",
(ah, co, cl),
).fetchone()
if exact:
self.conn.execute(
"""UPDATE trades SET seen_count=seen_count+1, last_seen=?,
lf=?, mlf=?, nlf=? WHERE id=?""",
(self.sequence, listing.lf, listing.mlf, listing.nlf, exact[0]),
)
self.exact += 1
return
if not self.no_fuzzy:
for old_id, oo, ol in self.conn.execute(
"""SELECT id, canon_offer, canon_lf FROM trades WHERE author_hash=?
ORDER BY last_seen DESC LIMIT 80""", (ah,),
):
if similar_update(oo, ol, co, cl, self.threshold):
self.conn.execute(
"""UPDATE trades SET offer=?, looking_for=?, canon_offer=?, canon_lf=?,
lf=?,mlf=?,nlf=?,seen_count=seen_count+1,
update_count=update_count+1,last_seen=? WHERE id=?""",
(listing.offer, listing.looking_for, co, cl, listing.lf,
listing.mlf, listing.nlf, self.sequence, old_id),
)
self.updated += 1
return
self.conn.execute(
"""INSERT INTO trades (author_hash, offer, looking_for, canon_offer,
canon_lf, last_seen, lf, mlf, nlf) VALUES(?,?,?,?,?,?,?,?,?)""",
(ah, listing.offer, listing.looking_for, co, cl, self.sequence,
listing.lf, listing.mlf, listing.nlf),
)
self.added += 1
def resolve_files(arguments: list[str]) -> list[Path]:
found: list[Path] = []
seen: set[Path] = set()
for arg in arguments:
candidates = [Path(p) for p in glob.glob(arg, recursive=True)] if glob.has_magic(arg) else [Path(arg)]
if not candidates:
raise FileNotFoundError(f"No files match {arg!r}")
for candidate in candidates:
if candidate.is_dir():
paths = sorted(p for p in candidate.rglob("*") if p.is_file() and p.suffix.lower() in INPUT_EXTENSIONS)
elif candidate.is_file():
paths = [candidate]
else:
raise FileNotFoundError(f"Input does not exist: {candidate}")
for path in paths:
identity = path.resolve()
if identity not in seen:
found.append(path)
seen.add(identity)
return found
def export_csv(conn: sqlite3.Connection, output: Path, detailed: bool) -> int:
output.parent.mkdir(parents=True, exist_ok=True)
count = 0
with output.open("w", encoding="utf-8-sig", newline="") as stream:
writer = csv.writer(stream)
if detailed:
writer.writerow(["offer", "looking_for", "lf", "mlf", "nlf",
"author_hash", "reposts_seen", "updates_seen"])
rows = conn.execute(
"""SELECT offer,looking_for,lf,mlf,nlf,author_hash,seen_count,update_count
FROM trades ORDER BY id"""
)
else:
writer.writerow(["offer", "looking_for"])
rows = conn.execute("SELECT offer,looking_for FROM trades ORDER BY id")
for row in rows:
writer.writerow([csv_safe(v) if isinstance(v, str) else v for v in row])
count += 1
return count
def export_scam_warnings(conn: sqlite3.Connection, output: Path) -> int:
output.parent.mkdir(parents=True, exist_ok=True)
count = 0
with output.open("w", encoding="utf-8-sig", newline="") as stream:
writer = csv.writer(stream)
writer.writerow(["reported_handles", "warning_text", "reporter_hash", "reports_seen"])
for handles, warning_text, reporter_hash, seen in conn.execute(
"""SELECT reported_handles,warning_text,reporter_hash,reports_seen
FROM scam_warnings ORDER BY id"""
):
writer.writerow([handles, excel_safe(warning_text), reporter_hash, seen])
count += 1
return count
def main(argv: list[str] | None = None) -> int:
p = argparse.ArgumentParser(description="Convert messy Discord copy-paste into a scalable deduplicated trade CSV")
p.add_argument("files", nargs="*", help="Input text files, folders or globs (otherwise pipe from clipboard)")
p.add_argument("-o", "--output", type=Path, default=Path("trades.csv"))
p.add_argument("--warnings-output", type=Path,
help="CSV for reported scam warnings (default: scammer_warnings.csv beside --output)")
p.add_argument("--state", type=Path, default=Path("trades_state.sqlite"))
p.add_argument("--import-json", type=Path, help="Import the old version's JSON history")
p.add_argument("--reset", action="store_true", help="Discard existing database rows before processing")
p.add_argument("--detailed", action="store_true", help="Export separate LF, MLF, NLF and deduplication metadata")
p.add_argument("--no-fuzzy", action="store_true", help="Disable merging similar inventory updates")
p.add_argument("--threshold", type=float, default=0.87, help="Fuzzy similarity threshold (default 0.87)")
p.add_argument("--progress-every", type=int, default=10000)
args = p.parse_args(argv)
if not 0 <= args.threshold <= 1:
p.error("--threshold must be between 0 and 1")
if args.progress_every < 0:
p.error("--progress-every must be >= 0")
if not args.files and sys.stdin.isatty():
p.print_help()
print("Example: Get-Clipboard -Raw | py discord_trade_parser.py", file=sys.stderr)
return 2
legacy = args.import_json
if args.state.suffix.lower() == ".json":
legacy = legacy or args.state
args.state = args.state.with_suffix(".sqlite")
if legacy is None and args.state == Path("trades_state.sqlite") and Path("trades_state.json").exists():
legacy = Path("trades_state.json")
if args.state.resolve() == args.output.resolve():
p.error("--output and --state cannot be the same path")
warnings_output = args.warnings_output or args.output.with_name("scammer_warnings.csv")
if warnings_output.resolve() in {args.output.resolve(), args.state.resolve()}:
p.error("--warnings-output must differ from --output and --state")
try:
files = resolve_files(args.files) if args.files else []
except FileNotFoundError as e:
p.error(str(e))
if args.files and not files:
p.error("No text files found")
new_state = not args.state.exists()
try:
conn = open_database(args.state)
try:
if args.reset:
conn.execute("DELETE FROM trades")
conn.execute("DELETE FROM scam_warnings")
conn.commit()
elif new_state and legacy and legacy.exists():
count = import_previous_state(conn, legacy)
conn.commit()
print(f"Imported {count} listings from {legacy}", file=sys.stderr)
store = TradeStore(conn, args.threshold, args.no_fuzzy)
messages = 0
skipped = 0
warnings_found = 0
conn.execute("BEGIN")
streams = []
if files:
# Open files one by one; the total input is never held in RAM.
for path in files:
with path.open("r", encoding="utf-8-sig", errors="replace") as stream:
for message in iter_messages(stream):
messages += 1
trade_message, warnings = extract_scam_warnings(message)
for warning in warnings:
record_scam_warning(conn, warning)
warnings_found += len(warnings)
listings = parse_listings(trade_message)
if listings:
for listing in listings:
store.add(listing)
else:
skipped += 1
if args.progress_every and messages % args.progress_every == 0:
print(f"Processed {messages:,} messages ...", file=sys.stderr)
else:
for message in iter_messages(sys.stdin):
messages += 1
trade_message, warnings = extract_scam_warnings(message)
for warning in warnings:
record_scam_warning(conn, warning)
warnings_found += len(warnings)
listings = parse_listings(trade_message)
if listings:
for listing in listings:
store.add(listing)
else:
skipped += 1
if args.progress_every and messages % args.progress_every == 0:
print(f"Processed {messages:,} messages ...", file=sys.stderr)
conn.commit()
rows = export_csv(conn, args.output, args.detailed)
warning_rows = export_scam_warnings(conn, warnings_output)
print(f"Messages: {messages:,}; excluded (no identifiable offer): {skipped:,}; "
f"new listings: {store.added:,}; exact reposts: {store.exact:,}; "
f"similar updates: {store.updated:,}; CSV rows: {rows:,}; "
f"warning reports: {warnings_found:,}; warning CSV rows: {warning_rows:,}")
print(f"Saved {args.output}, {warnings_output}, and {args.state}")
return 0
except Exception:
conn.rollback()
raise
finally:
conn.close()
except (OSError, sqlite3.Error, ValueError, KeyError, json.JSONDecodeError) as e:
print(f"Error: {e}", file=sys.stderr)
return 1
if __name__ == "__main__":
raise SystemExit(main())