You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

技术求助:如何使用Python发布YouTube社区帖子

使用Python通过YouTube API发布社区帖子

前提准备

  • 你的YouTube频道必须符合社区帖子启用要求(至少1000订阅者,或为已验证频道/合作伙伴)
  • 创建OAuth 2.0凭据(社区帖子属于用户授权操作,无法使用API密钥)
  • 安装依赖库:
pip install google-api-python-client oauth2client

代码实现

from googleapiclient.discovery import build
from oauth2client.file import Storage
from oauth2client.tools import run_flow
from oauth2client.client import OAuth2WebServerFlow

# 替换为你的OAuth 2.0信息
CLIENT_ID = '你的客户端ID'
CLIENT_SECRET = '你的客户端密钥'
SCOPE = 'https://www.googleapis.com/auth/youtube.force-ssl'
REDIRECT_URI = 'urn:ietf:wg:oauth:2.0:oob'

def get_auth_service():
    storage = Storage('credentials.json')
    creds = storage.get()
    if not creds or creds.invalid:
        flow = OAuth2WebServerFlow(CLIENT_ID, CLIENT_SECRET, SCOPE, redirect_uri=REDIRECT_URI)
        creds = run_flow(flow, storage)
    return build('youtube', 'v3', credentials=creds)

def post_community_post(youtube, content):
    request = youtube.activities().insert(
        part='snippet',
        body={
            'snippet': {
                'type': 'communityPost',
                'description': content
            }
        }
    )
    response = request.execute()
    print(f"帖子发布成功,ID: {response['id']}")

if __name__ == '__main__':
    youtube_service = get_auth_service()
    post_community_post(youtube_service, "这是一条API测试社区帖子!")

关键注意点

  • 目前activities.insert的communityPost类型仅支持纯文本内容,添加图片、投票等媒体内容的官方文档说明有限,建议先从纯文本测试
  • 授权时必须申请youtube.force-ssl或youtube权限范围,否则会返回权限不足错误
  • 若频道未满足社区帖子启用条件,调用API会返回403 Forbidden错误

内容的提问来源于stack exchange,提问作者rent

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 11:35:19