finish poc
This commit is contained in:
1 parent
f73be9c6d0
commit
18b18e9ff2
36 files changed
+9192
-5439
No files matched your search
@@ -0,0 +1,5 @@
|
||||
"""
|
||||
Instagram Graph API 예제 모듈
|
||||
|
||||
각 기능별 실행 가능한 예제를 제공합니다.
|
||||
"""
|
||||
@@ -0,0 +1,109 @@
|
||||
"""
|
||||
Instagram Graph API 계정 정보 조회 예제
|
||||
|
||||
비즈니스/크리에이터 계정의 프로필 정보를 조회합니다.
|
||||
|
||||
실행 방법:
|
||||
```bash
|
||||
export INSTAGRAM_ACCESS_TOKEN="your_access_token"
|
||||
python -m poc.instagram1.examples.account_example
|
||||
```
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
import sys
|
||||
|
||||
# 로깅 설정
|
||||
logging.basicConfig(
|
||||
level=logging.INFO,
|
||||
format="%(asctime)s [%(levelname)s] %(message)s",
|
||||
handlers=[logging.StreamHandler(sys.stdout)],
|
||||
)
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
async def example_get_account():
|
||||
"""계정 정보 조회 예제"""
|
||||
from poc.instagram1 import InstagramGraphClient, AuthenticationError
|
||||
|
||||
print("\n" + "=" * 60)
|
||||
print("계정 정보 조회")
|
||||
print("=" * 60)
|
||||
|
||||
try:
|
||||
async with InstagramGraphClient() as client:
|
||||
account = await client.get_account()
|
||||
|
||||
print(f"\n📱 계정 정보")
|
||||
print("-" * 40)
|
||||
print(f"🆔 ID: {account.id}")
|
||||
print(f"👤 사용자명: @{account.username}")
|
||||
print(f"📛 이름: {account.name or '(없음)'}")
|
||||
print(f"📊 계정 타입: {account.account_type}")
|
||||
print(f"🖼️ 프로필 사진: {account.profile_picture_url or '(없음)'}")
|
||||
|
||||
print(f"\n📈 통계")
|
||||
print("-" * 40)
|
||||
print(f"👥 팔로워: {account.followers_count:,}명")
|
||||
print(f"👤 팔로잉: {account.follows_count:,}명")
|
||||
print(f"📷 게시물: {account.media_count:,}개")
|
||||
|
||||
if account.biography:
|
||||
print(f"\n📝 자기소개")
|
||||
print("-" * 40)
|
||||
print(f"{account.biography}")
|
||||
|
||||
if account.website:
|
||||
print(f"\n🌐 웹사이트: {account.website}")
|
||||
|
||||
except AuthenticationError as e:
|
||||
print(f"❌ 인증 에러: {e}")
|
||||
except Exception as e:
|
||||
print(f"❌ 에러: {e}")
|
||||
|
||||
|
||||
async def example_get_account_id():
|
||||
"""계정 ID만 조회 예제"""
|
||||
from poc.instagram1 import InstagramGraphClient
|
||||
|
||||
print("\n" + "=" * 60)
|
||||
print("계정 ID 조회 (캐시 테스트)")
|
||||
print("=" * 60)
|
||||
|
||||
try:
|
||||
async with InstagramGraphClient() as client:
|
||||
# 첫 번째 호출 (API 요청)
|
||||
print("\n1️⃣ 첫 번째 조회 (API 호출)")
|
||||
account_id = await client.get_account_id()
|
||||
print(f" 계정 ID: {account_id}")
|
||||
|
||||
# 두 번째 호출 (캐시 사용)
|
||||
print("\n2️⃣ 두 번째 조회 (캐시)")
|
||||
account_id_cached = await client.get_account_id()
|
||||
print(f" 계정 ID: {account_id_cached}")
|
||||
|
||||
print("\n✅ 캐시 동작 확인 완료")
|
||||
|
||||
except Exception as e:
|
||||
print(f"❌ 에러: {e}")
|
||||
|
||||
|
||||
async def main():
|
||||
"""모든 계정 예제 실행"""
|
||||
print("\n👤 Instagram Graph API 계정 예제")
|
||||
print("=" * 60)
|
||||
|
||||
# 계정 정보 조회
|
||||
await example_get_account()
|
||||
|
||||
# 계정 ID 캐시 테스트
|
||||
await example_get_account_id()
|
||||
|
||||
print("\n" + "=" * 60)
|
||||
print("✅ 예제 완료")
|
||||
print("=" * 60)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,142 @@
|
||||
"""
|
||||
Instagram Graph API 인증 예제
|
||||
|
||||
토큰 검증, 교환, 갱신 기능을 테스트합니다.
|
||||
|
||||
실행 방법:
|
||||
```bash
|
||||
# 환경변수 설정
|
||||
export INSTAGRAM_ACCESS_TOKEN="your_access_token"
|
||||
export INSTAGRAM_APP_ID="your_app_id"
|
||||
export INSTAGRAM_APP_SECRET="your_app_secret"
|
||||
|
||||
# 실행
|
||||
cd /path/to/project
|
||||
python -m poc.instagram1.examples.auth_example
|
||||
```
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
import sys
|
||||
from datetime import datetime, timezone
|
||||
|
||||
# 로깅 설정
|
||||
logging.basicConfig(
|
||||
level=logging.INFO,
|
||||
format="%(asctime)s [%(levelname)s] %(message)s",
|
||||
handlers=[logging.StreamHandler(sys.stdout)],
|
||||
)
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
async def example_debug_token():
|
||||
"""토큰 검증 예제"""
|
||||
from poc.instagram1 import InstagramGraphClient, AuthenticationError
|
||||
|
||||
print("\n" + "=" * 60)
|
||||
print("1. 토큰 검증 (Debug Token)")
|
||||
print("=" * 60)
|
||||
|
||||
try:
|
||||
async with InstagramGraphClient() as client:
|
||||
token_info = await client.debug_token()
|
||||
data = token_info.data
|
||||
|
||||
print(f"✅ 토큰 유효: {data.is_valid}")
|
||||
print(f"📱 앱 이름: {data.application}")
|
||||
print(f"👤 사용자 ID: {data.user_id}")
|
||||
print(f"🔐 권한: {', '.join(data.scopes)}")
|
||||
print(f"⏰ 만료 시각: {data.expires_at_datetime}")
|
||||
|
||||
# 만료까지 남은 시간 계산
|
||||
remaining = data.expires_at_datetime - datetime.now(timezone.utc)
|
||||
print(f"⏳ 남은 시간: {remaining.days}일 {remaining.seconds // 3600}시간")
|
||||
|
||||
if data.is_expired:
|
||||
print("⚠️ 토큰이 만료되었습니다. 갱신이 필요합니다.")
|
||||
|
||||
except AuthenticationError as e:
|
||||
print(f"❌ 인증 에러: {e}")
|
||||
except ValueError as e:
|
||||
print(f"⚠️ 설정 에러: {e}")
|
||||
print(" app_id와 app_secret 환경변수를 설정해주세요.")
|
||||
except Exception as e:
|
||||
print(f"❌ 에러: {e}")
|
||||
|
||||
|
||||
async def example_exchange_token():
|
||||
"""토큰 교환 예제 (단기 → 장기)"""
|
||||
from poc.instagram1 import InstagramGraphClient, AuthenticationError
|
||||
|
||||
print("\n" + "=" * 60)
|
||||
print("2. 토큰 교환 (Short-lived → Long-lived)")
|
||||
print("=" * 60)
|
||||
|
||||
try:
|
||||
async with InstagramGraphClient() as client:
|
||||
new_token = await client.exchange_long_lived_token()
|
||||
|
||||
print(f"✅ 토큰 교환 성공")
|
||||
print(f"🔑 새 토큰: {new_token.access_token[:20]}...")
|
||||
print(f"📝 토큰 타입: {new_token.token_type}")
|
||||
print(f"⏰ 유효 기간: {new_token.expires_in}초 ({new_token.expires_in // 86400}일)")
|
||||
|
||||
print("\n💡 새 토큰을 환경변수에 저장하세요:")
|
||||
print(f' export INSTAGRAM_ACCESS_TOKEN="{new_token.access_token}"')
|
||||
|
||||
except AuthenticationError as e:
|
||||
print(f"❌ 인증 에러: {e}")
|
||||
print(" 이미 장기 토큰이거나, 토큰이 유효하지 않습니다.")
|
||||
except ValueError as e:
|
||||
print(f"⚠️ 설정 에러: {e}")
|
||||
except Exception as e:
|
||||
print(f"❌ 에러: {e}")
|
||||
|
||||
|
||||
async def example_refresh_token():
|
||||
"""토큰 갱신 예제"""
|
||||
from poc.instagram1 import InstagramGraphClient, AuthenticationError
|
||||
|
||||
print("\n" + "=" * 60)
|
||||
print("3. 토큰 갱신 (Long-lived Token Refresh)")
|
||||
print("=" * 60)
|
||||
|
||||
try:
|
||||
async with InstagramGraphClient() as client:
|
||||
refreshed = await client.refresh_token()
|
||||
|
||||
print(f"✅ 토큰 갱신 성공")
|
||||
print(f"🔑 갱신된 토큰: {refreshed.access_token[:20]}...")
|
||||
print(f"⏰ 유효 기간: {refreshed.expires_in}초 ({refreshed.expires_in // 86400}일)")
|
||||
|
||||
except AuthenticationError as e:
|
||||
print(f"❌ 인증 에러: {e}")
|
||||
print(" 장기 토큰만 갱신 가능합니다.")
|
||||
print(" 만료 24시간 전부터 갱신할 수 있습니다.")
|
||||
except Exception as e:
|
||||
print(f"❌ 에러: {e}")
|
||||
|
||||
|
||||
async def main():
|
||||
"""모든 인증 예제 실행"""
|
||||
print("\n🔐 Instagram Graph API 인증 예제")
|
||||
print("=" * 60)
|
||||
|
||||
# 1. 토큰 검증
|
||||
await example_debug_token()
|
||||
|
||||
# 2. 토큰 교환 (주의: 실제로 토큰이 교환됩니다)
|
||||
# await example_exchange_token()
|
||||
|
||||
# 3. 토큰 갱신 (주의: 실제로 토큰이 갱신됩니다)
|
||||
# await example_refresh_token()
|
||||
|
||||
print("\n" + "=" * 60)
|
||||
print("✅ 예제 완료")
|
||||
print("=" * 60)
|
||||
print("\n💡 토큰 교환/갱신을 테스트하려면 해당 함수의 주석을 해제하세요.")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,266 @@
|
||||
"""
|
||||
Instagram Graph API 댓글 관리 예제
|
||||
|
||||
미디어의 댓글을 조회하고 답글을 작성합니다.
|
||||
|
||||
실행 방법:
|
||||
```bash
|
||||
export INSTAGRAM_ACCESS_TOKEN="your_access_token"
|
||||
python -m poc.instagram1.examples.comments_example
|
||||
```
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
import sys
|
||||
|
||||
# 로깅 설정
|
||||
logging.basicConfig(
|
||||
level=logging.INFO,
|
||||
format="%(asctime)s [%(levelname)s] %(message)s",
|
||||
handlers=[logging.StreamHandler(sys.stdout)],
|
||||
)
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
async def example_get_comments():
|
||||
"""댓글 목록 조회 예제"""
|
||||
from poc.instagram1 import InstagramGraphClient
|
||||
|
||||
print("\n" + "=" * 60)
|
||||
print("1. 댓글 목록 조회")
|
||||
print("=" * 60)
|
||||
|
||||
try:
|
||||
async with InstagramGraphClient() as client:
|
||||
# 미디어 목록에서 댓글이 있는 게시물 찾기
|
||||
media_list = await client.get_media_list(limit=10)
|
||||
|
||||
media_with_comments = None
|
||||
for media in media_list.data:
|
||||
if media.comments_count > 0:
|
||||
media_with_comments = media
|
||||
break
|
||||
|
||||
if not media_with_comments:
|
||||
print("⚠️ 댓글이 있는 게시물이 없습니다.")
|
||||
return
|
||||
|
||||
print(f"\n📷 미디어 정보")
|
||||
print("-" * 50)
|
||||
print(f" ID: {media_with_comments.id}")
|
||||
caption_preview = (
|
||||
media_with_comments.caption[:40] + "..."
|
||||
if media_with_comments.caption and len(media_with_comments.caption) > 40
|
||||
else media_with_comments.caption or "(캡션 없음)"
|
||||
)
|
||||
print(f" 캡션: {caption_preview}")
|
||||
print(f" 댓글 수: {media_with_comments.comments_count}")
|
||||
|
||||
# 댓글 조회
|
||||
comments = await client.get_comments(
|
||||
media_id=media_with_comments.id,
|
||||
limit=10,
|
||||
)
|
||||
|
||||
print(f"\n💬 댓글 목록 ({len(comments.data)}개)")
|
||||
print("-" * 50)
|
||||
|
||||
for i, comment in enumerate(comments.data, 1):
|
||||
print(f"\n{i}. @{comment.username}")
|
||||
print(f" 📝 {comment.text}")
|
||||
print(f" ❤️ 좋아요: {comment.like_count}")
|
||||
print(f" 📅 {comment.timestamp}")
|
||||
|
||||
# 답글이 있는 경우
|
||||
if comment.replies and comment.replies.data:
|
||||
print(f" 💬 답글 ({len(comment.replies.data)}개):")
|
||||
for reply in comment.replies.data[:3]: # 최대 3개만 표시
|
||||
print(f" └─ @{reply.username}: {reply.text[:30]}...")
|
||||
|
||||
except Exception as e:
|
||||
print(f"❌ 에러: {e}")
|
||||
|
||||
|
||||
async def example_find_comments_to_reply():
|
||||
"""답글이 필요한 댓글 찾기"""
|
||||
from poc.instagram1 import InstagramGraphClient
|
||||
|
||||
print("\n" + "=" * 60)
|
||||
print("2. 답글이 필요한 댓글 찾기")
|
||||
print("=" * 60)
|
||||
|
||||
try:
|
||||
async with InstagramGraphClient() as client:
|
||||
# 최근 게시물 조회
|
||||
media_list = await client.get_media_list(limit=5)
|
||||
|
||||
unanswered_comments = []
|
||||
|
||||
for media in media_list.data:
|
||||
if media.comments_count == 0:
|
||||
continue
|
||||
|
||||
comments = await client.get_comments(media.id, limit=20)
|
||||
|
||||
for comment in comments.data:
|
||||
# 답글이 없는 댓글 찾기
|
||||
has_replies = comment.replies and len(comment.replies.data) > 0
|
||||
if not has_replies:
|
||||
unanswered_comments.append({
|
||||
"media_id": media.id,
|
||||
"comment": comment,
|
||||
"media_caption": media.caption[:30] if media.caption else "(없음)",
|
||||
})
|
||||
|
||||
if not unanswered_comments:
|
||||
print("✅ 모든 댓글에 답글이 달려있습니다.")
|
||||
return
|
||||
|
||||
print(f"\n⚠️ 답글이 필요한 댓글 ({len(unanswered_comments)}개)")
|
||||
print("-" * 50)
|
||||
|
||||
for i, item in enumerate(unanswered_comments[:10], 1): # 최대 10개
|
||||
comment = item["comment"]
|
||||
print(f"\n{i}. 게시물: {item['media_caption']}...")
|
||||
print(f" 댓글 ID: {comment.id}")
|
||||
print(f" @{comment.username}: {comment.text[:50]}...")
|
||||
print(f" 📅 {comment.timestamp}")
|
||||
|
||||
except Exception as e:
|
||||
print(f"❌ 에러: {e}")
|
||||
|
||||
|
||||
async def example_reply_comment():
|
||||
"""댓글에 답글 작성 예제 (테스트용 - 실제 게시됨)"""
|
||||
from poc.instagram1 import InstagramGraphClient
|
||||
|
||||
print("\n" + "=" * 60)
|
||||
print("3. 댓글 답글 작성 (테스트)")
|
||||
print("=" * 60)
|
||||
|
||||
# ⚠️ 실제 답글이 작성되므로 주의
|
||||
print(f"\n⚠️ 이 예제는 실제로 답글을 작성합니다!")
|
||||
print(f" 테스트하려면 아래 코드의 주석을 해제하세요.")
|
||||
|
||||
# try:
|
||||
# async with InstagramGraphClient() as client:
|
||||
# # 먼저 답글할 댓글 찾기
|
||||
# media_list = await client.get_media_list(limit=5)
|
||||
#
|
||||
# target_comment = None
|
||||
# for media in media_list.data:
|
||||
# if media.comments_count > 0:
|
||||
# comments = await client.get_comments(media.id, limit=5)
|
||||
# if comments.data:
|
||||
# target_comment = comments.data[0]
|
||||
# break
|
||||
#
|
||||
# if not target_comment:
|
||||
# print("⚠️ 답글할 댓글을 찾을 수 없습니다.")
|
||||
# return
|
||||
#
|
||||
# print(f"\n답글 대상 댓글:")
|
||||
# print(f" ID: {target_comment.id}")
|
||||
# print(f" @{target_comment.username}: {target_comment.text[:50]}...")
|
||||
#
|
||||
# # 답글 작성
|
||||
# reply = await client.reply_comment(
|
||||
# comment_id=target_comment.id,
|
||||
# message="Thanks for your comment! 🙏"
|
||||
# )
|
||||
#
|
||||
# print(f"\n✅ 답글 작성 완료!")
|
||||
# print(f" 답글 ID: {reply.id}")
|
||||
# print(f" 내용: {reply.text}")
|
||||
#
|
||||
# except Exception as e:
|
||||
# print(f"❌ 에러: {e}")
|
||||
|
||||
|
||||
async def example_comment_analytics():
|
||||
"""댓글 분석 예제"""
|
||||
from poc.instagram1 import InstagramGraphClient
|
||||
|
||||
print("\n" + "=" * 60)
|
||||
print("4. 댓글 분석")
|
||||
print("=" * 60)
|
||||
|
||||
try:
|
||||
async with InstagramGraphClient() as client:
|
||||
# 최근 게시물의 댓글 분석
|
||||
media_list = await client.get_media_list(limit=10)
|
||||
|
||||
total_comments = 0
|
||||
total_likes_on_comments = 0
|
||||
commenters = set()
|
||||
all_comments = []
|
||||
|
||||
for media in media_list.data:
|
||||
if media.comments_count == 0:
|
||||
continue
|
||||
|
||||
comments = await client.get_comments(media.id, limit=50)
|
||||
|
||||
for comment in comments.data:
|
||||
total_comments += 1
|
||||
total_likes_on_comments += comment.like_count
|
||||
if comment.username:
|
||||
commenters.add(comment.username)
|
||||
all_comments.append(comment)
|
||||
|
||||
print(f"\n📊 댓글 통계 (최근 10개 게시물)")
|
||||
print("-" * 50)
|
||||
print(f" 💬 총 댓글 수: {total_comments:,}")
|
||||
print(f" 👥 고유 댓글 작성자: {len(commenters):,}명")
|
||||
print(f" ❤️ 댓글 좋아요 합계: {total_likes_on_comments:,}")
|
||||
|
||||
if total_comments > 0:
|
||||
avg_likes = total_likes_on_comments / total_comments
|
||||
print(f" 📈 댓글당 평균 좋아요: {avg_likes:.1f}")
|
||||
|
||||
# 가장 좋아요가 많은 댓글
|
||||
if all_comments:
|
||||
top_comment = max(all_comments, key=lambda c: c.like_count)
|
||||
print(f"\n🏆 가장 인기 있는 댓글")
|
||||
print(f" @{top_comment.username}: {top_comment.text[:40]}...")
|
||||
print(f" ❤️ {top_comment.like_count}개 좋아요")
|
||||
|
||||
# 가장 많이 댓글 단 사용자
|
||||
if commenters:
|
||||
from collections import Counter
|
||||
commenter_counts = Counter(
|
||||
c.username for c in all_comments if c.username
|
||||
)
|
||||
top_commenter = commenter_counts.most_common(1)[0]
|
||||
print(f"\n🥇 가장 활발한 댓글러")
|
||||
print(f" @{top_commenter[0]}: {top_commenter[1]}개 댓글")
|
||||
|
||||
except Exception as e:
|
||||
print(f"❌ 에러: {e}")
|
||||
|
||||
|
||||
async def main():
|
||||
"""모든 댓글 예제 실행"""
|
||||
print("\n💬 Instagram Graph API 댓글 예제")
|
||||
print("=" * 60)
|
||||
|
||||
# 댓글 목록 조회
|
||||
await example_get_comments()
|
||||
|
||||
# 답글이 필요한 댓글 찾기
|
||||
await example_find_comments_to_reply()
|
||||
|
||||
# 답글 작성 (기본적으로 비활성화)
|
||||
await example_reply_comment()
|
||||
|
||||
# 댓글 분석
|
||||
await example_comment_analytics()
|
||||
|
||||
print("\n" + "=" * 60)
|
||||
print("✅ 예제 완료")
|
||||
print("=" * 60)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,239 @@
|
||||
"""
|
||||
Instagram Graph API 인사이트 조회 예제
|
||||
|
||||
계정 및 미디어의 성과 지표를 조회합니다.
|
||||
|
||||
실행 방법:
|
||||
```bash
|
||||
export INSTAGRAM_ACCESS_TOKEN="your_access_token"
|
||||
python -m poc.instagram1.examples.insights_example
|
||||
```
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
import sys
|
||||
|
||||
# 로깅 설정
|
||||
logging.basicConfig(
|
||||
level=logging.INFO,
|
||||
format="%(asctime)s [%(levelname)s] %(message)s",
|
||||
handlers=[logging.StreamHandler(sys.stdout)],
|
||||
)
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
async def example_account_insights():
|
||||
"""계정 인사이트 조회 예제"""
|
||||
from poc.instagram1 import InstagramGraphClient, InstagramPermissionError
|
||||
|
||||
print("\n" + "=" * 60)
|
||||
print("1. 계정 인사이트 조회")
|
||||
print("=" * 60)
|
||||
|
||||
try:
|
||||
async with InstagramGraphClient() as client:
|
||||
# 일간 인사이트 조회
|
||||
metrics = ["impressions", "reach", "profile_views"]
|
||||
insights = await client.get_account_insights(
|
||||
metrics=metrics,
|
||||
period="day",
|
||||
)
|
||||
|
||||
print(f"\n📊 계정 인사이트 (일간)")
|
||||
print("-" * 50)
|
||||
|
||||
for insight in insights.data:
|
||||
value = insight.latest_value
|
||||
print(f"\n📈 {insight.title}")
|
||||
print(f" 이름: {insight.name}")
|
||||
print(f" 기간: {insight.period}")
|
||||
print(f" 값: {value:,}" if isinstance(value, int) else f" 값: {value}")
|
||||
if insight.description:
|
||||
print(f" 설명: {insight.description[:50]}...")
|
||||
|
||||
# 특정 메트릭 조회
|
||||
reach = insights.get_metric("reach")
|
||||
if reach:
|
||||
print(f"\n✅ 도달(reach) 직접 조회: {reach.latest_value:,}")
|
||||
|
||||
except InstagramPermissionError as e:
|
||||
print(f"❌ 권한 에러: {e}")
|
||||
print(" 비즈니스 계정이 필요하거나, 인사이트 권한이 없습니다.")
|
||||
except Exception as e:
|
||||
print(f"❌ 에러: {e}")
|
||||
|
||||
|
||||
async def example_account_insights_periods():
|
||||
"""다양한 기간의 계정 인사이트 조회"""
|
||||
from poc.instagram1 import InstagramGraphClient
|
||||
|
||||
print("\n" + "=" * 60)
|
||||
print("2. 기간별 계정 인사이트 비교")
|
||||
print("=" * 60)
|
||||
|
||||
try:
|
||||
async with InstagramGraphClient() as client:
|
||||
periods = ["day", "week", "days_28"]
|
||||
metrics = ["impressions", "reach"]
|
||||
|
||||
for period in periods:
|
||||
print(f"\n📅 기간: {period}")
|
||||
print("-" * 30)
|
||||
|
||||
try:
|
||||
insights = await client.get_account_insights(
|
||||
metrics=metrics,
|
||||
period=period,
|
||||
)
|
||||
|
||||
for insight in insights.data:
|
||||
value = insight.latest_value
|
||||
print(f" {insight.name}: {value:,}" if isinstance(value, int) else f" {insight.name}: {value}")
|
||||
|
||||
except Exception as e:
|
||||
print(f" ⚠️ 조회 실패: {e}")
|
||||
|
||||
except Exception as e:
|
||||
print(f"❌ 에러: {e}")
|
||||
|
||||
|
||||
async def example_media_insights():
|
||||
"""미디어 인사이트 조회 예제"""
|
||||
from poc.instagram1 import InstagramGraphClient, InstagramPermissionError
|
||||
|
||||
print("\n" + "=" * 60)
|
||||
print("3. 미디어 인사이트 조회")
|
||||
print("=" * 60)
|
||||
|
||||
try:
|
||||
async with InstagramGraphClient() as client:
|
||||
# 먼저 미디어 목록 조회
|
||||
media_list = await client.get_media_list(limit=3)
|
||||
if not media_list.data:
|
||||
print("⚠️ 게시물이 없습니다.")
|
||||
return
|
||||
|
||||
for media in media_list.data:
|
||||
print(f"\n📷 미디어: {media.id}")
|
||||
print(f" 타입: {media.media_type}")
|
||||
caption_preview = (
|
||||
media.caption[:30] + "..."
|
||||
if media.caption and len(media.caption) > 30
|
||||
else media.caption or "(캡션 없음)"
|
||||
)
|
||||
print(f" 캡션: {caption_preview}")
|
||||
print("-" * 40)
|
||||
|
||||
try:
|
||||
insights = await client.get_media_insights(media.id)
|
||||
|
||||
for insight in insights.data:
|
||||
value = insight.latest_value
|
||||
print(f" 📈 {insight.name}: {value:,}" if isinstance(value, int) else f" 📈 {insight.name}: {value}")
|
||||
|
||||
except InstagramPermissionError as e:
|
||||
print(f" ⚠️ 권한 부족: 인사이트 조회 불가")
|
||||
except Exception as e:
|
||||
print(f" ⚠️ 조회 실패: {e}")
|
||||
|
||||
except Exception as e:
|
||||
print(f"❌ 에러: {e}")
|
||||
|
||||
|
||||
async def example_media_insights_detail():
|
||||
"""미디어 인사이트 상세 조회"""
|
||||
from poc.instagram1 import InstagramGraphClient
|
||||
|
||||
print("\n" + "=" * 60)
|
||||
print("4. 미디어 인사이트 상세 분석")
|
||||
print("=" * 60)
|
||||
|
||||
try:
|
||||
async with InstagramGraphClient() as client:
|
||||
# 첫 번째 미디어 가져오기
|
||||
media_list = await client.get_media_list(limit=1)
|
||||
if not media_list.data:
|
||||
print("⚠️ 게시물이 없습니다.")
|
||||
return
|
||||
|
||||
media = media_list.data[0]
|
||||
print(f"\n📷 분석 대상 미디어")
|
||||
print(f" ID: {media.id}")
|
||||
print(f" 게시일: {media.timestamp}")
|
||||
print(f" 좋아요: {media.like_count:,}")
|
||||
print(f" 댓글: {media.comments_count:,}")
|
||||
|
||||
# 다양한 메트릭 조회
|
||||
all_metrics = [
|
||||
"impressions", # 노출 수
|
||||
"reach", # 도달 수
|
||||
"engagement", # 상호작용 수 (좋아요 + 댓글 + 저장)
|
||||
"saved", # 저장 수
|
||||
]
|
||||
|
||||
try:
|
||||
insights = await client.get_media_insights(
|
||||
media_id=media.id,
|
||||
metrics=all_metrics,
|
||||
)
|
||||
|
||||
print(f"\n📊 성과 분석")
|
||||
print("-" * 50)
|
||||
|
||||
# 인사이트 값 추출
|
||||
impressions = insights.get_metric("impressions")
|
||||
reach = insights.get_metric("reach")
|
||||
engagement = insights.get_metric("engagement")
|
||||
saved = insights.get_metric("saved")
|
||||
|
||||
if impressions and reach:
|
||||
imp_val = impressions.latest_value or 0
|
||||
reach_val = reach.latest_value or 0
|
||||
print(f" 👁️ 노출: {imp_val:,}")
|
||||
print(f" 🎯 도달: {reach_val:,}")
|
||||
if reach_val > 0:
|
||||
frequency = imp_val / reach_val
|
||||
print(f" 🔄 빈도: {frequency:.2f} (노출/도달)")
|
||||
|
||||
if engagement:
|
||||
eng_val = engagement.latest_value or 0
|
||||
print(f" 💪 참여: {eng_val:,}")
|
||||
if reach and reach.latest_value:
|
||||
eng_rate = (eng_val / reach.latest_value) * 100
|
||||
print(f" 📈 참여율: {eng_rate:.2f}%")
|
||||
|
||||
if saved:
|
||||
print(f" 💾 저장: {saved.latest_value:,}")
|
||||
|
||||
except Exception as e:
|
||||
print(f" ⚠️ 인사이트 조회 실패: {e}")
|
||||
|
||||
except Exception as e:
|
||||
print(f"❌ 에러: {e}")
|
||||
|
||||
|
||||
async def main():
|
||||
"""모든 인사이트 예제 실행"""
|
||||
print("\n📊 Instagram Graph API 인사이트 예제")
|
||||
print("=" * 60)
|
||||
|
||||
# 계정 인사이트
|
||||
await example_account_insights()
|
||||
|
||||
# 기간별 인사이트 비교
|
||||
await example_account_insights_periods()
|
||||
|
||||
# 미디어 인사이트
|
||||
await example_media_insights()
|
||||
|
||||
# 미디어 인사이트 상세
|
||||
await example_media_insights_detail()
|
||||
|
||||
print("\n" + "=" * 60)
|
||||
print("✅ 예제 완료")
|
||||
print("=" * 60)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,236 @@
|
||||
"""
|
||||
Instagram Graph API 미디어 관리 예제
|
||||
|
||||
미디어 조회, 이미지/비디오 게시 기능을 테스트합니다.
|
||||
|
||||
실행 방법:
|
||||
```bash
|
||||
export INSTAGRAM_ACCESS_TOKEN="your_access_token"
|
||||
python -m poc.instagram1.examples.media_example
|
||||
```
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
import sys
|
||||
|
||||
# 로깅 설정
|
||||
logging.basicConfig(
|
||||
level=logging.INFO,
|
||||
format="%(asctime)s [%(levelname)s] %(message)s",
|
||||
handlers=[logging.StreamHandler(sys.stdout)],
|
||||
)
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
async def example_get_media_list():
|
||||
"""미디어 목록 조회 예제"""
|
||||
from poc.instagram1 import InstagramGraphClient
|
||||
|
||||
print("\n" + "=" * 60)
|
||||
print("1. 미디어 목록 조회")
|
||||
print("=" * 60)
|
||||
|
||||
try:
|
||||
async with InstagramGraphClient() as client:
|
||||
media_list = await client.get_media_list(limit=5)
|
||||
|
||||
print(f"\n📷 최근 게시물 ({len(media_list.data)}개)")
|
||||
print("-" * 50)
|
||||
|
||||
for i, media in enumerate(media_list.data, 1):
|
||||
caption_preview = (
|
||||
media.caption[:40] + "..."
|
||||
if media.caption and len(media.caption) > 40
|
||||
else media.caption or "(캡션 없음)"
|
||||
)
|
||||
print(f"\n{i}. [{media.media_type}] {caption_preview}")
|
||||
print(f" 🆔 ID: {media.id}")
|
||||
print(f" ❤️ 좋아요: {media.like_count:,}")
|
||||
print(f" 💬 댓글: {media.comments_count:,}")
|
||||
print(f" 📅 게시일: {media.timestamp}")
|
||||
print(f" 🔗 링크: {media.permalink}")
|
||||
|
||||
# 페이지네이션 정보
|
||||
if media_list.paging and media_list.paging.next:
|
||||
print(f"\n📄 다음 페이지 있음")
|
||||
|
||||
except Exception as e:
|
||||
print(f"❌ 에러: {e}")
|
||||
|
||||
|
||||
async def example_get_media_detail():
|
||||
"""미디어 상세 조회 예제"""
|
||||
from poc.instagram1 import InstagramGraphClient
|
||||
|
||||
print("\n" + "=" * 60)
|
||||
print("2. 미디어 상세 조회")
|
||||
print("=" * 60)
|
||||
|
||||
try:
|
||||
async with InstagramGraphClient() as client:
|
||||
# 먼저 목록에서 첫 번째 미디어 ID 가져오기
|
||||
media_list = await client.get_media_list(limit=1)
|
||||
if not media_list.data:
|
||||
print("⚠️ 게시물이 없습니다.")
|
||||
return
|
||||
|
||||
media_id = media_list.data[0].id
|
||||
print(f"\n조회할 미디어 ID: {media_id}")
|
||||
|
||||
# 상세 조회
|
||||
media = await client.get_media(media_id)
|
||||
|
||||
print(f"\n📷 미디어 상세 정보")
|
||||
print("-" * 50)
|
||||
print(f"🆔 ID: {media.id}")
|
||||
print(f"📝 타입: {media.media_type}")
|
||||
print(f"🖼️ URL: {media.media_url}")
|
||||
print(f"📅 게시일: {media.timestamp}")
|
||||
print(f"❤️ 좋아요: {media.like_count:,}")
|
||||
print(f"💬 댓글: {media.comments_count:,}")
|
||||
print(f"🔗 퍼머링크: {media.permalink}")
|
||||
|
||||
if media.caption:
|
||||
print(f"\n📝 캡션:")
|
||||
print(f" {media.caption}")
|
||||
|
||||
# 캐러셀인 경우 하위 미디어 표시
|
||||
if media.children:
|
||||
print(f"\n📚 캐러셀 하위 미디어 ({len(media.children)}개)")
|
||||
for j, child in enumerate(media.children, 1):
|
||||
print(f" {j}. [{child.media_type}] {child.media_url}")
|
||||
|
||||
except Exception as e:
|
||||
print(f"❌ 에러: {e}")
|
||||
|
||||
|
||||
async def example_publish_image():
|
||||
"""이미지 게시 예제 (테스트용 - 실제 게시됨)"""
|
||||
from poc.instagram1 import InstagramGraphClient, MediaPublishError
|
||||
|
||||
print("\n" + "=" * 60)
|
||||
print("3. 이미지 게시 (테스트)")
|
||||
print("=" * 60)
|
||||
|
||||
# ⚠️ 실제 게시되므로 주의
|
||||
# 테스트 이미지 URL (공개 접근 가능해야 함)
|
||||
TEST_IMAGE_URL = "https://example.com/test-image.jpg"
|
||||
TEST_CAPTION = "Test post from Instagram Graph API POC #test"
|
||||
|
||||
print(f"\n⚠️ 이 예제는 실제로 게시물을 작성합니다!")
|
||||
print(f" 이미지 URL: {TEST_IMAGE_URL}")
|
||||
print(f" 캡션: {TEST_CAPTION}")
|
||||
print(f"\n 테스트하려면 아래 코드의 주석을 해제하세요.")
|
||||
|
||||
# try:
|
||||
# async with InstagramGraphClient() as client:
|
||||
# media = await client.publish_image(
|
||||
# image_url=TEST_IMAGE_URL,
|
||||
# caption=TEST_CAPTION,
|
||||
# )
|
||||
# print(f"\n✅ 게시 완료!")
|
||||
# print(f" 🆔 미디어 ID: {media.id}")
|
||||
# print(f" 🔗 링크: {media.permalink}")
|
||||
# except MediaPublishError as e:
|
||||
# print(f"❌ 게시 실패: {e}")
|
||||
# except Exception as e:
|
||||
# print(f"❌ 에러: {e}")
|
||||
|
||||
|
||||
async def example_publish_video():
|
||||
"""비디오 게시 예제 (테스트용 - 실제 게시됨)"""
|
||||
from poc.instagram1 import InstagramGraphClient, MediaPublishError
|
||||
|
||||
print("\n" + "=" * 60)
|
||||
print("4. 비디오/릴스 게시 (테스트)")
|
||||
print("=" * 60)
|
||||
|
||||
# ⚠️ 실제 게시되므로 주의
|
||||
TEST_VIDEO_URL = "https://example.com/test-video.mp4"
|
||||
TEST_CAPTION = "Test video from Instagram Graph API POC #test"
|
||||
|
||||
print(f"\n⚠️ 이 예제는 실제로 게시물을 작성합니다!")
|
||||
print(f" 비디오 URL: {TEST_VIDEO_URL}")
|
||||
print(f" 캡션: {TEST_CAPTION}")
|
||||
print(f"\n 테스트하려면 아래 코드의 주석을 해제하세요.")
|
||||
|
||||
# try:
|
||||
# async with InstagramGraphClient() as client:
|
||||
# media = await client.publish_video(
|
||||
# video_url=TEST_VIDEO_URL,
|
||||
# caption=TEST_CAPTION,
|
||||
# share_to_feed=True,
|
||||
# )
|
||||
# print(f"\n✅ 게시 완료!")
|
||||
# print(f" 🆔 미디어 ID: {media.id}")
|
||||
# print(f" 🔗 링크: {media.permalink}")
|
||||
# except MediaPublishError as e:
|
||||
# print(f"❌ 게시 실패: {e}")
|
||||
# except Exception as e:
|
||||
# print(f"❌ 에러: {e}")
|
||||
|
||||
|
||||
async def example_publish_carousel():
|
||||
"""캐러셀 게시 예제 (테스트용 - 실제 게시됨)"""
|
||||
from poc.instagram1 import InstagramGraphClient, MediaPublishError
|
||||
|
||||
print("\n" + "=" * 60)
|
||||
print("5. 캐러셀(멀티 이미지) 게시 (테스트)")
|
||||
print("=" * 60)
|
||||
|
||||
# ⚠️ 실제 게시되므로 주의
|
||||
TEST_IMAGE_URLS = [
|
||||
"https://example.com/image1.jpg",
|
||||
"https://example.com/image2.jpg",
|
||||
"https://example.com/image3.jpg",
|
||||
]
|
||||
TEST_CAPTION = "Test carousel from Instagram Graph API POC #test"
|
||||
|
||||
print(f"\n⚠️ 이 예제는 실제로 게시물을 작성합니다!")
|
||||
print(f" 이미지 수: {len(TEST_IMAGE_URLS)}개")
|
||||
print(f" 캡션: {TEST_CAPTION}")
|
||||
print(f"\n 테스트하려면 아래 코드의 주석을 해제하세요.")
|
||||
|
||||
# try:
|
||||
# async with InstagramGraphClient() as client:
|
||||
# media = await client.publish_carousel(
|
||||
# media_urls=TEST_IMAGE_URLS,
|
||||
# caption=TEST_CAPTION,
|
||||
# )
|
||||
# print(f"\n✅ 게시 완료!")
|
||||
# print(f" 🆔 미디어 ID: {media.id}")
|
||||
# print(f" 🔗 링크: {media.permalink}")
|
||||
# except MediaPublishError as e:
|
||||
# print(f"❌ 게시 실패: {e}")
|
||||
# except Exception as e:
|
||||
# print(f"❌ 에러: {e}")
|
||||
|
||||
|
||||
async def main():
|
||||
"""모든 미디어 예제 실행"""
|
||||
print("\n📷 Instagram Graph API 미디어 예제")
|
||||
print("=" * 60)
|
||||
|
||||
# 미디어 목록 조회
|
||||
await example_get_media_list()
|
||||
|
||||
# 미디어 상세 조회
|
||||
await example_get_media_detail()
|
||||
|
||||
# 이미지 게시 (기본적으로 비활성화)
|
||||
await example_publish_image()
|
||||
|
||||
# 비디오 게시 (기본적으로 비활성화)
|
||||
await example_publish_video()
|
||||
|
||||
# 캐러셀 게시 (기본적으로 비활성화)
|
||||
await example_publish_carousel()
|
||||
|
||||
print("\n" + "=" * 60)
|
||||
print("✅ 예제 완료")
|
||||
print("=" * 60)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
Reference in new issue
Block a user