AI 가 만든 UTM 링크 20개를 규칙으로 검사하기
캠페인 20개의 UTM 링크를 AI 로 만들고 urllib.parse 로 필수 파라미터·대소문자·공백·중복·매체 이름을 검사한 뒤, 걸린 행만 다시 요청하는 방법입니다.
UTM 링크는 한 글자만 달라도 GA4 에서 다른 소스로 집계됩니다. AI 가 만든 링크는 눈으로 보면 다 비슷해서 틀린 줄을 놓치기 쉽습니다. 규칙은 스크립트가 세고, AI 는 걸린 행만 다시 씁니다. 같은 방식으로 메타 설명을 검사하는 글은 AI 가 쓴 메타 설명 검사 에 있습니다.
[1] 검사 기준의 출처부터 확인합니다. 구글 애널리틱스 도움말 Collect campaign data with custom URLs 에는 다음 두 가지가 나옵니다.
utm_term 과 utm_content 는 선택(optional)이라고 합니다. 공백이나 URL 인코딩, 캠페인 이름 형식에 대한 규정은 이 문서에 없습니다. 그래서 아래의 「소문자만」「공백 금지」「매체 이름은 정해 둔 목록 안에서」는 구글 규칙이 아니라 팀 규칙입니다.
[2] 캠페인 목록을 탭으로 구분한 파일로 둡니다. 열은 id · 소스 · 매체 · 캠페인 설명 · 랜딩 URL 이고 쇼핑몰과 캠페인은 모두 지어낸 것입니다. c11 과 c16 은 랜딩 URL 에 원래 쿼리(ref=blog · order=1)가 붙어 있어서, 링크를 이어 붙일 때 ? 가 두 번 들어가는지 보려고 넣었습니다.
c01 newsletter email 봄 신상 안내 https://shop.example.com/springc02 newsletter email 장바구니 리마인드 https://shop.example.com/cartc03 google cpc 브랜드 검색 광고 https://shop.example.com/c04 google cpc 겨울 세일 검색 광고 https://shop.example.com/winter-salec05 instagram paid_social 릴스 신제품 티저 https://shop.example.com/newc06 instagram social 프로필 링크 https://shop.example.com/c07 facebook paid_social 재방문 유도 리타기팅 https://shop.example.com/cartc08 naver cpc 쇼핑 검색 광고 https://shop.example.com/productsc09 kakao social 채널 메시지 쿠폰 https://shop.example.com/couponc10 youtube video 리뷰 영상 설명란 https://shop.example.com/reviewc11 blog referral 제휴 블로그 후기 https://shop.example.com/products?ref=blogc12 partner-a affiliate 제휴 배너 https://shop.example.com/partnersc13 newsletter email 회원 등급 안내 https://shop.example.com/membershipc14 popup banner 첫 구매 10% 할인 https://shop.example.com/welcomec15 qr offline 매장 포스터 QR https://shop.example.com/storec16 sms sms 배송 완료 후 리뷰 요청 https://shop.example.com/review?order=1c17 linkedin paid_social B2B 단체 주문 안내 https://shop.example.com/b2bc18 x social 신제품 공지 게시물 https://shop.example.com/newc19 podcast audio 스폰서 멘트 https://shop.example.com/podcastc20 google display 배너 리마케팅 https://shop.example.com/cart#top[3] 프롬프트 머리말을 만듭니다. 출력 형식만 못 박고 대소문자나 이름 규칙은 일부러 적지 않았습니다. 규칙을 알려 주지 않았을 때 어떻게 나오는지 보기 위해서입니다.
아래는 마케팅 캠페인 20개입니다. 열은 탭으로 구분되며 id, 소스(source), 매체(medium), 캠페인 설명, 랜딩 URL 순입니다.각 캠페인의 UTM 링크를 만들어 주세요. 규칙:- 랜딩 URL 에 utm 파라미터를 붙인 완성된 URL 하나.- 출력은 한 줄에 JSON 객체 하나(JSON Lines): {"id": "...", "url": "..."}- 다른 텍스트, 코드 펜스 금지. [4] 머리말과 목록을 이어 붙여 claude -p 로 실행합니다. 한 번 답하고 끝나는 비대화형 실행이고 --max-turns 1 로 한 턴만 허용합니다.
$ cat head.txt campaigns.tsv > prompt.1.txt$ claude -p --model sonnet --max-turns 1 < prompt.1.txt > out.1.jsonl$ head -3 out.1.jsonl{"id": "c01", "url": "https://shop.example.com/spring?utm_source=newsletter&utm_medium=email&utm_campaign=spring_new_arrivals"}{"id": "c02", "url": "https://shop.example.com/cart?utm_source=newsletter&utm_medium=email&utm_campaign=cart_reminder"}{"id": "c03", "url": "https://shop.example.com/?utm_source=google&utm_medium=cpc&utm_campaign=brand_search"}[5] 검사 스크립트를 만듭니다. urlsplit 으로 쿼리를 떼고 parse_qsl 로 파라미터를 읽습니다. 확인하는 것은 필수 3개 · 같은 키 반복 · utm_ 키와 값의 대문자 · 공백 · 소스/매체/캠페인이 완전히 같은 링크 · (선택) 허용 매체 목록입니다.
#!/usr/bin/env python3"""usage: check_utm.py out.jsonl [medium,medium,...]"""import sys, json, re, collectionsfrom urllib.parse import urlsplit, parse_qsl REQ = ("utm_source", "utm_medium", "utm_campaign")ALLOWED = set(sys.argv[2].split(",")) if len(sys.argv) > 2 else Nonerows = [json.loads(l) for l in open(sys.argv[1], encoding="utf-8") if l.strip()]q = {r["id"]: parse_qsl(urlsplit(r["url"]).query, keep_blank_values=True) for r in rows}combo = lambda p: tuple(dict((k.lower(), v) for k, v in p).get(k, "") for k in REQ)seen = collections.defaultdict(list)for i, p in q.items(): seen[combo(p)].append(i)bad = 0for r in rows: i, p, errs = r["id"], q[r["id"]], [] for k in REQ: if not dict(p).get(k, "").strip(): errs.append(f"missing {k}") for k, n in collections.Counter(k for k, _ in p).items(): if n > 1: errs.append(f"repeated {k}") for k, v in p: if k.lower().startswith("utm_") and k != k.lower(): errs.append(f"key case {k}") if k.startswith("utm_") and v != v.lower(): errs.append(f"value case {k}={v}") if k.startswith("utm_") and re.search(r"\s", v): errs.append(f"space in {k}") m = dict(p).get("utm_medium", "") if ALLOWED and m and m.lower() not in ALLOWED: errs.append(f"medium {m} not in list") if " " in r["url"]: errs.append("raw space in url") dup = [x for x in seen[combo(p)] if x != i] if dup and all(combo(p)): errs.append("same source/medium/campaign as " + ",".join(dup)) print(f"{i} {'FAIL ' + '; '.join(errs) if errs else 'ok'}") bad += bool(errs)print(f"{len(rows)} urls, {bad} failed")sys.exit(1 if bad else 0)[6] 먼저 매체 목록 없이 검사합니다. 이번 실행에서는 20개가 모두 통과했습니다.
$ python3 -I check_utm.py out.1.jsonl | tail -1; echo "exit ${PIPESTATUS[0]}"20 urls, 0 failedexit 0세 값 모두 소문자에 공백 대신 밑줄이었고, ref=blog · order=1 도 & 로 이어졌습니다. 채널 이름을 한글·대소문자 혼용(뉴스레터 · Google Ads)으로 바꿔 한 번 더 돌려 봐도 결함은 없었습니다.
[7] 형식은 맞아도 이름이 흔들립니다. 같은 20개를 두 번 받았더니 youtube 의 매체가 한 번은 video, 한 번은 social 이었고 linkedin 은 paid_social 과 social 로 나뉘었습니다. 이름 목록을 정해 두고 검사 스크립트 둘째 인자로 넘깁니다.
$ M=email,cpc,paid_social,social,display,affiliate,referral,sms,offline$ python3 -I check_utm.py out.1.jsonl $M | grep -v ' ok$'; echo "exit ${PIPESTATUS[0]}"c10 FAIL medium video not in listc14 FAIL medium banner not in listc19 FAIL medium audio not in list20 urls, 3 failedexit 1[8] 걸린 3개만 다시 요청합니다. 이전 링크와 검사 결과를 붙이고, 바꿀 것은 매체뿐이라고 못 박습니다.
아래 캠페인의 UTM 링크가 매체(utm_medium) 규칙에 맞지 않습니다. 목록의 id 만 다시 만들어 주세요.- utm_medium 은 email, cpc, paid_social, social, display, affiliate, referral, sms, offline 중 하나만.- utm_source · utm_campaign 은 이전 링크 그대로 두고 utm_medium 만 바꿀 것.- 출력은 한 줄에 JSON 객체 하나: {"id": "...", "url": "..."} 다른 텍스트 금지. 이전 링크와 검사 결과:{"id": "c10", "url": "https://shop.example.com/review?utm_source=youtube&utm_medium=video&utm_campaign=review_video_description"}{"id": "c14", "url": "https://shop.example.com/welcome?utm_source=popup&utm_medium=banner&utm_campaign=first_purchase_10off"}{"id": "c19", "url": "https://shop.example.com/podcast?utm_source=podcast&utm_medium=audio&utm_campaign=sponsor_mention"}c10 FAIL medium video not in listc14 FAIL medium banner not in listc19 FAIL medium audio not in list$ claude -p --model sonnet --max-turns 1 < prompt.3.txt > out.3.jsonl$ cat out.3.jsonl{"id": "c10", "url": "https://shop.example.com/review?utm_source=youtube&utm_medium=referral&utm_campaign=review_video_description"}{"id": "c14", "url": "https://shop.example.com/welcome?utm_source=popup&utm_medium=display&utm_campaign=first_purchase_10off"}{"id": "c19", "url": "https://shop.example.com/podcast?utm_source=podcast&utm_medium=referral&utm_campaign=sponsor_mention"}[9] 두 파일을 id 기준으로 합쳐(뒤 파일이 앞 파일을 덮어씁니다) merged.jsonl 로 저장하고 다시 검사합니다.
$ python3 -I check_utm.py merged.jsonl $M | tail -1; echo "exit ${PIPESTATUS[0]}"20 urls, 0 failedexit 0통과는 했지만 광고 영상 설명란이나 팟캐스트 스폰서를 referral 로 보는 것이 맞는지는 스크립트가 알 수 없습니다. 목록 안의 어느 이름을 쓸지는 사람이 정합니다.
[10] 모델이 이번에는 형식 결함을 내지 않았으므로, 나머지 검사가 도는지는 out.1.jsonl 을 손으로 망가뜨린 bad.jsonl 로 확인합니다. c02 소스에 대문자, c04 캠페인에 공백, c06 에서 매체 삭제, c08 에 utm_source 추가(반복), c12 키를 UTM_source 로, c18 을 c01 과 같은 소스·매체·캠페인으로 바꿨습니다. 모델이 만든 오류가 아닙니다.
$ python3 -I check_utm.py bad.jsonl $M | grep -v ' ok$'; echo "exit ${PIPESTATUS[0]}"c01 FAIL same source/medium/campaign as c18c02 FAIL value case utm_source=Newsletterc04 FAIL space in utm_campaign; raw space in urlc06 FAIL missing utm_mediumc08 FAIL repeated utm_source; value case utm_source=Naverc10 FAIL medium video not in listc12 FAIL missing utm_source; key case UTM_sourcec14 FAIL medium banner not in listc18 FAIL same source/medium/campaign as c01c19 FAIL medium audio not in list20 urls, 10 failedexit 1c10 · c14 · c19 는 손대지 않은 원래 행에서 나온 매체 목록 위반입니다.