cài | python
cài | pip install google-auth google-auth-oauthlib google-auth-httplib2 google-api-python-client pyinstaller
------------------------------------------------------------------------------------
tạo API và tải file secret.json | https://console.cloud.google.com/apis/dashboard?inv=1&invt=Abwftw&project=livestream-458811
------------------------------------------------------------------------------------
tạo file dang_nhap.py
------------------------------------------------------------------------------------
import os
import sys
import pickle
from google_auth_oauthlib.flow import InstalledAppFlow
# Phạm vi truy cập API
SCOPES = ["https://www.googleapis.com/auth/youtube.force-ssl"]
def resource_path(relative_path):
"""
Trả về đường dẫn thực tế đến tài nguyên khi chạy file .exe (PyInstaller onefile).
Nếu đang chạy bằng Python, trả về đường dẫn gốc.
"""
if hasattr(sys, "_MEIPASS"):
return os.path.join(sys._MEIPASS, relative_path)
return os.path.join(os.path.abspath("."), relative_path)
def main():
# Đường dẫn tới file secret.json
secret_file = resource_path("secret.json")
# Bắt đầu luồng xác thực
flow = InstalledAppFlow.from_client_secrets_file(secret_file, SCOPES)
credentials = flow.run_local_server(port=8080)
# Lưu token
with open("token.pkl", "wb") as token_file:
pickle.dump(credentials, token_file)
print("✅ Đăng nhập thành công. Token đã được lưu vào token.pkl.")
if __name__ == "__main__":
main()
------------------------------------------------------------------------------------
tạo file khoa_luong.py
------------------------------------------------------------------------------------
import os
import sys
import pickle
from datetime import datetime, timedelta
from googleapiclient.discovery import build
def resource_path(relative_path):
if hasattr(sys, '_MEIPASS'):
return os.path.join(sys._MEIPASS, relative_path)
return os.path.join(os.path.abspath("."), relative_path)
def main():
token_file = resource_path("token.pkl")
with open(token_file, "rb") as f:
credentials = pickle.load(f)
youtube = build("youtube", "v3", credentials=credentials)
print("⏳ Đang lấy luồng, vui lòng đợi trong giây lát...\n")
scheduled_time = (datetime.utcnow() + timedelta(minutes=5)).isoformat("T") + "Z"
broadcast_response = youtube.liveBroadcasts().insert(
part="snippet,status,contentDetails",
body={
"snippet": {
"title": "Livestream thử nghiệm",
"scheduledStartTime": scheduled_time
},
"status": {"privacyStatus": "unlisted"},
"contentDetails": {"monitorStream": {"enableMonitorStream": False}}
}
).execute()
broadcast_id = broadcast_response["id"]
stream_response = youtube.liveStreams().insert(
part="snippet,cdn",
body={
"snippet": {
"title": "Khóa Stream RTMP"
},
"cdn": {
"frameRate": "30fps",
"ingestionType": "rtmp",
"resolution": "1080p"
}
}
).execute()
stream_id = stream_response["id"]
youtube.liveBroadcasts().bind(
part="id,contentDetails",
id=broadcast_id,
streamId=stream_id
).execute()
print("\n✅ Hoàn tất! Dưới đây là thông tin kết nối livestream:")
print("🔑 Stream URL:", stream_response["cdn"]["ingestionInfo"]["ingestionAddress"])
print("🗝️ Stream Key:", stream_response["cdn"]["ingestionInfo"]["streamName"])
input("\nNhấn Enter để thoát...")
if __name__ == "__main__":
main()
------------------------------------------------------------------------------------
biên dịch thành file .exe
pyinstaller --onefile --add-data "secret.json;." dang_nhap.py
pyinstaller --onefile --add-data "token.pkl;." khoa_luong.py
2025-05-04