OpenTok Python SDK
The OpenTok Python SDK provides server-side functionality for interacting with the OpenTok platform, which is part of the Vonage Video API. It enables developers to generate sessions and tokens for OpenTok applications, manage archiving of video sessions, and utilize other core video functionalities. The library is actively maintained, with the current version being 3.13.0, and receives regular updates.
Warnings
- breaking The main class for interacting with the SDK was renamed from `OpenTok` to `Client` in version 3.x.x. Code using `from opentok import OpenTok` or `OpenTok.OpenTok()` will fail in versions 3.0 and above.
- breaking As of v3.10.0, the `Client.generate_token()` method now generates JWT (JSON Web Token) formatted tokens by default. Previously, it generated T1 tokens by default.
- gotcha The `opentok` Python SDK is specifically for the legacy Tokbox/OpenTok platform, even though OpenTok is now part of the Vonage Video API. For new projects or migrations to the unified Vonage platform, it is recommended to use the `vonage` Python SDK, which has a different import path (`from vonage import Vonage` then `vonage_client.video`) and uses different authentication (application ID and private key instead of API key/secret).
- gotcha The default `media_mode` for sessions created via `create_session()` changed from `MediaModes.routed` to `MediaModes.relayed` in v2.2.1. Relayed (peer-to-peer) sessions have limitations, particularly regarding archiving or certain advanced features, which require `routed` sessions.
Install
-
pip install opentok
Imports
- Client
from opentok import Client
- MediaModes
from opentok import MediaModes
Quickstart
import os
from opentok import Client, MediaModes
# Replace with your OpenTok API key and secret
API_KEY = os.environ.get('OPENTOK_API_KEY', 'YOUR_API_KEY')
API_SECRET = os.environ.get('OPENTOK_API_SECRET', 'YOUR_API_SECRET')
if not API_KEY or not API_SECRET or API_KEY == 'YOUR_API_KEY':
print("WARNING: Please set OPENTOK_API_KEY and OPENTOK_API_SECRET environment variables or replace placeholders.")
exit(1)
try:
# Initialize an OpenTok Client instance
opentok_client = Client(API_KEY, API_SECRET)
# Create a session that uses the OpenTok Media Router
# The routed mode is required for features like archiving.
# For a relayed (peer-to-peer) session, use MediaModes.relayed or omit parameter for default.
session = opentok_client.create_session(media_mode=MediaModes.routed)
session_id = session.session_id
print(f"Session ID: {session_id}")
# Generate a token for a publisher role in this session
# By default (since v3.10.0), JWTs are generated. For legacy T1 tokens, use `use_jwt=False`.
token = opentok_client.generate_token(session_id)
print(f"Generated Token: {token}")
# In a real application, you would send `session_id` and `token` to your client-side application.
except Exception as e:
print(f"An error occurred: {e}")