Basic Usage Example
This example demonstrates the basic usage of vtpy: connecting to VTube Studio, authenticating, and retrieving statistics.
Full Code
1"""Basic usage example for vtpy - connecting, authenticating, and getting stats."""
2
3import asyncio
4from vtpy import VTS
5from vtpy.data.requests import StatisticsRequestData
6from vtpy.error import VTSRequestError
7
8
9async def main():
10 """Main function demonstrating basic VTS connection and stats retrieval."""
11 # Initialize VTS client
12 vts = VTS(plugin_name="ExamplePlugin", plugin_developer="ExampleDeveloper")
13
14 try:
15 # Connect to VTube Studio at port 8001 and authenticate
16 print("Connecting to VTube Studio at localhost:8001...")
17 auth_token = await vts.start(host="localhost", port=8001, save_auth_token=False)
18 print(f"Successfully authenticated! Token: {auth_token[:20]}...")
19
20 # Get VTube Studio statistics
21 print("\nRequesting VTube Studio statistics...")
22 stats_response = await vts.request_statistics(StatisticsRequestData())
23
24 # Display statistics
25 stats = stats_response.data
26 print("\n=== VTube Studio Statistics ===")
27 print(f"Version: {stats.vTubeStudioVersion}")
28 print(f"Uptime: {stats.uptime} seconds")
29 print(f"Framerate: {stats.framerate} FPS")
30 print(f"Allowed Plugins: {stats.allowedPlugins}")
31 print(f"Connected Plugins: {stats.connectedPlugins}")
32 print(f"Started with Steam: {stats.startedWithSteam}")
33 print(f"Window Size: {stats.windowWidth}x{stats.windowHeight}")
34 print(f"Fullscreen: {stats.windowIsFullscreen}")
35
36 except ConnectionError as e:
37 print(f"Connection error: {e}", exc_info=True)
38 print("Make sure VTube Studio is running and the WebSocket API is enabled.", exc_info=True)
39 except ValueError as e:
40 print(f"Authentication error: {e}", exc_info=True)
41 print("You may need to approve the authentication request in VTube Studio.", exc_info=True)
42 except VTSRequestError as e:
43 print(f"VTube Studio Request error: {e}", exc_info=True)
44 except Exception as e:
45 print(f"Unexpected error: {e}", exc_info=True)
46 finally:
47 # Clean up connection
48 if vts.connected:
49 print("\nClosing connection...")
50 await vts.close()
51 print("Disconnected.")
52
53
54if __name__ == "__main__":
55 asyncio.run(main())
Explanation
Import Required Modules
import asyncio from vtpy import VTS from vtpy.data.requests import StatisticsRequestData from vtpy.error import VTSRequestError
Initialize VTS Client
vts = VTS(plugin_name="ExamplePlugin", plugin_developer="ExampleDeveloper")
The
VTSclass is the main interface for interacting with VTube Studio.Connect and Authenticate
auth_token = await vts.start(host="localhost", port=8001, save_auth_token=False)
The
start()method: - Connects to VTube Studio via WebSocket - Handles authentication automatically - Returns the authentication tokenMake API Requests
stats_response = await vts.request_statistics(StatisticsRequestData()) stats = stats_response.data
Request statistics from VTube Studio and access the response data.
Error Handling
The example handles various error types: -
ConnectionError: Connection issues -ValueError: Authentication failures -VTSRequestError: API request errorsCleanup
if vts.connected: await vts.close()
Always close the connection when done.
Expected Output
When run successfully, you should see output like:
Connecting to VTube Studio at localhost:8001...
Successfully authenticated! Token: abc123def456...
Requesting VTube Studio statistics...
=== VTube Studio Statistics ===
Version: 1.x.x
Uptime: 1234 seconds
Framerate: 60 FPS
Allowed Plugins: 10
Connected Plugins: 1
Started with Steam: False
Window Size: 1920x1080
Fullscreen: False
Closing connection...
Disconnected.