feat: version 2.0.0

This commit is contained in:
AURUMVORXX
2025-04-15 12:20:31 +03:00
parent dfcf695f24
commit 988f901dc8
44 changed files with 3143 additions and 1378 deletions

View File

@@ -1 +1,159 @@
print('Hello')
__version__ = '2.0.0'
from .server import PythonWebsocketServer
from .functions.chat import sendMessageToAll
from .functions.chat import sendMessageToPlayer
from .functions.chat import sendPlayerMessageToAll
from .functions.chat import sendPlayerMessageToPlayer
from .functions.math import getDistance2d
from .functions.math import getDistance3d
from .functions.math import getVectorAngle
from .functions.game import getHostname
from .functions.game import getMaxSlots
from .functions.game import getPlayersCount
from .functions.game import exit
from .functions.game import getDayLength
from .functions.game import getServerDescription
from .functions.game import getServerWorld
from .functions.game import getTime
from .functions.game import serverLog
from .functions.game import setDayLength
from .functions.game import setServerDescription
from .functions.game import setServerWorld
from .functions.game import setTime
from .functions.npc import clearNpcActions
from .functions.npc import createNpc
from .functions.npc import destroyNpc
from .functions.npc import getNpcAction
from .functions.npc import getNpcActions
from .functions.npc import getNpcActionsCount
from .functions.npc import getNpcHostPlayer
from .functions.npc import getNpcLastActionId
from .functions.npc import isNpc
from .functions.npc import isNpcActionFinished
from .functions.npc import npcAttackMelee
from .functions.npc import npcAttackRanged
from .functions.npc import npcSpellCast
from .functions.npc import npcUseClosestMob
from .functions.npc import setNpcHostPlayer
from .functions.player import addBan
from .functions.player import applyPlayerOverlay
from .functions.player import ban
from .functions.player import drawWeapon
from .functions.player import equipItem
from .functions.player import getPlayerAmulet
from .functions.player import getPlayerAngle
from .functions.player import getPlayerAni
from .functions.player import getPlayerArmor
from .functions.player import getPlayerAtVector
from .functions.player import getPlayerBelt
from .functions.player import getPlayerCameraPosition
from .functions.player import getPlayerCollision
from .functions.player import getPlayerColor
from .functions.player import getPlayerContext
from .functions.player import getPlayerDexterity
from .functions.player import getPlayerFaceAnis
from .functions.player import getPlayerFatness
from .functions.player import getPlayerFocus
from .functions.player import getPlayerHealth
from .functions.player import getPlayerHelmet
from .functions.player import getPlayerIP
from .functions.player import getPlayerInstance
from .functions.player import getPlayerInvisible
from .functions.player import getPlayerMacAddr
from .functions.player import getPlayerMana
from .functions.player import getPlayerMaxHealth
from .functions.player import getPlayerMaxMana
from .functions.player import getPlayerMeleeWeapon
from .functions.player import getPlayerName
from .functions.player import getPlayerPing
from .functions.player import getPlayerPosition
from .functions.player import getPlayerRangedWeapon
from .functions.player import getPlayerRespawnTime
from .functions.player import getPlayerRing
from .functions.player import getPlayerScale
from .functions.player import getPlayerSerial
from .functions.player import getPlayerShield
from .functions.player import getPlayerSkillWeapon
from .functions.player import getPlayerSpell
from .functions.player import getPlayerStrength
from .functions.player import getPlayerTalent
from .functions.player import getPlayerVirtualWorld
from .functions.player import getPlayerVisual
from .functions.player import getPlayerWeaponMode
from .functions.player import getPlayerWorld
from .functions.player import giveItem
from .functions.player import hitPlayer
from .functions.player import isPlayerConnected
from .functions.player import isPlayerDead
from .functions.player import isPlayerSpawned
from .functions.player import isPlayerUnconscious
from .functions.player import kick
from .functions.player import playAni
from .functions.player import playFaceAni
from .functions.player import readySpell
from .functions.player import removeItem
from .functions.player import removePlayerOverlay
from .functions.player import removeWeapon
from .functions.player import setPlayerAngle
from .functions.player import setPlayerCollision
from .functions.player import setPlayerColor
from .functions.player import setPlayerContext
from .functions.player import setPlayerDexterity
from .functions.player import setPlayerFatness
from .functions.player import setPlayerHealth
from .functions.player import setPlayerInstance
from .functions.player import setPlayerInvisible
from .functions.player import setPlayerMana
from .functions.player import setPlayerMaxHealth
from .functions.player import setPlayerMaxMana
from .functions.player import setPlayerName
from .functions.player import setPlayerPosition
from .functions.player import setPlayerRespawnTime
from .functions.player import setPlayerScale
from .functions.player import setPlayerSkillWeapon
from .functions.player import setPlayerStrength
from .functions.player import setPlayerTalent
from .functions.player import setPlayerVirtualWorld
from .functions.player import setPlayerVisual
from .functions.player import setPlayerWeaponMode
from .functions.player import setPlayerWorld
from .functions.player import spawnPlayer
from .functions.player import stopAni
from .functions.player import stopFaceAni
from .functions.player import unequipItem
from .functions.player import unreadySpell
from .functions.player import unspawnPlayer
from .functions.player import useItem
from .functions.player import useItemToState
from .functions.streamer import findNearbyPlayers
from .functions.streamer import getStreamedPlayersByPlayer
from .functions.streamer import getSpawnedPlayersForPlayer
from .functions.waypoint import getNearestWaypoint
from .functions.waypoint import getWaypoint
from .functions.event import addEvent
from .functions.event import callEvent
from .functions.event import event
from .functions.event import removeEventHandler
from .functions.event import toggleEvent
from .functions.event import removeEvent
from .constants import Constant
from .classes.daedalus import Daedalus
from .classes.damage import DamageDescription
from .classes.items import ItemGround
from .classes.items import ItemsGround
from .classes.mds import Mds
from .classes.sky import Sky
# from exception import set_default_logger
# from exception import handle_exception

14
src/pyg2o/call_repr.py Normal file
View File

@@ -0,0 +1,14 @@
import inspect
def get_call_repr():
frame = inspect.currentframe().f_back
func_name = frame.f_code.co_name
args_info = inspect.getargvalues(frame)
# Формируем аргументы в виде строки
args_str = []
for arg in args_info.args:
val = args_info.locals[arg]
args_str.append(f"{val!r}" if not isinstance(val, str) else f"'{val}'")
return f"{func_name}({', '.join(args_str)})"

View File

View File

@@ -0,0 +1,54 @@
from ..server import PythonWebsocketServer
class Daedalus:
"""
This class represents Daedalus scripting interface.
Original: [Daedalus](https://gothicmultiplayerteam.gitlab.io/docs/0.3.0/script-reference/server-classes/game/Daedalus/)
"""
@staticmethod
async def index(value : str) -> int:
"""
This method will get the daedalus symbol index by its name.
**Parameters:**
* `str` **name**: the name of the daedalus symbol.
**Returns `int`:**
the daedalus symbol index number.
"""
data = f'return Daedalus.index({value})'
server = await PythonWebsocketServer.get_server()
result = await server.make_request(data)
return result
@staticmethod
async def symbol(value : str) -> dict:
"""
This method will get the daedalus symbol by its name.
**Parameters:**
* `str` **name**: the name of the daedalus symbol.
**Returns `dict`:**
the daedalus symbol (empty if there's no symbol with given name)
"""
data = f'return Daedalus.symbol({value})'
server = await PythonWebsocketServer.get_server()
result = await server.make_request(data)
return result
@staticmethod
async def instance(value : str) -> dict:
"""
This method will get the all of the daedalus instance variables.
**Parameters:**
* `str` **instanceName**: the name of the daedalus instance.
**Returns `dict`:**
the object containing all of the daedalus instance variables.
"""
data = f'return Daedalus.instance({value})'
server = await PythonWebsocketServer.get_server()
result = await server.make_request(data)
return result

View File

@@ -0,0 +1,94 @@
class DamageDescription():
"""
This class represents damage information.
Original: [DamageDescription](https://gothicmultiplayerteam.gitlab.io/docs/0.3.0/script-reference/server-classes/item/DamageDescription//)
## `int` flags
Represents the damage flags.
## `int` damage
Represents the total damage taken.
## `str` item_instance *(read-only)*
!!! note
Can be empty if there is no weapon.
Represents the weapon instance used to deal damage.
## `int` distance
Represents the total distance, calculated from origin point to target.
## `int` spell_id
Represents the spell id.
## `int` spell_level
Represents the level of chargeable spells.
## `str` node
!!! note
Can be empty if there was no projectile.
Represents the name of the node hit by a point projectile.
"""
def __init__(self):
self._flags : int = 0
self._damage : int = 0
self._item_instance : str = ''
self._distance : int = 0
self._spell_id : int = 0
self._spell_level : int = 0
self._node : str = 0
def _initialize(self, **kwargs):
self.__dict__.update(kwargs)
@property
def flags(self) -> int:
return self._flags
@flags.setter
def flags(self, value):
self._flags = value
@property
def damage(self) -> int:
return self._damage
@damage.setter
def damage(self, value):
self._damage = value
@property
def item_instance(self) -> str:
return self._item_instance
@property
def distance(self) -> int:
return self._distance
@distance.setter
def distance(self, value):
self._distance = value
@property
def spell_id(self) -> int:
return self._spell_id
@spell_id.setter
def spell_id(self, value):
self._spell_id = value
@property
def spell_level(self) -> int:
return self._spell_level
@spell_level.setter
def spell_level(self, value):
self._spell_level = value
@property
def node(self) -> str:
return self._node
@node.setter
def node(self, value):
self._node = value

132
src/pyg2o/classes/items.py Normal file
View File

@@ -0,0 +1,132 @@
from ..server import PythonWebsocketServer
class ItemsGround:
"""
This class represents item ground manager.
Original: [ItemsGround](https://gothicmultiplayerteam.gitlab.io/docs/0.3.0/script-reference/server-classes/item/ItemsGround/)
"""
@staticmethod
async def getById(id : int):
"""
This method will retrieve the item ground object by its unique id.
**Parameters:**
* `int` **itemGroundId**: the unique item ground id.
**Returns `ItemGround`:**
the item ground object or `throws an exception` if the object cannot be found.
"""
data = f'return ItemsGround.getById({id})'
# TODO: Добавить десериализацию ItemGround
server = await PythonWebsocketServer.get_server()
result = await server.make_request(data)
return result
@staticmethod
async def create(data : dict) -> int:
"""
This method will create the item ground.
**Parameters:**
* `dict {instance, amount=1, physicsEnabled=false position={x=0,y=0,z=0}, rotation={x=0,y=0,z=0}, world=CONFIG_WORLD, virtualWorld=0}`:
* `string` **instance**: the scripting instance of game item.
* `bool` **physicsEnabled**: the physics state of the item ground.
* `dict {x, y, z}` **position**: the position of the item ground in the world.
* `dict {x, y, z}` **rotation**: the rotation of the item ground in the world.
* `string` **world**: the world the item ground is in (.ZEN file path).
* `int` **virtualWorld**: the virtual world id in range <0, 65535>.
**Returns `int`:**
the item ground id.
"""
data = f'return ItemsGround.create({data})'
server = await PythonWebsocketServer.get_server()
result = await server.make_request(data)
return result
@staticmethod
async def destroy(id : int):
"""
This method will destroy the item ground by it's unique id.
**Parameters:**
* `int` **itemGroundId**: the item ground unique id.
"""
data = f'return ItemsGround.destroy({id})'
server = await PythonWebsocketServer.get_server()
result = await server.make_request(data)
return result
class ItemGround:
"""
This class represents item on the ground.
Original: [ItemGround](https://gothicmultiplayerteam.gitlab.io/docs/0.3.0/script-reference/server-classes/item/ItemGround//)
## `int` id *(read-only)*
Represents the unique id of the item ground.
## `str` instance *(read-only)*
Represents the item instance of the item ground.
## `int` amount *(read-only)*
Represents the item amount of item ground.
## `str` world *(read-only)*
Represents the item ground world (.ZEN file path).
## `int` virtualWorld
Represents the virtual world of item ground.
"""
def __init__(self):
self._id = -1
self._instance = ''
self._amount = -1
self._world = -1
self._virtualWorld = -1
self._position = -1
self._rotation = -1
def getPosition(self) -> dict:
"""
This method will get the item ground position on the world.
**Returns `tuple(float, float, float)`:**
`X-Y-Z` item ground position on the world.
"""
return self._position
def getRotation(self) -> dict:
"""
This method will get the item ground rotation on the world.
**Returns `tuple(float, float, float)`:**
`X-Y-Z` item ground roration on the world.
"""
return self._rotation
@property
def id(self) -> int:
return self._id
@property
def instance(self) -> str:
return self._instance
@property
def amount(self) -> int:
return self._amount
@property
def world(self) -> str:
return self._world
@property
def virtualWorld(self) -> int:
return self._virtualWorld
@virtualWorld.setter
def virtualWorld(self, value):
self._virtualWorld = value
def _initialize(self, **kwargs):
self.__dict__.update(kwargs)

38
src/pyg2o/classes/mds.py Normal file
View File

@@ -0,0 +1,38 @@
from ..server import PythonWebsocketServer
class Mds:
"""
This class represents mds manager for conversion between mds id & mds instance. This manager will work for every registered mds in `mds.xml` file.
Original: [Mds](https://gothicmultiplayerteam.gitlab.io/docs/0.3.0/script-reference/shared-classes/mds/Mds/)
"""
@staticmethod
async def id(mdsName : str) -> int:
"""
This method will convert the mds name to mds id.
**Parameters:**
* `str` **mdsName**: the mds name, e.g: `"HumanS_Sprint.mds"`.
**Returns `int`:**
the unique mds id.
"""
data = f'return Mds.id({mdsName})'
server = await PythonWebsocketServer.get_server()
result = await server.make_request(data)
return result
@staticmethod
async def name(mdsId : int) -> str:
"""
This method will convert the mds id to mds name.
**Parameters:**
* `int` **mdsId**: the mds id.
**Returns `str`:**
the mds name, e.g: `"HumanS_Sprint.mds"`.
"""
data = f'return Mds.id({mdsId})'
server = await PythonWebsocketServer.get_server()
result = await server.make_request(data)
return result

161
src/pyg2o/classes/sky.py Normal file
View File

@@ -0,0 +1,161 @@
from ..server import PythonWebsocketServer
class Sky:
"""
This class represents data packet that gets send over the network.
Original: [Sky](https://gothicmultiplayerteam.gitlab.io/docs/0.3.0/script-reference/server-classes/game/Sky/)
## `int` weather
Represents the sky weather. For more information see [Weather Constants](../../constants/weather.md)
## `bool` raining
Represents the raining/snowing state.
## `bool` renderLightning
Represents the lightning feature during raining state.
Lightning will only be rendered during raining and when weatherWeight is larger than 0.5
## `float` windScale
Represents the sky wind scale used during raining/snowing.
## `bool` dontRain
Represents the sky dontRain feature.
When it's enabled, the rain/snow won't fall.
"""
@staticmethod
async def get_weather():
data = 'return Sky.weather'
server = await PythonWebsocketServer.get_server()
result = await server.make_request(data)
return result
@staticmethod
async def set_weather(value):
data = 'return Sky.weather = value'
server = await PythonWebsocketServer.get_server()
result = await server.make_request(data)
return result
@staticmethod
async def get_raining():
data = 'return Sky.raining'
server = await PythonWebsocketServer.get_server()
result = await server.make_request(data)
return result
@staticmethod
async def set_raining(value):
data = 'return Sky.raining = value'
server = await PythonWebsocketServer.get_server()
result = await server.make_request(data)
return result
@staticmethod
async def get_renderLightning():
data = 'return Sky.renderLightning'
server = await PythonWebsocketServer.get_server()
result = await server.make_request(data)
return result
@staticmethod
async def set_renderLightning(value):
data = 'return Sky.renderLightning = value'
server = await PythonWebsocketServer.get_server()
result = await server.make_request(data)
return result
@staticmethod
async def get_windScale():
data = 'return Sky.windScale'
server = await PythonWebsocketServer.get_server()
result = await server.make_request(data)
return result
@staticmethod
async def set_windScale(value):
data = 'return Sky.windScale = value'
server = await PythonWebsocketServer.get_server()
result = await server.make_request(data)
return result
@staticmethod
async def get_dontRain():
data = 'return Sky.dontRain'
server = await PythonWebsocketServer.get_server()
result = await server.make_request(data)
return result
@staticmethod
async def set_dontRain(value):
data = 'return Sky.dontRain = value'
server = await PythonWebsocketServer.get_server()
result = await server.make_request(data)
return result
@staticmethod
async def setRainStartTime(hour : int, minute : int):
"""
This method will set the sky weather time when it starts raining/snowing.
**Parameters:**
* `int` **hour**: the sky weather raining start hour.
* `int` **minute**: the sky weather raining start min.
"""
data = f'return Sky.setRainStartTime({hour}, {minute})'
server = await PythonWebsocketServer.get_server()
result = await server.make_request(data)
return result
@staticmethod
async def setRainStopTime(hour : int, minute : int):
"""
This method will set the sky weather time when it stops raining/snowing.
**Parameters:**
* `int` **hour**: the sky weather raining stop hour.
* `int` **minute**: the sky weather raining stop min.
"""
data = f'return Sky.setRainStopTime({hour}, {minute})'
server = await PythonWebsocketServer.get_server()
result = await server.make_request(data)
return result
@staticmethod
async def getRainStartTime() -> dict:
"""
This method will get the sky weather time when it starts raining/snowing.
**Returns `dict`:**
* `int` **hour**: the sky weather raining start hour.
* `int` **minute**: the sky weather raining start min.
"""
data = 'return Sky.getRainStartTime()'
server = await PythonWebsocketServer.get_server()
result = await server.make_request(data)
return result
@staticmethod
async def getRainStopTime() -> dict:
"""
This method will get the sky weather time when it stops raining/snowing.
**Returns `dict`:**
* `int` **hour**: the sky weather raining stop hour.
* `int` **minute**: the sky weather raining stop min.
"""
data = 'return Sky.getRainStopTime()'
server = await PythonWebsocketServer.get_server()
result = await server.make_request(data)
return result

View File

@@ -0,0 +1,129 @@
import inspect
class Constant:
AC_SPEED_HACK = None
DAMAGE_CTX = None
EQUIPMENT_CTX = None
DAMAGE_UNKNOWN = None
DAMAGE_BARRIER = None
DAMAGE_BLUNT = None
DAMAGE_EDGE = None
DAMAGE_FIRE = None
DAMAGE_FLY = None
DAMAGE_MAGIC = None
DAMAGE_POINT = None
DAMAGE_FALL = None
DEBUG_MODE = None
CLIENT_SIDE = None
SERVER_SIDE = None
HAND_LEFT = None
HAND_RIGHT = None
ITEM_CAT_NONE = None
ITEM_CAT_NF = None
ITEM_CAT_FF = None
ITEM_CAT_MUN = None
ITEM_CAT_ARMOR = None
ITEM_CAT_FOOD = None
ITEM_CAT_DOCS = None
ITEM_CAT_POTION = None
ITEM_CAT_LIGHT = None
ITEM_CAT_RUNE = None
ITEM_CAT_MAGIC = None
ITEM_FLAG_DAG = None
ITEM_FLAG_SWD = None
ITEM_FLAG_AXE = None
ITEM_FLAG_2HD_SWD = None
ITEM_FLAG_2HD_AXE = None
ITEM_FLAG_SHIELD = None
ITEM_FLAG_BOW = None
ITEM_FLAG_CROSSBOW = None
ITEM_FLAG_RING = None
ITEM_FLAG_AMULET = None
ITEM_FLAG_BELT = None
ITEM_FLAG_DROPPED = None
ITEM_FLAG_MI = None
ITEM_FLAG_MULTI = None
ITEM_FLAG_NFOCUS = None
ITEM_FLAG_CREATEAMMO = None
ITEM_FLAG_NSPLIT = None
ITEM_FLAG_DRINK = None
ITEM_FLAG_TORCH = None
ITEM_FLAG_THROW = None
ITEM_FLAG_ACTIVE = None
ITEM_WEAR_NO = None
ITEM_WEAR_TORSO = None
ITEM_WEAR_HEAD = None
ITEM_WEAR_LIGHT = None
DISCONNECTED = None
LOST_CONNECTION = None
HAS_CRASHED = None
ATTACK_RUN = None
ATTACK_FORWARD = None
ATTACK_LEFT = None
ATTACK_RIGHT = None
ACTION_CLEAR_QUEUE = None
ACTION_APPLY_OVERLAY = None
ACTION_REMOVE_OVERLAY = None
ACTION_PLAY_ANI = None
ACTION_STOP_ANI = None
ACTION_EQUIP_ITEM = None
ACTION_UNEQUIP_ITEM = None
ACTION_WEAPON_MODE = None
ACTION_DRAW_WEAPON = None
ACTION_REMOVE_WEAPON = None
ACTION_USE_ITEM = None
ACTION_USE_ITEM_TO_STATE = None
ACTION_READY_SPELL = None
ACTION_UNREADY_SPELL = None
ACTION_ATTACK_MELEE_WEAPON = None
ACTION_ATTACK_RANGED_WEAPON = None
ACTION_SPELL_CAST = None
ACTION_USE_MOB_SCHEME = None
ACTION_SHOOT_AT = None
ACTION_START_AIM_AT = None
ACTION_STOP_AIM_AT = None
ACTION_SCRIPT = None
WEAPON_1H = None
WEAPON_2H = None
WEAPON_BOW = None
WEAPON_CBOW = None
TALENT_1H = None
TALENT_2H = None
TALENT_BOW = None
TALENT_CROSSBOW = None
TALENT_PICK_LOCKS = None
TALENT_PICKPOCKET = None
TALENT_MAGE = None
TALENT_SNEAK = None
TALENT_REGENERATE = None
TALENT_FIREMASTER = None
TALENT_ACROBATIC = None
TALENT_PICKPOCKET_UNUSED = None
TALENT_SMITH = None
TALENT_RUNES = None
TALENT_ALCHEMY = None
TALENT_THROPHY = None
TALENT_A = None
TALENT_B = None
TALENT_C = None
TALENT_D = None
TALENT_E = None
TALENT_MAX = None
WEAPONMODE_NONE = None
WEAPONMODE_FIST = None
WEAPONMODE_DAG = None
WEAPONMODE_1HS = None
WEAPONMODE_2HS = None
WEAPONMODE_BOW = None
WEAPONMODE_CBOW = None
WEAPONMODE_MAG = None
WEAPONMODE_MAX = None
WEATHER_SNOW = None
WEATHER_RAIN = None
@classmethod
def _update(cls, constants):
existing_vars = [name for name, _ in inspect.getmembers(cls) if not name.startswith('_') and not inspect.ismodule(_)]
for key, val in constants.items():
if key in existing_vars:
setattr(cls, key, val)

View File

View File

@@ -0,0 +1,98 @@
from ..server import PythonWebsocketServer
from ..call_repr import get_call_repr
async def sendMessageToAll(r : int, g : int, b : int, text : str):
"""
This function will send a chat message to every connected player.
Sending a message triggers client side event [onPlayerMessage](../../defaultEvents/player/onPlayerMessage.md) with playerid set as `-1`.
Original: [sendMessageToAll](https://gothicmultiplayerteam.gitlab.io/docs/0.3.0/script-reference/server-functions/chat/sendMessageToAll/)
## Declaration
```python
async def sendMessageToAll(r : int, g : int, b : int, text : str)
```
## Parameters
* `int` **r**: the red color component in RGB model.
* `int` **g**: the green color component in RGB model.
* `int` **b**: the blue color component in RGB model.
* `str` **text**: that will be send.
"""
data = f'return {get_call_repr()}'
server = await PythonWebsocketServer.get_server()
result = await server.make_request(data)
return result
async def sendMessageToPlayer(playerid : int, r : int, g : int, b : int, text : str):
"""
This function will send a chat message to specific player.
Sending a message triggers client side event [onPlayerMessage](../../defaultEvents/player/onPlayerMessage.md) with playerid set as `-1`.
Original: [sendMessageToPlayer](https://gothicmultiplayerteam.gitlab.io/docs/0.3.0/script-reference/server-functions/chat/sendMessageToPlayer/)
## Declaration
```python
async def sendMessageToPlayer(playerid : int, r : int, g : int, b : int, text : str)
```
## Parameters
* `int` **playerid**: the id of the player which will receive a message.
* `int` **r**: the red color component in RGB model.
* `int` **g**: the green color component in RGB model.
* `int` **b**: the blue color component in RGB model.
* `str` **text**: that will be send.
"""
data = f'return {get_call_repr()}'
server = await PythonWebsocketServer.get_server()
result = await server.make_request(data)
return result
async def sendPlayerMessageToAll(senderid : int, r : int, g : int, b : int, text : str):
"""
This function will send a chat message from one player to every player. Sending a message
Sending a message triggers client side event [onPlayerMessage](../../defaultEvents/player/onPlayerMessage.md) with playerid set as **senderid**.
Original: [sendPlayerMessageToAll](https://gothicmultiplayerteam.gitlab.io/docs/0.3.0/script-reference/server-functions/chat/sendPlayerMessageToAll/)
## Declaration
```python
async def sendPlayerMessageToAll(senderid : int, r : int, g : int, b : int, text : str)
```
## Parameters
* `int` **senderid**: the id of the player which will send a message.
* `int` **r**: the red color component in RGB model.
* `int` **g**: the green color component in RGB model.
* `int` **b**: the blue color component in RGB model.
* `str` **text**: that will be send.
"""
data = f'return {get_call_repr()}'
server = await PythonWebsocketServer.get_server()
result = await server.make_request(data)
return result
async def sendPlayerMessageToPlayer(senderid : int, receiverid : int, r : int, g : int, b : int, text : str):
"""
This function will send a chat message from one player to another player.
Sending a message triggers client side event [onPlayerMessage](../../defaultEvents/player/onPlayerMessage.md) with playerid set as **senderid**.
Original: [sendPlayerMessageToPlayer](https://gothicmultiplayerteam.gitlab.io/docs/0.3.0/script-reference/server-functions/chat/sendPlayerMessageToPlayer/)
## Declaration
```python
async def sendPlayerMessageToPlayer(senderid : int, receiverid : int, r : int, g : int, b : int, text : str)
```
## Parameters
* `int` **senderid**: the id of the player which will send a message.
* `int` **receiverid**: the id of the player which will receive a message.
* `int` **r**: the red color component in RGB model.
* `int` **g**: the green color component in RGB model.
* `int` **b**: the blue color component in RGB model.
* `str` **text**: that will be send.
"""
data = f'return {get_call_repr()}'
server = await PythonWebsocketServer.get_server()
result = await server.make_request(data)
return result

View File

@@ -0,0 +1,737 @@
from typing import Literal, overload
from functools import wraps
from ..serialize import _deserialize
eventList = {}
disabledEventList = []
async def callEvent(evtName : str, **kwargs : list):
"""
This function will notify (call) every handler bound to specified event.
Original: [callEvent](https://gothicmultiplayerteam.gitlab.io/docs/0.3.0/script-reference/shared-functions/event/callEvent/)
## Declaration
```python
def callEvent(evtName : str, **kwargs : list)
```
## Parameters
* `str` **name**: the name of the event
* `**dict` **kwargs**: the variable number of arguments.
## Usage
```python
import g2o
g2o.addEvent('testEvt')
@g2o.event('testEvt')
def onTestEvent(**kwargs):
print(f'{kwargs['name']} called my beautiful test event')
g2o.callEvent('testEvt', name = 'Diego')
```
"""
isEventCancelled = False
if evtName in eventList and evtName not in disabledEventList:
for event in eventList[evtName]:
event['function'].eventName = evtName
event['function'].cancelled = isEventCancelled
result = await event['function'](**kwargs)
if result != None:
isEventCancelled = not result
return isEventCancelled
def addEvent(name : str):
"""
This function will register a new event with specified name.
Events can be used to notify function(s) when something will happen, like player joins the server, etc.
Original: [addEvent](https://gothicmultiplayerteam.gitlab.io/docs/0.3.0/script-reference/shared-functions/event/addEvent/)
## Declaration
```python
def addEvent(name)
```
## Parameters
* `str` **name**: the name of the event
## Usage
```python
import g2o
g2o.addEvent('testEvt')
```
"""
if not name in eventList:
eventList[name] = []
@overload
def event(event_name: Literal['onPlayerUseCheat'], priority: int = 9999) -> None:
'''
!!! note
Detecting some type of forbidden tools may take, even a few minutes. Server need time to analyze player data.
## Parameters:
* **playerid**: str - the id of the player who used some type of trainer/cheat.
* **type**: int - the type of used trainer/cheat. For more information see AntiCheat constants.
'''
...
@overload
def event(event_name: Literal['onBan'], priority: int = 9999) -> None:
'''
!!! note
If serial/mac/ip/name indexes doesn't exist, then the parameters has not been specified when ban was added.
This event is triggered when new ban is being added.
## Parameters:
* **banInfo**: dict
* **mac**: str - MAC address of the banned player.
* **ip**: str - IP address of the banned player.
* **serial**: str - serial of the banned player.
* **name**: str - nickname of the banned player.
* **timestamp**: int - timestamp when the ban expires.
'''
...
@overload
def event(event_name: Literal['onExit'], priority: int = 9999) -> None:
'''
This event is triggered when server is going to shut down.
You can use it, to save some data before closing up, or do something else.
## Parameters:
No parameters.
'''
...
@overload
def event(event_name: Literal['onInit'], priority: int = 9999) -> None:
'''
This event is triggered when server successfully starts up.
## Parameters:
No parameters.
'''
...
@overload
def event(event_name: Literal['onTick'], priority: int = 9999) -> None:
'''
This event is triggered in every server main loop iteration.
## Parameters:
No parameters.
'''
...
@overload
def event(event_name: Literal['onTime'], priority: int = 9999) -> None:
'''
This event is triggered each time when game time minute passes.
## Parameters:
* **day**: int - the current ingame day.
* **hour**: int - the current ingame hour.
* **min**: int - the current ingame minutes.
'''
...
@overload
def event(event_name: Literal['onUnban'], priority: int = 9999) -> None:
'''
!!! note
If serial/mac/ip/name indexes doesn't exist, then the parameters has not been specified when ban was added.
This event is triggered when ban with specified info is being removed.
## Parameters:
* **banInfo**: dict
* **mac**: str - MAC address of the banned player.
* **ip**: str - IP address of the banned player.
* **serial**: str - serial of the banned player.
* **name**: str - nickname of the banned player.
* **timestamp**: int - timestamp when the ban expires.
'''
...
@overload
def event(event_name: Literal['onNpcActionFinished'], priority: int = 9999) -> None:
'''
This event is triggered when NPC action was finished.
## Parameters:
* **npc_id**: int - the npc identifier.
* **action_type**: int - the action type.
* **action_id**: int - the unique action identifier.
* **result**: bool - the result of finished action.
'''
...
@overload
def event(event_name: Literal['onNpcActionSent'], priority: int = 9999) -> None:
'''
This event is triggered when server sends NPC action to streamed players.
## Parameters:
* **npc_id**: int - the npc identifier.
* **action_type**: int - the action type.
* **action_id**: int - the unique action identifier.
'''
...
@overload
def event(event_name: Literal['onNpcChangeHostPlayer'], priority: int = 9999) -> None:
'''
This event is triggered when NPC host is changed. Every remote NPC is hosted by one of spawned players in order to get valid position of NPC.
## Parameters:
* **npc_id**: int - the npc identifier.
* **current_id**: int - the id of the current host, can be -1 if there is no current host.
* **previous_id**: int - the id of the previous host, can be -1 if there was no previous host.
'''
...
@overload
def event(event_name: Literal['onNpcCreated'], priority: int = 9999) -> None:
'''
This event is triggered when remote NPC is created.
## Parameters:
* **npc_id**: int - the id of the newly created remote npc.
'''
...
@overload
def event(event_name: Literal['onNpcDestroyed'], priority: int = 9999) -> None:
'''
This event is triggered when remote NPC is destroyed.
## Parameters:
* **npc_id**: int - the id of the destroyed remote npc.
'''
...
@overload
def event(event_name: Literal['onPlayerChangeColor'], priority: int = 9999) -> None:
'''
This event is triggered when player nickname color was changed for all players.
## Parameters:
* **playerid**: int - the id of the player whose nickname color was changed.
* **r**: int - the amount of red in the nickname color ``(0 - 255)``.
* **g**: int - the amount of green in the nickname color ``(0 - 255)``.
* **b**: int - the amount of blue in the nickname color ``(0 - 255)``.
'''
...
@overload
def event(event_name: Literal['onPlayerChangeFocus'], priority: int = 9999) -> None:
'''
This event is triggered when player targets another player.
## Parameters:
* **playerid**: int - the id of the player which changes the focus.
* **oldFocusId**: int - the old playerid targeted by the player. Can be ``-1`` if player wasn't targeting other player.
* **newFocusId**: int - the new playerid targeted by the player. Can be ``-1`` if player doesn't target anyone.
'''
...
@overload
def event(event_name: Literal['onPlayerChangeHealth'], priority: int = 9999) -> None:
'''
This event is triggered when player health changes.
## Parameters:
* **playerid**: int - the id of the player whose health points gets changed.
* **previous**: int - the previous health points of the player.
* **current**: int - the current health points of the player.
'''
...
@overload
def event(event_name: Literal['onPlayerChangeMana'], priority: int = 9999) -> None:
'''
This event is triggered when player mana changes.
## Parameters:
* **playerid**: int - the id of the player whose mana points gets changed.
* **previous**: int - the previous mana points of the player.
* **current**: int - the current mana points of the player.
'''
...
@overload
def event(event_name: Literal['onPlayerChangeMaxHealth'], priority: int = 9999) -> None:
'''
This event is triggered when player maximum health changes.
## Parameters:
* **playerid**: int - the id of the player whose maximum health points gets changed.
* **previous**: int - the previous maximum health points of the player.
* **current**: int - the current maximum health points of the player.
'''
...
@overload
def event(event_name: Literal['onPlayerChangeMaxMana'], priority: int = 9999) -> None:
'''
This event is triggered when player maximum mana changes.
## Parameters:
* **playerid**: int - the id of the player whose maximum mana points gets changed.
* **previous**: int - the previous maximum mana points of the player.
* **current**: int - the current maximum mana points of the player.
'''
...
@overload
def event(event_name: Literal['onPlayerChangeWeaponMode'], priority: int = 9999) -> None:
'''
This event is triggered when player changes the weapon mode.
## Parameters:
* **playerid**: int - the id of the player which changes the weapon mode.
* **previous**: int - the old weapon mode which was used by the player. For more information see Weapon mode constants.
* **current**: int - the new weapon mode in which player is currently using. For more information see Weapon mode constants.
'''
...
@overload
def event(event_name: Literal['onPlayerChangeWorld'], priority: int = 9999) -> None:
'''
This event is triggered when player tries to change his currently played world (ZEN).
## Parameters:
* **playerid**: int - the id of the player who tries to change the played world.
* **world**: str - a filename name of the world.
* **waypoint**: str - a name of the waypoint that the player will be teleported to.
'''
...
@overload
def event(event_name: Literal['onPlayerCommand'], priority: int = 9999) -> None:
'''
This event is triggered when a player uses command on the chat.
Command always begins with forward slash ``/``.
## Parameters:
* **playerid**: int - the id of the player who typed the command.
* **command**: str - used command name on the chat.
* **params**: str - command parameters divided by space.
'''
...
@overload
def event(event_name: Literal['onPlayerDamage'], priority: int = 9999) -> None:
'''
This event is triggered when one player hits another player.
## Parameters:
* **playerid**: int - the id of the player who was hit.
* **killerid**: int - the id of the killer. If killerid is set to ``-1``, it means that there was no killer. In this particular case damage source can be fall from a tall object or scripts.
* **description**: DamageDescription - a structure containing damage information. For more information see DamageDescription
'''
...
@overload
def event(event_name: Literal['onPlayerDead'], priority: int = 9999) -> None:
'''
This event is triggered when one player kills another player.
## Parameters:
* **playerid**: int - the id of the player who died.
* **killerid**: int - the id of the player who killed other player. If killerid is set to -1, it means that there was no killer.
'''
...
@overload
def event(event_name: Literal['onPlayerDisconnect'], priority: int = 9999) -> None:
'''
This event is triggered when a player gets disconnected with the server.
## Parameters:
* **playerid**: int - the id of the player who joined the server.
* **reason**: int - the reason why player got disconnected. For more information see Network constants.
'''
...
# TODO: Отмена ивента
@overload
def event(event_name: Literal['onPlayerDropItem'], priority: int = 9999) -> None:
'''
!!! note
Cancelling this event will delete the dropped item from the world.
This event is triggered when player drops an item from his inventory to the ground.
## Parameters:
* **playerid**: int - the id of the player who tries to drop the item on the ground.
* **itemGround**: ItemGround - the ground item object which represents the dropped item by the player.
'''
...
@overload
def event(event_name: Literal['onPlayerEnterWorld'], priority: int = 9999) -> None:
'''
This event is triggered when player entered the world (ZEN) and was successfully spawned in it.
## Parameters:
* **playerid**: int - the id of the player who entered the world.
* **world**: str - a filename name of the world.
'''
...
@overload
def event(event_name: Literal['onPlayerEquipAmulet'], priority: int = 9999) -> None:
'''
This event is triggered when player equips or unequips amulet. When item is unequiped, ``None`` is returned instead.
## Parameters:
* **playerid**: int - the id of the player who equips an amulet.
* **instance**: str|None - the item instance from Daedalus scripts.
'''
...
@overload
def event(event_name: Literal['onPlayerEquipArmor'], priority: int = 9999) -> None:
'''
This event is triggered when player equips or unequips armor. When item is unequiped, ``null`` is returned instead.
## Parameters:
* **playerid**: int - the id of the player who equips an armor.
* **instance**: str|None - the item instance from Daedalus scripts.
'''
...
@overload
def event(event_name: Literal['onPlayerEquipBelt'], priority: int = 9999) -> None:
'''
This event is triggered when player equips or unequips belt. When item is unequiped, ``null`` is returned instead.
## Parameters:
* **playerid**: int - the id of the player who equips a belt.
* **instance**: str|None - the item instance from Daedalus scripts.
'''
...
@overload
def event(event_name: Literal['onPlayerEquipHandItem'], priority: int = 9999) -> None:
'''
This event is triggered when game adds item to player hand, e.g: when player opens or consumes any item. When item is removed from hand, ``null is returned instead.
## Parameters:
* **playerid**: int - the id of the player who equips a hand item.
* **hand**: int - the id of the hand in which player holds item. For more information see Hand constants.
* **instance**: str|None - the item instance from Daedalus scripts.
'''
...
@overload
def event(event_name: Literal['onPlayerEquipHelmet'], priority: int = 9999) -> None:
'''
This event is triggered when player equips or unequips helmet. When item is unequiped, ``null`` is returned instead.
## Parameters:
* **playerid**: int - the id of the player who equips a helmet.
* **instance**: str|None - the item instance from Daedalus scripts.
'''
...
@overload
def event(event_name: Literal['onPlayerEquipMeleeWeapon'], priority: int = 9999) -> None:
'''
This event is triggered when player equips or unequips melee weapon. When item is unequiped, ``null`` is returned instead.
## Parameters:
* **playerid**: int - the id of the player who equips melee weapon.
* **instance**: str|None - the item instance from Daedalus scripts.
'''
...
@overload
def event(event_name: Literal['onPlayerEquipRangedWeapon'], priority: int = 9999) -> None:
'''
This event is triggered when player equips or unequips ranged weapon. When item is unequiped, ``null`` is returned instead.
## Parameters:
* **playerid**: int - the id of the player who equips ranged weapon.
* **instance**: str|None - the item instance from Daedalus scripts.
'''
...
@overload
def event(event_name: Literal['onPlayerEquipRing'], priority: int = 9999) -> None:
'''
This event is triggered when player equips or unequips ring. When item is unequiped, ``null`` item id is returned instead.
## Parameters:
* **playerid**: int - the id of the player who equips a ring.
* **handId**: int - the hand id that the player is putting the ring on.
* **instance**: str|None - the item instance from Daedalus scripts.
'''
...
@overload
def event(event_name: Literal['onPlayerEquipShield'], priority: int = 9999) -> None:
'''
This event is triggered when player equips or unequips shield. When item is unequiped, ``null`` is returned instead.
## Parameters:
* **playerid**: int - the id of the player who equips a shield.
* **instance**: str|None - the item instance from Daedalus scripts.
'''
...
@overload
def event(event_name: Literal['onPlayerEquipSpell'], priority: int = 9999) -> None:
'''
This event is triggered when player equips or unequips scroll or rune. When item is unequiped, ``null`` is returned instead.
## Parameters:
* **playerid**: the id of the player who equips a spell.
* **slotId**: int - the slot id that the player puts the spell on in range <0, 6>.
* **instance**: str|None - the item instance from Daedalus scripts.
'''
...
@overload
def event(event_name: Literal['onPlayerJoin'], priority: int = 9999) -> None:
'''
This event is triggered when a player successfully joined the server.
## Parameters:
* **playerid**: int - the id of the player who joined the server.
'''
...
@overload
def event(event_name: Literal['onPlayerMessage'], priority: int = 9999) -> None:
'''
This event is triggered when a player types the message on the chat.
## Parameters:
* **playerid**: int - the id of the player who typed the message.
'''
...
@overload
def event(event_name: Literal['onPlayerMobInteract'], priority: int = 9999) -> None:
'''
This event is triggered when player interacts with any kind of mob object in the world. In Gothic, mobs are special vobs on the map, that hero can interact with. For example bed, door, chest etc.
## Parameters:
* **playerid**: int - the id of the player who interacts with mob.
* **from**: int - represents previous state of mob. If value is ``1``, then mob was used, in any other case value is ``0``.
* **to**: int - represents current state of mob. If value is ``1``, then mob is used, in any other case value is ``0``.
'''
...
@overload
def event(event_name: Literal['onPlayerRespawn'], priority: int = 9999) -> None:
'''
This event is triggered when a player respawns after death.
## Parameters:
* **playerid**: int - the id of the player who respawned after death.
'''
...
@overload
def event(event_name: Literal['onPlayerShoot'], priority: int = 9999) -> None:
'''
This event is triggered when player shoot using ranged weapon.
## Parameters:
* **playerid**: int - the id of the player who just shot.
* **munition**: str|None - the item instance from Daedalus scripts.
'''
...
@overload
def event(event_name: Literal['onPlayerSpellCast'], priority: int = 9999) -> None:
'''
!!! note
Right now transformation and summon spells are not supported, despite this event will be triggered for them. Cancelling this event willl prevent this action to be synced to other players.
This event is triggered when player is casting some spell.
## Parameters:
* **playerid**: int - the id of the player who casts the spell.
* **munition**: str|None - the item instance from Daedalus scripts.
* **spellLevel**: int - the level of charged spell
'''
...
@overload
def event(event_name: Literal['onPlayerSpellSetup'], priority: int = 9999) -> None:
'''
This event is triggered when player prepares the spell.
## Parameters:
* **playerid**: int - the id of the player who prepares the spell.
* **munition**: str|None - the item instance from Daedalus scripts.
'''
...
# TODO: Отмена ивента
@overload
def event(event_name: Literal['onPlayerTakeItem'], priority: int = 9999) -> None:
'''
!!! note
Even if this event is triggered it doesn't mean, that player will get item to his inventory. It only means, that the player tried to get the item from the ground. Server is the last decide if the item can be taken from the ground. Canceling this event will prevent the item to be taken from the ground.
This event is triggered when player takes an item from the ground.
## Parameters:
* **playerid**: int - the id of the player who tries to take the ground item.
* **itemGround**: ItemGround - the ground item object which player tried to to take.
'''
...
@overload
def event(event_name: Literal['onPlayerTeleport'], priority: int = 9999) -> None:
'''
This event is triggered when player gets teleported by the game to the specified vob.
## Parameters:
* **playerid**: int - the id of the player who gets teleported by the game.
* **vobName**: str - represents the name of the vob that player gets teleported to.
'''
...
@overload
def event(event_name: Literal['onPlayerToggleFaceAni'], priority: int = 9999) -> None:
'''
This event is triggered when player face animation is toggled (played or stopped), due to eating or other activities.
## Parameters:
* **playerid**: int - the id of the player which toggled face animation.
* **aniName**: str - the face animation name.
* **toggle**: bool - ``True`` when player is started playing face animation, otherwise ``False``.
'''
...
def event(event_name: str, priority: int = 9999) -> None:
def inlineEvt(func):
if event_name not in eventList:
return None
@wraps(func)
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
eventList[event_name].append({'function': wrapper, 'priority': priority})
eventList[event_name].sort(key = lambda x: x['priority'])
return wrapper
return inlineEvt
def removeEventHandler(name : str, func : object):
"""
This function will unbind function from specified event.
Original: [removeEventHandler](https://gothicmultiplayerteam.gitlab.io/docs/0.3.0/script-reference/shared-functions/event/removeEventHandler/)
## Declaration
```python
def removeEventHandler(name : str, func : object)
```
## Parameters
* `str` **name**: the name of the event
* `object` **func**: the reference to a function which is currently bound to specified event.
## Usage
```python
import g2o
@g2o.event('onTime')
def onTimeEvt(**kwargs):
print('Calling only once')
g2o.removeEventHandler('onTime', onTimeEvt)
```
"""
if not name in eventList:
pass
for index, item in enumerate(eventList[name]):
if item['function'] == func:
del eventList[name][index]
def toggleEvent(name : str, toggle : bool):
'''
!!! note
By default every event is toggled `on` (enabled).
This function will toggle event (enable or disable it globally). By toggling event off, you can completely disable certain event from calling it's handlers.
Original: [toggleEvent](https://gothicmultiplayerteam.gitlab.io/docs/0.3.0/script-reference/shared-functions/event/toggleEvent/)
## Declaration
```python
def toggleEvent(name : str, toggle : bool)
```
## Parameters
* `str` **name**: the name of the event
* `bool` **toggle**: `false` if you want to disable the event, otherwise true.
## Usage
```python
import g2o
@g2o.event('onTime')
def onTimeEvt(**kwargs):
print('Calling only once')
g2o.toggleEvent('onTime', false)
```
'''
if not toggle and name not in disabledEventList:
disabledEventList.append(name)
elif toggle and name in disabledEventList:
disabledEventList.remove(name)
def removeEvent(name : str):
'''
!!! warning
Removing an event also cause all event handlers to unregister.
This function will unregister an event with specified name.
Original: [removeEvent](https://gothicmultiplayerteam.gitlab.io/docs/0.3.0/script-reference/shared-functions/event/removeEvent/)
## Declaration
```python
def removeEvent(name : str)
```
## Parameters
* `str` **name**: the name of the event
## Usage
```python
import g2o
@g2o.event('onTime')
def onTimeEvt(**kwargs):
print('Calling only once')
g2o.removeEvent('onTime')
```
'''
if name in eventList:
eventList.pop(name)
## registering default events
addEvent('onInit')
addEvent('onExit')
addEvent('onTick')
addEvent('onTime')
addEvent('onBan')
addEvent('onUnban')
addEvent('onPlayerChangeColor')
addEvent('onPlayerChangeFocus')
addEvent('onPlayerChangeHealth')
addEvent('onPlayerChangeMana')
addEvent('onPlayerChangeMaxHealth')
addEvent('onPlayerChangeMaxMana')
addEvent('onPlayerChangeWeaponMode')
addEvent('onPlayerChangeWorld')
addEvent('onPlayerCommand')
addEvent('onPlayerDamage')
addEvent('onPlayerDead')
addEvent('onPlayerDisconnect')
addEvent('onPlayerDropItem')
addEvent('onPlayerEnterWorld')
addEvent('onPlayerJoin')
addEvent('onPlayerMessage')
addEvent('onPlayerMobInteract')
addEvent('onPlayerRespawn')
addEvent('onPlayerShoot')
addEvent('onPlayerSpellCast')
addEvent('onPlayerSpellSetup')
addEvent('onPlayerTakeItem')
addEvent('onPlayerTeleport')
addEvent('onPlayerToggleFaceAni')
addEvent('onPlayerEquipAmulet')
addEvent('onPlayerEquipArmor')
addEvent('onPlayerEquipBelt')
addEvent('onPlayerEquipHandItem')
addEvent('onPlayerEquipHelmet')
addEvent('onPlayerEquipMeleeWeapon')
addEvent('onPlayerEquipRangedWeapon')
addEvent('onPlayerEquipRing')
addEvent('onPlayerEquipShield')
addEvent('onPlayerEquipSpell')
addEvent('onPacket')
addEvent('onPlayerUseCheat')
addEvent('onNpcActionFinished')
addEvent('onNpcActionSent')
addEvent('onNpcChangeHostPlayer')
addEvent('onNpcCreated')
addEvent('onNpcDestroyed')
addEvent('onWebsocketConnect')
addEvent('onWebsocketDisconnect')

280
src/pyg2o/functions/game.py Normal file
View File

@@ -0,0 +1,280 @@
from ..server import PythonWebsocketServer
from ..call_repr import get_call_repr
async def getHostname() -> str:
"""
This function will get the hostname of the server.
Original: [getHostname](https://gothicmultiplayerteam.gitlab.io/docs/0.3.0/script-reference/shared-functions/game/getHostname/)
## Declaration
```python
async def getHostname() -> str
```
## Returns
`str`: Server hostname.
## Usage
```python
import g2o
@g2o.event('onInit')
def evtInit(**kwargs):
print('Server hostname:', g2o.getHostname())
```
"""
data = f'return {get_call_repr()}'
server = await PythonWebsocketServer.get_server()
result = await server.make_request(data)
return result
async def getMaxSlots() -> int:
"""
This function will get the max number of slots available on the server.
Original: [getMaxSlots](https://gothicmultiplayerteam.gitlab.io/docs/0.3.0/script-reference/shared-functions/game/getMaxSlots/)
## Declaration
```python
async def getMaxSlots() -> int
```
## Returns
`int`: Max slots number on the server.
## Usage
```python
import g2o
@g2o.event('onInit')
def evtInit(**kwargs):
print('Server max slots:', g2o.getMaxSlots())
```
"""
data = f'return {get_call_repr()}'
server = await PythonWebsocketServer.get_server()
result = await server.make_request(data)
return result
async def getPlayersCount() -> int:
"""
This function will get the max number of slots available on the server.
Original: [getPlayersCount](https://gothicmultiplayerteam.gitlab.io/docs/0.3.0/script-reference/shared-functions/game/getPlayersCount/)
## Declaration
```python
async def getPlayersCount() -> int
```
## Returns
`int`: Number of players on the server.
## Usage
```python
import g2o
@g2o.event('onInit')
def evtInit(**kwargs):
print('Players online:', g2o.getPlayersCount())
```
"""
data = f'return {get_call_repr()}'
server = await PythonWebsocketServer.get_server()
result = await server.make_request(data)
return result
async def exit(exitCode : int = 0):
"""
This function will close the server with specified exit code.
Original: [exit](https://gothicmultiplayerteam.gitlab.io/docs/0.3.0/script-reference/server-functions/game/exit/)
## Declaration
```python
async def exit(exitCode : int = 0)
```
## Parameters
* `int` **exitCode**: exit status for g2o server.
"""
data = f'return {get_call_repr()}'
server = await PythonWebsocketServer.get_server()
result = await server.make_request(data)
return result
async def getDayLength() -> float:
"""
The function is used to get the day length in miliseconds.
Original: [getDayLength](https://gothicmultiplayerteam.gitlab.io/docs/0.3.0/script-reference/server-functions/game/getDayLength/)
## Declaration
```python
async def getDayLength() -> float
```
## Returns
`float`: the current day length in miliseconds.
"""
data = f'return {get_call_repr()}'
server = await PythonWebsocketServer.get_server()
result = await server.make_request(data)
return result
async def getServerDescription() -> str:
"""
This function will get the description of the server.
Original: [getServerDescription](https://gothicmultiplayerteam.gitlab.io/docs/0.3.0/script-reference/server-functions/game/getServerDescription/)
## Declaration
```python
async def getServerDescription() -> str
```
## Returns
`str`: Server description.
"""
data = f'return {get_call_repr()}'
server = await PythonWebsocketServer.get_server()
result = await server.make_request(data)
return result
async def getServerWorld() -> str:
"""
The function is used to get the path of the default world on the server.
Original: [getServerWorld](https://gothicmultiplayerteam.gitlab.io/docs/0.3.0/script-reference/server-functions/game/getServerWorld/)
## Declaration
```python
async def getServerWorld() -> str
```
## Returns
`str`: The world path name.
"""
data = f'return {get_call_repr()}'
server = await PythonWebsocketServer.get_server()
result = await server.make_request(data)
return result
async def getTime() -> dict:
"""
The function is used to get the path of the default world on the server.
Original: [getTime](https://gothicmultiplayerteam.gitlab.io/docs/0.3.0/script-reference/server-functions/game/getTime/)
## Declaration
```python
async def getTime() -> dict
```
## Returns
`dict {day, hour, min}`: The current time in the game.
"""
data = f'return {get_call_repr()}'
server = await PythonWebsocketServer.get_server()
result = await server.make_request(data)
return result
async def serverLog(text : str):
"""
This function will log the text into server.log file.
Original: [serverLog](https://gothicmultiplayerteam.gitlab.io/docs/0.3.0/script-reference/server-functions/game/serverLog/)
## Declaration
```python
async def serverLog(text : str)
```
## Parameters
`str` **text**: the text message that you want to append to server.log file.
"""
data = f'return {get_call_repr()}'
server = await PythonWebsocketServer.get_server()
result = await server.make_request(data)
return result
async def setDayLength(miliseconds : float):
"""
!!! note
Day length can't be smaller than 10 000 miliseconds.
This function will set the day length in miliseconds.
Original: [setDayLength](https://gothicmultiplayerteam.gitlab.io/docs/0.3.0/script-reference/server-functions/game/setDayLength/)
## Declaration
```python
async def setDayLength(miliseconds : float)
```
## Parameters
`float` **miliseconds**: day length in miliseconds.
"""
data = f'return {get_call_repr()}'
server = await PythonWebsocketServer.get_server()
result = await server.make_request(data)
return result
async def setServerDescription(description : str):
"""
This function will set the description of the server.
Original: [setServerDescription](https://gothicmultiplayerteam.gitlab.io/docs/0.3.0/script-reference/server-functions/game/setServerDescription/)
## Declaration
```python
async def setServerDescription(description : str)
```
## Parameters
`str` **description**: the server description.
## Returns
`bool`: `true` if server description was set successfully, otherwise `false`.
"""
data = f'return {get_call_repr()}'
server = await PythonWebsocketServer.get_server()
result = await server.make_request(data)
return result
async def setServerWorld(world : str):
"""
!!! note
The server world limit is set to 32 characters.
!!! note
If the target world path is written with backslashes instead of normal slashes, you need to escape it with another backslashes e.g. "NEWWORLD\\NEWWORLD.ZEN".
This function will change the default world to which players will enter after joining.
Original: [setServerWorld](https://gothicmultiplayerteam.gitlab.io/docs/0.3.0/script-reference/server-functions/game/setServerWorld/)
## Declaration
```python
async def setServerWorld(world : str)
```
## Parameters
`str` **world**: the path to the target world.
"""
data = f'return {get_call_repr()}'
server = await PythonWebsocketServer.get_server()
result = await server.make_request(data)
return result
async def setTime(hour : int, min : int, day : int = 0):
"""
This function will set the current time in the game to the given time, for all the players.
Original: [setTime](https://gothicmultiplayerteam.gitlab.io/docs/0.3.0/script-reference/server-functions/game/setTime/)
## Declaration
```python
async def setTime(hour : int, min : int, day : int = 0)
```
## Parameters
`int` **hour**: the hour of new time (in the range between 0-23).
`int` **min**: the minute of new time (in the range between 0-59).
`int` **day**: the day of new time.
"""
data = f'return {get_call_repr()}'
server = await PythonWebsocketServer.get_server()
result = await server.make_request(data)
return result

View File

@@ -0,0 +1,76 @@
from ..server import PythonWebsocketServer
from ..call_repr import get_call_repr
async def getDistance2d(x1 : float, y1: float, x2 : float, y2 : float) -> float:
"""
This function will get the 2d distance between two points.
Original: [getDistance2d](https://gothicmultiplayerteam.gitlab.io/docs/0.3.0/script-reference/shared-functions/math/getDistance2d/)
## Declaration
```python
async def getDistance2d(x1 : float, y1: float, x2 : float, y2 : float) -> float
```
## Parameters
* `float` **x1**: the position on X axis of the first point.
* `float` **y1**: the position on Y axis of the first point.
* `float` **x2**: the position on X axis of the second point.
* `float` **y2**: the position on Y axis of the second point.
## Returns
`float`: Returns the calculated 2d distance between two points as floating point number.
"""
data = f'return {get_call_repr()}'
server = await PythonWebsocketServer.get_server()
result = await server.make_request(data)
return result
async def getDistance3d(x1 : float, y1: float, z1 : float, x2 : float, y2 : float, z2 : float) -> float:
"""
This function will get the 3d distance between two points.
Original: [getDistance3d](https://gothicmultiplayerteam.gitlab.io/docs/0.3.0/script-reference/shared-functions/math/getDistance3d/)
## Declaration
```python
async def getDistance3d(x1 : float, y1: float, z1 : float, x2 : float, y2 : float, z2 : float) -> float
```
## Parameters
* `float` **x1**: the position on X axis of the first point.
* `float` **y1**: the position on Y axis of the first point.
* `float` **z1**: the position on Z axis of the first point.
* `float` **x2**: the position on X axis of the second point.
* `float` **y2**: the position on Y axis of the second point.
* `float` **z2**: the position on Z axis of the second point.
## Returns
`float`: Returns the calculated 3d distance between two points as floating point number.
"""
data = f'return {get_call_repr()}'
server = await PythonWebsocketServer.get_server()
result = await server.make_request(data)
return result
async def getVectorAngle(x1 : float, y1: float, x2 : float, y2 : float) -> float:
"""
This function will get angle on Y axis directed towards the second point.
Original: [getVectorAngle](https://gothicmultiplayerteam.gitlab.io/docs/0.3.0/script-reference/shared-functions/math/getVectorAngle/)
## Declaration
```python
async def getVectorAngle(x1 : float, y1: float, x2 : float, y2 : float) -> float
```
## Parameters
* `float` **x1**: the position on X axis of the first point.
* `float` **y1**: the position on Y axis of the first point.
* `float` **x2**: the position on X axis of the second point.
* `float` **y2**: the position on Y axis of the second point.
## Returns
`float`: Returns the angle on Y axis directed towards the second point.
"""
data = f'return {get_call_repr()}'
server = await PythonWebsocketServer.get_server()
result = await server.make_request(data)
return result

308
src/pyg2o/functions/npc.py Normal file
View File

@@ -0,0 +1,308 @@
from ..server import PythonWebsocketServer
from ..call_repr import get_call_repr
async def clearNpcActions(npc_id : int):
"""
This function clears remote NPC actions queue. Remote NPCs uses actions queue to execute thier tasks.
Original: [clearNpcActions](https://gothicmultiplayerteam.gitlab.io/docs/0.3.0/script-reference/server-functions/npc/clearNpcActions/)
## Declaration
```python
async def clearNpcActions(npc_id : int)
```
## Parameters
`int` **npc_id**: the npc identifier.
"""
data = f'return {get_call_repr()}'
server = await PythonWebsocketServer.get_server()
result = await server.make_request(data)
return result
async def createNpc(name : str, instance : str = 'PC_HERO') -> int:
"""
!!! note
By default npcs won't be added to world. In order to do that, you have to call [spawnPlayer](../player/spawnPlayer.md).
!!! note
Remote NPC id will always begins from max slots value.
This function creates remote NPC.
Original: [createNpc](https://gothicmultiplayerteam.gitlab.io/docs/0.3.0/script-reference/server-functions/npc/createNpc/)
## Declaration
```python
async def createNpc(name : str, instance : str = 'PC_HERO') -> int
```
## Parameters
`str` **name**: the displayed name of the npc.
`str` **instance**: the instance name of for the npc.
"""
data = f'return {get_call_repr()}'
server = await PythonWebsocketServer.get_server()
result = await server.make_request(data)
return result
async def destroyNpc(npc_id : int) -> bool:
"""
This function destroys remote NPC.
Original: [destroyNpc](https://gothicmultiplayerteam.gitlab.io/docs/0.3.0/script-reference/server-functions/npc/destroyNpc/)
## Declaration
```python
async def destroyNpc(npc_id : int) -> bool
```
## Parameters
`int` **npc_id**: the identifier of npc.
## Returns
`bool`: `true` when npc was successfully destroyed, otherwise false`.
"""
data = f'return {get_call_repr()}'
server = await PythonWebsocketServer.get_server()
result = await server.make_request(data)
return result
async def getNpcAction(npc_id : int, index : int) -> dict:
"""
This function gets information about element on specified index in NPC action queue.
Original: [getNpcAction](https://gothicmultiplayerteam.gitlab.io/docs/0.3.0/script-reference/server-functions/npc/getNpcAction/)
## Declaration
```python
async def getNpcAction(npc_id : int, index : int) -> dict
```
## Parameters
`int` **npc_id**: the identifier of npc.
`int` **index**: the index of element in the queue.
## Returns
`dict {type, id, status}`: The table containing information about selected element.
"""
data = f'return {get_call_repr()}'
server = await PythonWebsocketServer.get_server()
result = await server.make_request(data)
return result
async def getNpcActions(npc_id : int) -> list:
"""
This function gets informations about elements in NPC action queue.
Original: [getNpcActions](https://gothicmultiplayerteam.gitlab.io/docs/0.3.0/script-reference/server-functions/npc/getNpcActions/)
## Declaration
```python
async def getNpcActions(npc_id : int) -> list
```
## Parameters
`int` **npc_id**: the identifier of npc.
## Returns
`list [{type, id}]`: The array containing information about queue elements.
"""
data = f'return {get_call_repr()}'
server = await PythonWebsocketServer.get_server()
result = await server.make_request(data)
return result
async def getNpcActionsCount(npc_id : int) -> int:
"""
This function gets elements count in NPC action queue.
Original: [getNpcActionsCount](https://gothicmultiplayerteam.gitlab.io/docs/0.3.0/script-reference/server-functions/npc/getNpcActionsCount/)
## Declaration
```python
async def getNpcActionsCount(npc_id : int) -> int
```
## Parameters
`int` **npc_id**: the identifier of npc.
## Returns
`int`: The count of elements inside queue, otherwise `-1`.
"""
data = f'return {get_call_repr()}'
server = await PythonWebsocketServer.get_server()
result = await server.make_request(data)
return result
async def getNpcHostPlayer(npc_id : int) -> int:
"""
This function gets NPC host player id.
Original: [getNpcHostPlayer](https://gothicmultiplayerteam.gitlab.io/docs/0.3.0/script-reference/server-functions/npc/getNpcHostPlayer/)
## Declaration
```python
async def getNpcHostPlayer(npc_id : int) -> int
```
## Parameters
`int` **npc_id**: the identifier of npc.
## Returns
`int`: the host player identifier. If there is no host player `-1` is returned instead.
"""
data = f'return {get_call_repr()}'
server = await PythonWebsocketServer.get_server()
result = await server.make_request(data)
return result
async def getNpcLastActionId(npc_id : int) -> int:
"""
This function gets last action identifier, that was enqued to the NPC action queue. Every action in queue has associated unique id, by which can be identified.
Original: [getNpcLastActionId](https://gothicmultiplayerteam.gitlab.io/docs/0.3.0/script-reference/server-functions/npc/getNpcLastActionId/)
## Declaration
```python
async def getNpcLastActionId(npc_id : int) -> int
```
## Parameters
`int` **npc_id**: the identifier of npc.
## Returns
`int`: The last finished action identifier, otherwise `-1`.
"""
data = f'return {get_call_repr()}'
server = await PythonWebsocketServer.get_server()
result = await server.make_request(data)
return result
async def isNpc(npc_id : int) -> bool:
"""
This function checks whether id related to given object is remote NPC.
Original: [isNpc](https://gothicmultiplayerteam.gitlab.io/docs/0.3.0/script-reference/server-functions/npc/isNpc/)
## Declaration
```python
async def isNpc(npc_id : int) -> bool
```
## Parameters
`int` **npc_id**: the identifier of npc.
## Returns
`bool`: `true` when object is NPC, otherwise `false`.
"""
data = f'return {get_call_repr()}'
server = await PythonWebsocketServer.get_server()
result = await server.make_request(data)
return result
async def isNpcActionFinished(npc_id : int, action_id : int) -> bool:
"""
This function checks whether specified NPC action was finished.
Original: [isNpcActionFinished](https://gothicmultiplayerteam.gitlab.io/docs/0.3.0/script-reference/server-functions/npc/isNpcActionFinished/)
## Declaration
```python
async def isNpcActionFinished(npc_id : int, action_id : int) -> bool
```
## Parameters
`int` **npc_id**: the identifier of npc.
`int` **action_id**: the unique action identifier.
## Returns
`bool`: `true` if specified action identifier was already finished, otherwise `false`.
"""
data = f'return {get_call_repr()}'
server = await PythonWebsocketServer.get_server()
result = await server.make_request(data)
return result
async def npcAttackMelee(attacker_id : int, enemy_id : int, attack_type : int, combo : int):
"""
!!! note
Combo is internal Gothic value. Its behaviour can be sometimes undefined. For example -1 value doesn't work for not humanoid NPCs.
This function enqueues attack melee action to the remote NPC action queue.
Original: [npcAttackMelee](https://gothicmultiplayerteam.gitlab.io/docs/0.3.0/script-reference/server-functions/npc/npcAttackMelee/)
## Declaration
```python
async def npcAttackMelee(attacker_id : int, enemy_id : int, attack_type : int, combo : int)
```
## Parameters
`int` **attacker_id**: the remote npc id.
`int` **enemy_id**: the remote npc or player id.
`int` **attack_type**: the type of attack.
`int` **combol**: the combo sequence. For `-1` execute next command immediately.
"""
data = f'return {get_call_repr()}'
server = await PythonWebsocketServer.get_server()
result = await server.make_request(data)
return result
async def npcAttackRanged(attacker_id : int, enemy_id : int):
"""
This function enqueues attack ranged action to the remote NPC action queue.
Original: [npcAttackRanged](https://gothicmultiplayerteam.gitlab.io/docs/0.3.0/script-reference/server-functions/npc/npcAttackRanged/)
## Declaration
```python
async def npcAttackRanged(attacker_id : int, enemy_id : int)
```
## Parameters
`int` **attacker_id**: the remote npc id.
`int` **enemy_id**: the remote npc or player id.
"""
data = f'return {get_call_repr()}'
server = await PythonWebsocketServer.get_server()
result = await server.make_request(data)
return result
async def npcSpellCast(attacker_id : int, enemy_id : int):
"""
This function enqueues spell cast action to the remote NPC action queue.
Original: [npcSpellCast](https://gothicmultiplayerteam.gitlab.io/docs/0.3.0/script-reference/server-functions/npc/npcSpellCast/)
## Declaration
```python
async def npcSpellCast(attacker_id : int, enemy_id : int)
```
## Parameters
`int` **attacker_id**: the remote npc id.
`int` **enemy_id**: the remote npc or player id.
"""
data = f'return {get_call_repr()}'
server = await PythonWebsocketServer.get_server()
result = await server.make_request(data)
return result
async def npcUseClosestMob(npc_id : int, sceme : str, target_state : int):
"""
This function enqueues use closest mob action to the remote NPC action queue.
Original: [npcUseClosestMob](https://gothicmultiplayerteam.gitlab.io/docs/0.3.0/script-reference/server-functions/npc/npcUseClosestMob/)
## Declaration
```python
async def npcUseClosestMob(npc_id : int, sceme : str, target_state : int)
```
## Parameters
`int` **npc_id**: the npc identifier.
`str` **sceme**: the animation sceme name, e.g: `"BENCH"` when you want to interact with bench.
`int` **target_state**: the target state, use `1` if you want to start interaction and `-1` to end it.
"""
data = f'return {get_call_repr()}'
server = await PythonWebsocketServer.get_server()
result = await server.make_request(data)
return result
async def setNpcHostPlayer(npc_id : int, host_id : int) -> bool:
"""
This function sets new NPC host player.
Original: [setNpcHostPlayer](https://gothicmultiplayerteam.gitlab.io/docs/0.3.0/script-reference/server-functions/npc/setNpcHostPlayer/)
## Declaration
```python
async def setNpcHostPlayer(npc_id : int, host_id : int) -> bool
```
## Parameters
`int` **npc_id**: the npc identifier.
`int` **host_id**: the player host identifier.
## Returns
`bool`: `true` if host was successfully changed, otherwise `false`.
"""
data = f'return {get_call_repr()}'
server = await PythonWebsocketServer.get_server()
result = await server.make_request(data)
return result

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,65 @@
from ..server import PythonWebsocketServer
from ..call_repr import get_call_repr
async def findNearbyPlayers(position : dict, radius : int, world : str, virtual_world : int = 0) -> list:
"""
This function will search for nearest players, that matches given query arguments.
Original: [findNearbyPlayers](https://gothicmultiplayerteam.gitlab.io/docs/0.3.0/script-reference/server-functions/streamer/findNearbyPlayers/)
## Declaration
```python
async def findNearbyPlayers(position : dict, radius : int, world : str, virtual_world : int = 0) -> list
```
## Parameters
`dict {x, y, z}` **position**: the centroid position.
`int` **radius**: the maximum radius to search from centroid.
`str` **world**: the world used to find players.
`int` **virtual_world**: the virtual world used to find players.
## Returns
`list [int]`: ids of nearby players.
"""
data = f'return {get_call_repr()}'
server = await PythonWebsocketServer.get_server()
result = await server.make_request(data)
return result
async def getSpawnedPlayersForPlayer(id : int) -> list:
"""
This function is used to retrieve currently spawned players for given player.
Original: [getSpawnedPlayersForPlayer](https://gothicmultiplayerteam.gitlab.io/docs/0.3.0/script-reference/server-functions/streamer/getSpawnedPlayersForPlayer/)
## Declaration
```python
async def getSpawnedPlayersForPlayer(id : int) -> list
```
## Parameters
`int` **id**: the player id.
## Returns
`list [int]`: ids of spawned players.
"""
data = f'return {get_call_repr()}'
server = await PythonWebsocketServer.get_server()
result = await server.make_request(data)
return result
async def getStreamedPlayersByPlayer(id : int) -> list:
"""
This function is used to retrieve currently streamed players by given player. More details: Streamed players are basically clients, that has spawned given player in their game. Please notice, that player can be spawned only one way. Which means that there are situation were player 1 is spawned for player 2, but not the other way arount. Simple examples: - Invisible players cannot be seen, but they can see everyone nearby. - Flying around world using camera.
Original: [getStreamedPlayersByPlayer](https://gothicmultiplayerteam.gitlab.io/docs/0.3.0/script-reference/server-functions/streamer/getStreamedPlayersByPlayer/)
## Declaration
```python
async def getStreamedPlayersByPlayer(id : int) -> list
```
## Parameters
`int` **id**: the player id.
## Returns
`list [int]`: ids of streamed players.
"""
data = f'return {get_call_repr()}'
server = await PythonWebsocketServer.get_server()
result = await server.make_request(data)
return result

View File

@@ -0,0 +1,46 @@
from ..server import PythonWebsocketServer
from ..call_repr import get_call_repr
async def getNearestWaypoint(world : str, x : int, y : int, z : int) -> dict:
"""
This function is used to retrieve the information about nearest waypoint from the specified position.
Original: [getNearestWaypoint](https://gothicmultiplayerteam.gitlab.io/docs/0.3.0/script-reference/server-functions/waypoint/getNearestWaypoint/)
## Declaration
```python
async def getNearestWaypoint(world : str, x : int, y : int, z : int) -> dict
```
## Parameters
`str` **world**: the world name in which the waypoint exists.
`int` **x**: the position in the world on the x axis.
`int` **y**: the position in the world on the y axis.
`int` **z**: the position in the world on the z axis.
## Returns
`dict {name, x, y, z}`: Waypoint information.
"""
data = f'return {get_call_repr()}'
server = await PythonWebsocketServer.get_server()
result = await server.make_request(data)
return result
async def getWaypoint(world : str, name : str) -> dict:
"""
This function is used to retrieve the position of specified waypoint.
Original: [getWaypoint](https://gothicmultiplayerteam.gitlab.io/docs/0.3.0/script-reference/server-functions/waypoint/getWaypoint/)
## Declaration
```python
async def getWaypoint(world : str, name : str) -> dict
```
## Parameters
`str` **world**: the world name in which the waypoint exists.
`str` **name**: the name of the waypoint.
## Returns
`dict {x, y, z}`: The position of waypoint.
"""
data = f'return {get_call_repr()}'
server = await PythonWebsocketServer.get_server()
result = await server.make_request(data)
return result

14
src/pyg2o/serialize.py Normal file
View File

@@ -0,0 +1,14 @@
def _deserialize(className, data):
from .classes.damage import DamageDescription
from .classes.items import ItemGround
className = className[4:]
new_cls = None
if className == 'DamageDescription':
new_cls = DamageDescription()
elif className == 'ItemGround':
new_cls = ItemGround()
new_cls._initialize(**data)
return new_cls

126
src/pyg2o/server.py Normal file
View File

@@ -0,0 +1,126 @@
import websockets
import asyncio
import logging
import json
import uuid
from typing import Optional
from .constants import Constant
from .functions.event import callEvent
from .serialize import _deserialize
class PythonWebsocketServer:
_current_server = None
def __init__(self, host: str, port: int, whitelist: list[str], ping_interval: int = 30, silent: bool = False):
self.host: str = host
self.port: int = port
self.ping_interval: int = ping_interval
self.whitelist = whitelist
self.silent = silent
self.requests_list: dict[str, asyncio.Future] = dict()
self._stop_event: asyncio.Event = asyncio.Event()
self.connected_socket: Optional[websockets.ClientConnection] = None
@classmethod
async def get_server(cls):
return cls._current_server
async def start(self):
async with websockets.serve(
self.handle_connection,
host=self.host,
port=self.port,
ping_interval=self.ping_interval,
):
logging.info(f'[PyG2O] Server is started at ws://{self.host}:{self.port}')
PythonWebsocketServer._current_server = self
await self._stop_event.wait()
async def stop(self):
PythonWebsocketServer._current_server = None
self.connected_socket = None
self._stop_event.set()
async def make_request(self, data: str):
if (self.connected_socket is None):
return None
request_id = str(uuid.uuid4())
self.requests_list[request_id] = asyncio.get_running_loop().create_future()
request = {
'uuid': request_id,
'args': data,
}
request = json.dumps(request)
formatted_request = request.replace("'", '\\"')
formatted_request = formatted_request.replace("False", 'false')
formatted_request = formatted_request.replace("True", 'true')
await self.connected_socket.send(formatted_request)
result = await asyncio.wait_for(
self.requests_list[request_id],
timeout=30
)
return result
async def handle_connection(self, websocket: websockets.ClientConnection):
if (websocket.remote_address[0] not in self.whitelist or self.connected_socket is not None):
await websocket.close(4000, 'Connection denied')
return
self.connected_socket = websocket
self.is_connected = websocket
if (not self.silent):
logging.info(f'Client connected: {websocket.remote_address}')
asyncio.create_task(callEvent('onWebsocketConnect', **{}))
try:
async for message in websocket:
message_json = json.loads(message)
# Deserializing objects
if ('args' in message_json):
formatted_args = dict()
for key, value in message_json['args'].items():
if not key.startswith('obj_'):
formatted_args[key] = value
continue
formatted_args[value['name']] = _deserialize(key, value['data'])
message_json['args'] = formatted_args
# Processing events
if ('event' in message_json):
asyncio.create_task(callEvent(message_json['event'], **formatted_args))
continue
# Processing requests from Squirrel side
if ('type' in message_json):
Constant._update(message_json['args'])
continue
# Processing made requests
if (
'uuid' in message_json and
message_json['uuid'] in self.requests_list.keys()
):
self.requests_list[message_json['uuid']].set_result(next(iter(message_json['args'].values())))
except json.JSONDecodeError as e:
logging.exception(f'[PyG2O] JSON Exception: {e}')
except Exception as e:
logging.exception(f'[PyG2O] Exception: {e}')
finally:
if (not self.silent):
logging.info('Client disconnected')
self.is_connected = None
self.connected_socket = None
asyncio.create_task(callEvent('onWebsocketDisconnect', **{}))