Skip to content

Commit 50855ee

Browse files
committed
refactor: removed instance export from plugin and fixed code to adhere to POSIX standard
1 parent 0ec40aa commit 50855ee

File tree

4 files changed

+44
-46
lines changed

4 files changed

+44
-46
lines changed

plugins/dpsn/dpsn_plugin_gamesdk/dpsn_plugin.py

Lines changed: 1 addition & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,10 @@
11
import os
2-
from dotenv import load_dotenv
32
from dpsn_client.client import DpsnClient, DPSNError
43
from datetime import datetime
54
from game_sdk.game.custom_types import Function, Argument, FunctionResultStatus
65
from typing import Dict, Any, Callable, Tuple, Optional
76
import json
87
import logging
9-
10-
# Load .env variables
11-
load_dotenv()
12-
138
# Configure logging for the plugin (optional, but good practice)
149
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
1510
logger = logging.getLogger("DpsnPlugin")
@@ -285,7 +280,5 @@ def _handle_client_error(self, error: DPSNError):
285280
self._initialized = False
286281
else:
287282
logger.warning("Client error received, but plugin was already not marked as initialized.")
288-
289-
# Create plugin instance
290-
plugin = DpsnPlugin()
283+
291284

plugins/dpsn/examples/dpsn_agent.py

Lines changed: 15 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -7,13 +7,17 @@
77
import threading
88
import signal
99
from typing import Dict, Any, Tuple
10-
11-
parent_dir = str(Path(__file__).parent.parent)
12-
sys.path.append(parent_dir)
13-
10+
from dotenv import load_dotenv
1411
from game_sdk.game.agent import Agent, WorkerConfig
1512
from game_sdk.game.custom_types import FunctionResult, FunctionResultStatus, Function, Argument
16-
from dpsn_plugin_gamesdk.dpsn_plugin import plugin
13+
from dpsn_plugin_gamesdk.dpsn_plugin import DpsnPlugin
14+
load_dotenv()
15+
16+
dpsn_plugin = DpsnPlugin(
17+
dpsn_url=os.getenv("DPSN_URL"),
18+
pvt_key=os.getenv("PVT_KEY")
19+
)
20+
1721

1822
# Global message counter and timestamp
1923
message_count = 0
@@ -134,7 +138,7 @@ def exit_program():
134138
)
135139

136140
# Set the callback in the plugin instance *before* running the agent
137-
plugin.set_message_callback(handle_incoming_message)
141+
dpsn_plugin.set_message_callback(handle_incoming_message)
138142
# --- End Message Handler Setup ---
139143

140144
def get_agent_state_fn(function_result: FunctionResult, current_state: dict) -> dict:
@@ -187,14 +191,15 @@ def get_worker_state(function_result: FunctionResult, current_state: dict) -> di
187191
worker_description="Worker specialized in managing DPSN topic subscriptions, unsubscriptions, message handling, and shutdown.",
188192
get_state_fn=get_worker_state,
189193
action_space=[
190-
plugin.get_function("subscribe"),
191-
plugin.get_function("unsubscribe"),
192-
plugin.get_function("shutdown"),
194+
dpsn_plugin.get_function("subscribe"),
195+
dpsn_plugin.get_function("unsubscribe"),
196+
dpsn_plugin.get_function("shutdown"),
193197
check_status_function,
194198
complete_task_function # Add the task completion function
195199
],
196200
)
197201

202+
198203
# Initialize the agent
199204
agent = Agent(
200205
api_key=os.environ.get("GAME_API_KEY"),
@@ -253,4 +258,4 @@ def get_worker_state(function_result: FunctionResult, current_state: dict) -> di
253258
except Exception as e:
254259
print(f"Error running agent:{e}")
255260
import traceback
256-
traceback.print_exc()
261+
traceback.print_exc()

plugins/dpsn/examples/dpsn_worker.py

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,25 @@
11
import sys
22
import os
3+
from dotenv import load_dotenv
34
from pathlib import Path
45
from typing import Dict, Any, List
56
from datetime import datetime
67
import time # Import time for sleep
7-
8-
# Add the parent directory to Python path
9-
parent_dir = str(Path(__file__).parent.parent)
10-
sys.path.append(parent_dir)
8+
load_dotenv()
119

1210
# Import FunctionResultStatus to check the status enum
1311
from game_sdk.game.custom_types import FunctionResultStatus
14-
from dpsn_plugin_gamesdk.dpsn_plugin import plugin
12+
from dpsn_plugin_gamesdk.dpsn_plugin import DpsnPlugin
1513

1614
class DpsnWorker:
1715
"""
1816
DPSN Worker for processing market data and executing trades (Synchronous Version)
1917
"""
2018
def __init__(self):
21-
self.plugin = plugin
19+
self.plugin = DpsnPlugin(
20+
dpsn_url=os.getenv("DPSN_URL"),
21+
pvt_key=os.getenv("PVT_KEY")
22+
)
2223
self.trades: List[Dict[str, Any]] = []
2324
self.is_running = False
2425

@@ -128,4 +129,5 @@ def main():
128129

129130
if __name__ == "__main__":
130131
# Run main directly without asyncio
131-
main()
132+
main()
133+

plugins/dpsn/examples/test_dpsn_game_functions.py

Lines changed: 19 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -3,23 +3,24 @@
33
from pathlib import Path
44
import time
55
from datetime import datetime
6+
from game_sdk.game.custom_types import Function, Argument, FunctionResultStatus
7+
from dotenv import load_dotenv
8+
load_dotenv()
69

7-
# Add the parent directory to Python path
8-
parent_dir = str(Path(__file__).parent.parent)
9-
sys.path.append(parent_dir)
1010

11-
from dpsn_plugin_gamesdk.dpsn_plugin import plugin
11+
12+
from dpsn_plugin_gamesdk.dpsn_plugin import DpsnPlugin
13+
14+
dpsn_plugin=DpsnPlugin(
15+
dpsn_url=os.getenv("DPSN_URL"),
16+
pvt_key=os.getenv("PVT_KEY")
17+
)
1218

1319
def test_dpsn_connection():
1420
"""Test DPSN connection and basic functionality"""
1521
print("\n🔄 Testing DPSN Connection...")
1622

17-
# Initialize DPSN client (without options since the method doesn't accept them)
18-
result = plugin.initialize()
19-
if not result["success"]:
20-
print(f"❌ Failed to initialize DPSN: {result.get('error')}")
21-
return False
22-
23+
2324
# Wait for connection to stabilize
2425
time.sleep(1)
2526
print("✅ DPSN initialized successfully")
@@ -36,13 +37,13 @@ def handle_message(message_data):
3637
print(f"Received message on {topic}: {payload}")
3738

3839
# Set the callback
39-
plugin.set_message_callback(handle_message)
40+
dpsn_plugin.set_message_callback(handle_message)
4041

4142
# Test topic
4243
topic = "0xe14768a6d8798e4390ec4cb8a4c991202c2115a5cd7a6c0a7ababcaf93b4d2d4/SOLUSDT/ohlc"
4344

4445
print(f"Subscribing to topic: {topic}")
45-
result = plugin.subscribe(topic)
46+
result = dpsn_plugin.subscribe(topic)
4647
if not result["success"]:
4748
print(f"❌ Failed to subscribe to topic: {result.get('error')}")
4849
return False
@@ -52,26 +53,24 @@ def handle_message(message_data):
5253

5354
try:
5455
while True:
55-
if not plugin.client.dpsn_broker.is_connected():
56+
if not dpsn_plugin.client.dpsn_broker.is_connected():
5657
print("Connection lost, attempting to reconnect...")
57-
plugin.initialize()
58+
dpsn_plugin.initialize()
5859
time.sleep(1)
59-
plugin.subscribe(topic)
60+
dpsn_plugin.subscribe(topic)
6061
time.sleep(1)
6162

6263
except KeyboardInterrupt:
6364
print("\n⚠️ Test interrupted by user")
6465
return True
6566

66-
return True
67-
6867
def test_shutdown():
6968
"""Test graceful shutdown"""
7069
print("\n🔄 Testing Shutdown...")
7170

72-
result = plugin.shutdown()
73-
if not result["success"]:
74-
print(f"❌ Failed to shutdown: {result.get('error')}")
71+
status,message,extra = dpsn_plugin.shutdown()
72+
if status is not FunctionResultStatus.DONE:
73+
print(f"❌ Failed to shutdown")
7574
return False
7675

7776
print("✅ Shutdown successful")
@@ -86,7 +85,6 @@ def main():
8685
if not test_dpsn_connection():
8786
return
8887

89-
# Test subscription and message reception
9088
if not test_subscribe_and_receive():
9189
return
9290

0 commit comments

Comments
 (0)