Update Discord trade listings
This commit is contained in:
+118
-4
@@ -21,6 +21,7 @@ Reported scam warnings with named accounts go to scammer_warnings.csv.
|
||||
Offer cleanup removes copied channel labels, timestamps, and chat instructions.
|
||||
Standalone SSS stat listings and broad offered options such as "All Gamepasses"
|
||||
remain in the CSV. A broad option does not mean every item will be exchanged.
|
||||
Dyno bot notices are ignored before trade extraction.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -30,6 +31,7 @@ from collections import Counter
|
||||
import csv
|
||||
from dataclasses import dataclass
|
||||
from difflib import SequenceMatcher
|
||||
from functools import lru_cache
|
||||
import glob
|
||||
import hashlib
|
||||
import html
|
||||
@@ -252,6 +254,71 @@ UNIT_MENTION = re.compile(
|
||||
for name in KNOWN_UNIT_NAMES) + r")(?!\w)",
|
||||
re.I,
|
||||
)
|
||||
AUTOCORRECT_NAMES = tuple(sorted(
|
||||
{name for name in KNOWN_UNIT_NAMES if len(name.replace(" ", "")) >= 5},
|
||||
key=str.casefold,
|
||||
))
|
||||
AUTOCORRECT_EXACT = frozenset(name.casefold() for name in KNOWN_UNIT_NAMES)
|
||||
|
||||
|
||||
def one_typo_apart(left: str, right: str) -> bool:
|
||||
"""Accept one insertion, deletion, replacement, or adjacent swap."""
|
||||
left, right = left.casefold(), right.casefold()
|
||||
if left == right:
|
||||
return False
|
||||
if abs(len(left) - len(right)) > 1:
|
||||
return False
|
||||
if len(left) == len(right):
|
||||
different = [i for i, (a, b) in enumerate(zip(left, right)) if a != b]
|
||||
return len(different) == 1 or (
|
||||
len(different) == 2 and different[1] == different[0] + 1
|
||||
and left[different[0]] == right[different[1]]
|
||||
and left[different[1]] == right[different[0]]
|
||||
)
|
||||
short, long = sorted((left, right), key=len)
|
||||
return any(short == long[:i] + long[i + 1:] for i in range(len(long)))
|
||||
|
||||
|
||||
@lru_cache(maxsize=4096)
|
||||
def correct_unit_typo(name: str) -> str:
|
||||
if name.casefold() in AUTOCORRECT_EXACT:
|
||||
return name
|
||||
matches = [known for known in AUTOCORRECT_NAMES if one_typo_apart(name, known)]
|
||||
return matches[0] if len(matches) == 1 else name
|
||||
|
||||
|
||||
def autocorrect_unit_names(value: str) -> str:
|
||||
"""Correct one clear typo beside a variant cue or in a bare item."""
|
||||
|
||||
def before_status(match: re.Match[str]) -> str:
|
||||
words = match.group("phrase").split()
|
||||
for width in range(min(3, len(words)), 0, -1):
|
||||
candidate = " ".join(words[-width:])
|
||||
fixed = correct_unit_typo(candidate)
|
||||
if fixed != candidate:
|
||||
return " ".join(words[:-width] + [fixed]) + " " + match.group("status")
|
||||
return match.group()
|
||||
|
||||
value = re.sub(
|
||||
r"(?<!\w)(?P<phrase>[A-Za-z]+(?:\s+[A-Za-z]+){0,2})\s+"
|
||||
r"(?P<status>Evo|Unevo)\b",
|
||||
before_status, value, flags=re.I,
|
||||
)
|
||||
value = re.sub(
|
||||
r"\bShiny\s+(?P<name>[A-Za-z]+)\b(?=\s*(?:[|,;/)]|$))",
|
||||
lambda m: "Shiny " + correct_unit_typo(m.group("name")), value, flags=re.I,
|
||||
)
|
||||
parts = value.split("|")
|
||||
for index, part in enumerate(parts):
|
||||
bare = re.fullmatch(
|
||||
r"(?P<prefix>\s*(?:(?:x?\d+x?)\s+)?(?:Shiny\s+)?)"
|
||||
r"(?P<name>[A-Za-z]+(?:\s+[A-Za-z]+){0,2})(?P<trailing>\s*)",
|
||||
part, flags=re.I,
|
||||
)
|
||||
if bare:
|
||||
parts[index] = (bare.group("prefix") + correct_unit_typo(bare.group("name")) +
|
||||
bare.group("trailing"))
|
||||
return "|".join(parts)
|
||||
ALIASED_UNITS = ("Cid", "Mist Ninja", "Inhuman", "Aizen", "Elf Mage",
|
||||
"Boros", "Poseidon", "Buddha", "Gilgamesh", "Alucard",
|
||||
"Thorfinn", "Homura", "Sakamoto", "Shizo", "Doflamingo",
|
||||
@@ -430,7 +497,12 @@ 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}")
|
||||
REPORT_HANDLE = re.compile(r"(?<![\w@])@[A-Za-z0-9_.-]{2,32}(?:#\d{4})?")
|
||||
SCAM_LIST_HEADING = re.compile(r"^\s*scammers?\s+list\s*:\s*(.*)$", re.I)
|
||||
SCAM_LIST_HANDLES = re.compile(
|
||||
r"\s*@[A-Za-z0-9_.-]{2,32}(?:#\d{4})?"
|
||||
r"(?:\s*[/,;|]\s*@[A-Za-z0-9_.-]{2,32}(?:#\d{4})?)*\s*"
|
||||
)
|
||||
SCAM_WARNING_START = re.compile(
|
||||
r"\bscamm?er\s+@[A-Za-z0-9_.-]{2,32}|"
|
||||
r"['\"`]?@[A-Za-z0-9_.-]{2,32}['\"`]?"
|
||||
@@ -561,6 +633,15 @@ class Message:
|
||||
body: str
|
||||
|
||||
|
||||
def is_dyno_message(msg: Message) -> bool:
|
||||
"""Identify Dyno by its Discord author, never by text in a user's offer."""
|
||||
identity = msg.author.casefold()
|
||||
return bool(re.fullmatch(
|
||||
r"(?:display:dyno(?:#\d{4}|\s*\(bot\))?|handle:dyno(?:\.gg)?)",
|
||||
identity,
|
||||
))
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ScamWarning:
|
||||
reported_handles: str
|
||||
@@ -651,7 +732,8 @@ def iter_messages(lines: Iterable[str]) -> Iterator[Message]:
|
||||
text = "\n".join(body).strip()
|
||||
if not text:
|
||||
return None
|
||||
return Message(author or "unknown:" + uuid.uuid4().hex, text)
|
||||
message = Message(author or "unknown:" + uuid.uuid4().hex, text)
|
||||
return None if is_dyno_message(message) else message
|
||||
|
||||
while peek(0) is not None:
|
||||
p0 = peek(0)
|
||||
@@ -700,7 +782,34 @@ 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():
|
||||
lines = msg.body.splitlines()
|
||||
index = 0
|
||||
while index < len(lines):
|
||||
raw = lines[index]
|
||||
heading = SCAM_LIST_HEADING.fullmatch(raw)
|
||||
if heading:
|
||||
list_lines = [heading.group(1)] if heading.group(1) else []
|
||||
next_index = index + 1
|
||||
while next_index < len(lines):
|
||||
candidate = lines[next_index].strip()
|
||||
if not candidate:
|
||||
next_index += 1
|
||||
continue
|
||||
if not SCAM_LIST_HANDLES.fullmatch(candidate):
|
||||
break
|
||||
list_lines.append(candidate)
|
||||
next_index += 1
|
||||
handles = list(dict.fromkeys(
|
||||
match.group()[1:] for line in list_lines
|
||||
for match in REPORT_HANDLE.finditer(line)
|
||||
))
|
||||
if handles:
|
||||
warnings.append(ScamWarning(" | ".join(handles),
|
||||
"Scammer List: " + " / ".join(list_lines),
|
||||
hash_author(msg.author)))
|
||||
index = next_index
|
||||
continue
|
||||
index += 1
|
||||
fragments = raw.split("|")
|
||||
kept_fragments: list[str] = []
|
||||
found = False
|
||||
@@ -863,6 +972,7 @@ def normalize_unit_names(value: str) -> str:
|
||||
value = MAMY_ALIAS_CHAIN.sub(collapse_mamy_aliases, value)
|
||||
for pattern, canonical in UNIT_NAME_RULES:
|
||||
value = pattern.sub(canonical, value)
|
||||
value = autocorrect_unit_names(value)
|
||||
value = re.sub(r"\b(?:1\s+)?Evo\s+Shiny\s+Somber\s*\(\s*Somber Evo\s*\)",
|
||||
"1x Shiny Somber Evo", value, flags=re.I)
|
||||
value = re.sub(r"\bEvo\s+Shiny\s+Doll\s*\(\s*Doll Evo\s*\)",
|
||||
@@ -2032,6 +2142,8 @@ def parse_listing(msg: Message) -> Listing | None:
|
||||
|
||||
def parse_listings(msg: Message) -> list[Listing]:
|
||||
"""Split explicit Friend(s) sections into trades with a separate identity."""
|
||||
if is_dyno_message(msg):
|
||||
return []
|
||||
if not any(FRIEND_BOUNDARY.search(line) for line in msg.body.splitlines()):
|
||||
listing = parse_listing(msg)
|
||||
return expand_friend_listings([listing]) if listing else []
|
||||
@@ -2480,7 +2592,9 @@ 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)
|
||||
# Explicit quoting keeps spreadsheet editors from treating the leading
|
||||
# apostrophe in an Excel-escaped @handle as a CSV quote character.
|
||||
writer = csv.writer(stream, quoting=csv.QUOTE_ALL)
|
||||
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
|
||||
|
||||
Reference in New Issue
Block a user