#!/usr/bin/env python3 """SNS の予約投稿(X・LinkedIn)。 予定表 sns/schedule.json に入っている投稿のうち、時刻が来たものを投稿し、 結果を sns/posted.json に残す。GitHub Actions から15分ごとに動かす。 使い方: python tools/sns_autopost.py check 予定表と投稿文を確かめる(投稿しない) python tools/sns_autopost.py run --dry-run 時刻が来ているものを表示するだけ python tools/sns_autopost.py run 投稿する(Actions 用) python tools/sns_autopost.py preview 日時と本文の一覧 sns/schedule_preview.md を作り直す 二重投稿を防ぐため、投稿の前に「投稿中」と記録して push し、push できなければ投稿しない。 「投稿中」のまま残ったもの(投稿できたか分からないもの)は、自動ではやり直さない。 外部ライブラリは使わない(標準ライブラリだけ)。 """ import argparse import base64 import datetime as dt import hashlib import hmac import html import json import os import re import secrets import subprocess import sys import time import urllib.error import urllib.parse import urllib.request ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SCHEDULE = os.path.join(ROOT, "sns", "schedule.json") POSTED = os.path.join(ROOT, "sns", "posted.json") PLATFORMS = ("x", "linkedin") STALE_HOURS = 12 # 予定時刻からこれ以上遅れたら投稿せず「見送り」にする X_LIMIT = 280 # X の重み付き文字数の上限(無料のアカウント @pixelstomotors) X_LONG_LIMIT = 25000 # 有料プラン(Plus)の @adaptdesignjp の長文の上限(2026-11-22 から) def x_limit(entry): """投稿先のアカウントで上限を変える。@pixelstomotors(account: ptm)は無料なので280。""" if os.environ.get("X_LONG_POSTS") == "1" or entry.get("account") != "ptm": return X_LONG_LIMIT return X_LIMIT LINKEDIN_LIMIT = 3000 LINKEDIN_COMMENT_LIMIT = 1250 LINKEDIN_VERSION = os.environ.get("LINKEDIN_VERSION") or "202605" JST = dt.timezone(dt.timedelta(hours=9)) UA = "PixelstoMotors-autopost/1.0" # ---------- 予定表・記録 ---------- def load_json(path, default): if not os.path.exists(path): return default with open(path, encoding="utf-8") as f: return json.load(f) def save_json(path, data): with open(path, "w", encoding="utf-8") as f: json.dump(data, f, ensure_ascii=False, indent=2) f.write("\n") def parse_time(s): t = dt.datetime.fromisoformat(s) if t.tzinfo is None: raise ValueError(f"post_at にタイムゾーンがありません(例 2026-10-25T08:00:00+09:00): {s}") return t def load_source(entry): path = os.path.join(ROOT, entry["source"]) with open(path, encoding="utf-8") as f: return json.load(f) LANGS = ("ja", "en") def lang_of(entry): return entry.get("lang", "ja") def x_links_on(): """X の投稿にリンクを付けるか。リポジトリの Variables の X_LINKS が 1 のときだけ付ける(ないときは付けない)。 付けないときは、本文の URL の行を外し、リンクの返信もしない。""" return os.environ.get("X_LINKS", "0") == "1" def texts_for(entry, src): """投稿文を取り出す。lang が en のときは posts.x_en / linkedin_en / linkedin_comment_en と meta.url_en(なければ meta.url)を使う(マンガの英語の投稿)。""" posts = src.get("posts", {}) meta = src.get("meta", {}) sfx = "_en" if lang_of(entry) == "en" else "" if entry["platform"] == "x": # 画像(最大4枚)と、自分への返信(リンクはここに置く)。2026-10-31 英語のマンガの投稿から imgs = posts.get("x" + sfx + "_images") or [] site = (meta.get("url" + sfx) or meta.get("url", "") or "https://pixelstomotors.com").split("/", 3) base = "/".join(site[:3]) if len(site) >= 3 else "https://pixelstomotors.com" text = posts.get("x" + sfx, "").strip() if not x_links_on(): # リンクを外す(2026-10-31 から。リンク入りの投稿は1本0.20ドル、リンクなしは0.015ドル) lines = [URL_RE.sub("", l).rstrip() for l in text.split("\n") if URL_RE.sub("", l).strip() or not URL_RE.search(l)] text = re.sub(r"\n{3,}", "\n\n", "\n".join(lines)).strip() vid = posts.get("x" + sfx + "_video") or "" # 動画(1本)。画像と一緒には付けられない # リンクを外すと、リンクのカード(表紙の絵)も出ない。画像も動画もない投稿は、投稿のときに # 絵を自動で付ける(x_fallback_images)。2026-11-03 マンガ第132話が文だけで出たため fb = None if not x_links_on() and not imgs and not vid: manga = meta.get("manga_url") or meta.get("url" + sfx) or meta.get("url", "") m = re.search(r"/(?:manga|english-4-koma)/ep(\d+)", manga) fb = {"manga_ep": int(m.group(1)) if m else None, "manga_page": manga if m else "", "lang": lang_of(entry), "youtube_id": meta.get("youtube_id") or "", "page": meta.get("url" + sfx) or meta.get("url", ""), "base": base} return {"text": text, "video": (vid if vid.startswith("http") else base + vid) if vid else "", "images": [u if u.startswith("http") else base + u for u in imgs], "alts": posts.get("x" + sfx + "_alts") or [], "reply": (posts.get("x" + sfx + "_reply") or "").strip(), "quote": str(posts.get("x" + sfx + "_quote") or "").strip(), "fallback": fb} return { "text": posts.get("linkedin" + sfx, "").strip(), "comment": posts.get("linkedin_comment" + sfx, "").strip(), "url": meta.get("url" + sfx) or meta.get("url", ""), # YouTube の本編(2026-10-30 から LinkedIn にもリンクで出す)はカードの題を YouTube のタイトルにする "title": (meta.get("youtube_title") if meta.get("kind") == "youtube_video" else None) or meta.get("title" + sfx) or meta.get("title", ""), "description": meta.get("meta_description" + sfx) or meta.get("meta_description", ""), } # ---------- 文字数 ---------- URL_RE = re.compile(r"https?://\S+") def x_weighted_length(text): """X の数え方:URL は23、ラテン文字などは1、日本語・絵文字などは2。""" n = 23 * len(URL_RE.findall(text)) for ch in URL_RE.sub("", text): c = ord(ch) light = c <= 4351 or 8192 <= c <= 8205 or 8208 <= c <= 8223 or 8242 <= c <= 8247 n += 1 if light else 2 return n def validate(entry, src): """問題があれば説明の文字列のリストを返す。""" errs = [] t = texts_for(entry, src) if not t["text"]: key = {"x": "x", "linkedin": "linkedin"}[entry["platform"]] + ("_en" if lang_of(entry) == "en" else "") errs.append(f"投稿文が空です(posts.{key})") if entry["platform"] == "x": n = x_weighted_length(t["text"]) lim = x_limit(entry) if n > lim: errs.append(f"X の文字数が上限を超えています({n} / {lim})") if t.get("video") and t["images"]: errs.append("X は動画と画像を一緒に付けられません(x_video か x_images のどちらか)") if len(t["images"]) > 4: errs.append(f"X の画像は4枚までです({len(t['images'])}枚)") if t["alts"] and len(t["alts"]) != len(t["images"]): errs.append("X の画像の説明(_alts)の数が画像の数と合いません") if t["reply"] and x_weighted_length(t["reply"]) > x_limit(entry): errs.append(f"X の返信の文字数が上限を超えています({x_weighted_length(t['reply'])} / {x_limit(entry)})") else: if len(t["text"]) > LINKEDIN_LIMIT: errs.append(f"LinkedIn の文字数が上限を超えています({len(t['text'])} / {LINKEDIN_LIMIT})") if t["comment"] and len(t["comment"]) > LINKEDIN_COMMENT_LIMIT: errs.append(f"LinkedIn のコメントが長すぎます({len(t['comment'])} / {LINKEDIN_COMMENT_LIMIT})") if not t["url"]: errs.append("meta.url(記事の URL)がありません") return errs # ---------- LinkedIn の柱と枠(2026-11-09 エイイチが採用・2026-11-13 に組み直し) ---------- # LinkedIn は平日 17:00 に1日1本。曜日ごとに柱(投稿の種類)を決める。 # 2026-11-14 から:月・木=課題地図、火・水・金=研究の記録。業界の読み解きとひとりとAI は LinkedIn に出さない(X だけ)。 # 研究の記録が火曜だけで予約が半年先まで延びたため、エイイチが週3本にし、課題地図の週2本を残した(LOG504)。 # 2026-11-10〜11-13 は前の決まり(月・木=課題地図、火=研究の記録、水・金=業界の読み解き、金=ひとりとAI)で確かめる。 # マンガ・英語・研究の外側の作業の記録は LinkedIn に出さない(X だけ)。docs/sns_autopost.md「LinkedIn の柱と枠」 LINKEDIN_RULE_FROM = dt.datetime(2026, 11, 10, tzinfo=JST) LINKEDIN_RULE_V2_FROM = dt.datetime(2026, 11, 14, tzinfo=JST) LINKEDIN_SLOT = (17, 0) LINKEDIN_PILLARS_V1 = {"issue": (0, 3), "research": (1,), "reading": (2, 4), "ai": (4,)} LINKEDIN_PILLARS = {"issue": (0, 3), "research": (1, 2, 4), "reading": (), "ai": ()} def linkedin_active(pillar, when): """その日時の決まりで、その柱を LinkedIn に出すか(曜日が1つもない柱は出さない)。""" return bool(linkedin_days(pillar, when)) def linkedin_days(pillar, when): """その日時に当てはまる決まりで、柱の曜日(0=月)を返す。""" table = LINKEDIN_PILLARS_V1 if when < LINKEDIN_RULE_V2_FROM else LINKEDIN_PILLARS return table[pillar] def next_linkedin_slot(schedule, pillar, after, exclude_id=None): """after より後で、その柱の曜日の 17:00 のうち、LinkedIn の予約がまだない最初の日時(JST の ISO 文字列)。""" used = {parse_time(e["post_at"]).astimezone(JST).date() for e in schedule.get("posts", []) if e.get("platform") == "linkedin" and e.get("id") != exclude_id} start = max(after, LINKEDIN_RULE_FROM).astimezone(JST) d = start.date() for _ in range(800): t = dt.datetime(d.year, d.month, d.day, *LINKEDIN_SLOT, tzinfo=JST) if t > start and d.weekday() in linkedin_days(pillar, t) and d not in used: return t.isoformat() d += dt.timedelta(days=1) raise RuntimeError("LinkedIn の空いている枠が見つかりません") def linkedin_rule_errors(schedule): errs, per_day = [], {} for e in schedule.get("posts", []): if e.get("platform") != "linkedin": continue try: t = parse_time(e["post_at"]).astimezone(JST) except (KeyError, ValueError): continue if t < LINKEDIN_RULE_FROM: continue where = f"{e['id']}(LinkedIn の決まり)" per_day.setdefault(t.date(), []).append(e["id"]) if lang_of(e) != "ja": errs.append(f"{where}: LinkedIn は日本語だけです") if os.path.basename(e.get("source", "")).startswith(("MANGA_", "SHORT_")): errs.append(f"{where}: マンガとショートは LinkedIn に出しません") p = e.get("pillar") if p not in LINKEDIN_PILLARS: errs.append(f"{where}: pillar(issue・research・reading・ai のどれか)がありません") continue days = linkedin_days(p, t) if (t.hour, t.minute) != LINKEDIN_SLOT or t.weekday() not in days: errs.append(f"{where}: {p} の枠({'・'.join('月火水木金土日'[w] for w in days)}曜 17:00)ではありません: {e['post_at']}") for d, ids in sorted(per_day.items()): if len(ids) > 1: errs.append(f"{d}: LinkedIn が1日に{len(ids)}本あります(1日1本まで): {', '.join(ids)}") return errs def check_schedule(schedule): errs = linkedin_rule_errors(schedule) ids = set() for i, e in enumerate(schedule.get("posts", [])): where = f"posts[{i}] {e.get('id', '(id なし)')}" for k in ("id", "source", "platform", "post_at"): if k not in e: errs.append(f"{where}: {k} がありません") if any(k not in e for k in ("id", "source", "platform", "post_at")): continue if e["id"] in ids: errs.append(f"{where}: id が重複しています") ids.add(e["id"]) try: parse_time(e["post_at"]) except ValueError as ex: errs.append(f"{where}: {ex}") if lang_of(e) not in LANGS: errs.append(f"{where}: lang は ja か en です") continue if e["platform"] not in PLATFORMS: errs.append(f"{where}: platform は x か linkedin です") continue try: src = load_source(e) except (OSError, json.JSONDecodeError) as ex: errs.append(f"{where}: 投稿文のファイルが読めません({ex})") continue errs += [f"{where}: {m}" for m in validate(e, src)] return errs # ---------- HTTP ---------- class ApiError(Exception): def __init__(self, status, body, where): super().__init__(f"{where}: HTTP {status} {body[:500]}") self.status = status def http(method, url, headers=None, body=None, where=""): data = body if isinstance(body, (dict, list)): data = json.dumps(body, ensure_ascii=False).encode("utf-8") req = urllib.request.Request(url, data=data, method=method, headers={"User-Agent": UA, **(headers or {})}) try: with urllib.request.urlopen(req, timeout=60) as r: raw = r.read() return r.status, dict(r.headers), raw except urllib.error.HTTPError as ex: raise ApiError(ex.code, ex.read().decode("utf-8", "replace"), where) from None # ---------- X ---------- def oauth1_header(method, url, ck, cs, tk, ts, query=None): """query: URL の ? の後ろの値(署名に入れる。GET の STATUS で使う。url には ? を含めない)""" q = lambda s: urllib.parse.quote(str(s), safe="~") params = { "oauth_consumer_key": ck, "oauth_nonce": secrets.token_hex(16), "oauth_signature_method": "HMAC-SHA1", "oauth_timestamp": str(int(time.time())), "oauth_token": tk, "oauth_version": "1.0", } base_params = "&".join(f"{q(k)}={q(v)}" for k, v in sorted({**params, **(query or {})}.items())) base = "&".join([method.upper(), q(url), q(base_params)]) key = f"{q(cs)}&{q(ts)}".encode() params["oauth_signature"] = base64.b64encode(hmac.new(key, base.encode(), hashlib.sha1).digest()).decode() return "OAuth " + ", ".join(f'{q(k)}="{q(v)}"' for k, v in sorted(params.items())) # 投稿先の X アカウント(2026-11-22 X を2つに分けた)。予定表の行の "account" で選ぶ。 # なし / "adaptdesign" … @adaptdesignjp(X_ACCESS_TOKEN / X_ACCESS_SECRET) # "ptm" … @pixelstomotors(X_PTM_ACCESS_TOKEN / X_PTM_ACCESS_SECRET。アプリの鍵は同じ) # ptm の鍵がまだ無いときは @adaptdesignjp に出す(止めずに今までどおり出すため)。 X_ACCOUNT = None def x_env(): env = {k: os.environ.get(k, "") for k in ("X_API_KEY", "X_API_SECRET", "X_ACCESS_TOKEN", "X_ACCESS_SECRET")} if X_ACCOUNT == "ptm": tok, sec = os.environ.get("X_PTM_ACCESS_TOKEN", ""), os.environ.get("X_PTM_ACCESS_SECRET", "") if tok and sec: env["X_ACCESS_TOKEN"], env["X_ACCESS_SECRET"] = tok, sec else: print(" @pixelstomotors の鍵がまだ無いので @adaptdesignjp に出します") missing = [k for k, v in env.items() if not v] if missing: raise RuntimeError(f"X の鍵が設定されていません: {', '.join(missing)}") return env def x_call(path, body, where): env = x_env() url = os.environ.get("X_API_BASE", "https://api.x.com") + path auth = oauth1_header("POST", url, env["X_API_KEY"], env["X_API_SECRET"], env["X_ACCESS_TOKEN"], env["X_ACCESS_SECRET"]) _, _, raw = http("POST", url, {"Authorization": auth, "Content-Type": "application/json"}, body, where) return json.loads(raw or b"{}") def x_upload_image(img_url, alt=""): """画像をサイトから取って X に上げ、media の id を返す(v2 の /2/media/upload。base64 の JSON で1回で送る)。 説明(alt)は /2/media/metadata で付ける。説明だけ失敗しても画像は使う。""" req = urllib.request.Request(img_url, headers={"User-Agent": UA}) with urllib.request.urlopen(req, timeout=60) as r: data = r.read() if len(data) > 5 * 1024 * 1024: raise RuntimeError(f"画像が 5MB を超えています: {img_url}") res = x_call("/2/media/upload", {"media": base64.b64encode(data).decode(), "media_category": "tweet_image"}, "X 画像のアップロード") mid = str((res.get("data") or {}).get("id") or res.get("media_id_string") or "") if not mid: raise RuntimeError(f"X 画像のアップロードの返事に id がありません: {str(res)[:300]}") if alt: try: x_call("/2/media/metadata", {"id": mid, "metadata": {"alt_text": {"text": alt[:1000]}}}, "X 画像の説明") except Exception as ex: print(f"画像の説明は付けられませんでした(画像はそのまま使う): {ex}") return mid def x_upload_video(video_url): """動画をサイトから取って X に上げ、media の id を返す(2026-11-02 ショート「AIあるある」を X に先に出すため)。 v2 の分けて送る形: initialize(JSON)→ append(multipart・4MB ずつ)→ finalize → 処理が終わるまで STATUS を見る。""" req = urllib.request.Request(video_url, headers={"User-Agent": UA}) with urllib.request.urlopen(req, timeout=120) as r: data = r.read() if len(data) > 512 * 1024 * 1024: raise RuntimeError(f"動画が大きすぎます: {video_url}") env = x_env() base = os.environ.get("X_API_BASE", "https://api.x.com") res = x_call("/2/media/upload/initialize", {"media_type": "video/mp4", "total_bytes": len(data), "media_category": "tweet_video"}, "X 動画の準備") mid = str((res.get("data") or {}).get("id") or "") if not mid: raise RuntimeError(f"X 動画の準備の返事に id がありません: {str(res)[:300]}") step = 4 * 1024 * 1024 for k, i in enumerate(range(0, len(data), step)): boundary = "----p2m" + secrets.token_hex(12) body = (f"--{boundary}\r\nContent-Disposition: form-data; name=\"segment_index\"\r\n\r\n{k}\r\n" f"--{boundary}\r\nContent-Disposition: form-data; name=\"media\"; filename=\"chunk{k}.mp4\"\r\n" f"Content-Type: application/octet-stream\r\n\r\n").encode() + data[i:i + step] + f"\r\n--{boundary}--\r\n".encode() url = f"{base}/2/media/upload/{mid}/append" auth = oauth1_header("POST", url, env["X_API_KEY"], env["X_API_SECRET"], env["X_ACCESS_TOKEN"], env["X_ACCESS_SECRET"]) http("POST", url, {"Authorization": auth, "Content-Type": f"multipart/form-data; boundary={boundary}"}, body, f"X 動画の送信 {k}") res = x_call(f"/2/media/upload/{mid}/finalize", b"", "X 動画の仕上げ") info = (res.get("data") or {}).get("processing_info") for _ in range(60): if not info or info.get("state") == "succeeded": return mid if info.get("state") == "failed": raise RuntimeError(f"X 動画の処理に失敗しました: {str(info)[:300]}") time.sleep(max(1, int(info.get("check_after_secs", 3)))) url = f"{base}/2/media/upload" qs = {"command": "STATUS", "media_id": mid} auth = oauth1_header("GET", url, env["X_API_KEY"], env["X_API_SECRET"], env["X_ACCESS_TOKEN"], env["X_ACCESS_SECRET"], qs) _, _, raw = http("GET", url + "?" + urllib.parse.urlencode(qs), {"Authorization": auth}, where="X 動画の処理の確認") info = (json.loads(raw or b"{}").get("data") or {}).get("processing_info") raise RuntimeError("X 動画の処理が3分たっても終わりませんでした") def _url_ok(u): try: http("GET", u, where="画像の確かめ") return True except Exception: return False def x_fallback_images(fb): """リンクなしの X 投稿に付ける絵の URL のリストを返す(取れなければ空)。 マンガ(ショートの元のマンガも)→ 4コマの4枚 manga_ep{N}[en]_p1〜p4.webp。 なければ YouTube のサムネイル → 記事・マンガのページの og:image(表紙)の順。""" if not fb: return [] if fb.get("manga_ep"): sfx = "en" if fb.get("lang") == "en" else "" panels = [f"{fb['base']}/media/manga_ep{fb['manga_ep']}{sfx}_p{i}.webp" for i in range(1, 5)] if all(_url_ok(u) for u in panels): return panels if fb.get("youtube_id"): for size in ("maxresdefault", "hqdefault"): u = f"https://i.ytimg.com/vi/{fb['youtube_id']}/{size}.jpg" if _url_ok(u): return [u] for page in (fb.get("manga_page"), fb.get("page")): if page and "youtu" not in page: img = og_image(page) if img: return [img] return [] def post_x(t): x_env() body = {"text": t["text"]} imgs = t.get("images") or [] if not imgs and not t.get("video") and t.get("fallback"): try: imgs = x_fallback_images(t["fallback"]) print(f" リンクなしなので絵を付けます({len(imgs)}枚): " + " ".join(imgs)) except Exception as ex: print(f" 絵は付けずに投稿します({ex})") imgs = [] if t.get("video"): body["media"] = {"media_ids": [x_upload_video(t["video"])]} elif imgs and not t.get("images"): # 自動で付ける絵は、上げられなくても文だけで出す try: body["media"] = {"media_ids": [x_upload_image(u) for u in imgs]} except Exception as ex: print(f" 絵は付けずに投稿します({ex})") elif imgs: alts = t.get("alts") or [""] * len(imgs) try: body["media"] = {"media_ids": [x_upload_image(u, a) for u, a in zip(imgs, alts)]} except Exception as ex: # 画面写真が R2 にまだ無いときなど。2026-11-22 から、投稿そのものは止めずに文だけで出す print(f" ::warning::画像を上げられないので文だけで出します({ex})") if t.get("quote"): # 引用(2026-11-22 から)。posts.x_quote に引用する投稿の id body["quote_tweet_id"] = t["quote"] res = x_call("/2/tweets", body, "X 投稿") pid = res["data"]["id"] result = {"post_id": pid, "url": f"https://x.com/i/web/status/{pid}"} # 自分への返信(リンクを本文に入れないための置き場所)。返信だけ失敗しても本文は出ている if t.get("reply") and x_links_on(): try: r2 = x_call("/2/tweets", {"text": t["reply"], "reply": {"in_reply_to_tweet_id": pid}}, "X 返信") result["reply_id"] = r2["data"]["id"] except Exception as ex: result["comment_error"] = str(ex)[:500] return result # ---------- LinkedIn ---------- def li_headers(token, versioned=True): h = {"Authorization": f"Bearer {token}", "X-Restli-Protocol-Version": "2.0.0", "Content-Type": "application/json"} if versioned: h["LinkedIn-Version"] = LINKEDIN_VERSION return h def li_base(): return os.environ.get("LINKEDIN_API_BASE", "https://api.linkedin.com") def li_person(token): urn = os.environ.get("LINKEDIN_PERSON_URN", "") if urn: return urn _, _, raw = http("GET", li_base() + "/v2/userinfo", {"Authorization": f"Bearer {token}"}, where="LinkedIn 本人確認") return f"urn:li:person:{json.loads(raw)['sub']}" def og_image(page_url): """記事ページの og:image の URL を取る。取れなければ None。""" try: _, _, raw = http("GET", page_url, where="記事ページ") except Exception: return None page = raw.decode("utf-8", "replace") for pat in (r']+property=["\']og:image["\'][^>]+content=["\']([^"\']+)', r']+content=["\']([^"\']+)["\'][^>]+property=["\']og:image["\']'): m = re.search(pat, page) if m: return urllib.parse.urljoin(page_url, html.unescape(m.group(1))) return None def li_thumbnail(token, person, page_url): """記事の表紙画像を LinkedIn に上げて image の URN を返す。失敗したら None(表紙なしで投稿する)。""" try: m = re.search(r"(?:youtu\.be/|youtube\.com/(?:watch\?v=|shorts/))([\w-]{6,})", page_url) if m: # YouTube の動画は、ページを読まずにサムネイルを直接取る(同意の画面などで og:image が取れないことがあるため) img = f"https://i.ytimg.com/vi/{m.group(1)}/hqdefault.jpg" for size in ("maxresdefault", "hqdefault"): try: http("GET", f"https://i.ytimg.com/vi/{m.group(1)}/{size}.jpg", where="YouTube のサムネイル") img = f"https://i.ytimg.com/vi/{m.group(1)}/{size}.jpg"; break except Exception: continue else: img = og_image(page_url) if not img: return None _, _, data = http("GET", img, where="表紙画像") _, _, raw = http("POST", li_base() + "/rest/images?action=initializeUpload", li_headers(token), {"initializeUploadRequest": {"owner": person}}, "LinkedIn 画像の準備") v = json.loads(raw)["value"] # Content-Type を付けないと urllib が form の形(x-www-form-urlencoded)で送り、HTTP 400 になる(2026-10-25 LOG375 で起きた) ctype = "image/png" if img.lower().split("?")[0].endswith(".png") else "image/jpeg" http("PUT", v["uploadUrl"], {"Authorization": f"Bearer {token}", "Content-Type": ctype}, data, "LinkedIn 画像の送信") return v["image"] except Exception as ex: print(f" 表紙画像は付けずに投稿します({ex})") return None def post_linkedin(t): token = os.environ.get("LINKEDIN_ACCESS_TOKEN", "") if not token: raise RuntimeError("LinkedIn のトークンが設定されていません: LINKEDIN_ACCESS_TOKEN") person = li_person(token) article = {"source": t["url"], "title": t["title"] or t["url"]} if t["description"]: article["description"] = t["description"] thumb = li_thumbnail(token, person, t["url"]) if thumb: article["thumbnail"] = thumb body = { "author": person, "commentary": li_escape(t["text"]), "visibility": "PUBLIC", "distribution": {"feedDistribution": "MAIN_FEED", "targetEntities": [], "thirdPartyDistributionChannels": []}, "content": {"article": article}, "lifecycleState": "PUBLISHED", "isReshareDisabledByAuthor": False, } _, headers, _ = http("POST", li_base() + "/rest/posts", li_headers(token), body, "LinkedIn 投稿") urn = {k.lower(): v for k, v in headers.items()}.get("x-restli-id", "") result = {"post_id": urn, "url": f"https://www.linkedin.com/feed/update/{urn}/" if urn else ""} if t.get("comment") and urn: try: enc = urllib.parse.quote(urn, safe="") payload = {"actor": person, "object": urn, "message": {"text": t["comment"]}} try: _, h2, _ = http("POST", f"{li_base()}/rest/socialActions/{enc}/comments", li_headers(token), payload, "LinkedIn コメント") except ApiError as ex: # 版つきの口(rest/)は w_member_social だけでは 403(partnerApiSocialActions。2026-10-25 LOG375 で起きた)。 # 版なしの口(v2/)で1回だけやり直す if ex.status != 403: raise h = {"Authorization": f"Bearer {token}", "Content-Type": "application/json", "X-Restli-Protocol-Version": "2.0.0"} _, h2, _ = http("POST", f"{li_base()}/v2/socialActions/{enc}/comments", h, payload, "LinkedIn コメント(v2)") result["comment_id"] = {k.lower(): v for k, v in h2.items()}.get("x-restli-id", "posted") except Exception as ex: # 本文は出ているので、コメントだけ失敗として残す(本文はやり直さない) result["comment_error"] = str(ex)[:500] return result def li_escape(text): """LinkedIn の commentary は little text 形式。記号はエスケープが要る(しないと本文が途中で切れる)。 ハッシュタグ(#語)はハッシュタグとして残す。""" s = re.sub(r"([\\|{}@\[\]()<>#*_~])", r"\\\1", text) return re.sub(r"\\#(\w+)", r"{hashtag|\\#|\1}", s) # ---------- 一覧(sns/schedule_preview.md) ---------- PREVIEW = os.path.join(ROOT, "sns", "schedule_preview.md") WEEKDAYS = "月火水木金土日" STATUS_JA = {"posted": "投稿済み", "failed": "失敗", "unknown": "要確認(出たか不明)", "posting": "要確認(投稿中で止まった)", "skipped_stale": "見送り"} def md_quote(text): """本文を引用の形にする。改行はそのまま残し、行頭の # が見出しにならないようにする。""" lines = [] for line in text.split("\n"): line = re.sub(r"^(\s*)([#>\-*+]|\d+\.)", r"\1\\\2", line) lines.append("> " + line + " " if line else ">") return "\n".join(lines) def write_preview(schedule=None, posted=None): schedule = schedule if schedule is not None else load_json(SCHEDULE, {"posts": []}) posted = posted if posted is not None else load_json(POSTED, {}) entries = sorted(schedule.get("posts", []), key=lambda e: parse_time(e["post_at"])) upcoming = [e for e in entries if e["id"] not in posted] done = [e for e in reversed(entries) if e["id"] in posted] out = ["# SNS 予約一覧", "", "予定表(`sns/schedule.json`)から自動で作る一覧。**このファイルは手で直さない**(次の更新で上書きされる)。", "中身を変えたいときは、`sns/LOG{番号}_sns_posts.json` か予定表を直す。", "", f"## これから出す({len(upcoming)}本)", ""] if not upcoming: out += ["予約はありません。", ""] for e in upcoming: out += preview_block(e, "予約中") out += [f"## 出したもの・止まったもの({len(done)}本)", ""] if not done: out += ["まだありません。", ""] for e in done: p = posted[e["id"]] status = STATUS_JA.get(p.get("status"), p.get("status", "")) out += preview_block(e, status, p) with open(PREVIEW, "w", encoding="utf-8") as f: f.write("\n".join(out).rstrip() + "\n") def preview_block(e, status, result=None): t = parse_time(e["post_at"]).astimezone(JST) when = f"{t.month}/{t.day}({WEEKDAYS[t.weekday()]}){t.hour}:{t.minute:02d}" name = {"x": "X", "linkedin": "LinkedIn"}.get(e["platform"], e["platform"]) if e["platform"] == "x": name += " @pixelstomotors" if e.get("account") == "ptm" else " @adaptdesignjp" name += "(英語)" if lang_of(e) == "en" else "(日本語)" lines = [f"### {when} ・ {name} ・ {e['id']} ・ {status}", ""] try: src = load_source(e) tx = texts_for(e, src) meta = src.get("meta", {}) sfx = "_en" if lang_of(e) == "en" else "" info = f"リンク先:[{meta.get('title' + sfx) or meta.get('title', '')}]({meta.get('url' + sfx) or meta.get('url', '')})" if e["platform"] == "x": info += f" / 文字数 {x_weighted_length(tx['text'])} / {x_limit(e)}" if tx.get("images"): info += f" / 画像 {len(tx['images'])}枚" lines += [info, "", md_quote(tx["text"]), ""] if e["platform"] == "x" and tx.get("reply"): lines += ["返信:", "", md_quote(tx["reply"]), ""] except (OSError, json.JSONDecodeError, KeyError) as ex: lines += [f"(投稿文が読めません:{ex})", ""] if result: if result.get("url"): lines += [f"投稿:{result['url']}", ""] if result.get("error"): lines += [f"エラー:`{result['error'][:300]}`", ""] return lines # ---------- git ---------- def git(*args): return subprocess.run(["git", "-C", ROOT, *args], capture_output=True, text=True) def commit_and_push(message): """posted.json と一覧を commit して push。成功したら True。""" if os.environ.get("AUTOPOST_GIT") != "1": return True try: write_preview() git("add", "sns/schedule_preview.md") except Exception as ex: print(f"一覧の更新に失敗しました(投稿には影響しません): {ex}") git("add", "sns/posted.json") r = git("commit", "-m", message) if r.returncode != 0 and "nothing to commit" not in (r.stdout + r.stderr): print(r.stdout, r.stderr) return False for _ in range(3): if git("push", "origin", "HEAD").returncode == 0: return True # 途中で別の push があったら取り込んでやり直す if git("pull", "--rebase", "origin", "HEAD").returncode != 0: git("rebase", "--abort") return False return False # ---------- 実行 ---------- def now_utc(): s = os.environ.get("AUTOPOST_NOW") return parse_time(s) if s else dt.datetime.now(dt.timezone.utc) def run(dry_run): global X_ACCOUNT schedule = load_json(SCHEDULE, {"posts": []}) errs = check_schedule(schedule) if errs: print("予定表に問題があります。直すまで投稿しません。") for e in errs: print(" - " + e) return 1 posted = load_json(POSTED, {}) now = now_utc() failed = False due = sorted((e for e in schedule["posts"] if e["id"] not in posted and parse_time(e["post_at"]) <= now), key=lambda e: parse_time(e["post_at"])) if not due: print("時刻が来ている投稿はありません。") return 0 for e in due: late = now - parse_time(e["post_at"]) stamp = now.astimezone(JST).isoformat(timespec="seconds") if late > dt.timedelta(hours=STALE_HOURS): print(f"[{e['id']}] 予定から {late} 遅れているので見送ります") if not dry_run: posted[e["id"]] = {"status": "skipped_stale", "at": stamp, "post_at": e["post_at"]} save_json(POSTED, posted) commit_and_push(f"SNS自動投稿:{e['id']} を見送り(予定から{STALE_HOURS}時間以上遅れ)") continue t = texts_for(e, load_source(e)) if dry_run: extra = "" if t.get("images"): extra += f"\n画像 {len(t['images'])}枚: " + " ".join(t["images"]) elif t.get("fallback"): fi = x_fallback_images(t["fallback"]) extra += f"\n自動で付ける絵 {len(fi)}枚: " + " ".join(fi) if t.get("reply"): extra += f"\n返信:\n{t['reply']}" print(f"[{e['id']}] {e['platform']} に投稿します(試し・送らない)\n----\n{t['text']}{extra}\n----") continue # 1) 先に「投稿中」を push。push できなければ投稿しない(二重投稿を防ぐ) posted[e["id"]] = {"status": "posting", "at": stamp, "platform": e["platform"]} save_json(POSTED, posted) if not commit_and_push(f"SNS自動投稿:{e['id']} を投稿中"): print(f"[{e['id']}] 記録を push できなかったので投稿しません") return 1 # 2) 投稿 try: X_ACCOUNT = e.get("account") result = post_x(t) if e["platform"] == "x" else post_linkedin(t) posted[e["id"]] = {"status": "posted", "at": stamp, "platform": e["platform"], **result} print(f"[{e['id']}] 投稿しました {result.get('url', '')}") if result.get("comment_error"): # 本文は出ているので Actions は赤くしない。コメントは手で付ける(posted.json の comment_error に理由) print(f"[{e['id']}] コメント(X は返信)は付けられませんでした(本文は出ています。手で付けてください): {result['comment_error']}") except Exception as ex: msg = str(ex) if isinstance(ex, ApiError) and ex.status == 401: msg = "認証が切れているか鍵が違います。" + ( "LinkedIn のトークン(60日で切れる)を作り直してください。 " if e["platform"] == "linkedin" else "") + msg # 相手から断られた(HTTP のエラーが返った・鍵がない)なら出ていない=failed。 # 通信が途中で切れたなどで分からないときは unknown(手で確かめる) status = "failed" if isinstance(ex, (ApiError, RuntimeError)) else "unknown" posted[e["id"]] = {"status": status, "at": stamp, "platform": e["platform"], "error": msg[:800]} print(f"[{e['id']}] 投稿に失敗しました({status}): {msg}") failed = True # 3) 結果を push save_json(POSTED, posted) commit_and_push(f"SNS自動投稿:{e['id']} の結果({posted[e['id']]['status']})") return 1 if failed else 0 def verify(): """鍵が使えるかを、投稿せずに確かめる(X は自分の名前を読む・LinkedIn は本人確認)。""" ok = True try: env = {k: os.environ.get(k, "") for k in ("X_API_KEY", "X_API_SECRET", "X_ACCESS_TOKEN", "X_ACCESS_SECRET")} if not all(env.values()): raise RuntimeError("X の鍵が足りません") url = os.environ.get("X_API_BASE", "https://api.x.com") + "/2/users/me" auth = oauth1_header("GET", url, env["X_API_KEY"], env["X_API_SECRET"], env["X_ACCESS_TOKEN"], env["X_ACCESS_SECRET"]) _, _, raw = http("GET", url, {"Authorization": auth}, where="X 本人確認") print(f"X: OK(@{json.loads(raw)['data']['username']})") ptok, psec = os.environ.get("X_PTM_ACCESS_TOKEN", ""), os.environ.get("X_PTM_ACCESS_SECRET", "") if ptok and psec: auth = oauth1_header("GET", url, env["X_API_KEY"], env["X_API_SECRET"], ptok, psec) _, _, raw = http("GET", url, {"Authorization": auth}, where="X 本人確認(ptm)") print(f"X ptm: OK(@{json.loads(raw)['data']['username']})") else: print("X ptm: 鍵はまだありません(ptm の行は @adaptdesignjp に出ます)") # 画像のアップロードも確かめる(上げるだけで投稿はしない。2026-10-31 英語のマンガに画像を付けるようにしたため) mid = x_upload_image("https://pixelstomotors.com/media/manga_ep133en_p1.webp", "verify upload") print(f"X 画像のアップロード: OK(media id {mid}。投稿はしていない)") except Exception as ex: ok = False print(f"X: NG {ex}") try: token = os.environ.get("LINKEDIN_ACCESS_TOKEN", "") if not token: raise RuntimeError("LinkedIn のトークンがありません") _, _, raw = http("GET", li_base() + "/v2/userinfo", {"Authorization": f"Bearer {token}"}, where="LinkedIn 本人確認") print(f"LinkedIn: OK({json.loads(raw).get('name', '')})") except Exception as ex: ok = False print(f"LinkedIn: NG {ex}") return 0 if ok else 1 def main(): ap = argparse.ArgumentParser() ap.add_argument("command", choices=["check", "run", "preview", "verify"]) ap.add_argument("--dry-run", action="store_true") a = ap.parse_args() if a.command == "verify": return verify() if a.command == "preview": write_preview() print(f"一覧を書きました: {os.path.relpath(PREVIEW, ROOT)}") return 0 if a.command == "check": errs = check_schedule(load_json(SCHEDULE, {"posts": []})) for e in errs: print(" - " + e) print("問題ありません。" if not errs else f"{len(errs)} 件の問題があります。") return 1 if errs else 0 return run(a.dry_run) if __name__ == "__main__": sys.exit(main())