[Instagram Reels] Phase 2 완성 - instagram_bot.py: publish_reels() 추가 (MP4 → Reels API) - upload_video_container(), wait_for_video_ready() 구현 - 로컬 경로 → 공개 URL 자동 변환 (image_host.get_public_video_url()) - scheduler.py: job_distribute_instagram_reels() 추가 (10:30) - image_host.py: get_public_video_url() + 로컬 비디오 서버 추가 - VIDEO_HOST_BASE_URL 환경변수 지원 (Tailscale/CDN) [writer_bot.py] 신규 — 독립 실행형 글쓰기 봇 - api_content.py manual-write 엔드포인트에서 subprocess 호출 가능 - run_pending(): 오늘 날짜 미처리 글감 자동 처리 - run_from_topic(): 직접 주제 지정 - run_from_file(): JSON 파일 지정 - CLI: python bots/writer_bot.py [--topic "..." | --file path.json | --limit N] [보조 시스템 신규] v3.1 CLI + Assist 모드 - blog.cmd: venv Python 경유 Windows 런처 - blog_runtime.py + runtime_guard.py: 실행 진입점 + venv 검증 - blog_engine_cli.py: 대시보드 API 기반 CLI (blog status, blog review 등) - bots/assist_bot.py: URL 기반 수동 어시스트 파이프라인 - dashboard/backend/api_assist.py + frontend/Assist.jsx: 수동모드 탭 [engine_loader.py] v3.1 개선 - OpenClawWriter: --json 플래그 + payloads 파싱 + plain text 폴백 - ClaudeWebWriter: Playwright 쿠키 세션 (Cloudflare 차단으로 현재 비활성) - GeminiWebWriter: gemini-webapi 비공식 클라이언트 [scheduler.py] v3.1 개선 - _call_openclaw(): 플레이스홀더 → EngineLoader 실제 호출 - _build_openclaw_prompt(): 구조화된 HTML 원고 프롬프트 - data/originals/: 원본 article JSON 저장 경로 추가 [설정/환경] 정비 - .env.example: SEEDANCE/ELEVENLABS/GEMINI/RUNWAY 복원 + VIDEO_HOST_BASE_URL, GEMINI_WEB_* , REMOTE_CLAUDE_POLLING_ENABLED 추가 - scripts/setup.bat: data/originals, outputs, assist, novels, config/novels 디렉토리 생성 + 폰트 다운로드 + blog.cmd 기반 Task Scheduler 등록 - requirements.txt: fastapi, uvicorn, python-multipart 추가 Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
115 lines
3.4 KiB
Python
115 lines
3.4 KiB
Python
"""
|
|
Remote Claude Bot
|
|
텔레그램 메시지를 Claude Agent SDK에 전달하고 결과를 돌려보냅니다.
|
|
실행: python bots/remote_claude.py
|
|
"""
|
|
import asyncio
|
|
import logging
|
|
import os
|
|
from pathlib import Path
|
|
|
|
from dotenv import load_dotenv
|
|
from telegram import Update
|
|
from telegram.ext import Application, MessageHandler, CommandHandler, filters, ContextTypes
|
|
from claude_agent_sdk import query, ClaudeAgentOptions, ResultMessage
|
|
|
|
load_dotenv()
|
|
|
|
BASE_DIR = Path(__file__).parent.parent
|
|
TELEGRAM_BOT_TOKEN = os.getenv('TELEGRAM_BOT_TOKEN', '')
|
|
TELEGRAM_CHAT_ID = int(os.getenv('TELEGRAM_CHAT_ID', '0'))
|
|
REMOTE_CLAUDE_POLLING_ENABLED = os.getenv('REMOTE_CLAUDE_POLLING_ENABLED', '').lower() in {'1', 'true', 'yes', 'on'}
|
|
|
|
logging.basicConfig(
|
|
level=logging.INFO,
|
|
format='%(asctime)s [%(levelname)s] %(message)s',
|
|
)
|
|
logger = logging.getLogger(__name__)
|
|
|
|
MAX_MSG_LEN = 4000
|
|
|
|
|
|
def split_message(text: str) -> list[str]:
|
|
chunks = []
|
|
while len(text) > MAX_MSG_LEN:
|
|
chunks.append(text[:MAX_MSG_LEN])
|
|
text = text[MAX_MSG_LEN:]
|
|
if text:
|
|
chunks.append(text)
|
|
return chunks
|
|
|
|
|
|
async def run_claude(prompt: str) -> str:
|
|
result_text = ""
|
|
try:
|
|
async for message in query(
|
|
prompt=prompt,
|
|
options=ClaudeAgentOptions(
|
|
cwd=str(BASE_DIR),
|
|
allowed_tools=["Read", "Write", "Edit", "Bash", "Glob", "Grep"],
|
|
permission_mode="bypassPermissions",
|
|
max_turns=30,
|
|
)
|
|
):
|
|
if isinstance(message, ResultMessage):
|
|
result_text = message.result
|
|
except Exception as e:
|
|
result_text = f"오류: {e}"
|
|
return result_text or "(완료)"
|
|
|
|
|
|
async def handle_message(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
|
if update.message.chat_id != TELEGRAM_CHAT_ID:
|
|
return
|
|
|
|
prompt = update.message.text.strip()
|
|
logger.info(f"명령 수신: {prompt[:80]}")
|
|
|
|
await update.message.reply_text("처리 중...")
|
|
await context.bot.send_chat_action(chat_id=TELEGRAM_CHAT_ID, action="typing")
|
|
|
|
result = await run_claude(prompt)
|
|
|
|
for chunk in split_message(result):
|
|
await update.message.reply_text(chunk)
|
|
|
|
|
|
async def cmd_help(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
|
if update.message.chat_id != TELEGRAM_CHAT_ID:
|
|
return
|
|
await update.message.reply_text(
|
|
"Remote Claude Bot\n\n"
|
|
"자연어로 아무 지시나 입력하세요.\n\n"
|
|
"예시:\n"
|
|
"• scheduler.py 상태 확인해줘\n"
|
|
"• 수집봇 지금 실행해줘\n"
|
|
"• .env 파일 내용 보여줘\n"
|
|
"• requirements.txt에 패키지 추가해줘\n"
|
|
"• 오늘 로그 확인해줘\n\n"
|
|
"/help — 이 메시지"
|
|
)
|
|
|
|
|
|
def main():
|
|
if not REMOTE_CLAUDE_POLLING_ENABLED:
|
|
logger.info("Remote Claude Bot polling 비활성화 — 기본 운영은 scheduler.py Telegram 리스너 사용")
|
|
return
|
|
|
|
if not TELEGRAM_BOT_TOKEN:
|
|
logger.error("TELEGRAM_BOT_TOKEN이 없습니다.")
|
|
return
|
|
|
|
app = Application.builder().token(TELEGRAM_BOT_TOKEN).build()
|
|
app.add_handler(CommandHandler('help', cmd_help))
|
|
app.add_handler(MessageHandler(
|
|
filters.TEXT & ~filters.COMMAND & filters.Chat(TELEGRAM_CHAT_ID),
|
|
handle_message
|
|
))
|
|
|
|
logger.info(f"Remote Claude Bot 시작 (chat_id={TELEGRAM_CHAT_ID})")
|
|
app.run_polling(drop_pending_updates=True)
|
|
|
|
|
|
if __name__ == '__main__':
|
|
main()
|