Gerador de vídeos narrativos (Godot + FFmpeg), painel Next.js, serviço de voz, Clipador de lives e Publicador para YouTube, TikTok e Instagram. Inclui a leitura das visualizações dos posts para o Dashboard e o botão "Publicar no <rede>" nos cartões das publicações. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
190 lines
9.5 KiB
Python
190 lines
9.5 KiB
Python
"""TikTok pelo TikTok Studio (modo sessão logada): tiktok.com/tiktokstudio/upload.
|
|
|
|
ATENÇÃO: seletores escritos pela estrutura conhecida da página (nomes acessíveis em PT e EN, atributos
|
|
`data-e2e`) e AINDA NÃO VALIDADOS COM UMA CONTA REAL. Corrigir só neste dicionário. O TikTok mostra captcha com
|
|
frequência: quando aparecer, o envio para em `needs_login` — o usuário resolve na janela; nunca automatizamos isso.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import re
|
|
import time
|
|
from typing import Any
|
|
|
|
from ..base import JobSpec, Progress, PublishError, PublishResult, Sleep
|
|
from .common import (Uploader, caption_key, click_through, detect_block, dismiss_tips, fill_text, find, needs_login,
|
|
require, step_pause)
|
|
|
|
UPLOAD_URL = "https://www.tiktok.com/tiktokstudio/upload?from=upload"
|
|
|
|
SELECTORS: dict[str, list[tuple]] = {
|
|
"login": [("role", "button", r"^(Entrar|Log in)$"), ("css", "[data-e2e='top-login-button']"),
|
|
("role", "link", r"^(Entrar|Log in)$")],
|
|
"file_input": [("css", "input[type='file'][accept*='video']"), ("css", "input[type='file']")],
|
|
"caption": [("css", "div[contenteditable='true'].public-DraftEditor-content"),
|
|
("css", ".caption-editor div[contenteditable='true']"), ("css", "div[contenteditable='true']")],
|
|
# Fim do envio do arquivo (a página mostra "Enviado"/"Uploaded" junto ao nome do arquivo).
|
|
"uploaded": [("text", r"^(Enviado|Carregado|Uploaded)\b"), ("css", "[data-e2e='upload-success']")],
|
|
"privacy_dropdown": [("role", "combobox", r"(Quem pode (ver|assistir)|Who can (watch|view))"),
|
|
("css", "[data-e2e='video-setting-privacy'] [role='button'], .view-auth-container [role='button']")],
|
|
"privacy_public": [("role", "option", r"^(Todos|Todo mundo|Everyone)$"), ("text", r"^(Todos|Everyone)$")],
|
|
"privacy_private": [("role", "option", r"^(Somente você|Só você|Only you|Only me)$"),
|
|
("text", r"^(Somente você|Só você|Only you|Only me)$")],
|
|
"show_more": [("role", "button", r"^(Mostrar mais|Exibir mais|Show more)$"), ("text", r"^(Mostrar mais|Show more)$")],
|
|
"ai_toggle": [("role", "switch", r"(gerado por IA|AI-generated)"),
|
|
("css", "[data-e2e='aigc_container'] input[type='checkbox'], [data-e2e='aigc_container'] [role='switch']")],
|
|
"post": [("css", "button[data-e2e='post_video_button']"), ("role", "button", r"^(Publicar|Postar|Post)$")],
|
|
"post_now": [("role", "button", r"^(Publicar agora|Postar agora|Post now)$")],
|
|
"posted": [("text", r"(Seu vídeo foi publicado|vídeo (está|foi) (sendo )?publicado|Your video (has been|is being) "
|
|
r"(posted|published)|Gerenciar suas publicações|Manage your posts|Vídeo publicado|Video posted)")],
|
|
}
|
|
|
|
VIDEO_ID = re.compile(r"tiktok\.com/@([\w.-]+)/video/(\d+)")
|
|
|
|
|
|
def check(page: Any, sleep: Sleep = time.sleep) -> str | None:
|
|
page.goto(UPLOAD_URL, wait_until="domcontentloaded")
|
|
step_pause(sleep, 2.0, 3.5)
|
|
reason = detect_block(page, SELECTORS["login"])
|
|
if reason:
|
|
return reason
|
|
if find(page, SELECTORS["file_input"], timeout_s=15, visible=False, sleep=sleep) is None:
|
|
return "não achei o campo de envio do TikTok Studio (a conta pode não estar logada)"
|
|
return None
|
|
|
|
|
|
def _guard(page: Any) -> None:
|
|
reason = detect_block(page, SELECTORS["login"])
|
|
if reason:
|
|
raise needs_login(reason)
|
|
|
|
|
|
def upload(page: Any, spec: JobSpec, progress: Progress, sleep: Sleep = time.sleep) -> PublishResult:
|
|
progress("Abrindo o TikTok Studio…", 0.02)
|
|
reason = check(page, sleep)
|
|
if reason:
|
|
raise needs_login(reason)
|
|
require(page, SELECTORS["file_input"], "o campo de arquivo", visible=False, sleep=sleep).set_input_files(str(spec.file))
|
|
progress("Enviando vídeo pelo TikTok Studio…", 0.1)
|
|
step_pause(sleep, 2.0, 4.0)
|
|
_guard(page)
|
|
|
|
caption = require(page, SELECTORS["caption"], "o campo de legenda", timeout_s=60, sleep=sleep)
|
|
# Com o vídeo carregado, o Studio às vezes abre um aviso de novidade por cima de tudo ("Veja a prévia…").
|
|
step_pause(sleep, 1.0, 2.0)
|
|
dismiss_tips(page, sleep)
|
|
fill_text(caption, spec.caption[:2200], sleep)
|
|
# Fecha a lista de sugestões de hashtag/menção que aparece ao digitar "#" ou "@".
|
|
page.keyboard.press("Escape")
|
|
step_pause(sleep)
|
|
|
|
want_private = spec.privacy in ("private", "unlisted")
|
|
dropdown = find(page, SELECTORS["privacy_dropdown"], timeout_s=5, sleep=sleep)
|
|
if dropdown is not None:
|
|
click_through(dropdown, sleep)
|
|
step_pause(sleep)
|
|
click_through(require(page, SELECTORS["privacy_private" if want_private else "privacy_public"],
|
|
"a opção de privacidade", sleep=sleep), sleep)
|
|
step_pause(sleep)
|
|
elif want_private:
|
|
raise PublishError("Não achei onde escolher a privacidade no TikTok Studio; não publiquei para não expor um "
|
|
"vídeo que era para ser privado.")
|
|
|
|
if spec.ai_generated:
|
|
more = find(page, SELECTORS["show_more"], timeout_s=3, sleep=sleep)
|
|
if more is not None:
|
|
click_through(more, sleep)
|
|
step_pause(sleep)
|
|
toggle = find(page, SELECTORS["ai_toggle"], timeout_s=5, visible=False, sleep=sleep)
|
|
if toggle is None:
|
|
raise PublishError("Não achei o rótulo \"Conteúdo gerado por IA\" no TikTok Studio; não publiquei sem ele.")
|
|
if (toggle.get_attribute("aria-checked") or "").lower() != "true" and not _is_checked(toggle):
|
|
click_through(toggle, sleep)
|
|
step_pause(sleep)
|
|
|
|
progress("Esperando o envio terminar…", 0.5)
|
|
if find(page, SELECTORS["uploaded"], timeout_s=30 * 60, sleep=sleep) is None:
|
|
raise PublishError("O envio pelo TikTok Studio não terminou em 30 minutos. Confira a internet e tente de novo.")
|
|
_guard(page)
|
|
|
|
post = require(page, SELECTORS["post"], "o botão Publicar", timeout_s=60, sleep=sleep)
|
|
for _ in range(60): # o botão fica desabilitado enquanto a verificação de conteúdo roda
|
|
if post.is_enabled():
|
|
break
|
|
sleep(2)
|
|
dismiss_tips(page, sleep)
|
|
click_through(post, sleep)
|
|
progress("Publicando…", 0.9)
|
|
step_pause(sleep, 2.0, 4.0)
|
|
now_button = find(page, SELECTORS["post_now"], timeout_s=5, sleep=sleep)
|
|
if now_button is not None:
|
|
click_through(now_button, sleep)
|
|
step_pause(sleep)
|
|
_guard(page)
|
|
if find(page, SELECTORS["posted"], timeout_s=90, sleep=sleep) is None and "tiktokstudio/content" not in page.url:
|
|
raise PublishError("Cliquei em Publicar mas o TikTok não confirmou. Confira no app antes de tentar de novo.")
|
|
url = find_video_url(page, spec.caption, sleep, progress=progress)
|
|
match = VIDEO_ID.search(url or "")
|
|
if match:
|
|
return PublishResult(match.group(2), f"https://www.tiktok.com/@{match.group(1)}/video/{match.group(2)}", False,
|
|
"Publicado no TikTok (Studio)")
|
|
return PublishResult(None, None, False, "Publicado no TikTok (Studio), mas o vídeo não apareceu na lista do Studio "
|
|
"em ~3 min; link não encontrado")
|
|
|
|
|
|
CONTENT_URL = "https://www.tiktok.com/tiktokstudio/content"
|
|
|
|
# Na lista "Publicações" do Studio (validado com conta real em 17/11/2026), cada linha tem um <a href="/@conta/video/<id>">
|
|
# e a descrição do post. Só aceita o link cuja linha contém o começo da legenda enviada: nunca pegar o de outro vídeo.
|
|
_LINK_FOR_CAPTION_JS = """(key) => {
|
|
const norm = (s) => (s || "").replace(/\\s+/g, " ").trim().toLowerCase();
|
|
const want = norm(key);
|
|
for (const a of document.querySelectorAll("a[href*='/video/']")) {
|
|
if (!want) return a.href;
|
|
let el = a;
|
|
for (let i = 0; i < 10 && el; i++, el = el.parentElement) {
|
|
if (norm(el.innerText).includes(want)) return a.href;
|
|
}
|
|
}
|
|
return null;
|
|
}"""
|
|
|
|
|
|
def find_video_url(page: Any, caption: str, sleep: Sleep = time.sleep, attempts: int = 12, reads: int = 5,
|
|
progress: Progress | None = None) -> str | None:
|
|
"""Link do vídeo recém-publicado (ideia do dono, 17/11/2026: "esperar um pouco e depois ir em /content ver se o
|
|
vídeo já está lá"). A lista do Studio NÃO se atualiza sozinha e o vídeo novo só entra depois de processar: espera
|
|
um pouco, abre (ou recarrega) a lista e procura por ~15 s; não achou ⇒ recarrega de novo. Até `attempts` cargas
|
|
(~3 min). Na 1ª, se o Studio já levou para a lista sozinho, só lê."""
|
|
key = caption_key(caption)
|
|
sleep(5)
|
|
for attempt in range(attempts):
|
|
if progress:
|
|
progress(f"Publicado. Esperando o vídeo aparecer na lista do Studio para pegar o link "
|
|
f"({attempt + 1} de {attempts})…", 0.95)
|
|
if attempt > 0 or "tiktokstudio/content" not in (page.url or ""):
|
|
try:
|
|
page.goto(CONTENT_URL, wait_until="domcontentloaded")
|
|
except Exception: # noqa: BLE001 - rede oscilando: tenta de novo na próxima carga
|
|
sleep(3)
|
|
continue
|
|
for _ in range(reads):
|
|
try:
|
|
href = page.evaluate(_LINK_FOR_CAPTION_JS, key)
|
|
except Exception: # noqa: BLE001 - página trocando no meio da leitura: tenta de novo
|
|
href = None
|
|
if href and VIDEO_ID.search(href):
|
|
return href
|
|
sleep(3)
|
|
return None
|
|
|
|
|
|
def _is_checked(locator: Any) -> bool:
|
|
try:
|
|
return bool(locator.is_checked())
|
|
except Exception: # noqa: BLE001 - nem todo switch é checkbox nativo
|
|
return False
|
|
|
|
|
|
UPLOADER = Uploader("tiktok", UPLOAD_URL, check, upload)
|