diff --git a/.github/workflows/python-ci.yml b/.github/workflows/python-ci.yml
new file mode 100644
index 00000000..8e115dda
--- /dev/null
+++ b/.github/workflows/python-ci.yml
@@ -0,0 +1,24 @@
+# This workflow will install Python dependencies, run tests and lint with a single version of Python
+# For more information see: https://help.github.com/actions/language-and-framework-guides/using-python-with-github-actions
+
+name: Python CI
+
+on: [push, fork, pull_request]
+
+jobs:
+ build:
+
+ runs-on: ubuntu-latest
+
+ steps:
+ - uses: actions/checkout@v4
+ - name: Set up uv
+ uses: astral-sh/setup-uv@v5
+ with:
+ python-version: "3.12"
+ - name: Install dependencies
+ run: uv sync
+ - name: Lint with ruff
+ run: uv run ruff check .
+ - name: Run tests
+ run: uv run pytest
diff --git a/.github/workflows/pythonapp.yml b/.github/workflows/pythonapp.yml
deleted file mode 100644
index 94052e6c..00000000
--- a/.github/workflows/pythonapp.yml
+++ /dev/null
@@ -1,29 +0,0 @@
-# This workflow will install Python dependencies, run tests and lint with a single version of Python
-# For more information see: https://help.github.com/actions/language-and-framework-guides/using-python-with-github-actions
-
-name: Python lint
-
-on: [push, fork, pull_request]
-
-jobs:
- build:
-
- runs-on: ubuntu-latest
-
- steps:
- - uses: actions/checkout@v2
- - name: Set up Python 3.12
- uses: actions/setup-python@v1
- with:
- python-version: 3.12
- - name: Install dependencies
- run: |
- python -m pip install --upgrade pip
- pip install -r requirements.txt
- - name: Lint with flake8
- run: |
- pip install flake8
- # stop the build if there are Python syntax errors or undefined names
- flake8 . --count --select=E9,F63,F7,F82 --show-source --statistics
- # exit-zero treats all errors as warnings. The GitHub editor is 127 chars wide
- flake8 . --count --exit-zero --max-complexity=10 --max-line-length=127 --statistics
diff --git a/.travis.yml b/.travis.yml
deleted file mode 100644
index e01b74c2..00000000
--- a/.travis.yml
+++ /dev/null
@@ -1,14 +0,0 @@
-language: python
-python:
- - "3.11"
-stages:
- - execute
-
-install:
- - pip install -r requirements.txt
-
-jobs:
- include:
- - stage: execute
- name: "Starting the Server"
- script: python start_server.py
\ No newline at end of file
diff --git a/Dockerfile b/Dockerfile
index 62aeb953..69286257 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -4,12 +4,14 @@ RUN apk --no-cache add git
WORKDIR /app
-COPY requirements.txt start_server.py ./
-RUN pip install --upgrade pip
-RUN pip install -r requirements.txt
+COPY --from=ghcr.io/astral-sh/uv:latest /uv /uvx /bin/
+
+COPY pyproject.toml uv.lock ./
+RUN uv sync --frozen --no-dev --no-install-project
COPY server/ server/
COPY migrations/ migrations/
COPY storage/ storage/
+COPY start_server.py ./
-CMD python ./start_server.py
+CMD ["uv", "run", "python", "./start_server.py"]
diff --git a/README.md b/README.md
index 9e894f6a..fbec2249 100644
--- a/README.md
+++ b/README.md
@@ -3,6 +3,42 @@
KFO-Server is the official Python-based server for Attorney Online, forked from tsuserver3.
+If you are looking to use KFO-Server to set up a server, see [Server setup](#server-setup) below.
+
+## Development setup
+
+To set up KFO-Server for development, follow these instructions.
+
+First, install dependencies:
+
+```bash
+uv sync
+```
+
+Then you can run the server using uv:
+
+```bash
+uv run python start_server.py
+```
+
+### Run linter
+
+```(bash)
+uv run ruff check .
+```
+
+### Run tests
+
+```(bash)
+uv run tox
+```
+
+### Run formatter
+
+```(bash)
+uv run ruff format .
+```
+
## Server setup
In order to set up the server, you must follow these instructions. This assumes you are familiar with using a terminal.
@@ -22,42 +58,21 @@ If you don't want to use Git, you can download the latest zip of KFO-Server [her
### Install dependencies
-In order to install dependencies, you will need to open a terminal.
-
-On Windows, you can do this by pressing Win+R, typing in `cmd`, and pressing Enter.
-On Linux, you can do this by pressing Ctrl+Alt+T.
-
-You should then navigate to the folder where the server is located.
-
-Take note that depending on your operating system, the command for python may be python3 or python.
-You should also verify the version by running `python --version` or `python3 --version`.
-
-First, we need to create the virtual environment. This can be done by running the following command:
+Install [uv](https://docs.astral.sh/uv/getting-started/installation/), then run:
```bash
-python -m venv venv
+uv sync
```
-Then, we need to activate the virtual environment.
-If you're on a unix system (bash or similar), you can run the following command:
-
-```bash
-./venv/bin/pip install -r requirements.txt
-```
-
-If you're on Windows (cmd), you may have to do this instead:
-
-```batch
-venv\Scripts\pip install -r requirements.txt
-```
+This will create a virtual environment and install all dependencies.
-### Configure tsuserver
+### Configure KFO-Server
* Copy `config_sample` to `config`
* Edit the values in the `.yaml` files to your liking.
* Be sure to check your YAML file for syntax errors. Use this website:
* *Use spaces only; do not use tabs.*
-* You don't need to copy characters into the `characters` folder *unless* you specifically chose to disable iniswapping in an area (in `areas.yaml`). In this case, all tsuserver needs to know is the `char.ini` of each character. It doesn't need sprites.
+* You don't need to copy characters into the `characters` folder *unless* you specifically chose to disable iniswapping in an area (in `areas.yaml`). In this case, all KFO-Server needs to know is the `char.ini` of each character. It doesn't need sprites.
### Run
@@ -70,7 +85,7 @@ To stop the server, press Ctrl+C in the terminal.
You can also use docker to run KFO-server. First you need to install [Docker](https://get.docker.com/) and [Docker Compose](https://docs.docker.com/compose/install/).
-Once you have everything configured, do `docker-compose up`. It will build the image and start tsuserver up for you. If you accidentally restart the server, the container will automatically start back up. If you're not understanding why it's starting, try starting it up manually:
+Once you have everything configured, do `docker-compose up`. It will build the image and start KFO-Server up for you. If you accidentally restart the server, the container will automatically start back up. If you're not understanding why it's starting, try starting it up manually:
## Pro Tips
@@ -82,6 +97,6 @@ Once you have everything configured, do `docker-compose up`. It will build the i
## License
-This server is licensed under the AGPLv3 license. In short, if you use a modified version of tsuserver3, you *must* distribute its source licensed under the AGPLv3 as well, and notify your users where the modified source may be found. The main difference between the AGPL and the GPL is that for the AGPL, network use counts as distribution. If you do not accept these terms, you should use [serverD](https://github.com/Attorney-Online-Engineering-Task-Force/serverD), which uses GPL rather than AGPL.
+This server is licensed under the AGPLv3 license. In short, if you use a modified version of KFO-Server, you *must* distribute its source licensed under the AGPLv3 as well, and notify your users where the modified source may be found. The main difference between the AGPL and the GPL is that for the AGPL, network use counts as distribution. If you do not accept these terms, you should use [serverD](https://github.com/Attorney-Online-Engineering-Task-Force/serverD), which uses GPL rather than AGPL.
See the [LICENSE](LICENSE.md) file for more information.
diff --git a/config_sample/config.yaml b/config_sample/config.yaml
index 6ee25318..70f4052e 100644
--- a/config_sample/config.yaml
+++ b/config_sample/config.yaml
@@ -48,14 +48,14 @@ websocket_port: 50001
# Whether the server is open to secure websocket connections
use_securewebsockets: false
-# Port that is advertised to the masterserver for WSS connections (KFO-Server does not accept SSL directly)
+# Port advertised to the masterserver for WSS connections (KFO-Server does not accept SSL directly)
secure_websocket_port: 443
# WebAO Asset URL for hosting files. Leave blank to use vanilla
asset_url:
# Whether the server should be advertised on the server list.
-use_masterserver: true
+use_masterserver: false
# How the server should be listed on the server list.
masterserver_name: My First Server
masterserver_description: This is my flashy new server
diff --git a/docker-compose.yml b/docker-compose.yml
index 6dce6734..150be54d 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -1,8 +1,7 @@
-version: "3.3"
services:
- tsuserver:
+ kfo-server:
build: .
- image: tsuserver
+ image: kfo-server
ports:
- 27016:27016
- 50001:50001
diff --git a/pyproject.toml b/pyproject.toml
index 753cf096..73f92a46 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -1,5 +1,48 @@
-[tool.black]
+[project]
+name = "kfo-server"
+version = "0.1.0"
+description = "KFO Attorney Online Server"
+readme = "README.md"
+requires-python = ">=3.11"
+dependencies = [
+ "aiohttp>=3.13.2",
+ "arrow>=1.3.0",
+ "discord.py>=2.5.2",
+ "ruff",
+ "geoip2>=4.7.0",
+ "oyaml>=1.0",
+ "pystun3>=1.0.0",
+ "pytest",
+ "PyYAML>=6.0.1",
+ "requests>=2.31.0",
+ "timeparse-plus>=1.2.0",
+ "tox>=4",
+ "websockets>=12.0",
+]
+
+[build-system]
+requires = ["setuptools>=61.0"]
+build-backend = "setuptools.build_meta"
+
+[tool.setuptools]
+packages = ["server"]
+
+[tool.ruff]
line-length = 120
-target-version = ["py311"]
-# You can add patterns here if you need to exclude generated files, etc.
-# extend-exclude = []
+target-version = "py311"
+# Exclude utility scripts from linting
+exclude = ["scripts/"]
+
+[tool.ruff.format]
+quote-style = "double"
+indent-style = "space"
+skip-magic-trailing-comma = false
+
+[tool.ruff.lint]
+# E741: Ambiguous variable name (e.g., 'l') - used intentionally in list comprehensions
+ignore = ["E741"]
+
+[tool.ruff.lint.per-file-ignores]
+# E402: Module level import not at top of file - imports must come after __all__ definitions
+# F403: Star imports - intentional for re-exporting command modules
+"server/commands/__init__.py" = ["E402", "F403"]
diff --git a/requirements.txt b/requirements.txt
deleted file mode 100644
index d9593f29..00000000
--- a/requirements.txt
+++ /dev/null
@@ -1,24 +0,0 @@
-aiohttp==3.13.2
-aiosignal==1.4.0
-arrow==1.3.0
-async-timeout==4.0.3
-attrs==23.1.0
-certifi==2023.7.22
-charset-normalizer==3.3.2
-discord.py==2.5.2
-frozenlist==1.6.0
-geoip2==4.7.0
-idna==3.4
-maxminddb==2.5.1
-multidict==6.4.3
-oyaml==1.0
-pystun3==1.0.0
-python-dateutil==2.8.2
-PyYAML==6.0.1
-requests==2.31.0
-six==1.16.0
-timeparse-plus==1.2.0
-types-python-dateutil==2.8.19.14
-urllib3==2.1.0
-websockets==12.0
-yarl==1.20.0
diff --git a/scripts/music2yaml.py b/scripts/music2yaml.py
index 1ba69615..34f42f69 100644
--- a/scripts/music2yaml.py
+++ b/scripts/music2yaml.py
@@ -2,8 +2,6 @@
import os
import sys
-from shutil import copy2
-
os.chdir(os.path.dirname(__file__))
arg = ""
@@ -24,9 +22,7 @@
" use_unique_folder: True #If true, this music will be contained entirely within its own folder e.g. base/music//*.mp3\n"
)
if droppedFile:
- input(
- "Writing .ogg and .mp3 and categorizing them based on file argument to music.yaml. Press ENTER to begin."
- )
+ input("Writing .ogg and .mp3 and categorizing them based on file argument to music.yaml. Press ENTER to begin.")
for line in droppedFile.readlines():
try:
line = line.rstrip()
@@ -42,18 +38,12 @@
# tag = TinyTag.get(line)
# duration = tag.duration
duration = -1
- File.write(
- ' - name: "{}"\n'.format(current_category + "/" + line)
- )
+ File.write(' - name: "{}"\n'.format(current_category + "/" + line))
File.write(" length: {}\n".format(duration))
print("Name: {} Length: {}".format(line, duration))
except:
Err.write("Error for {}\n".format(line))
- input(
- "Unable to process song: {}! Press ENTER to continue.".format(
- line
- )
- )
+ input("Unable to process song: {}! Press ENTER to continue.".format(line))
except:
continue
else:
@@ -88,11 +78,7 @@
# tag = TinyTag.get(line)
# duration = tag.duration
duration = -1
- File.write(
- ' - name: "{}"\n'.format(
- current_category + "/" + song.name
- )
- )
+ File.write(' - name: "{}"\n'.format(current_category + "/" + song.name))
File.write(" length: {}\n".format(duration))
print("Name: {} Length: {}".format(song.name, duration))
diff --git a/server/area.py b/server/area.py
index 9c1c5e77..c4832a9d 100644
--- a/server/area.py
+++ b/server/area.py
@@ -57,7 +57,7 @@ def timer_expired(self):
self.static = datetime.timedelta(0)
self.started = False
- self.area.broadcast_ooc(f"Timer {self.id+1} has expired.")
+ self.area.broadcast_ooc(f"Timer {self.id + 1} has expired.")
self.call_commands()
def call_commands(self):
@@ -206,7 +206,7 @@ def __init__(self, area_manager, name):
self.red_team = set()
self.blue_team = set()
# Clients who cast votes
- self.votes_cast = set()
+ self.votes_cast = set()
# What percentage of valid voters needs to vote to force-end the minigame, rounded
self.votes_percentage = 0.7
# Minigame name
@@ -294,7 +294,7 @@ def __init__(self, area_manager, name):
self.auto_pair = False
self.auto_pair_max = "triple"
self.auto_pair_cycle = False
-
+
# list of areas to broadcast ic messages to
self.broadcast_list = []
@@ -307,8 +307,7 @@ def name(self):
def name(self, value):
self._name = value.strip()
while "" in self._name or "" in self._name:
- self._name = self._name.replace(
- "", "").replace("", "")
+ self._name = self._name.replace("", "").replace("", "")
self.abbreviation = self.abbreviate()
@property
@@ -432,7 +431,7 @@ def load(self, area):
self.pos_lock.clear()
for pos in _pos_lock:
pos = pos.lower()
- if pos != "none" and not (pos in self.pos_lock):
+ if pos != "none" and pos not in self.pos_lock:
self.pos_lock.append(pos.lower())
if "evidence_mod" in area:
@@ -557,12 +556,12 @@ def load(self, area):
self.pos_dark = area["pos_dark"]
if "desc_dark" in area:
self.desc_dark = area["desc_dark"]
- if 'passing_msg' in area:
- self.passing_msg = area['passing_msg']
- if 'msg_delay' in area:
- self.msg_delay = area['msg_delay']
- if 'present_reveals_evidence' in area:
- self.present_reveals_evidence = area['present_reveals_evidence']
+ if "passing_msg" in area:
+ self.passing_msg = area["passing_msg"]
+ if "msg_delay" in area:
+ self.msg_delay = area["msg_delay"]
+ if "present_reveals_evidence" in area:
+ self.present_reveals_evidence = area["present_reveals_evidence"]
if "evidence" in area and len(area["evidence"]) > 0:
self.evi_list.evidences.clear()
@@ -592,8 +591,7 @@ def load(self, area):
evidence = value["evidence"]
if "password" in value:
password = value["password"]
- self.link(key, locked, hidden, target_pos,
- can_peek, evidence, password)
+ self.link(key, locked, hidden, target_pos, can_peek, evidence, password)
# Update the clients in that area
if self.dark:
@@ -607,9 +605,7 @@ def load(self, area):
if self.music_autoplay:
for client in self.clients:
if self.music != client.playing_audio[0]:
- client.send_command(
- "MC", self.music, -1, "", self.music_looping, 0, self.music_effects
- )
+ client.send_command("MC", self.music, -1, "", self.music_looping, 0, self.music_effects)
if "can_battle" in area:
self.can_battle = area["can_battle"]
@@ -709,7 +705,7 @@ def play_client_ambience(self, client):
client.send_command(
"area_ambient",
# for compatibility with the KFO method, navigate out of sounds/ambience into sounds/music
- "../music/"+self.ambience,
+ "../music/" + self.ambience,
)
else:
# AO packet
@@ -722,8 +718,7 @@ def play_client_ambience(self, client):
"",
1,
1,
- int(MusicEffect.FADE_OUT |
- MusicEffect.FADE_IN | MusicEffect.SYNC_POS),
+ int(MusicEffect.FADE_OUT | MusicEffect.FADE_IN | MusicEffect.SYNC_POS),
)
def new_client(self, client):
@@ -733,9 +728,7 @@ def new_client(self, client):
database.log_area("area.join", client, self)
if self.music_autoplay and self.music != client.playing_audio[0]:
- client.send_command(
- "MC", self.music, -1, "", self.music_looping, 0, self.music_effects
- )
+ client.send_command("MC", self.music, -1, "", self.music_looping, 0, self.music_effects)
# Update the timers for the client
self.update_timers(client)
@@ -802,8 +795,7 @@ def remove_client(self, client):
# Remove their owner status due to single_cm pref. remove_owner will unlock the area if they were the last CM.
if client in self._owners:
self.remove_owner(client)
- client.send_ooc(
- "You can only be a CM of a single area in this hub.")
+ client.send_ooc("You can only be a CM of a single area in this hub.")
if self.locking_allowed:
# Since anyone can lock/unlock, unlock if we were the last client in this area and it was locked.
if len(self.clients) - 1 <= 0:
@@ -828,7 +820,7 @@ def remove_client(self, client):
else:
self.broadcast_player_list_to_target(client)
- #Battle system
+ # Battle system
if client in client.area.fighters:
if client.area.battle_started:
client.battle.current_client = None
@@ -911,8 +903,7 @@ def unlink(self, target):
try:
del self.links[str(target)]
except KeyError:
- raise AreaError(
- f"Link {target} does not exist in Area {self.name}!")
+ raise AreaError(f"Link {target} does not exist in Area {self.name}!")
def is_char_available(self, char_id):
"""
@@ -927,9 +918,7 @@ def is_char_available(self, char_id):
def get_rand_avail_char_id(self):
"""Get a random available character ID."""
- avail_set = set(range(len(self.area_manager.char_list))) - {
- x.char_id for x in self.clients
- }
+ avail_set = set(range(len(self.area_manager.char_list))) - {x.char_id for x in self.clients}
if len(avail_set) == 0:
raise AreaError("No available characters.")
return random.choice(tuple(avail_set))
@@ -949,11 +938,7 @@ def send_owner_command(self, cmd, *args):
for c in self.owners:
if c in self.clients:
continue
- if (
- c.remote_listen == 3
- or (cmd == "CT" and c.remote_listen == 2)
- or (cmd == "MS" and c.remote_listen == 1)
- ):
+ if c.remote_listen == 3 or (cmd == "CT" and c.remote_listen == 2) or (cmd == "MS" and c.remote_listen == 1):
c.send_command(cmd, *args)
def send_owner_ic(self, bg, cmd, *args):
@@ -981,9 +966,7 @@ def broadcast_ooc(self, msg):
:param msg: message
"""
self.send_command("CT", self.server.config["hostname"], msg, "1")
- self.send_owner_command(
- "CT", f"[{self.id}]" + self.server.config["hostname"], msg, "1"
- )
+ self.send_owner_command("CT", f"[{self.id}]" + self.server.config["hostname"], msg, "1")
def broadcast_action(self, client, msg):
"""
@@ -1002,51 +985,50 @@ def broadcast_action(self, client, msg):
continue
if not c.ooc_actions:
continue
- if (
- c.remote_listen == 3
- or c.remote_listen == 2
- ):
+ if c.remote_listen == 3 or c.remote_listen == 2:
c.send_command(cmd, f"[{self.id}]" + self.server.config["hostname"], msg, "1")
- def send_ic(self,
- client=None,
- msg_type="1",
- pre=0,
- folder="",
- anim="",
- msg="",
- pos="",
- sfx="",
- emote_mod=0,
- cid=-1,
- sfx_delay=0,
- button=0,
- evidence=[0],
- flip=0,
- ding=0,
- color=0,
- showname="",
- charid_pair=-1,
- other_folder="",
- other_emote="",
- offset_pair=0,
- other_offset=0,
- other_flip=0,
- nonint_pre=0,
- sfx_looping="0",
- screenshake=0,
- frames_shake="",
- frames_realization="",
- frames_sfx="",
- additive=0,
- effect="",
- targets=None,
- third_charid=-1,
- third_folder="",
- third_emote=0,
- third_offset="",
- third_flip=0,
- video=""):
+ def send_ic(
+ self,
+ client=None,
+ msg_type="1",
+ pre=0,
+ folder="",
+ anim="",
+ msg="",
+ pos="",
+ sfx="",
+ emote_mod=0,
+ cid=-1,
+ sfx_delay=0,
+ button=0,
+ evidence=[0],
+ flip=0,
+ ding=0,
+ color=0,
+ showname="",
+ charid_pair=-1,
+ other_folder="",
+ other_emote="",
+ offset_pair=0,
+ other_offset=0,
+ other_flip=0,
+ nonint_pre=0,
+ sfx_looping="0",
+ screenshake=0,
+ frames_shake="",
+ frames_realization="",
+ frames_sfx="",
+ additive=0,
+ effect="",
+ targets=None,
+ third_charid=-1,
+ third_folder="",
+ third_emote=0,
+ third_offset="",
+ third_flip=0,
+ video="",
+ ):
"""
Send an IC message from a client to all applicable clients in the area.
:param client: speaker
@@ -1062,22 +1044,17 @@ def send_ic(self,
lst = list(self.testimony[idx])
lst[4] = "}}}" + msg[2:]
self.testimony[idx] = tuple(lst)
- self.broadcast_ooc(
- f"{client.showname} has amended Statement {idx+1}.")
+ self.broadcast_ooc(f"{client.showname} has amended Statement {idx + 1}.")
if not self.recording:
self.testimony_send(idx)
except IndexError:
- client.send_ooc(
- f"Something went wrong, couldn't amend Statement {idx+1}!"
- )
+ client.send_ooc(f"Something went wrong, couldn't amend Statement {idx + 1}!")
return
- adding = msg.strip(
- ) != "" and self.recording and client is not None
+ adding = msg.strip() != "" and self.recording and client is not None
if client and msg.startswith("++") and len(self.testimony) > 0:
if len(self.testimony) >= 30:
- client.send_ooc(
- "Maximum testimony statement amount reached! (30)")
+ client.send_ooc("Maximum testimony statement amount reached! (30)")
return
adding = True
elif client:
@@ -1088,7 +1065,7 @@ def send_ic(self,
target = ""
# message contains an "at" sign aka we're referring to someone specific
if "@" in lwr:
- target = lwr[lwr.find("@") + 1:]
+ target = lwr[lwr.find("@") + 1 :]
try:
opponent = None
target = target.lower()
@@ -1119,8 +1096,7 @@ def send_ic(self,
commands.ooc_cmd_concede(client, "")
# Shouter provided target but no opponent was found
elif target != "" or self.minigame in ["Cross Swords", "Scrum Debate"]:
- raise AreaError(
- "Interjection minigame - target not found!")
+ raise AreaError("Interjection minigame - target not found!")
# Minigame didn't swap as a result of this shout, don't display the shout
if self.minigame != "" and self.minigame == old_minigame:
@@ -1177,23 +1153,17 @@ def send_ic(self,
client.area.last_ic_message is not None
and client.area.last_ic_message[8] == client.char_id
and client.area.last_ic_message[16] != -1
- and int(client.area.last_ic_message[16].split("^")[0])
- in opposing_team
+ and int(client.area.last_ic_message[16].split("^")[0]) in opposing_team
):
# Set the pair to the person who it was last msg
- charid_pair = int(
- client.area.last_ic_message[16].split("^")[0]
- )
+ charid_pair = int(client.area.last_ic_message[16].split("^")[0])
# The person we were trying to find is no longer on the opposing team
else:
# Search through the opposing team's characters
for other_cid in opposing_team:
charid_pair = other_cid
# If last message's charid matches a member of this team, prioritize theirs
- if (
- client.area.last_ic_message is not None
- and other_cid == client.area.last_ic_message[8]
- ):
+ if client.area.last_ic_message is not None and other_cid == client.area.last_ic_message[8]:
break
# If our pair opponent is found
if charid_pair != -1:
@@ -1220,8 +1190,7 @@ def send_ic(self,
or pos != self.last_ic_message[8]
or self.last_ic_message[4].strip() != ""
):
- database.log_area("chat.ic", client,
- client.area, message=msg)
+ database.log_area("chat.ic", client, client.area, message=msg)
if targets is None:
targets = self.clients
@@ -1234,12 +1203,7 @@ def send_ic(self,
continue
# pos doesn't match listen_pos, we're not listening so make this an OOC message instead
if c.area == self and c.listen_pos is not None:
- if (
- type(c.listen_pos) is list
- and not (pos in c.listen_pos)
- or c.listen_pos == "self"
- and pos != c.pos
- ):
+ if type(c.listen_pos) is list and pos not in c.listen_pos or c.listen_pos == "self" and pos != c.pos:
name = ""
if cid != -1:
name = self.area_manager.char_list[cid]
@@ -1248,8 +1212,7 @@ def send_ic(self,
# Send the mesage as OOC.
# Woulda been nice if there was a packet to send messages to IC log
# without displaying it in the viewport.
- c.send_command(
- "CT", f"[pos '{pos}'] {name}", msg)
+ c.send_command("CT", f"[pos '{pos}'] {name}", msg)
continue
# Before we send the message, if our remote_listen is different...
@@ -1259,51 +1222,52 @@ def send_ic(self,
msg_to_send = msg
if c.area != self:
msg_to_send = "}}}[" + str(self.id) + "] {{{" + msg
- c.send_command("MS", msg_type,
- pre,
- folder,
- # if we're in first person mode, treat our msgs as narration
- "" if c == client and client.firstperson else anim,
- msg_to_send,
- pos,
- sfx,
- emote_mod,
- cid,
- sfx_delay,
- button,
- evidence,
- flip,
- ding,
- color,
- showname,
- charid_pair,
- other_folder,
- other_emote,
- offset_pair,
- other_offset,
- other_flip,
- nonint_pre,
- sfx_looping,
- screenshake,
- frames_shake,
- frames_realization,
- frames_sfx,
- additive,
- effect,
- third_charid,
- third_folder,
- third_emote,
- third_offset,
- third_flip,
- video)
+ c.send_command(
+ "MS",
+ msg_type,
+ pre,
+ folder,
+ # if we're in first person mode, treat our msgs as narration
+ "" if c == client and client.firstperson else anim,
+ msg_to_send,
+ pos,
+ sfx,
+ emote_mod,
+ cid,
+ sfx_delay,
+ button,
+ evidence,
+ flip,
+ ding,
+ color,
+ showname,
+ charid_pair,
+ other_folder,
+ other_emote,
+ offset_pair,
+ other_offset,
+ other_flip,
+ nonint_pre,
+ sfx_looping,
+ screenshake,
+ frames_shake,
+ frames_realization,
+ frames_sfx,
+ additive,
+ effect,
+ third_charid,
+ third_folder,
+ third_emote,
+ third_offset,
+ third_flip,
+ video,
+ )
if self.recording:
# See if the testimony is supposed to end here.
scrunched = "".join(e for e in msg if e.isalnum())
if len(scrunched) > 0 and scrunched.lower() == "end":
self.recording = False
- self.broadcast_ooc(
- f"[{client.id}] {client.showname} has ended the testimony."
- )
+ self.broadcast_ooc(f"[{client.id}] {client.showname} has ended the testimony.")
self.send_command("RT", "testimony1", 1)
return
if anim == "" or pos == "":
@@ -1345,19 +1309,18 @@ def send_ic(self,
frames_sfx, # 27
additive, # 28
effect, # 29
- third_charid, # 30
- third_folder, # 31
- third_emote, # 32
- third_offset, # 33
- third_flip, # 34
- video, #35
+ third_charid, # 30
+ third_folder, # 31
+ third_emote, # 32
+ third_offset, # 33
+ third_flip, # 34
+ video, # 35
)
self.last_ic_message = args
if adding:
if len(self.testimony) >= 30:
- client.send_ooc(
- "Maximum testimony statement amount reached! (30)")
+ client.send_ooc("Maximum testimony statement amount reached! (30)")
return
if msg.startswith("++"):
msg = msg[2:]
@@ -1405,12 +1368,12 @@ def send_ic(self,
frames_sfx, # 27
additive, # 28
effect, # 29
- third_charid, # 30
- third_folder, # 31
- third_emote, # 32
- third_offset, # 33
- third_flip, # 34
- video, # 35
+ third_charid, # 30
+ third_folder, # 31
+ third_emote, # 32
+ third_offset, # 33
+ third_flip, # 34
+ video, # 35
)
if idx == -1:
# Add one statement at the very end.
@@ -1420,7 +1383,7 @@ def send_ic(self,
# Add one statement ahead of the one we're currently on.
idx += 1
self.testimony.insert(idx, args)
- self.broadcast_ooc(f"Statement {idx+1} added.")
+ self.broadcast_ooc(f"Statement {idx + 1} added.")
if not self.recording:
self.testimony_send(idx)
@@ -1471,11 +1434,8 @@ def broadcast_player_list(self):
def broadcast_player_list_to_target(self, target):
return_data = {}
- return_data['packet'] = 'player_list'
- special_allowed = (
- target.is_mod
- or target in self.owners
- )
+ return_data["packet"] = "player_list"
+ special_allowed = target.is_mod or target in self.owners
player_data_to_send = list()
player_stuff = list()
if (self.can_getarea and not self.dark) or special_allowed:
@@ -1491,15 +1451,14 @@ def broadcast_player_list_to_target(self, target):
chara_client_info["id"] = str(c.id)
chara_client_info["afk"] = str(c in self.afkers)
- #Append the Showname
+ # Append the Showname
# 1.5
player_stuff.append(str(c.showname))
chara_client_info["showname"] = str(c.showname)
# 1.5.1
-
- #Append the Character Name
+ # Append the Character Name
# 1.5
# if(c.icon_visible):
char_folder = "Spectator"
@@ -1511,7 +1470,7 @@ def broadcast_player_list_to_target(self, target):
# player_stuff.append("")
# chara_client_info["character"] = "NO_CHARA"
- if(target.is_mod):
+ if target.is_mod:
# chara_client_info["HDID"] = str(c.hdid)
chara_client_info["IPID"] = str(c.ipid)
@@ -1519,16 +1478,16 @@ def broadcast_player_list_to_target(self, target):
# chara_client_info["url"] = c.files[1]
# if(c.char_outfit):
- # chara_client_info["outfit"] = c.char_outfit
+ # chara_client_info["outfit"] = c.char_outfit
- if(c.desc):
+ if c.desc:
chara_client_info["status"] = c.desc
player_data_to_send.append(chara_client_info)
- return_data['data'] = player_data_to_send
-
+ return_data["data"] = player_data_to_send
+
json_data = json.dumps(return_data)
- target.send_command('JSN', json_data)
- target.send_command('LP', player_stuff)
+ target.send_command("JSN", json_data)
+ target.send_command("LP", player_stuff)
def parse_msg_delay(self, msg):
"""Just returns the delay value between messages.
@@ -1550,7 +1509,7 @@ def is_iniswap(self, client, preanim, anim, char, sfx):
client.iniswap = char
else:
client.iniswap = ""
-
+
if self.iniswap_allowed:
return False
# Our client is narrating or blankposting via slash command
@@ -1613,19 +1572,13 @@ def add_jukebox_vote(self, client, music_name, length=-1, showname=""):
return
if length == 0:
self.remove_jukebox_vote(client, False)
- if len(self.jukebox_votes) <= 1 or (
- not self.music_looper or self.music_looper.cancelled()
- ):
+ if len(self.jukebox_votes) <= 1 or (not self.music_looper or self.music_looper.cancelled()):
self.start_jukebox()
else:
self.remove_jukebox_vote(client, True)
- self.jukebox_votes.append(
- self.JukeboxVote(client, music_name, length, showname)
- )
+ self.jukebox_votes.append(self.JukeboxVote(client, music_name, length, showname))
client.send_ooc("Your song was added to the jukebox.")
- if len(self.jukebox_votes) == 1 or (
- not self.music_looper or self.music_looper.cancelled()
- ):
+ if len(self.jukebox_votes) == 1 or (not self.music_looper or self.music_looper.cancelled()):
self.start_jukebox()
def remove_jukebox_vote(self, client, silent):
@@ -1652,21 +1605,14 @@ def get_jukebox_picked(self):
song_list = self.server.music_list
# Hub music list
- if (
- self.area_manager.music_ref != ""
- and len(self.area_manager.music_list) > 0
- ):
+ if self.area_manager.music_ref != "" and len(self.area_manager.music_list) > 0:
if self.area_manager.replace_music:
song_list = self.area_manager.music_list
else:
song_list = song_list + self.area_manager.music_list
# Area music list
- if (
- self.music_ref != ""
- and self.music_ref != self.area_manager.music_ref
- and len(self.music_list) > 0
- ):
+ if self.music_ref != "" and self.music_ref != self.area_manager.music_ref and len(self.music_list) > 0:
if self.replace_music:
song_list = self.music_list
else:
@@ -1677,11 +1623,9 @@ def get_jukebox_picked(self):
if "category" in c:
# Either play a completely random category, or play a category the last song was in
if "songs" in c:
- if self.music == "" or self.music in [
- b["name"] for b in c["songs"]
- ]:
+ if self.music == "" or self.music in [b["name"] for b in c["songs"]]:
for s in c["songs"]:
- looping = ("length" not in s or s["length"] == -1)
+ looping = "length" not in s or s["length"] == -1
if not looping or s["name"] == self.music:
continue
songs = songs + [s]
@@ -1711,10 +1655,7 @@ def start_jukebox(self):
# we should check that.
# We also do a check if we were the last to play a song, just in case.
if not self.jukebox:
- if (
- self.music_player == "The Jukebox"
- and self.music_player_ipid == "has no IPID"
- ):
+ if self.music_player == "The Jukebox" and self.music_player_ipid == "has no IPID":
self.music = ""
return
@@ -1722,8 +1663,7 @@ def start_jukebox(self):
if vote_picked is None:
self.music = ""
- self.send_command("MC", self.music, -1, "", 1,
- 0, int(MusicEffect.FADE_OUT))
+ self.send_command("MC", self.music, -1, "", 1, 0, int(MusicEffect.FADE_OUT))
return
if vote_picked.name == self.music:
@@ -1775,15 +1715,11 @@ def start_jukebox(self):
else:
current_vote.chance += 1
- length = (
- vote_picked.length - 3
- ) # Remove a few seconds to have a smooth fade out
+ length = vote_picked.length - 3 # Remove a few seconds to have a smooth fade out
if length <= 0: # Length not defined
length = 120.0 # Play each song for at least 2 minutes
- self.music_looper = asyncio.get_running_loop().call_later(
- max(5, length), lambda: self.start_jukebox()
- )
+ self.music_looper = asyncio.get_running_loop().call_later(max(5, length), lambda: self.start_jukebox())
def set_ambience(self, name):
self.ambience = name
@@ -1848,29 +1784,28 @@ def change_background_suffix(self, bg_suffix, mode=1):
for client in self.clients:
client.send_command("BN", self.background, client.pos, self.overlay, mode)
-
def change_background(self, bg, overlay="", mode=1):
"""
Set the background and/or overlay.
-
+
parameters:
bg: background name
silent: should send the pre 2.8 packet or the new one?
overlay: overlay name (optional)
-
+
:raises: AreaError if `bg` is not in background list
-
+
BN packet implementation:
-
+
Before 2.8 (Changes after sending a IC message):
BN #
-
+
AO 2.8 (Clear viewport and update/change background position):
BN # #
-
+
AOG 1.0 (Put a additional image on top of the character):
BN # # # #
-
+
mode: 0 = pre 2.8 version (change background after IC message)
1 = 2.8 version (Change background immediately, clearing the viewport)
2 = Change background without clearing the viewport
@@ -1878,7 +1813,7 @@ def change_background(self, bg, overlay="", mode=1):
The client should be expected to implement at least the first two.
-
+
"""
if self.use_backgrounds_yaml:
if len(self.server.backgrounds) <= 0:
@@ -1925,9 +1860,7 @@ def change_status(self, value):
False,
)
if value.lower() == "hub":
- raise AreaError(
- 'Hub Status is a restricted value.'
- )
+ raise AreaError("Hub Status is a restricted value.")
if value.lower() == "lfp":
value = "looking-for-players"
self.status = value.upper()
@@ -2013,8 +1946,7 @@ def add_owner(self, client):
# Update their judge buttons
self.update_judge_buttons(client)
- self.broadcast_ooc(
- f"{client.showname} [{client.id}] is CM in this area now.")
+ self.broadcast_ooc(f"{client.showname} [{client.id}] is CM in this area now.")
def remove_owner(self, client, dc=False):
"""
@@ -2049,9 +1981,7 @@ def remove_owner(self, client, dc=False):
# Update their judge buttons
self.update_judge_buttons(client)
- self.broadcast_ooc(
- f"{client.showname} [{client.id}] is no longer CM in this area."
- )
+ self.broadcast_ooc(f"{client.showname} [{client.id}] is no longer CM in this area.")
def broadcast_area_list(self, client=None, refresh=False):
"""
@@ -2086,8 +2016,7 @@ def time_until_move(self, client):
:return: time left until you can move again or 0.
"""
secs = round(time.time() * 1000.0 - client.last_move_time)
- total = sum([client.move_delay, self.move_delay,
- self.area_manager.move_delay])
+ total = sum([client.move_delay, self.move_delay, self.area_manager.move_delay])
test = total * 1000.0 - secs
if test > 0:
return test
@@ -2151,28 +2080,31 @@ def vote_end_minigame(self, client):
return
valid_voters = [
- c for c in self.clients if
- not c.hidden and
- not c in self.afkers and
- not c in self.owners and
- c.char_id not in client.area.blue_team and
- c.char_id not in client.area.red_team
+ c
+ for c in self.clients
+ if not c.hidden
+ and c not in self.afkers
+ and c not in self.owners
+ and c.char_id not in client.area.blue_team
+ and c.char_id not in client.area.red_team
]
if client not in valid_voters:
- client.send_ooc("You're not qualified to vote-end this minigame! (You're a Spectator, Hidden or the area owner)")
+ client.send_ooc(
+ "You're not qualified to vote-end this minigame! (You're a Spectator, Hidden or the area owner)"
+ )
return
self.votes_cast.add(client)
votes_casted = len(self.votes_cast)
votes_needed = round(len(valid_voters) * self.votes_percentage)
- info = f'[{client.id}] {client.showname} is voting to end the minigame!'
+ info = f"[{client.id}] {client.showname} is voting to end the minigame!"
if votes_casted >= votes_needed:
client.area.end_minigame("Voted to end.")
- info += f'\nSuccessfully voted to end with ({votes_casted}/{votes_needed}) votes.'
+ info += f"\nSuccessfully voted to end with ({votes_casted}/{votes_needed}) votes."
else:
- info += f'({votes_casted}/{votes_needed}) votes left.'
-
+ info += f"({votes_casted}/{votes_needed}) votes left."
+
self.broadcast_ooc(info)
def start_debate(self, client, target, pta=False):
@@ -2206,9 +2138,7 @@ def start_debate(self, client, target, pta=False):
self.broadcast_ooc("🔴Red team conceded!")
self.end_minigame("~Red~ team conceded!")
return
- self.broadcast_ooc(
- f"[{client.id}] {client.showname} is now part of the {team} team!"
- )
+ self.broadcast_ooc(f"[{client.id}] {client.showname} is now part of the {team} team!")
database.log_area(
"minigame.sd",
client,
@@ -2219,8 +2149,7 @@ def start_debate(self, client, target, pta=False):
return
elif self.minigame == "Cross Swords":
if target == client:
- self.broadcast_ooc(
- f"[{client.id}] {client.showname} conceded!")
+ self.broadcast_ooc(f"[{client.id}] {client.showname} conceded!")
self.end_minigame(f"[{client.id}] {client.showname} conceded!")
return
if not self.can_scrum_debate:
@@ -2241,9 +2170,7 @@ def start_debate(self, client, target, pta=False):
self.minigame_schedule.cancel()
self.minigame = "Scrum Debate"
timer = timeleft + self.scrum_debate_added_time
- self.broadcast_ooc(
- f"[{client.id}] {client.showname} is now part of the {team} team!"
- )
+ self.broadcast_ooc(f"[{client.id}] {client.showname} is now part of the {team} team!")
database.log_area(
"minigame.sd",
client,
@@ -2258,8 +2185,7 @@ def start_debate(self, client, target, pta=False):
if pta and not self.can_panic_talk_action:
raise AreaError("You may not PTA in this area!")
if client == target:
- raise AreaError(
- "You cannot initiate a minigame against yourself!")
+ raise AreaError("You cannot initiate a minigame against yourself!")
self.old_invite_list = self.invite_list
self.old_muted = self.muted
@@ -2272,7 +2198,7 @@ def start_debate(self, client, target, pta=False):
self.blue_team.clear()
self.red_team.add(client.char_id)
self.blue_team.add(target.char_id)
-
+
self.votes_cast.clear()
if pta:
self.minigame = "Panic Talk Action"
@@ -2298,12 +2224,10 @@ def start_debate(self, client, target, pta=False):
song = self.cross_swords_song_start
else:
if target == client:
- self.broadcast_ooc(
- f"[{client.id}] {client.showname} conceded!")
+ self.broadcast_ooc(f"[{client.id}] {client.showname} conceded!")
self.end_minigame(f"[{client.id}] {client.showname} conceded!")
return
- raise AreaError(
- f"{self.minigame} is happening! You cannot interrupt it.")
+ raise AreaError(f"{self.minigame} is happening! You cannot interrupt it.")
timer = max(5, int(timer))
# Timer ID 2 is used, start it
@@ -2344,9 +2268,8 @@ def play_demo(self, client):
if len(self.demo) <= 0:
self.stop_demo()
return
- if not (client in self.owners):
- client.send_ooc(
- f"[Demo] Playback stopped due to you having insufficient permissions! (Not CM/GM anymore)")
+ if client not in self.owners:
+ client.send_ooc("[Demo] Playback stopped due to you having insufficient permissions! (Not CM/GM anymore)")
self.stop_demo()
return
@@ -2356,9 +2279,7 @@ def play_demo(self, client):
# It's a wait packet
if header == "wait":
secs = float(args[0]) / 1000
- self.demo_schedule = asyncio.get_running_loop().call_later(
- secs, lambda: self.play_demo(client)
- )
+ self.demo_schedule = asyncio.get_running_loop().call_later(secs, lambda: self.play_demo(client))
return
if header.startswith("/"): # It's a command call
# TODO: make this into a global function so commands can be called from anywhere in code...
@@ -2368,17 +2289,11 @@ def play_demo(self, client):
arg = " ".join(args)[:1024]
try:
called_function = f"ooc_cmd_{cmd}"
- if len(client.server.command_aliases) > 0 and not hasattr(
- commands, called_function
- ):
+ if len(client.server.command_aliases) > 0 and not hasattr(commands, called_function):
if cmd in client.server.command_aliases:
- called_function = (
- f"ooc_cmd_{client.server.command_aliases[cmd]}"
- )
+ called_function = f"ooc_cmd_{client.server.command_aliases[cmd]}"
if not hasattr(commands, called_function):
- client.send_ooc(
- f"[Demo] Invalid command: {cmd}. Use /help to find up-to-date commands."
- )
+ client.send_ooc(f"[Demo] Invalid command: {cmd}. Use /help to find up-to-date commands.")
self.stop_demo()
return
getattr(commands, called_function)(client, arg)
diff --git a/server/area_manager.py b/server/area_manager.py
index 4567352d..ede0ea1c 100644
--- a/server/area_manager.py
+++ b/server/area_manager.py
@@ -130,7 +130,7 @@ def __init__(self, hub_manager, name):
self.time_of_day = ""
self.timer = self.Timer()
-
+
# RPS-5 rules as default
self.rps_rules = [
["rock", "scissors", "lizard"],
@@ -149,8 +149,7 @@ def name(self):
def name(self, value):
self._name = value.strip()
while "" in self._name or "" in self._name:
- self._name = self._name.replace(
- "", "").replace("", "")
+ self._name = self._name.replace("", "").replace("", "")
self.abbreviation = self.abbreviate()
@property
@@ -227,7 +226,7 @@ def load(self, hub, destructive=False, ignore=[]):
else:
self.load_music(f"storage/musiclists/{hub[entry]}.yaml")
- if not ("character_data" in ignore) and "character_data" in hub:
+ if "character_data" not in ignore and "character_data" in hub:
try:
self.load_character_data(hub["character_data"])
except Exception:
@@ -237,7 +236,7 @@ def load(self, hub, destructive=False, ignore=[]):
if area == self.default_area(): # Do not remove the default area
continue
self.remove_area(area)
- if not ("areas" in ignore) and "areas" in hub:
+ if "areas" not in ignore and "areas" in hub:
self.load_areas(hub["areas"])
self.broadcast_area_list()
@@ -334,8 +333,7 @@ def clear_music(self):
def load_music(self, path):
try:
if not os.path.isfile(path):
- raise AreaError(
- f"Hub {self.name} trying to load music list: File path {path} is invalid!")
+ raise AreaError(f"Hub {self.name} trying to load music list: File path {path} is invalid!")
with open(path, "r", encoding="utf-8") as stream:
music_list = yaml.safe_load(stream)
@@ -371,8 +369,7 @@ def load_character_data(self, path="config/character_data.yaml"):
with open(path, "r") as chars:
data = yaml.safe_load(chars)
except Exception:
- raise AreaError(
- f"Hub {self.name} trying to load character data: File path {path} is invalid!")
+ raise AreaError(f"Hub {self.name} trying to load character data: File path {path} is invalid!")
try:
for char in data.copy():
@@ -381,8 +378,7 @@ def load_character_data(self, path="config/character_data.yaml"):
data[self.char_list[char]] = data.pop(char)
self.character_data = data
except Exception:
- raise AreaError(
- "Something went wrong while loading the character data!")
+ raise AreaError("Something went wrong while loading the character data!")
def save_character_data(self, path="config/character_data.yaml"):
"""
@@ -392,11 +388,9 @@ def save_character_data(self, path="config/character_data.yaml"):
"""
try:
with open(path, "w", encoding="utf-8") as stream:
- yaml.dump(self.character_data, stream,
- default_flow_style=False)
+ yaml.dump(self.character_data, stream, default_flow_style=False)
except Exception:
- raise AreaError(
- f"Hub {self.name} trying to save character data: File path {path} is invalid!")
+ raise AreaError(f"Hub {self.name} trying to save character data: File path {path} is invalid!")
def get_character_data(self, char, key, default_value=None):
"""
@@ -443,7 +437,7 @@ def remove_area(self, area):
:param area: target area instance.
"""
- if not (area in self.areas):
+ if area not in self.areas:
raise AreaError("Area not found.")
# Make a copy because it can change size during iteration
# (causes runtime error otherwise)
@@ -475,9 +469,9 @@ def swap_area(self, area1, area2, fix_links=True):
:param area2: second area to swap.
"""
- if not (area1 in self.areas):
+ if area1 not in self.areas:
raise AreaError("First area not found.")
- if not (area2 in self.areas):
+ if area2 not in self.areas:
raise AreaError("Second area not found.")
# Grab the indexes
a = self.areas.index(area1)
@@ -518,9 +512,7 @@ def add_owner(self, client):
client.area.broadcast_area_list(client)
client.area.broadcast_evidence_list()
- self.broadcast_ooc(
- f"[{client.id}] {client.showname} ({client.name}) is GM in this hub now."
- )
+ self.broadcast_ooc(f"[{client.id}] {client.showname} ({client.name}) is GM in this hub now.")
client.hide(True)
def remove_owner(self, client):
@@ -541,9 +533,7 @@ def remove_owner(self, client):
client.area.broadcast_area_list(client)
client.area.broadcast_evidence_list()
- self.broadcast_ooc(
- f"[{client.id}] {client.showname} ({client.name}) is no longer GM in this hub."
- )
+ self.broadcast_ooc(f"[{client.id}] {client.showname} ({client.name}) is no longer GM in this hub.")
client.hide(False)
def get_gms(self):
@@ -596,17 +586,15 @@ def get_areas_by_args(self, args):
# MAKE SURE TO RETURN A COPY AND NOT A DIRECT REFERENCE OR YOU'RE GONNA BE IN A WORLD OF HURT
return self.areas.copy()
# If arg is area range, e.g. 1-12, extend list by that range
- a_range = arg.split('-')
+ a_range = arg.split("-")
if len(a_range) == 2 and a_range[0].strip().isnumeric() and a_range[1].strip().isnumeric():
# unpack the range, turn it into a list and add it to the arglist
- arg_list += [*range(int(a_range[0]), int(a_range[1])+1)]
+ arg_list += [*range(int(a_range[0]), int(a_range[1]) + 1)]
continue
# Otherwise, just append the arg
arg_list.append(arg.lower())
for area in self.areas:
- if area.id in arg_list or \
- str(area.id) in arg_list or \
- area.name.lower() in arg_list:
+ if area.id in arg_list or str(area.id) in arg_list or area.name.lower() in arg_list:
area_list.append(area)
return area_list
@@ -649,7 +637,7 @@ def update_subtheme(self, client):
client.send_command("GM", self.subtheme)
# Set the time of day as well
client.send_command("TOD", self.time_of_day)
-
+
# AO portion
if client.subtheme != self.subtheme or client.time_of_day != self.time_of_day:
# ST is Subtheme, AO lacks time of day equivalent.
@@ -659,7 +647,7 @@ def update_subtheme(self, client):
else:
client.send_command("ST", self.subtheme, "1")
client.subtheme = self.subtheme
-
+
def broadcast_subtheme(self):
for client in self.clients:
self.update_subtheme(client)
@@ -677,17 +665,12 @@ def send_arup_players(self, clients=None):
for area in client.local_area_list:
playercount = -1
if not self.hide_clients and not area.hide_clients:
- playercount = len(
- [c for c in area.clients if not c.hidden])
+ playercount = len([c for c in area.clients if not c.hidden])
players_list.append(playercount)
playerhubcount = 0
for area in client.local_area_list:
for c in area.clients:
- if (
- not self.hide_clients
- and not area.hide_clients
- and not c.hidden
- ):
+ if not self.hide_clients and not area.hide_clients and not c.hidden:
playerhubcount = playerhubcount + 1
if len(self.server.hub_manager.hubs) > 1:
players_list[1] = playerhubcount
diff --git a/server/client_manager.py b/server/client_manager.py
index f69710e7..f6793c27 100644
--- a/server/client_manager.py
+++ b/server/client_manager.py
@@ -81,27 +81,20 @@ def __init__(self, server, transport, user_id, ipid):
self.mus_counter = 0
self.mus_mute_time = 0
self.mus_change_time = [
- x *
- self.server.config["music_change_floodguard"]["interval_length"]
- for x in range(
- self.server.config["music_change_floodguard"]["times_per_interval"]
- )
+ x * self.server.config["music_change_floodguard"]["interval_length"]
+ for x in range(self.server.config["music_change_floodguard"]["times_per_interval"])
]
self.wtce_counter = 0
self.wtce_mute_time = 0
self.wtce_time = [
x * self.server.config["wtce_floodguard"]["interval_length"]
- for x in range(
- self.server.config["wtce_floodguard"]["times_per_interval"]
- )
+ for x in range(self.server.config["wtce_floodguard"]["times_per_interval"])
]
self.ooc_counter = 0
self.ooc_mute_time = 0
self.ooc_time = [
x * self.server.config["ooc_floodguard"]["interval_length"]
- for x in range(
- self.server.config["ooc_floodguard"]["times_per_interval"]
- )
+ for x in range(self.server.config["ooc_floodguard"]["times_per_interval"])
]
# security stuff
self.clientscon = 0
@@ -182,16 +175,16 @@ def __init__(self, server, transport, user_id, ipid):
# The currently playing audio for this client. Keeping track so we don't replay the same audio erroneously
# (such as in the case of music_autoplay areas)
self.playing_audio = ["", ""]
-
+
# rainbowtext hell
self.rainbow = False
-
+
# rock paper scissors choice
self.rps_choice = ""
# Battle system stuff
self.battle = None
-
+
# If only the available areas should be displayed even as a GM
self.available_areas_only = False
@@ -255,31 +248,29 @@ def send_command(self, command, *args):
if len(args) > 16 and args[16]:
charid_pair = str(args[16])
self_offset_x = 0
- self_offset_y = 0
if len(args) > 19 and args[19]:
- offset = str(args[19]).replace('', '&').split('&')
+ offset = str(args[19]).replace("", "&").split("&")
self_offset_x = offset[0]
if len(offset) > 1:
- self_offset_y = offset[1]
+ offset[1]
offset_pair_x = 0
- offset_pair_y = 0
if len(args) > 20 and args[20]:
- offset = str(args[20]).replace('', '&').split('&')
+ offset = str(args[20]).replace("", "&").split("&")
offset_pair_x = offset[0]
if len(offset) > 1:
- offset_pair_y = offset[1]
+ offset[1]
self_offset_x_dro = 500
if self_offset_x:
- self_offset_x_dro = int((float(self_offset_x) / 100) * 960 + 480) # offset_pair
+ self_offset_x_dro = int((float(self_offset_x) / 100) * 960 + 480) # offset_pair
# self_offset_y_dro = 0
# if self_offset_y:
# self_offset_y_dro = int((float(self_offset_y) / 100) * 960 + 480) # offset_pair
# Pair data detected!
if (charid_pair and charid_pair != "-1") or (self_offset_x and self_offset_x != "0"):
pair_jsn_packet = {}
- pair_jsn_packet['packet'] = 'pair_data'
- pair_jsn_packet['data'] = {}
+ pair_jsn_packet["packet"] = "pair_data"
+ pair_jsn_packet["data"] = {}
other_emote = ""
other_folder = ""
other_flip = False
@@ -289,31 +280,31 @@ def send_command(self, command, *args):
other_emote = args[18]
if len(args) > 21:
other_flip = bool(int(args[21]))
- pair_jsn_packet['data']['character'] = other_folder
- pair_jsn_packet['data']['last_sprite'] = other_emote
- pair_jsn_packet['data']['flipped'] = other_flip
-
+ pair_jsn_packet["data"]["character"] = other_folder
+ pair_jsn_packet["data"]["last_sprite"] = other_emote
+ pair_jsn_packet["data"]["flipped"] = other_flip
+
# no y offset is supported and on DRO Client, the pairing offsets are measured in pixels rather than percentage
offset_pair_x_dro = 500
if offset_pair_x:
- offset_pair_x_dro = int((float(offset_pair_x) / 100) * 960 + 480) # other_offset
- pair_jsn_packet['data']['self_offset'] = self_offset_x_dro
- pair_jsn_packet['data']['offset_pair'] = offset_pair_x_dro
-
+ offset_pair_x_dro = int((float(offset_pair_x) / 100) * 960 + 480) # other_offset
+ pair_jsn_packet["data"]["self_offset"] = self_offset_x_dro
+ pair_jsn_packet["data"]["offset_pair"] = offset_pair_x_dro
+
# Send the result!
json_data = json.dumps(pair_jsn_packet)
- self.send_command('JSN', json_data)
+ self.send_command("JSN", json_data)
# No pair :(
else:
pair_jsn_packet = {}
- pair_jsn_packet['packet'] = 'pair'
- pair_jsn_packet['data'] = {}
- pair_jsn_packet['data']['pair_left'] = -1
- pair_jsn_packet['data']['pair_right'] = -1
- pair_jsn_packet['data']['offset_left'] = 0
- pair_jsn_packet['data']['offset_right'] = 0
+ pair_jsn_packet["packet"] = "pair"
+ pair_jsn_packet["data"] = {}
+ pair_jsn_packet["data"]["pair_left"] = -1
+ pair_jsn_packet["data"]["pair_right"] = -1
+ pair_jsn_packet["data"]["offset_left"] = 0
+ pair_jsn_packet["data"]["offset_right"] = 0
json_data = json.dumps(pair_jsn_packet)
- self.send_command('JSN', json_data)
+ self.send_command("JSN", json_data)
# Now, modify the packet
lst = list(args)
# make sure to pad the list out
@@ -321,7 +312,7 @@ def send_command(self, command, *args):
# append with 0s we're gonna replace anyway
lst.append(0)
lst[16] = "" # No video support :(
- lst[17] = hide_char # hide character if we're blankposting or narrating
+ lst[17] = hide_char # hide character if we're blankposting or narrating
lst[18] = -1 # would be target id, but we dunno who
lst[19] = self_offset_x_dro # offset_h
lst[20] = 0 # offset_v
@@ -355,9 +346,7 @@ def send_hub_info(self):
"""Send the hub info to the client."""
info = self.area.area_manager.info
if info != "":
- self.send_ooc(
- f"🌍HUB [{self.area.area_manager.id}] {self.area.area_manager.name} INFO🌍\r\n{info}\r\n"
- )
+ self.send_ooc(f"🌍HUB [{self.area.area_manager.id}] {self.area.area_manager.name} INFO🌍\r\n{info}\r\n")
def send_player_count(self):
"""
@@ -372,7 +361,7 @@ def send_timer_set_time(self, timer_id=None, new_time=None, start=False):
if timer_id == 0:
timer = self.area.area_manager.timer
else:
- timer = self.area.timers[timer_id-1]
+ timer = self.area.timers[timer_id - 1]
if self.software == "DRO":
# configuration. There's no situation where these values are different on KFO-Server
# step length cannot be manually modified yet
@@ -383,16 +372,16 @@ def send_timer_set_time(self, timer_id=None, new_time=None, start=False):
# as of 1.8.1, set timer format
self.send_command("TSR", timer_id, timer.format)
if start:
- self.send_command("TR", timer_id) # resume
+ self.send_command("TR", timer_id) # resume
else:
- self.send_command("TP", timer_id) # pause
+ self.send_command("TP", timer_id) # pause
else:
- if new_time == None:
- self.send_command("TI", timer_id, 1, 0) # Stop timer
- self.send_command("TI", timer_id, 3, 0) # Hide timer
+ if new_time is None:
+ self.send_command("TI", timer_id, 1, 0) # Stop timer
+ self.send_command("TI", timer_id, 3, 0) # Hide timer
else:
- self.send_command("TI", timer_id, 2, new_time) # Show timer
- self.send_command("TI", timer_id, int(not start), new_time) # Set timer with value and start
+ self.send_command("TI", timer_id, 2, new_time) # Show timer
+ self.send_command("TI", timer_id, int(not start), new_time) # Set timer with value and start
self.send_command("TF", timer_id, timer.format, new_time)
self.send_command("TIN", timer_id, timer.interval)
@@ -403,19 +392,19 @@ def send_timer_set_interval(self, timer_id, timer):
else:
current_time = int(timer.static.total_seconds()) * 1000
if timer_id == 0:
- self.area.area_manager.send_timer_set_time(timer_id, current_time, timer.started)
+ self.area.area_manager.send_timer_set_time(timer_id, current_time, timer.started)
else:
- self.area.send_timer_set_time(timer_id, current_time, timer.started)
+ self.area.send_timer_set_time(timer_id, current_time, timer.started)
def send_timer_set_step_length(self, timer_id=None, new_step_length=None):
if self.software == "DRO":
- self.send_command("TSS", timer_id, new_step_length) # set step
+ self.send_command("TSS", timer_id, new_step_length) # set step
else:
- pass # no ao equivalent
+ pass # no ao equivalent
def send_timer_set_firing_interval(self, timer_id=None, new_firing_interval=None):
if self.software == "DRO":
- self.send_command("TSF", timer_id, new_firing_interval) #set firing
+ self.send_command("TSF", timer_id, new_firing_interval) # set firing
else:
self.send_command("TIN", timer_id, new_firing_interval)
@@ -442,17 +431,20 @@ def disconnect(self):
def record_latest_area(self):
"""Record the client character's latest area if not in lobby, if not spectator and not GM/mod."""
- if self.area.area_manager.default_area() != self.area and self.char_id != -1 and self not in self.area.owners and not self.is_mod:
+ if (
+ self.area.area_manager.default_area() != self.area
+ and self.char_id != -1
+ and self not in self.area.owners
+ and not self.is_mod
+ ):
self.area.area_manager.set_character_data(self.char_id, "latest_area", self.area.id)
-
+
def kick_to_latest_area(self):
"""Kick the client to their character's latest recorded area."""
- latest_area = self.area.area_manager.get_character_data(
- self.char_id, "latest_area", None
- )
- if latest_area == None:
+ latest_area = self.area.area_manager.get_character_data(self.char_id, "latest_area", None)
+ if latest_area is None:
return
-
+
target_area = self.area.area_manager.get_area_by_id(latest_area)
if not target_area:
return
@@ -509,15 +501,14 @@ def change_character(self, char_id, force=False):
char_id == -1
and not (self.area.area_manager.can_spectate and self.area.can_spectate)
and not self.is_mod
- and not (self in self.area.owners)
+ and self not in self.area.owners
and not force
):
if not self.area.area_manager.can_spectate:
raise ClientError("Cannot spectate in this hub!")
raise ClientError("Cannot spectate in this area!")
old_char = self.char_name
- arup = (self.char_id == -1 or char_id == -
- 1) and self.char_id != char_id
+ arup = (self.char_id == -1 or char_id == -1) and self.char_id != char_id
self.char_id = char_id
self.pos = ""
self.send_command("PV", self.id, "CID", self.char_id)
@@ -552,17 +543,17 @@ def change_character(self, char_id, force=False):
if self.area.area_manager.autokick_to_latest_area:
self.kick_to_latest_area()
- else:
+ else:
# Record last known area ID for this character if not spectator/gm/mod, and hub autokick is not set
self.record_latest_area()
self.area.update_timers(self, running_only=True)
-
+
if not self.hidden and not self.sneaking:
self.area.broadcast_player_list()
else:
self.area.broadcast_player_list_to_target(self)
- self.area.broadcast_area_desc_to_target(self)
+ self.area.broadcast_area_desc_to_target(self)
def change_music_cd(self):
"""
@@ -579,26 +570,16 @@ def change_music_cd(self):
return 0
if self.mus_mute_time:
- if (
- time.time() - self.mus_mute_time
- < self.server.config["music_change_floodguard"]["mute_length"]
- ):
- return self.server.config["music_change_floodguard"][
- "mute_length"
- ] - (time.time() - self.mus_mute_time)
+ if time.time() - self.mus_mute_time < self.server.config["music_change_floodguard"]["mute_length"]:
+ return self.server.config["music_change_floodguard"]["mute_length"] - (
+ time.time() - self.mus_mute_time
+ )
else:
self.mus_mute_time = 0
- times_per_interval = self.server.config["music_change_floodguard"][
- "times_per_interval"
- ]
- interval_length = self.server.config["music_change_floodguard"][
- "interval_length"
- ]
+ times_per_interval = self.server.config["music_change_floodguard"]["times_per_interval"]
+ interval_length = self.server.config["music_change_floodguard"]["interval_length"]
if (
- time.time()
- - self.mus_change_time[
- (self.mus_counter - times_per_interval + 1) % times_per_interval
- ]
+ time.time() - self.mus_change_time[(self.mus_counter - times_per_interval + 1) % times_per_interval]
< interval_length
):
self.mus_mute_time = time.time()
@@ -618,20 +599,17 @@ def change_music(self, song, cid, showname="", effects=0, loop=True):
return
# Decode AO packet
- song = song.replace("", "#") \
- .replace("", "%") \
- .replace("", "$") \
- .replace("", "&")
+ song = song.replace("", "#").replace("", "%").replace("", "$").replace("", "&")
try:
- if song == "~stop.mp3" or song.strip() == "" or self.server.get_song_is_category(
- self.construct_music_list(), song
+ if (
+ song == "~stop.mp3"
+ or song.strip() == ""
+ or self.server.get_song_is_category(self.construct_music_list(), song)
):
name, length = "~stop.mp3", 0
else:
try:
- name, length = self.server.get_song_data(
- self.construct_music_list(), song
- )
+ name, length = self.server.get_song_data(self.construct_music_list(), song)
except ServerError:
if self.is_mod or self in self.area.owners:
name = song
@@ -641,28 +619,23 @@ def change_music(self, song, cid, showname="", effects=0, loop=True):
if not loop:
length = 0
- if (contains_URL(song)):
+ if contains_URL(song):
checked = False
# Only if url music is configured to be allowed
- if self.server.config["music_allow_url"] == True:
+ if self.server.config["music_allow_url"]:
if len(self.server.music_whitelist) <= 0:
checked = True
for line in self.server.music_whitelist:
if song.startswith(line):
checked = True
- if checked == False:
- self.send_ooc(
- "This URL is not allowed."
- )
+ if not checked:
+ self.send_ooc("This URL is not allowed.")
return
target_areas = [self.area]
- if len(self.broadcast_list) > 0 and (
- self.is_mod or self in self.area.owners
- ):
+ if len(self.broadcast_list) > 0 and (self.is_mod or self in self.area.owners):
try:
- a_list = ", ".join([str(a.id)
- for a in self.broadcast_list])
+ a_list = ", ".join([str(a.id) for a in self.broadcast_list])
self.send_ooc(f"Broadcasting to areas {a_list}")
target_areas = self.broadcast_list
except (AreaError, ValueError):
@@ -678,21 +651,15 @@ def change_music(self, song, cid, showname="", effects=0, loop=True):
)
continue
if not self.is_mod and self not in area.owners and not area.can_dj:
- self.send_ooc(
- f"You cannot change music in area [{area.id}] {area.name}!"
- )
+ self.send_ooc(f"You cannot change music in area [{area.id}] {area.name}!")
continue
if area.music_locked:
- self.send_ooc(
- f"You cannot change music in area [{area.id}] {area.name} - music is locked!"
- )
+ self.send_ooc(f"You cannot change music in area [{area.id}] {area.name} - music is locked!")
continue
if self.edit_ambience:
if self.is_mod or self in area.owners:
area.set_ambience(name)
- self.send_ooc(
- f"Setting area [{area.id}] {area.name} ambience to {name}."
- )
+ self.send_ooc(f"Setting area [{area.id}] {area.name} ambience to {name}.")
continue
else:
self.edit_ambinece = False
@@ -727,9 +694,7 @@ def change_music(self, song, cid, showname="", effects=0, loop=True):
self.area.panic_talk_action_song_end = song
elif self.editing_minigame_song_condition == 2:
self.area.panic_talk_action_song_concede = song
- self.send_ooc(
- f"Setting the {self.editing_minigame_song} {condition_str} song to {song}."
- )
+ self.send_ooc(f"Setting the {self.editing_minigame_song} {condition_str} song to {song}.")
self.editing_minigame_song = ""
self.editing_minigame_song_condition = 0
continue
@@ -745,9 +710,7 @@ def change_music(self, song, cid, showname="", effects=0, loop=True):
and not self.is_mod
and self not in area.owners
):
- self.send_ooc(
- f"Showname changes are forbidden in area [{area.id}] {area.name}!"
- )
+ self.send_ooc(f"Showname changes are forbidden in area [{area.id}] {area.name}!")
continue
# Effects info
@@ -756,16 +719,14 @@ def change_music(self, song, cid, showname="", effects=0, loop=True):
# Jukebox check
if area.jukebox and not self.is_mod and self not in area.owners:
area.add_jukebox_vote(self, name, length, showname)
- database.log_area(
- "jukebox.vote", self, area, message=name)
+ database.log_area("jukebox.vote", self, area, message=name)
else:
if self.change_music_cd():
self.send_ooc(
f"You changed song too many times. Please try again after {int(self.change_music_cd())} seconds."
)
return
- area.play_music(name, self.char_id,
- length, showname, effects)
+ area.play_music(name, self.char_id, length, showname, effects)
area.add_music_playing(self, name, showname)
# Broadcast for the rest
for a in area.broadcast_list:
@@ -778,8 +739,7 @@ def change_music(self, song, cid, showname="", effects=0, loop=True):
f"Error: song {song} was not accepted! View acceptable music by resetting your client's using /musiclist."
)
else:
- self.send_ooc(
- f"Error: song {song} was not accepted! (No permission)")
+ self.send_ooc(f"Error: song {song} was not accepted! (No permission)")
def wtce_mute(self):
"""
@@ -789,24 +749,14 @@ def wtce_mute(self):
if self.is_mod or self in self.area.owners:
return 0
if self.wtce_mute_time:
- if (
- time.time() - self.wtce_mute_time
- < self.server.config["wtce_floodguard"]["mute_length"]
- ):
- return self.server.config["wtce_floodguard"]["mute_length"] - (
- time.time() - self.wtce_mute_time
- )
+ if time.time() - self.wtce_mute_time < self.server.config["wtce_floodguard"]["mute_length"]:
+ return self.server.config["wtce_floodguard"]["mute_length"] - (time.time() - self.wtce_mute_time)
else:
self.wtce_mute_time = 0
- times_per_interval = self.server.config["wtce_floodguard"][
- "times_per_interval"
- ]
+ times_per_interval = self.server.config["wtce_floodguard"]["times_per_interval"]
interval_length = self.server.config["wtce_floodguard"]["interval_length"]
if (
- time.time()
- - self.wtce_time[
- (self.wtce_counter - times_per_interval + 1) % times_per_interval
- ]
+ time.time() - self.wtce_time[(self.wtce_counter - times_per_interval + 1) % times_per_interval]
< interval_length
):
self.wtce_mute_time = time.time()
@@ -814,7 +764,7 @@ def wtce_mute(self):
self.wtce_counter = (self.wtce_counter + 1) % times_per_interval
self.wtce_time[self.wtce_counter] = time.time()
return 0
-
+
def ooc_mute(self):
"""
Check if the client can use OOC or not.
@@ -823,24 +773,14 @@ def ooc_mute(self):
if self.is_mod or self in self.area.owners:
return 0
if self.ooc_mute_time:
- if (
- time.time() - self.ooc_mute_time
- < self.server.config["ooc_floodguard"]["mute_length"]
- ):
- return self.server.config["ooc_floodguard"]["mute_length"] - (
- time.time() - self.ooc_mute_time
- )
+ if time.time() - self.ooc_mute_time < self.server.config["ooc_floodguard"]["mute_length"]:
+ return self.server.config["ooc_floodguard"]["mute_length"] - (time.time() - self.ooc_mute_time)
else:
self.ooc_mute_time = 0
- times_per_interval = self.server.config["ooc_floodguard"][
- "times_per_interval"
- ]
+ times_per_interval = self.server.config["ooc_floodguard"]["times_per_interval"]
interval_length = self.server.config["ooc_floodguard"]["interval_length"]
if (
- time.time()
- - self.ooc_time[
- (self.ooc_counter - times_per_interval + 1) % times_per_interval
- ]
+ time.time() - self.ooc_time[(self.ooc_counter - times_per_interval + 1) % times_per_interval]
< interval_length
):
self.ooc_mute_time = time.time()
@@ -862,19 +802,15 @@ def clear_music(self):
def load_music(self, path):
"""Load a music list from a path. Use it for the local music list and reload it."""
- # TODO: Move the musiclist parsing function to tsuserver3.py or something
+ # TODO: Move the musiclist parsing function to kfoserver.py or something
try:
with open(path, "r", encoding="utf-8") as stream:
music_list = yaml.safe_load(stream)
prepath = ""
for item in music_list:
- if (
- "use_unique_folder" in item
- and item["use_unique_folder"] is True
- ):
- prepath = os.path.splitext(
- os.path.basename(path))[0] + "/"
+ if "use_unique_folder" in item and item["use_unique_folder"] is True:
+ prepath = os.path.splitext(os.path.basename(path))[0] + "/"
if "category" not in item:
continue
@@ -896,10 +832,7 @@ def construct_music_list(self):
song_list = self.server.music_list
# Hub music list
- if (
- self.area.area_manager.music_ref != ""
- and len(self.area.area_manager.music_list) > 0
- ):
+ if self.area.area_manager.music_ref != "" and len(self.area.area_manager.music_list) > 0:
if self.area.area_manager.replace_music:
song_list = self.area.area_manager.music_list
else:
@@ -921,10 +854,7 @@ def construct_music_list(self):
self.area.client_music
and self.area.area_manager.client_music
and self.music_ref != ""
- and not (
- self.music_ref
- in [self.area.music_ref, self.area.area_manager.music_ref]
- )
+ and self.music_ref not in [self.area.music_ref, self.area.area_manager.music_ref]
and len(self.music_list) > 0
):
if self.replace_music:
@@ -969,9 +899,7 @@ def reload_area_list(self, areas=[]):
f"🌍[{self.area.area_manager.id}] {self.area.area_manager.name}\n Double-Click me to see Hubs\n _______"
]
else:
- area_list = [
- f"🌍[{self.area.area_manager.id}] {self.area.area_manager.name}"
- ]
+ area_list = [f"🌍[{self.area.area_manager.id}] {self.area.area_manager.name}"]
if len(areas) > 0:
# This is where we can handle all the 'rendering', such as extra info etc.
for area in areas:
@@ -1010,12 +938,15 @@ def set_area(self, area, target_pos=""):
# When swapping between hubs, if the new hub charlist is different from ours or if the target hub has character autokick enabled,
# bring up the character select screen for the client
- if old_area.area_manager != area.area_manager and (area.area_manager.autokick_to_latest_area or old_area.area_manager.char_list != area.area_manager.char_list):
+ if old_area.area_manager != area.area_manager and (
+ area.area_manager.autokick_to_latest_area
+ or old_area.area_manager.char_list != area.area_manager.char_list
+ ):
# Send them that hub's char list
self.area.area_manager.send_characters(self)
self.char_select()
- if len(self.area.pos_lock) > 0 and not (target_pos in self.area.pos_lock):
+ if len(self.area.pos_lock) > 0 and target_pos not in self.area.pos_lock:
target_pos = self.area.pos_lock[0]
if self.area.dark:
target_pos = self.area.pos_dark
@@ -1050,10 +981,7 @@ def set_area(self, area, target_pos=""):
"FA",
*[
"🌐 Hubs 🌐\n Double-Click me to see Areas\n _______",
- *[
- f"[{hub.id}] {hub.name} (users: {hub.count})"
- for hub in self.server.hub_manager.hubs
- ],
+ *[f"[{hub.id}] {hub.name} (users: {hub.count})" for hub in self.server.hub_manager.hubs],
],
)
@@ -1087,17 +1015,17 @@ def set_area(self, area, target_pos=""):
try:
area_clients = self.get_area_clients(self.area.id)
if area_clients != "":
- msg += f'\nClients in area:{area_clients}'
+ msg += f"\nClients in area:{area_clients}"
except ClientError as ex:
- msg += f'\n{ex}'
+ msg += f"\n{ex}"
self.send_ooc(msg)
-
+
# DRO Client exclusive
self.area.broadcast_area_desc_to_target(self)
self.send_command("joined_area")
# We failed to enter the same area as whoever we've been following, break the follow
- if self.following is not None and not (self.following in self.area.clients):
+ if self.following is not None and self.following not in self.area.clients:
self.unfollow()
# Record last known area ID for this character if not spectator/gm/mod
@@ -1121,11 +1049,7 @@ def can_access_area(self, area):
def try_access_area(self, area, peek=False):
if self.frozen:
raise ClientError("You are frozen in place so you can't move!")
- if (
- self.area.locked
- and self not in self.area.owners
- and self.id not in self.area.invite_list
- ):
+ if self.area.locked and self not in self.area.owners and self.id not in self.area.invite_list:
raise ClientError("Current area is locked!")
if len(self.area.links) > 0:
@@ -1149,13 +1073,7 @@ def try_access_area(self, area, peek=False):
raise ClientError("Area is locked!")
if area.max_players > 0:
- players = len(
- [
- x
- for x in area.clients
- if (x not in area.owners and not x.is_mod and not x.hidden)
- ]
- )
+ players = len([x for x in area.clients if (x not in area.owners and not x.is_mod and not x.hidden)])
if players >= area.max_players:
raise ClientError("Area is full!")
elif area.max_players == 0:
@@ -1167,30 +1085,18 @@ def change_area(self, area, password=""):
:param area: area to switch to
"""
if self.area == area:
- raise ClientError(
- f"Failed to enter [{area.id}] {area.name}: User already in specified area."
- )
+ raise ClientError(f"Failed to enter [{area.id}] {area.name}: User already in specified area.")
allowed = (
- self.is_mod
- or self in area.owners
- or self.char_id == -1
- or area == area.area_manager.default_area()
+ self.is_mod or self in area.owners or self.char_id == -1 or area == area.area_manager.default_area()
)
if not allowed:
# If they're forced to follow, no escape.
- if (
- self.forced_to_follow
- and self.following is not None
- and self.following.area != area
- ):
- raise ClientError(
- "You can't escape when you've been forced to follow someone!"
- )
+ if self.forced_to_follow and self.following is not None and self.following.area != area:
+ raise ClientError("You can't escape when you've been forced to follow someone!")
try:
self.try_access_area(area)
except ClientError as ex:
- self.send_ooc(
- f"Failed to enter [{area.id}] {area.name}: {ex}")
+ self.send_ooc(f"Failed to enter [{area.id}] {area.name}: {ex}")
return
if (area.password != "" and password != area.password) or (
@@ -1210,12 +1116,8 @@ def change_area(self, area, password=""):
and self not in area.owners
):
if not area.area_manager.can_spectate:
- raise ClientError(
- f"Failed to enter [{area.id}] {area.name}: Cannot spectate in this hub!"
- )
- raise ClientError(
- f"Failed to enter [{area.id}] {area.name}: Cannot spectate that area!"
- )
+ raise ClientError(f"Failed to enter [{area.id}] {area.name}: Cannot spectate in this hub!")
+ raise ClientError(f"Failed to enter [{area.id}] {area.name}: Cannot spectate that area!")
target_pos = ""
if len(self.area.links) > 0:
@@ -1232,9 +1134,7 @@ def change_area(self, area, password=""):
# You gotta unhide first lol
self.hide(False)
self.area.broadcast_area_list(self)
- raise ClientError(
- f"Failed to enter [{area.id}] {area.name}: You had to leave your hiding spot!"
- )
+ raise ClientError(f"Failed to enter [{area.id}] {area.name}: You had to leave your hiding spot!")
delay = self.area.time_until_move(self)
if not self.forced_to_follow and not allowed and delay > 0:
@@ -1244,11 +1144,11 @@ def change_area(self, area, password=""):
)
# Mods and area owners can be any character regardless of availability
- if not (
- self.is_mod or self in area.owners or self.char_id == -1
- ) and not area.is_char_available(self.char_id):
+ if not (self.is_mod or self in area.owners or self.char_id == -1) and not area.is_char_available(
+ self.char_id
+ ):
self.check_char_taken(area)
-
+
old_area = self.area
self.set_area(area, target_pos)
self.last_move_time = round(time.time() * 1000.0)
@@ -1258,18 +1158,13 @@ def change_area(self, area, password=""):
if c.following == self:
if self.area.area_manager != c.area.area_manager:
# The person we're following may be trying to sneak away from us.
- c.unfollow(
- silent=not allowed and (
- self.hidden or self.sneaking)
- )
+ c.unfollow(silent=not allowed and (self.hidden or self.sneaking))
continue
# If they're still in the same hub, we're not hidden/sneaking or they're a mod, gm or cm
# Attempt to transfer to their area
try:
c.change_area(area)
- c.send_ooc(
- f"Following [{self.id}] {self.showname} to [{area.id}] {area.name}."
- )
+ c.send_ooc(f"Following [{self.id}] {self.showname} to [{area.id}] {area.name}.")
# Something obstructed us.
except ClientError as ex:
c.send_ooc(ex)
@@ -1280,17 +1175,12 @@ def change_area(self, area, password=""):
self.refresh_area_char_links(old_area)
reason = ""
- if (
- not self.area.dark
- and not self.area.force_sneak
- and not self.sneaking
- and not self.hidden
- ):
+ if not self.area.dark and not self.area.force_sneak and not self.sneaking and not self.hidden:
if not old_area.dark and not old_area.force_sneak:
if old_area.area_manager == self.area.area_manager:
if self.area.area_manager.passing_msg is True:
old_area.send_ic(
- msg=f'~~{"}}}"}[º{self.showname}º leaves to º{area.name}º.]',
+ msg=f"~~{'}}}'}[º{self.showname}º leaves to º{area.name}º.]",
emote_mod=1,
)
for c in old_area.clients:
@@ -1336,7 +1226,7 @@ def change_area(self, area, password=""):
)
if self.area.area_manager.passing_msg is True:
self.area.send_ic(
- msg=f'~~{"}}}"}[º{self.showname}º enters from º{old_area.name}º.]',
+ msg=f"~~{'}}}'}[º{self.showname}º enters from º{old_area.name}º.]",
emote_mod=1,
)
else:
@@ -1391,9 +1281,7 @@ def change_area(self, area, password=""):
)
if self.area.cannot_ic_interact(self):
- self.send_ooc(
- "This area is muted - you cannot talk in-character unless invited."
- )
+ self.send_ooc("This area is muted - you cannot talk in-character unless invited.")
# CU Packet
# CU#####%
@@ -1438,7 +1326,7 @@ def clear_user_links(self):
self.send_command("CU", "1", "2")
def get_new_area_user_links(self):
- """"
+ """ "
Get the char_urls of the new area that the client changed to.
And applying the changes.
"""
@@ -1454,8 +1342,6 @@ def get_new_area_user_links(self):
for client in clients:
self.add_user_link(client.char_name, client.char_url)
-
-
def refresh_area_char_links(self, old_area):
"""
Clears all user links in the old area.
@@ -1510,19 +1396,15 @@ def get_area_list(self, hidden=False, unlinked=False):
if not hidden and area.hidden:
continue
if len(self.area.links) > 0:
- if not (str(area.id) in self.area.links):
+ if str(area.id) not in self.area.links:
if not unlinked:
continue
- if (
- not hidden
- and self.area.links[str(area.id)]["hidden"] is True
- ):
+ if not hidden and self.area.links[str(area.id)]["hidden"] is True:
continue
if (
not hidden
and len(self.area.links[str(area.id)]["evidence"]) > 0
- and self.hidden_in
- not in self.area.links[str(area.id)]["evidence"]
+ and self.hidden_in not in self.area.links[str(area.id)]["evidence"]
):
continue
@@ -1547,7 +1429,7 @@ def send_area_list(self, full=False):
for _, area in enumerate(area_list):
if area.hidden:
continue
- msg += f'\n{self.get_area_info(area.id, highlight_self=True)}'
+ msg += f"\n{self.get_area_info(area.id, highlight_self=True)}"
self.send_ooc(msg)
def get_area_info(self, area_id, highlight_self=False, hub=None):
@@ -1570,12 +1452,7 @@ def get_area_info(self, area_id, highlight_self=False, hub=None):
owner = f"[CM(s): {area.get_owners()}]"
hidden = "📦" if area.hidden else ""
locked = "🔒" if area.locked else ""
- pathlocked = (
- "🚧"
- if str(area.id) in self.area.links
- and self.area.links[str(area.id)]["locked"]
- else ""
- )
+ pathlocked = "🚧" if str(area.id) in self.area.links and self.area.links[str(area.id)]["locked"] else ""
passworded = "🔑" if area.password != "" else ""
muted = "🔇" if area.muted else ""
dark = "🌑" if area.dark else ""
@@ -1589,17 +1466,19 @@ def get_area_info(self, area_id, highlight_self=False, hub=None):
info += "❌"
if not self.is_mod and self not in area.owners:
if area.hide_clients or area.area_manager.hide_clients or area.dark:
- users = ''
+ users = ""
else:
# We exclude hidden players here because we don't want them to count for the user count
player_list = [c for c in area.clients if not c.hidden]
- users = f' (users: {len(player_list)}) '
+ users = f" (users: {len(player_list)}) "
if area.hidden:
return ""
else:
- users = f' (users: {len(area.clients)}) '
+ users = f" (users: {len(area.clients)}) "
- info += f"[{area.id}] {area.name}{users}{status}{owner}{hidden}{locked}{pathlocked}{passworded}{muted}{dark}"
+ info += (
+ f"[{area.id}] {area.name}{users}{status}{owner}{hidden}{locked}{pathlocked}{passworded}{muted}{dark}"
+ )
return info
def get_area_clients(self, area_id, mods=False, afk_check=False, show_links=False, hub=None):
@@ -1633,19 +1512,27 @@ def get_area_clients(self, area_id, mods=False, afk_check=False, show_links=Fals
# Afterwards, sort the client list based on their unique role or status
sorted_clients = sorted(
sorted_clients,
- key=lambda x: 1
- if (x in area.afkers)
- else 2
- if x.hidden
- else 3
- if x.char_id == -1
- else 4
- if (x in area._owners)
- else 5
- if (x in area.area_manager.owners)
- else 6
- if x.is_mod
- else 0,
+ key=lambda x: (
+ 1
+ if (x in area.afkers)
+ else (
+ 2
+ if x.hidden
+ else (
+ 3
+ if x.char_id == -1
+ else (
+ 4
+ if (x in area._owners)
+ else 5
+ if (x in area.area_manager.owners)
+ else 6
+ if x.is_mod
+ else 0
+ )
+ )
+ )
+ ),
)
for c in sorted_clients:
info += "\r\n"
@@ -1688,16 +1575,11 @@ def send_areas_clients(self, mods=False, afk_check=False, show_links=False):
:param mods: if true, limit player list to mods
:param afk_check: if true, limit player list to afks
"""
- if (
- not self.is_mod
- and self not in self.area.area_manager.owners
- and self.char_id != -1
- ):
+ if not self.is_mod and self not in self.area.area_manager.owners and self.char_id != -1:
if self.blinded:
raise ClientError("You are blinded!")
if not self.area.area_manager.can_getareas:
- raise ClientError(
- "You cannot see players in all areas in this hub!")
+ raise ClientError("You cannot see players in all areas in this hub!")
info = "🗺️ Clients in Areas 🗺️\n"
cnt = 0
@@ -1711,7 +1593,7 @@ def send_areas_clients(self, mods=False, afk_check=False, show_links=False):
# We exclude hidden players here because we don't want them to count for the user count
client_list = [c for c in client_list if not c.hidden]
- area_info = f'{self.get_area_info(i)}:'
+ area_info = f"{self.get_area_info(i)}:"
if area_info == "":
continue
@@ -1722,10 +1604,7 @@ def send_areas_clients(self, mods=False, afk_check=False, show_links=False):
if area_info == "":
continue
- if (
- len(client_list) > 0
- or len(area.owners) > 0
- ):
+ if len(client_list) > 0 or len(area.owners) > 0:
cnt += len(client_list)
info += f"{area_info}\n"
if afk_check:
@@ -1738,26 +1617,16 @@ def send_hubs_clients(self, mods=False, afk_check=False, show_links=False):
"""
Send information over OOC about all hubs.
"""
- if (
- not self.is_mod
- and self not in self.area.area_manager.owners
- and self.char_id != -1
- ):
+ if not self.is_mod and self not in self.area.area_manager.owners and self.char_id != -1:
if self.blinded:
raise ClientError("You are blinded!")
if "can_gethubs" not in self.server.config or not self.server.config["can_gethubs"]:
- raise ClientError(
- "You are not permitted to use the /gethubs command in this server!"
- )
+ raise ClientError("You are not permitted to use the /gethubs command in this server!")
cnt = 0
info = "\n🗺️ Clients in Hubs 🗺️\n"
for hub in self.server.hub_manager.hubs:
hub_info = ""
- if (
- (not hub.can_getareas or hub.hide_clients)
- and not self.is_mod
- and self not in hub.owners
- ):
+ if (not hub.can_getareas or hub.hide_clients) and not self.is_mod and self not in hub.owners:
info += f"\n⛩[{hub.id}]{hub.name}⛩: ❌\n"
else:
for i in range(len(hub.areas)):
@@ -1775,9 +1644,7 @@ def send_hubs_clients(self, mods=False, afk_check=False, show_links=False):
continue
try:
- area_info += self.get_area_clients(
- i, mods, afk_check, show_links, hub=hub
- )
+ area_info += self.get_area_clients(i, mods, afk_check, show_links, hub=hub)
except ClientError:
area_info = ""
if area_info == "":
@@ -1786,9 +1653,7 @@ def send_hubs_clients(self, mods=False, afk_check=False, show_links=False):
if len(client_list) > 0 or len(area.owners) > 0:
cnt += len(client_list)
hub_info += f"{area_info}\n"
- if not hub_info == "" and (
- hub.can_getareas or self.is_mod or self in hub.owners
- ):
+ if not hub_info == "" and (hub.can_getareas or self.is_mod or self in hub.owners):
if not self.is_mod and self not in hub.owners:
hub_count = 0
for area in hub.areas:
@@ -1815,11 +1680,11 @@ def send_area_info(self, area_id, mods=False, afk_check=False, show_links=False)
if not self.is_mod and self not in self.area.owners:
if self.blinded:
raise ClientError("You are blinded!")
- area_info = f'📍 Clients in {self.get_area_info(area_id)} 📍'
+ area_info = f"📍 Clients in {self.get_area_info(area_id)} 📍"
try:
area_info += self.get_area_clients(area_id, mods, afk_check, show_links)
except ClientError as ex:
- area_info += f'\n{ex}'
+ area_info += f"\n{ex}"
info += area_info
self.send_ooc(info)
@@ -1879,9 +1744,7 @@ def char_select(self):
def get_available_char_list(self):
"""Get a list of character IDs that the client can select."""
if len(self.charcurse) > 0:
- avail_char_ids = set(range(len(self.area.area_manager.char_list))) and set(
- self.charcurse
- )
+ avail_char_ids = set(range(len(self.area.area_manager.char_list))) and set(self.charcurse)
else:
avail_char_ids = set(range(len(self.area.area_manager.char_list))) - {
x.char_id for x in self.area.clients
@@ -1901,8 +1764,7 @@ def auth_mod(self, password):
"""
modpasses = self.server.config["modpass"]
if isinstance(modpasses, dict):
- matches = [k for k in modpasses if modpasses[k]
- ["password"] == password]
+ matches = [k for k in modpasses if modpasses[k]["password"] == password]
elif modpasses == password:
matches = ["default"]
else:
@@ -1963,12 +1825,11 @@ def f_char_name_raw(self):
if self.iniswap != "":
return self.iniswap
- if ( self.char_id is None
- or self.char_id <= -1
- or self.char_id >= len(self.area.area_manager.char_list)):
+ if self.char_id is None or self.char_id <= -1 or self.char_id >= len(self.area.area_manager.char_list):
return ""
return self.area.area_manager.char_list[self.char_id]
+
@property
def f_char_name(self):
"""Get the name of either the character that the client is using or the iniswap."""
@@ -2001,15 +1862,12 @@ def showname(self, value):
@property
def move_delay(self):
"""Get the character's movement delay."""
- return self.area.area_manager.get_character_data(
- self.char_id, "move_delay", 0
- )
+ return self.area.area_manager.get_character_data(self.char_id, "move_delay", 0)
@move_delay.setter
def move_delay(self, value):
"""Set the character's move delay in the character data."""
- self.area.area_manager.set_character_data(
- self.char_id, "move_delay", value)
+ self.area.area_manager.set_character_data(self.char_id, "move_delay", value)
@property
def keys(self):
@@ -2019,8 +1877,7 @@ def keys(self):
@keys.setter
def keys(self, value):
"""Set the character's keys in the character data."""
- self.area.area_manager.set_character_data(
- self.char_id, "keys", value)
+ self.area.area_manager.set_character_data(self.char_id, "keys", value)
@property
def desc(self):
@@ -2030,8 +1887,7 @@ def desc(self):
@desc.setter
def desc(self, value):
"""Set the character's description character data."""
- self.area.area_manager.set_character_data(
- self.char_id, "desc", value)
+ self.area.area_manager.set_character_data(self.char_id, "desc", value)
@property
def hidden(self):
@@ -2041,34 +1897,28 @@ def hidden(self):
@property
def inventory(self):
"""Get the character's inventory."""
- return self.area.area_manager.get_character_data(
- self.char_id, "inventory", list()
- )
+ return self.area.area_manager.get_character_data(self.char_id, "inventory", list())
@inventory.setter
def inventory(self, value):
"""Set the character's inventory."""
- self.area.area_manager.set_character_data(
- self.char_id, "inventory", list(value))
+ self.area.area_manager.set_character_data(self.char_id, "inventory", list(value))
@property
def latest_area(self):
"""Get the character's latest occupied area ID."""
- return self.area.area_manager.get_character_data(
- self.char_id, "latest_area", None
- )
+ return self.area.area_manager.get_character_data(self.char_id, "latest_area", None)
- @inventory.setter
+ @latest_area.setter
def latest_area(self, value):
"""Set the character's latest occupied area ID."""
- self.area.area_manager.set_character_data(
- self.char_id, "latest_area", int(value))
-
+ self.area.area_manager.set_character_data(self.char_id, "latest_area", int(value))
+
def add_inventory_evidence(self, name, desc, image):
inventory = self.area.area_manager.get_character_data(self.char_id, "inventory", list())
inventory.append([name, desc, image])
self.area.area_manager.set_character_data(self.char_id, "inventory", inventory)
-
+
def remove_inventory_evidence(self, index):
inventory = self.area.area_manager.get_character_data(self.char_id, "inventory", list())
inventory.pop(index)
@@ -2085,9 +1935,7 @@ def hide(self, tog=True, target=None, hidden=False):
continue
if target.lower() == evi.name.lower() or target == str(i):
if not self.area.evi_list.can_hide_in(evi):
- raise ClientError(
- "Targeted evidence cannot be hidden in."
- )
+ raise ClientError("Targeted evidence cannot be hidden in.")
evidence = i
break
if evidence is not None:
@@ -2096,9 +1944,7 @@ def hide(self, tog=True, target=None, hidden=False):
c = evi.hiding_client
c.hide(False)
c.area.broadcast_area_list(c)
- raise ClientError(
- f"{c.showname} was already hiding in that evidence!"
- )
+ raise ClientError(f"{c.showname} was already hiding in that evidence!")
self.hidden_in = evidence
evi.hiding_client = self
msg += f" inside the {evi.name}"
@@ -2110,9 +1956,7 @@ def hide(self, tog=True, target=None, hidden=False):
evi.hiding_client = None
self.hidden_in = None
if not hidden:
- self.area.broadcast_ooc(
- f"{self.showname} emerges from the {evi.name}!"
- )
+ self.area.broadcast_ooc(f"{self.showname} emerges from the {evi.name}!")
# Impose all move delays as if we moved an area when unhiding so people have to be smart about it
self.last_move_time = round(time.time() * 1000.0)
@@ -2127,9 +1971,7 @@ def blind(self, tog=True):
msg = "no longer"
if tog:
msg = "now"
- self.send_ooc(
- f"You are {msg} blinded from the area and seeing non-broadcasted IC messages."
- )
+ self.send_ooc(f"You are {msg} blinded from the area and seeing non-broadcasted IC messages.")
self.send_command("LE", *self.area.get_evidence_list(self))
if not self.hidden and not self.sneaking:
self.area.broadcast_player_list()
@@ -2141,25 +1983,20 @@ def freeze(self, tog=True):
msg = "no longer"
if tog:
msg = "now"
- self.send_ooc(
- f"You are {msg} frozen from moving between areas."
- )
+ self.send_ooc(f"You are {msg} frozen from moving between areas.")
def sneak(self, tog=True):
self.sneaking = tog
msg = "no longer"
if tog:
msg = "now"
- self.send_ooc(
- f"You are {msg} sneaking (area transfer announcements will {msg} be hidden)."
- )
+ self.send_ooc(f"You are {msg} sneaking (area transfer announcements will {msg} be hidden).")
def follow(self, target):
try:
self.change_area(target.area)
self.following = target
- self.send_ooc(
- f"You are now following [{target.id}] {target.showname}.")
+ self.send_ooc(f"You are now following [{target.id}] {target.showname}.")
except ValueError:
raise
except (AreaError, ClientError):
@@ -2169,9 +2006,7 @@ def unfollow(self, silent=False):
if self.following is not None:
try:
if not silent:
- self.send_ooc(
- f"You are no longer following [{self.following.id}] {self.following.showname}."
- )
+ self.send_ooc(f"You are no longer following [{self.following.id}] {self.following.showname}.")
self.following = None
except Exception:
self.following = None
@@ -2181,7 +2016,7 @@ def change_position(self, pos=""):
Change the character's current position in the area.
:param pos: position in area (Default value = '')
"""
- if len(self.area.pos_lock) > 0 and not (pos in self.area.pos_lock) and pos != self.area.pos_dark:
+ if len(self.area.pos_lock) > 0 and pos not in self.area.pos_lock and pos != self.area.pos_dark:
poslist = ", ".join(str(l) for l in self.area.pos_lock)
raise ClientError(f"Invalid pos! Available pos are {poslist}.")
if self.hidden_in is not None:
@@ -2211,10 +2046,9 @@ def set_need_call_delay(self):
"""Begin the need cooldown."""
try:
self.need_call_time = round(
- time.time() * 1000.0
- + int(self.server.config["need_webhook"]["delay"]) * 1000.0
+ time.time() * 1000.0 + int(self.server.config["need_webhook"]["delay"]) * 1000.0
)
- except:
+ except Exception:
self.need_call_time = round(time.time() * 1000 + 60000)
def can_call_case(self):
@@ -2241,12 +2075,12 @@ def shake_message(self, message):
def rainbow_message(self, message):
"""Turn the message into rainbows (base color assumed to be blue)"""
# red orange yellow green cyan blue magenta
- color_array = ['~', '|', 'º', '`', '√', '', '№']
- constructed_message = ''
+ color_array = ["~", "|", "º", "`", "√", "", "№"]
+ constructed_message = ""
# pseudo-randomize the rainbows based on msg length
index = len(message) % len(color_array)
for symbol in message:
- symbol = f'{color_array[index]}{symbol}{color_array[index]}'
+ symbol = f"{color_array[index]}{symbol}{color_array[index]}"
constructed_message += symbol
index = (index + 1) % len(color_array)
return constructed_message
@@ -2258,14 +2092,14 @@ def __init__(self, server):
self.delays = {}
def set_spam_delay(self, ipid, spam_type, value):
- if not str(ipid) in self.delays:
+ if str(ipid) not in self.delays:
self.delays[str(ipid)] = {}
self.delays[str(ipid)][spam_type] = value
def get_spam_delay(self, ipid, spam_type):
- if not str(ipid) in self.delays:
+ if str(ipid) not in self.delays:
return 0
- if not spam_type in self.delays[str(ipid)]:
+ if spam_type not in self.delays[str(ipid)]:
return 0
return self.delays[str(ipid)][spam_type]
@@ -2290,8 +2124,7 @@ def new_client(self, transport):
peername = transport.get_extra_info("peername")[0]
- c = self.Client(self.server, transport, user_id,
- database.ipid(peername))
+ c = self.Client(self.server, transport, user_id, database.ipid(peername))
self.clients.add(c)
temp_ipid = c.ipid
for client in self.server.client_manager.clients:
@@ -2344,10 +2177,7 @@ def remove_client(self, client):
"FA",
*[
"🌐 Hubs 🌐\n Double-Click me to see Areas\n _______",
- *[
- f"[{hub.id}] {hub.name} (users: {hub.count})"
- for hub in self.server.hub_manager.hubs
- ],
+ *[f"[{hub.id}] {hub.name} (users: {hub.count})" for hub in self.server.hub_manager.hubs],
],
)
@@ -2390,7 +2220,7 @@ def get_targets(self, client, key, value, local=False, single=False, all_hub=Fal
targets.append(client)
elif key == TargetType.ID:
if client.id == value:
- targets.append(client)
+ targets.append(client)
elif key == TargetType.IPID:
if client.ipid == value:
targets.append(client)
@@ -2418,8 +2248,7 @@ def get_ooc_muted_clients(self):
def toggle_afk(self, client):
if client in client.area.afkers:
if not client.hidden and not client.sneaking:
- client.area.broadcast_ooc(
- "{} is no longer AFK.".format(client.showname))
+ client.area.broadcast_ooc("{} is no longer AFK.".format(client.showname))
client.send_ooc(
"You are no longer AFK. Welcome back!"
) # Making the server a bit friendly wouldn't hurt, right?
@@ -2448,7 +2277,7 @@ def get_multiclients(self, ipid=-1, hdid=""):
def get_mods(self):
return [c for c in self.clients if c.is_mod]
-
+
class BattleChar:
def __init__(self, client, fighter_name, fighter):
self.fighter = fighter_name
diff --git a/server/commands/__init__.py b/server/commands/__init__.py
index 5a3ba580..6978cf11 100644
--- a/server/commands/__init__.py
+++ b/server/commands/__init__.py
@@ -7,9 +7,7 @@ def call(client, cmd, arg):
if cmd in client.server.command_aliases:
called_function = f"ooc_cmd_{client.server.command_aliases[cmd]}"
if not hasattr(me, called_function):
- client.send_ooc(
- f"Invalid command: {cmd}. Use /help to find up-to-date commands."
- )
+ client.send_ooc(f"Invalid command: {cmd}. Use /help to find up-to-date commands.")
return
getattr(me, called_function)(client, arg)
@@ -68,11 +66,7 @@ def list_commands(submodule=""):
import inspect
cmds = ""
- modules = [
- a
- for a in submodules()
- if submodule == "" or a.__name__.split(".")[-1] == submodule
- ]
+ modules = [a for a in submodules() if submodule == "" or a.__name__.split(".")[-1] == submodule]
if len(modules) == 0:
raise AttributeError
for module in modules:
@@ -85,7 +79,7 @@ def list_commands(submodule=""):
doc = doc[: doc.find(".") + 1]
prefix = "ooc_cmd_"
if func.startswith(prefix):
- func = func[len(prefix):]
+ func = func[len(prefix) :]
cmds += f"{func} - {doc}\n"
return cmds
diff --git a/server/commands/admin.py b/server/commands/admin.py
index e9b12148..f09b30a8 100644
--- a/server/commands/admin.py
+++ b/server/commands/admin.py
@@ -54,9 +54,8 @@ def ooc_cmd_help(client, arg):
import inspect
if arg == "":
- msg = inspect.cleandoc(
- """
- Welcome to tsuserver3! You can use /help on any known
+ msg = inspect.cleandoc("""
+ Welcome to KFO-Server! You can use /help on any known
command to get up-to-date help on it.
You may also use /help to see available commands for that category.
@@ -66,8 +65,7 @@ def ooc_cmd_help(client, arg):
https://github.com/Crystalwarrior/KFO-Server/blob/master/README.md
Available Categories:
- """
- )
+ """)
msg += "\n"
msg += list_submodules()
client.send_ooc(msg)
@@ -83,9 +81,7 @@ def ooc_cmd_help(client, arg):
msg += list_commands(arg)
client.send_ooc(msg)
except AttributeError:
- client.send_ooc(
- f"No such command or submodule ({arg}) has been found in the help docs."
- )
+ client.send_ooc(f"No such command or submodule ({arg}) has been found in the help docs.")
@mod_only()
@@ -98,8 +94,7 @@ def ooc_cmd_kick(client, arg):
- "**" kicks everyone in the server.
"""
if len(arg) == 0:
- raise ArgumentError(
- "You must specify a target. Use /kick [reason]")
+ raise ArgumentError("You must specify a target. Use /kick [reason]")
elif arg[0] == "*":
targets = [c for c in client.area.clients if c != client]
elif arg[0] == "**":
@@ -114,15 +109,12 @@ def ooc_cmd_kick(client, arg):
ipid = int(raw_ipid)
except Exception:
raise ClientError(f"{raw_ipid} does not look like a valid IPID.")
- targets = client.server.client_manager.get_targets(
- client, TargetType.IPID, ipid, False
- )
+ targets = client.server.client_manager.get_targets(client, TargetType.IPID, ipid, False)
if targets:
reason = " ".join(args[1:])
for c in targets:
- database.log_misc("kick", client, target=c,
- data={"reason": reason})
+ database.log_misc("kick", client, target=c, data={"reason": reason})
client.send_ooc(f"{c.showname} was kicked.")
c.send_command("KK", reason)
c.disconnect()
@@ -175,9 +167,7 @@ def kickban(client, arg, ban_hdid):
raise ArgumentError("Invalid ban duration.")
unban_date = arrow.get().shift(seconds=duration).datetime
else:
- raise ArgumentError(
- f"Ambiguous input: {arg}\nPlease wrap your arguments " "in quotes."
- )
+ raise ArgumentError(f"Ambiguous input: {arg}\nPlease wrap your arguments in quotes.")
try:
raw_ipid = args[0]
@@ -197,24 +187,19 @@ def kickban(client, arg, ban_hdid):
char = None
hdid = None
if ipid is not None:
- targets = client.server.client_manager.get_targets(
- client, TargetType.IPID, ipid, False
- )
+ targets = client.server.client_manager.get_targets(client, TargetType.IPID, ipid, False)
if targets:
for c in targets:
if ban_hdid:
- database.ban(c.hdid, reason,
- ban_type="hdid", ban_id=ban_id)
+ database.ban(c.hdid, reason, ban_type="hdid", ban_id=ban_id)
hdid = c.hdid
c.send_command("KB", reason)
c.disconnect()
char = c.char_name
- database.log_misc("ban", client, target=c,
- data={"reason": reason})
+ database.log_misc("ban", client, target=c, data={"reason": reason})
client.send_ooc(f"{len(targets)} clients were kicked.")
client.send_ooc(f"{ipid} was banned. Ban ID: {ban_id}")
- client.server.webhooks.ban(
- ipid, ban_id, reason, client, hdid, char, unban_date)
+ client.server.webhooks.ban(ipid, ban_id, reason, client, hdid, char, unban_date)
@mod_only()
@@ -224,8 +209,7 @@ def ooc_cmd_unban(client, arg):
Usage: /unban
"""
if len(arg) == 0:
- raise ArgumentError(
- "You must specify a target. Use /unban ")
+ raise ArgumentError("You must specify a target. Use /unban ")
args = list(arg.split(" "))
client.send_ooc(f"Attempting to lift {len(args)} ban(s)...")
for ban_id in args:
@@ -250,9 +234,7 @@ def ooc_cmd_mute(client, arg):
for raw_ipid in args:
if raw_ipid.isdigit():
ipid = int(raw_ipid)
- clients = client.server.client_manager.get_targets(
- client, TargetType.IPID, ipid, False
- )
+ clients = client.server.client_manager.get_targets(client, TargetType.IPID, ipid, False)
if clients:
msg = "Muted the IPID " + str(ipid) + "'s following clients:"
for c in clients:
@@ -263,9 +245,7 @@ def ooc_cmd_mute(client, arg):
msg += "."
client.send_ooc(msg)
else:
- client.send_ooc(
- "No targets found. Use /mute ... for mute."
- )
+ client.send_ooc("No targets found. Use /mute ... for mute.")
else:
client.send_ooc(f"{raw_ipid} does not look like a valid IPID.")
@@ -283,9 +263,7 @@ def ooc_cmd_unmute(client, arg):
for raw_ipid in args:
if raw_ipid.isdigit():
ipid = int(raw_ipid)
- clients = client.server.client_manager.get_targets(
- client, TargetType.IPID, ipid, False
- )
+ clients = client.server.client_manager.get_targets(client, TargetType.IPID, ipid, False)
if clients:
msg = f"Unmuted the IPID ${str(ipid)}'s following clients:"
for c in clients:
@@ -296,9 +274,7 @@ def ooc_cmd_unmute(client, arg):
msg += "."
client.send_ooc(msg)
else:
- client.send_ooc(
- "No targets found. Use /unmute ... for unmute."
- )
+ client.send_ooc("No targets found. Use /unmute ... for unmute.")
else:
client.send_ooc(f"{raw_ipid} does not look like a valid IPID.")
@@ -382,11 +358,8 @@ def ooc_cmd_ooc_mute(client, arg):
Usage: /ooc_mute
"""
if len(arg) == 0:
- raise ArgumentError(
- "You must specify a target. Use /ooc_mute .")
- targets = client.server.client_manager.get_targets(
- client, TargetType.OOC_NAME, arg, False
- )
+ raise ArgumentError("You must specify a target. Use /ooc_mute .")
+ targets = client.server.client_manager.get_targets(client, TargetType.OOC_NAME, arg, False)
if not targets:
raise ArgumentError("Targets not found. Use /ooc_mute .")
for target in targets:
@@ -402,8 +375,7 @@ def ooc_cmd_ooc_unmute(client, arg):
Usage: /ooc_unmute
"""
if len(arg) == 0:
- raise ArgumentError(
- "You must specify a target. Use /ooc_unmute .")
+ raise ArgumentError("You must specify a target. Use /ooc_unmute .")
targets = client.server.client_manager.get_ooc_muted_clients()
if not targets:
raise ArgumentError("Targets not found. Use /ooc_unmute .")
@@ -422,10 +394,7 @@ def ooc_cmd_bans(client, _arg):
msg = "Last 5 bans:\n"
for ban in database.recent_bans():
time = arrow.get(ban.ban_date).humanize()
- msg += (
- f"{time}: {ban.banned_by_name} ({ban.banned_by}) issued ban "
- f"{ban.ban_id} ('{ban.reason}')\n"
- )
+ msg += f"{time}: {ban.banned_by_name} ({ban.banned_by}) issued ban {ban.ban_id} ('{ban.reason}')\n"
client.send_ooc(msg)
@@ -452,8 +421,7 @@ def ooc_cmd_baninfo(client, arg):
client.send_ooc("No ban found for this ID.")
else:
msg = f"Ban ID: {ban.ban_id}\n"
- msg += "Affected IPIDs: " + \
- ", ".join([str(ipid) for ipid in ban.ipids]) + "\n"
+ msg += "Affected IPIDs: " + ", ".join([str(ipid) for ipid in ban.ipids]) + "\n"
msg += "Affected HDIDs: " + ", ".join(ban.hdids) + "\n"
msg += f'Reason: "{ban.reason}"\n'
msg += f"Banned by: {ban.banned_by_name} ({ban.banned_by})\n"
@@ -523,8 +491,7 @@ def ooc_cmd_restart(client, arg):
if arg != client.server.config["restartpass"]:
raise ArgumentError("no")
print(f"!!!{client.name} called /restart!!!")
- client.server.send_all_cmd_pred(
- "CT", "WARNING", "Restarting the server...")
+ client.server.send_all_cmd_pred("CT", "WARNING", "Restarting the server...")
asyncio.get_running_loop().stop()
diff --git a/server/commands/area_access.py b/server/commands/area_access.py
index 7b1318ba..2e33aaeb 100644
--- a/server/commands/area_access.py
+++ b/server/commands/area_access.py
@@ -42,27 +42,18 @@ def ooc_cmd_area_lock(client, arg):
area_list = client.area.area_manager.get_areas_by_args(args)
for area in area_list:
if not client.is_mod and client not in area.owners:
- if not str(target_id) in client.keys:
+ if str(area.id) not in client.keys:
if area.locking_allowed and area != client.area:
- client.send_ooc(
- "You can only lock that area from within!")
+ client.send_ooc("You can only lock that area from within!")
continue
if not area.locking_allowed:
- client.send_ooc(
- f"You don't have the keys to {area.name}.")
+ client.send_ooc(f"You don't have the keys to {area.name}.")
continue
if not client.can_access_area(area):
- client.send_ooc(
- f"You have the keys to {area.name} but it is not accessible from your area."
- )
+ client.send_ooc(f"You have the keys to {area.name} but it is not accessible from your area.")
continue
- if (
- str(area.id) in client.area.links
- and client.area.links[str(area.id)]["locked"]
- ):
- client.send_ooc(
- f"You have the keys to {area.name} but the path is locked."
- )
+ if str(area.id) in client.area.links and client.area.links[str(area.id)]["locked"]:
+ client.send_ooc(f"You have the keys to {area.name} but the path is locked.")
continue
if area.locked:
client.send_ooc(f"Area {area.name} is already locked.")
@@ -94,8 +85,7 @@ def ooc_cmd_area_mute(client, arg):
continue
if area.muted:
- client.send_ooc(
- f"Area [{area.id}] {area.name} is already muted.")
+ client.send_ooc(f"Area [{area.id}] {area.name} is already muted.")
continue
area.mute()
area.broadcast_ooc("This area is now muted.")
@@ -125,8 +115,7 @@ def ooc_cmd_area_unmute(client, arg):
continue
if not area.muted:
- client.send_ooc(
- f"Area [{area.id}] {area.name} is already unmuted.")
+ client.send_ooc(f"Area [{area.id}] {area.name} is already unmuted.")
continue
area.unmute()
area.broadcast_ooc("This area is no longer muted.")
@@ -151,27 +140,18 @@ def ooc_cmd_area_unlock(client, arg):
area_list = client.area.area_manager.get_areas_by_args(args)
for area in area_list:
if not client.is_mod and client not in area.owners:
- if not str(target_id) in client.keys:
+ if str(area.id) not in client.keys:
if area.locking_allowed and area != client.area:
- client.send_ooc(
- "You can only unlock that area from within!")
+ client.send_ooc("You can only unlock that area from within!")
continue
if not area.locking_allowed:
- client.send_ooc(
- "You don't have the keys to {area.name}.")
+ client.send_ooc("You don't have the keys to {area.name}.")
continue
if not client.can_access_area(area):
- client.send_ooc(
- f"You have the keys to {area.name} but it is not accessible from your area."
- )
+ client.send_ooc(f"You have the keys to {area.name} but it is not accessible from your area.")
continue
- if (
- str(area.id) in client.area.links
- and client.area.links[str(area.id)]["locked"]
- ):
- client.send_ooc(
- f"You have the keys to {area.name} but the path is locked."
- )
+ if str(area.id) in client.area.links and client.area.links[str(area.id)]["locked"]:
+ client.send_ooc(f"You have the keys to {area.name} but the path is locked.")
continue
if not area.locked:
client.send_ooc(f"Area {area.name} is already unlocked.")
@@ -263,9 +243,7 @@ def ooc_cmd_link(client, arg):
area.link(client.area.id)
links.append(target_id)
links = ", ".join(str(link) for link in links)
- client.send_ooc(
- f"Area {client.area.name} has been linked with {links} (two-way)."
- )
+ client.send_ooc(f"Area {client.area.name} has been linked with {links} (two-way).")
client.area.broadcast_area_list()
area.broadcast_area_list()
except ValueError:
@@ -305,9 +283,7 @@ def ooc_cmd_unlink(client, arg):
except Exception:
continue
links = ", ".join(str(link) for link in links)
- client.send_ooc(
- f"Area {client.area.name} has been unlinked with {links} (two-way)."
- )
+ client.send_ooc(f"Area {client.area.name} has been unlinked with {links} (two-way).")
client.area.broadcast_area_list()
area.broadcast_area_list()
except ValueError:
@@ -330,7 +306,7 @@ def ooc_cmd_links(client, arg):
continue
hidden = "📦"
- if len(value["evidence"]) > 0 and not (client.hidden_in in value["evidence"]):
+ if len(value["evidence"]) > 0 and client.hidden_in not in value["evidence"]:
# Can't see hidden links
if not client.is_mod and client not in client.area.owners:
continue
@@ -383,9 +359,7 @@ def ooc_cmd_onelink(client, arg):
client.area.link(target_id)
links.append(target_id)
links = ", ".join(str(link) for link in links)
- client.send_ooc(
- f"Area {client.area.name} has been linked with {links} (one-way)."
- )
+ client.send_ooc(f"Area {client.area.name} has been linked with {links} (one-way).")
client.area.broadcast_area_list()
except ValueError:
raise ArgumentError("Area ID must be a number or abbreviation.")
@@ -401,14 +375,12 @@ def ooc_cmd_oneunlink(client, arg):
"""
args = arg.split()
if len(args) <= 0:
- raise ArgumentError(
- "Invalid number of arguments. Use /oneunlink ")
+ raise ArgumentError("Invalid number of arguments. Use /oneunlink ")
try:
links = []
for aid in args:
try:
- target_id = client.area.area_manager.get_area_by_abbreviation(
- aid).id
+ target_id = client.area.area_manager.get_area_by_abbreviation(aid).id
except Exception:
target_id = int(aid)
@@ -418,9 +390,7 @@ def ooc_cmd_oneunlink(client, arg):
except Exception:
continue
links = ", ".join(str(link) for link in links)
- client.send_ooc(
- f"Area {client.area.name} has been unlinked with {links} (one-way)."
- )
+ client.send_ooc(f"Area {client.area.name} has been unlinked with {links} (one-way).")
client.area.broadcast_area_list()
except ValueError:
raise ArgumentError("Area ID must be a number or abbreviation.")
@@ -435,40 +405,31 @@ def ooc_cmd_link_lock(client, arg):
"""
args = arg.split()
if len(args) <= 0:
- raise ArgumentError(
- "Invalid number of arguments. Use /link_lock ")
+ raise ArgumentError("Invalid number of arguments. Use /link_lock ")
try:
links = []
for aid in args:
try:
- target_id = client.area.area_manager.get_area_by_abbreviation(
- aid).id
+ target_id = client.area.area_manager.get_area_by_abbreviation(aid).id
except Exception:
target_id = int(aid)
if not client.is_mod and client not in client.area.owners:
if f"{client.area.id}-{target_id}" not in client.keys:
- client.send_ooc(
- f"You don't have the keys to the link {client.area.id}-{target_id}."
- )
+ client.send_ooc(f"You don't have the keys to the link {client.area.id}-{target_id}.")
continue
- target_area = client.area.area_manager.get_area_by_id(
- target_id)
+ target_area = client.area.area_manager.get_area_by_id(target_id)
if (
- f"{target_id}-{client.area.id}" in client.keys
- and str(client.area.id) in target_area.links
+ f"{target_id}-{client.area.id}" in client.keys and str(client.area.id) in target_area.links
): # Treat it as a single door/path if we have the keys both ways
target_area.links[str(client.area.id)]["locked"] = True
- client.send_ooc(
- f"Locked {client.area.id}-{target_id} both ways.")
+ client.send_ooc(f"Locked {client.area.id}-{target_id} both ways.")
client.area.links[str(target_id)]["locked"] = True
links.append(target_id)
if len(links) > 0:
links = ", ".join(str(link) for link in links)
client.send_ooc(f"Area {client.area.name} links {links} locked.")
except (ValueError, KeyError):
- raise ArgumentError(
- "Area ID must be a number or abbreviation and the link must exist."
- )
+ raise ArgumentError("Area ID must be a number or abbreviation and the link must exist.")
except (AreaError, ClientError):
raise
@@ -480,40 +441,31 @@ def ooc_cmd_link_unlock(client, arg):
"""
args = arg.split()
if len(args) <= 0:
- raise ArgumentError(
- "Invalid number of arguments. Use /link_unlock ")
+ raise ArgumentError("Invalid number of arguments. Use /link_unlock ")
try:
links = []
for aid in args:
try:
- target_id = client.area.area_manager.get_area_by_abbreviation(
- aid).id
+ target_id = client.area.area_manager.get_area_by_abbreviation(aid).id
except Exception:
target_id = int(aid)
if not client.is_mod and client not in client.area.owners:
if f"{client.area.id}-{target_id}" not in client.keys:
- client.send_ooc(
- f"You don't have the keys to the link {client.area.id}-{target_id}."
- )
+ client.send_ooc(f"You don't have the keys to the link {client.area.id}-{target_id}.")
continue
- target_area = client.area.area_manager.get_area_by_id(
- target_id)
+ target_area = client.area.area_manager.get_area_by_id(target_id)
if (
- f"{target_id}-{client.area.id}" in client.keys
- and str(client.area.id) in target_area.links
+ f"{target_id}-{client.area.id}" in client.keys and str(client.area.id) in target_area.links
): # Treat it as a single door/path if we have the keys both ways
target_area.links[str(client.area.id)]["locked"] = False
- client.send_ooc(
- f"Unlocked {client.area.id}-{target_id} both ways.")
+ client.send_ooc(f"Unlocked {client.area.id}-{target_id} both ways.")
client.area.links[str(target_id)]["locked"] = False
links.append(target_id)
if len(links) > 0:
links = ", ".join(str(link) for link in links)
client.send_ooc(f"Area {client.area.name} links {links} unlocked.")
except (ValueError, KeyError):
- raise ArgumentError(
- "Area ID must be a number or abbreviation and the link must exist."
- )
+ raise ArgumentError("Area ID must be a number or abbreviation and the link must exist.")
except (AreaError, ClientError):
raise
@@ -526,14 +478,12 @@ def ooc_cmd_link_hide(client, arg):
"""
args = arg.split()
if len(args) <= 0:
- raise ArgumentError(
- "Invalid number of arguments. Use /link_hide ")
+ raise ArgumentError("Invalid number of arguments. Use /link_hide ")
try:
links = []
for aid in args:
try:
- target_id = client.area.area_manager.get_area_by_abbreviation(
- aid).id
+ target_id = client.area.area_manager.get_area_by_abbreviation(aid).id
except Exception:
target_id = int(aid)
@@ -556,14 +506,12 @@ def ooc_cmd_link_unhide(client, arg):
"""
args = arg.split()
if len(args) <= 0:
- raise ArgumentError(
- "Invalid number of arguments. Use /link_unhide ")
+ raise ArgumentError("Invalid number of arguments. Use /link_unhide ")
try:
links = []
for aid in args:
try:
- target_id = client.area.area_manager.get_area_by_abbreviation(
- aid).id
+ target_id = client.area.area_manager.get_area_by_abbreviation(aid).id
except Exception:
target_id = int(aid)
@@ -586,20 +534,16 @@ def ooc_cmd_link_pos(client, arg):
"""
args = arg.split()
if len(args) <= 0:
- raise ArgumentError(
- "Invalid number of arguments. Use /link_unhide ")
+ raise ArgumentError("Invalid number of arguments. Use /link_unhide ")
try:
try:
- target_id = client.area.area_manager.get_area_by_abbreviation(
- args[0]).id
+ target_id = client.area.area_manager.get_area_by_abbreviation(args[0]).id
except Exception:
target_id = int(args[0])
- pos = ' '.join(args[1:])
+ pos = " ".join(args[1:])
client.area.links[str(target_id)]["target_pos"] = pos
- client.send_ooc(
- f'Area {client.area.name} link {target_id}\'s target pos set to "{pos}".'
- )
+ client.send_ooc(f'Area {client.area.name} link {target_id}\'s target pos set to "{pos}".')
except (ValueError, KeyError):
raise ArgumentError("Area ID must be a number or abbreviation.")
except (AreaError, ClientError):
@@ -614,14 +558,12 @@ def ooc_cmd_link_peekable(client, arg):
"""
args = arg.split()
if len(args) <= 0:
- raise ArgumentError(
- "Invalid number of arguments. Use /link_peekable ")
+ raise ArgumentError("Invalid number of arguments. Use /link_peekable ")
try:
links = []
for aid in args:
try:
- target_id = client.area.area_manager.get_area_by_abbreviation(
- aid).id
+ target_id = client.area.area_manager.get_area_by_abbreviation(aid).id
except Exception:
target_id = int(aid)
@@ -629,8 +571,7 @@ def ooc_cmd_link_peekable(client, arg):
links.append(target_id)
if len(links) > 0:
links = ", ".join(str(link) for link in links)
- client.send_ooc(
- f"Area {client.area.name} links {links} are now peekable.")
+ client.send_ooc(f"Area {client.area.name} links {links} are now peekable.")
except (ValueError, KeyError):
raise ArgumentError("Area ID must be a number or abbreviation.")
except (AreaError, ClientError):
@@ -645,14 +586,12 @@ def ooc_cmd_link_unpeekable(client, arg):
"""
args = arg.split()
if len(args) <= 0:
- raise ArgumentError(
- "Invalid number of arguments. Use /link_unpeekable ")
+ raise ArgumentError("Invalid number of arguments. Use /link_unpeekable ")
try:
links = []
for aid in args:
try:
- target_id = client.area.area_manager.get_area_by_abbreviation(
- aid).id
+ target_id = client.area.area_manager.get_area_by_abbreviation(aid).id
except Exception:
target_id = int(aid)
@@ -660,9 +599,7 @@ def ooc_cmd_link_unpeekable(client, arg):
links.append(target_id)
if len(links) > 0:
links = ", ".join(str(link) for link in links)
- client.send_ooc(
- f"Area {client.area.name} links {links} are no longer peekable."
- )
+ client.send_ooc(f"Area {client.area.name} links {links} are no longer peekable.")
except (ValueError, KeyError):
raise ArgumentError("Area ID must be a number or abbreviation.")
except (AreaError, ClientError):
@@ -678,9 +615,7 @@ def ooc_cmd_link_evidence(client, arg):
"""
args = arg.split()
if len(args) <= 0:
- raise ArgumentError(
- "Invalid number of arguments. Use /link_evidence [evi_id(s)]"
- )
+ raise ArgumentError("Invalid number of arguments. Use /link_evidence [evi_id(s)]")
link = None
evidences = []
try:
@@ -688,9 +623,7 @@ def ooc_cmd_link_evidence(client, arg):
if len(args) > 1:
for evi_id in args[1:]:
evi_id = int(evi_id) - 1
- client.area.evi_list.evidences[
- evi_id
- ] # Test if we can access target evidence
+ client.area.evi_list.evidences[evi_id] # Test if we can access target evidence
evidences.append(evi_id)
except IndexError:
raise ArgumentError("Evidence not found.")
@@ -704,13 +637,9 @@ def ooc_cmd_link_evidence(client, arg):
if len(link["evidence"]) > 0:
evi_list = ", ".join(str(evi + 1) for evi in link["evidence"])
- client.send_ooc(
- f"Area {client.area.name} link {args[0]} associated evidence IDs: {evi_list}."
- )
+ client.send_ooc(f"Area {client.area.name} link {args[0]} associated evidence IDs: {evi_list}.")
else:
- client.send_ooc(
- f"Area {client.area.name} link {args[0]} has no associated evidence."
- )
+ client.send_ooc(f"Area {client.area.name} link {args[0]} has no associated evidence.")
@mod_only(area_owners=True)
@@ -722,9 +651,7 @@ def ooc_cmd_unlink_evidence(client, arg):
"""
args = arg.split()
if len(args) <= 0:
- raise ArgumentError(
- "Invalid number of arguments. Use /unlink_evidence [evi_id(s)]"
- )
+ raise ArgumentError("Invalid number of arguments. Use /unlink_evidence [evi_id(s)]")
link = None
evidences = []
try:
@@ -741,14 +668,10 @@ def ooc_cmd_unlink_evidence(client, arg):
if len(evidences) > 0:
link["evidence"] = link["evidence"] - evidences
evi_list = ", ".join(str(evi + 1) for evi in evidences)
- client.send_ooc(
- f"Area {client.area.name} link {args[0]} is now unlinked from evidence IDs: {evi_list}."
- )
+ client.send_ooc(f"Area {client.area.name} link {args[0]} is now unlinked from evidence IDs: {evi_list}.")
else:
link["evidence"] = []
- client.send_ooc(
- f"Area {client.area.name} link {args[0]} associated evidences cleared."
- )
+ client.send_ooc(f"Area {client.area.name} link {args[0]} associated evidences cleared.")
def ooc_cmd_pw(client, arg):
@@ -761,10 +684,8 @@ def ooc_cmd_pw(client, arg):
link = None
password = ""
if arg == "":
- if not client.is_mod and not (client in client.area.owners):
- raise ArgumentError(
- "You are not allowed to see this area's password. Use /pw [password]"
- )
+ if not client.is_mod and client not in client.area.owners:
+ raise ArgumentError("You are not allowed to see this area's password. Use /pw [password]")
aid = client.area.id
else:
args = arg.split()
@@ -779,17 +700,11 @@ def ooc_cmd_pw(client, arg):
if password == "":
if client.is_mod or client in client.area.owners:
if link is not None and link["password"] != "":
- client.send_ooc(
- f'Link {client.area.id}-{area.id} password is: {link["password"]}'
- )
+ client.send_ooc(f"Link {client.area.id}-{area.id} password is: {link['password']}")
else:
- client.send_ooc(
- f"Area [{area.id}] {area.name} password is: {area.password}"
- )
+ client.send_ooc(f"Area [{area.id}] {area.name} password is: {area.password}")
else:
- raise ClientError(
- "You must provide a password. Use /pw [password]"
- )
+ raise ClientError("You must provide a password. Use /pw [password]")
else:
client.change_area(area, password=password)
except ValueError:
@@ -808,8 +723,7 @@ def ooc_cmd_setpw(client, arg):
"""
args = arg.split()
if len(args) == 0:
- raise ArgumentError(
- "Invalid number of arguments. Use /setpw [password]")
+ raise ArgumentError("Invalid number of arguments. Use /setpw [password]")
try:
password = ""
@@ -821,26 +735,20 @@ def ooc_cmd_setpw(client, arg):
link = client.area.links[num]
area = client.area.area_manager.get_area_by_id(int(num))
else:
- raise ArgumentError(
- "Targeted link does not exist in current area.")
+ raise ArgumentError("Targeted link does not exist in current area.")
else:
area = client.area.area_manager.get_area_by_id(int(args[0]))
if len(args) > 1:
password = args[1]
- if not client.is_mod and not (client in area.owners):
+ if not client.is_mod and client not in area.owners:
raise ClientError("You do not own that area!")
if link is not None:
link["password"] = password
- client.send_ooc(
- f"Link {client.area.id}-{area.id} password set to: {password}"
- )
+ client.send_ooc(f"Link {client.area.id}-{area.id} password set to: {password}")
else:
area.password = password
- client.send_ooc(
- f"Area [{area.id}] {area.name} password set to: {password}")
+ client.send_ooc(f"Area [{area.id}] {area.name} password set to: {password}")
except ValueError:
- raise ArgumentError(
- "Area ID must be a number, or a link ID must start with ! e.g. 5 vs !5."
- )
+ raise ArgumentError("Area ID must be a number, or a link ID must start with ! e.g. 5 vs !5.")
except (AreaError, ClientError):
raise
diff --git a/server/commands/areas.py b/server/commands/areas.py
index 7d8c5805..93da9d43 100644
--- a/server/commands/areas.py
+++ b/server/commands/areas.py
@@ -39,14 +39,14 @@
"ooc_cmd_clear_area_broadcast",
]
+
def ooc_cmd_overlay(client, arg):
"""
Set the overlay of an area.
Usage: /overlay
"""
if len(arg) == 0:
- client.send_ooc(
- f"Current overlay is {client.area.overlay}. Use /overlay_clear to clear it.")
+ client.send_ooc(f"Current overlay is {client.area.overlay}. Use /overlay_clear to clear it.")
return
if client not in client.area.owners and not client.is_mod and client.area.overlay_lock:
raise AreaError("This area's overlay system is locked!")
@@ -54,22 +54,18 @@ def ooc_cmd_overlay(client, arg):
raise AreaError("This area's background is locked!")
if client.area.cannot_ic_interact(client):
raise AreaError("You are not on the area's invite list!")
- if (
- not client.is_mod
- and not (client in client.area.owners)
- and client.char_id == -1
- ):
+ if not client.is_mod and client not in client.area.owners and client.char_id == -1:
raise ClientError("You may not do that while spectating!")
- if client.area.dark and not client.is_mod and not (client in client.area.owners):
+ if client.area.dark and not client.is_mod and client not in client.area.owners:
raise ClientError("You must be authorized to do that.")
try:
client.area.change_background(client.area._background, overlay=arg)
except AreaError:
raise
- client.area.broadcast_ooc(
- f"{client.showname} changed the overlay to {arg}.")
+ client.area.broadcast_ooc(f"{client.showname} changed the overlay to {arg}.")
database.log_area("overlay", client, client.area, message=arg)
+
def ooc_cmd_overlay_clear(client, arg):
"""
Clear the overlay of an area.
@@ -81,22 +77,18 @@ def ooc_cmd_overlay_clear(client, arg):
raise AreaError("This area's background is locked!")
if client.area.cannot_ic_interact(client):
raise AreaError("You are not on the area's invite list!")
- if (
- not client.is_mod
- and not (client in client.area.owners)
- and client.char_id == -1
- ):
+ if not client.is_mod and client not in client.area.owners and client.char_id == -1:
raise ClientError("You may not do that while spectating!")
- if client.area.dark and not client.is_mod and not (client in client.area.owners):
+ if client.area.dark and not client.is_mod and client not in client.area.owners:
raise ClientError("You must be authorized to do that.")
try:
client.area.change_background(client.area._background, overlay="")
except AreaError:
raise
- client.area.broadcast_ooc(
- f"{client.showname} cleared the overlay.")
+ client.area.broadcast_ooc(f"{client.showname} cleared the overlay.")
database.log_area("overlay_clear", client, client.area)
+
def ooc_cmd_bg(client, arg):
"""
Set the background of an area.
@@ -110,27 +102,21 @@ def ooc_cmd_bg(client, arg):
suffix = ""
if client.area.background_suffix:
suffix = client.area.background_suffix
- client.send_ooc(
- f"Current background is '{client.area._background}' + '{suffix}'.{pos_lock}")
+ client.send_ooc(f"Current background is '{client.area._background}' + '{suffix}'.{pos_lock}")
return
if client not in client.area.owners and not client.is_mod and client.area.bg_lock:
raise AreaError("This area's background is locked!")
if client.area.cannot_ic_interact(client):
raise AreaError("You are not on the area's invite list!")
- if (
- not client.is_mod
- and not (client in client.area.owners)
- and client.char_id == -1
- ):
+ if not client.is_mod and client not in client.area.owners and client.char_id == -1:
raise ClientError("You may not do that while spectating!")
- if client.area.dark and not client.is_mod and not (client in client.area.owners):
+ if client.area.dark and not client.is_mod and client not in client.area.owners:
raise ClientError("You must be authorized to do that.")
try:
client.area.change_background(arg)
except AreaError:
raise
- client.area.broadcast_ooc(
- f"{client.showname} changed the background to {arg}.")
+ client.area.broadcast_ooc(f"{client.showname} changed the background to {arg}.")
database.log_area("bg", client, client.area, message=arg)
@@ -146,8 +132,7 @@ def ooc_cmd_bg_suffix(client, arg):
client.area.change_background_suffix(arg)
except AreaError:
raise
- client.send_ooc(
- f"You changed the background suffix to {arg}.")
+ client.send_ooc(f"You changed the background suffix to {arg}.")
database.log_area("bg", client, client.area, message=arg)
@@ -180,28 +165,15 @@ def ooc_cmd_status(client, arg):
if len(arg) == 0:
client.send_ooc(f"Current status: {client.area.status}")
else:
- if (
- not client.area.can_change_status
- and not client.is_mod
- and client not in client.area.owners
- ):
- raise AreaError(
- "This area's status cannot be changed by anyone who's not a CM or mod!"
- )
+ if not client.area.can_change_status and not client.is_mod and client not in client.area.owners:
+ raise AreaError("This area's status cannot be changed by anyone who's not a CM or mod!")
if client.area.cannot_ic_interact(client):
raise AreaError("You are not on the area's invite list!")
- if (
- not client.is_mod
- and client not in client.area.owners
- and client.char_id == -1
- ):
+ if not client.is_mod and client not in client.area.owners and client.char_id == -1:
raise ClientError("You may not do that while spectating!")
try:
client.area.change_status(arg)
- client.area.broadcast_ooc(
- "{} changed status to {}.".format(
- client.showname, client.area.status)
- )
+ client.area.broadcast_ooc("{} changed status to {}.".format(client.showname, client.area.status))
database.log_area("status", client, client.area, message=arg)
except AreaError:
raise
@@ -221,12 +193,7 @@ def ooc_cmd_area(client, arg):
a = arg.split(" ")[0]
aid = a.strip("[]")
if (
- (
- a.startswith("[")
- and a.endswith("]")
- and aid.isdigit()
- and area.id == int(aid)
- )
+ (a.startswith("[") and a.endswith("]") and aid.isdigit() and area.id == int(aid))
or area.name.lower() == arg.lower()
or area.abbreviation == arg
or (arg.isdigit() and area.id == int(arg))
@@ -235,8 +202,7 @@ def ooc_cmd_area(client, arg):
return
raise AreaError("Targeted area not found!")
except ValueError:
- raise ArgumentError(
- "Area ID must be a name, abbreviation or a number.")
+ raise ArgumentError("Area ID must be a name, abbreviation or a number.")
except (AreaError, ClientError):
raise
@@ -251,9 +217,7 @@ def ooc_cmd_area_visible(client, arg):
client.available_areas_only = not client.available_areas_only
toggle = "enabled" if client.available_areas_only else "disabled"
client.area.broadcast_area_list(client)
- client.send_ooc(
- f"You have {toggle} only displaying player-visible areas."
- )
+ client.send_ooc(f"You have {toggle} only displaying player-visible areas.")
def ooc_cmd_autogetarea(client, arg):
@@ -263,9 +227,7 @@ def ooc_cmd_autogetarea(client, arg):
"""
client.autogetarea = not client.autogetarea
toggle = "enabled" if client.autogetarea else "disabled"
- client.send_ooc(
- f"You have {toggle} automatic /getarea."
- )
+ client.send_ooc(f"You have {toggle} automatic /getarea.")
def ooc_cmd_getarea(client, arg):
@@ -279,8 +241,7 @@ def ooc_cmd_getarea(client, arg):
if area.id == client.area.id or (client.is_mod or client in area.owners):
aid = int(arg)
else:
- raise ClientError(
- "Can't see that area - insufficient permissions!")
+ raise ClientError("Can't see that area - insufficient permissions!")
client.send_area_info(aid)
client.area.broadcast_player_list_to_target(client)
@@ -292,6 +253,7 @@ def ooc_cmd_getareas(client, arg):
"""
client.send_areas_clients()
+
def ooc_cmd_gethubs(client, arg):
"""
Show information about all hubs.
@@ -299,6 +261,7 @@ def ooc_cmd_gethubs(client, arg):
"""
client.send_hubs_clients()
+
def ooc_cmd_getlink(client, arg):
"""
Show information about the current area, or target area id with sufficient permissions.
@@ -311,8 +274,7 @@ def ooc_cmd_getlink(client, arg):
if area.id == client.area.id or (client.is_mod or client in area.owners):
aid = int(arg)
else:
- raise ClientError(
- "Can't see that area - insufficient permissions!")
+ raise ClientError("Can't see that area - insufficient permissions!")
client.send_area_info(aid, show_links=True)
@@ -324,6 +286,7 @@ def ooc_cmd_getlinks(client, arg):
"""
client.send_areas_clients(show_links=True)
+
def ooc_cmd_getafk(client, arg):
"""
Show currently AFK-ing players in the current area or in all areas.
@@ -348,11 +311,7 @@ def ooc_cmd_invite(client, arg):
if not arg:
msg = "Current invite list:\n"
msg += "\n".join(
- [
- f"[{c.id}] {c.showname}"
- for c in client.server.client_manager.clients
- if c.id in client.area.invite_list
- ]
+ [f"[{c.id}] {c.showname}" for c in client.server.client_manager.clients if c.id in client.area.invite_list]
)
msg += "\nUse /invite to invite someone."
client.send_ooc(msg)
@@ -362,15 +321,9 @@ def ooc_cmd_invite(client, arg):
try:
if args[0] == "*":
- targets = [
- c
- for c in client.area.clients
- if c != client and c != client.area.owners
- ]
+ targets = [c for c in client.area.clients if c != client and c != client.area.owners]
else:
- targets = client.server.client_manager.get_targets(
- client, TargetType.ID, int(args[0]), False
- )
+ targets = client.server.client_manager.get_targets(client, TargetType.ID, int(args[0]), False)
except ValueError:
raise ArgumentError("Area ID must be a number or *.")
@@ -378,8 +331,7 @@ def ooc_cmd_invite(client, arg):
for c in targets:
client.area.invite_list.add(c.id)
client.send_ooc(f"{c.showname} is invited to your area.")
- c.send_ooc(
- f"You were invited and given access to {client.area.name}.")
+ c.send_ooc(f"You were invited and given access to {client.area.name}.")
database.log_area("invite", client, client.area, target=c)
except Exception:
raise ClientError("You must specify a target. Use /invite ")
@@ -397,25 +349,16 @@ def ooc_cmd_uninvite(client, arg):
args = arg.split(" ")
try:
if args[0] == "*":
- targets = [
- c
- for c in client.area.clients
- if c != client and c != client.area.owners
- ]
+ targets = [c for c in client.area.clients if c != client and c != client.area.owners]
else:
- targets = client.server.client_manager.get_targets(
- client, TargetType.ID, int(args[0]), False
- )
+ targets = client.server.client_manager.get_targets(client, TargetType.ID, int(args[0]), False)
except ValueError:
raise ArgumentError("Area ID must be a number or *.")
if targets:
try:
for c in targets:
- client.send_ooc(
- "You have removed {} from the whitelist.".format(
- c.showname)
- )
+ client.send_ooc("You have removed {} from the whitelist.".format(c.showname))
c.send_ooc("You were removed from the area whitelist.")
database.log_area("uninvite", client, client.area, target=c)
client.area.invite_list.discard(c.id)
@@ -440,96 +383,57 @@ def ooc_cmd_area_kick(client, arg):
Usage: /area_kick [destination] [target_pos]
"""
if not arg:
- raise ClientError(
- "You must specify a target. Use /area_kick [destination] [target_pos]"
- )
+ raise ClientError("You must specify a target. Use /area_kick [destination] [target_pos]")
args = shlex.split(arg)
# Kick everyone but AFKers
if args[0] == "afk":
- targets = client.server.client_manager.get_targets(
- client, TargetType.AFK, args[0], False
- )
+ targets = client.server.client_manager.get_targets(client, TargetType.AFK, args[0], False)
# Kick everyone but owners
elif args[0] == "*":
- targets = [
- c
- for c in client.area.clients
- if c != client and c != client.area.owners
- ]
+ targets = [c for c in client.area.clients if c != client and c != client.area.owners]
# Kick everyone in area
elif args[0] == "**":
- targets = [
- c
- for c in client.area.clients
- ]
+ targets = [c for c in client.area.clients]
# Kick everyone in hub
elif args[0] == "***":
- targets = [
- c
- for c in client.area.area_manager.clients
- ]
+ targets = [c for c in client.area.area_manager.clients]
else:
# Try to find by char name first
- targets = client.server.client_manager.get_targets(
- client, TargetType.CHAR_NAME, args[0]
- )
+ targets = client.server.client_manager.get_targets(client, TargetType.CHAR_NAME, args[0])
# If that doesn't work, find by client ID
if len(targets) == 0 and args[0].isdigit():
- targets = client.server.client_manager.get_targets(
- client, TargetType.ID, int(args[0])
- )
+ targets = client.server.client_manager.get_targets(client, TargetType.ID, int(args[0]))
# If that doesn't work, find by OOC Name
if len(targets) == 0:
- targets = client.server.client_manager.get_targets(
- client, TargetType.OOC_NAME, args[0]
- )
+ targets = client.server.client_manager.get_targets(client, TargetType.OOC_NAME, args[0])
if len(targets) == 0:
- client.send_ooc(
- f"No targets found by search term '{args[0]}'."
- )
+ client.send_ooc(f"No targets found by search term '{args[0]}'.")
return
try:
for c in targets:
# We're a puny CM, we can't do this.
- if (
- not client.is_mod
- and client not in client.area.area_manager.owners
- and c not in client.area.clients
- ):
- raise ArgumentError(
- "You can't kick someone from another area as a CM!"
- )
+ if not client.is_mod and client not in client.area.area_manager.owners and c not in client.area.clients:
+ raise ArgumentError("You can't kick someone from another area as a CM!")
if len(args) == 1:
area = client.area
else:
try:
- area = client.area.area_manager.get_area_by_id(
- int(args[1]))
+ area = client.area.area_manager.get_area_by_id(int(args[1]))
except AreaError:
raise
- if (
- not client.is_mod
- and client not in client.area.area_manager.owners
- and client not in area.owners
- ):
- raise ArgumentError(
- "You can't kick someone to an area you don't own as a CM!"
- )
+ if not client.is_mod and client not in client.area.area_manager.owners and client not in area.owners:
+ raise ArgumentError("You can't kick someone to an area you don't own as a CM!")
target_pos = ""
old_area = c.area
if len(args) >= 3:
target_pos = args[2]
c.set_area(area, target_pos)
- c.send_ooc(
- f"You were kicked from [{old_area.id}] {old_area.name} to [{area.id}] {area.name}."
- )
- database.log_area(
- "area_kick", client, client.area, target=c, message=area.id
- )
+ c.send_ooc(f"You were kicked from [{old_area.id}] {old_area.name} to [{area.id}] {area.name}.")
+ database.log_area("area_kick", client, client.area, target=c, message=area.id)
client.area.invite_list.discard(c.id)
client.send_ooc(
f"Kicked [{c.id}] {c.showname} from [{old_area.id}] {old_area.name} to [{area.id}] {area.name}."
@@ -567,7 +471,7 @@ def ooc_cmd_pos_lock(client, arg):
pos = client.area.pos_dark
client.send_ooc(f"Current darkness pos is {pos}.")
return
- if not client.is_mod and not (client in client.area.owners):
+ if not client.is_mod and client not in client.area.owners:
raise ClientError("You must be authorized to do that.")
client.area.pos_dark = arg
client.area.broadcast_ooc(f"Locked darkness pos into {arg}.")
@@ -584,7 +488,7 @@ def ooc_cmd_pos_lock(client, arg):
ooc_cmd_pos_lock_clear(client, arg)
return
- if not client.is_mod and not (client in client.area.owners):
+ if not client.is_mod and client not in client.area.owners:
raise ClientError("You must be authorized to do that.")
client.area.pos_lock.clear()
@@ -602,9 +506,7 @@ def ooc_cmd_pos_lock(client, arg):
pos = ", ".join(str(p_lock) for p_lock in client.area.pos_lock)
client.area.broadcast_ooc(f"Locked pos into {pos}.")
- client.area.send_command(
- "SD", "*".join(client.area.pos_lock)
- ) # set that juicy pos dropdown
+ client.area.send_command("SD", "*".join(client.area.pos_lock)) # set that juicy pos dropdown
@mod_only(area_owners=True)
@@ -623,9 +525,7 @@ def ooc_cmd_knock(client, arg):
Usage: /knock
"""
if arg == "":
- raise ArgumentError(
- "Failed to knock: you need to input an accessible area name or ID to knock!"
- )
+ raise ArgumentError("Failed to knock: you need to input an accessible area name or ID to knock!")
if client.blinded:
raise ClientError("Failed to knock: you are blinded!")
try:
@@ -644,44 +544,27 @@ def ooc_cmd_knock(client, arg):
allowed = client.is_mod or client in area.owners or client in client.area.owners
if not allowed and area != client.area:
if len(client.area.links) > 0:
- if not str(area.id) in client.area.links:
- raise ClientError(
- f"Failed to knock on [{area.id}] {area.name}: That area is inaccessible!"
- )
+ if str(area.id) not in client.area.links:
+ raise ClientError(f"Failed to knock on [{area.id}] {area.name}: That area is inaccessible!")
if str(area.id) in client.area.links:
# Get that link reference
link = client.area.links[str(area.id)]
# Link requires us to be inside a piece of evidence
- if (
- len(link["evidence"]) > 0
- and client.hidden_in not in link["evidence"]
- ):
- raise ClientError(
- f"Failed to knock on [{area.id}] {area.name}: That area is inaccessible!"
- )
+ if len(link["evidence"]) > 0 and client.hidden_in not in link["evidence"]:
+ raise ClientError(f"Failed to knock on [{area.id}] {area.name}: That area is inaccessible!")
if client.area.locked and client.id not in client.area.invite_list:
- raise ClientError(
- f"Failed to knock on [{area.id}] {area.name}: Current area is locked!"
- )
+ raise ClientError(f"Failed to knock on [{area.id}] {area.name}: Current area is locked!")
area.send_command("RT", "knock")
if area == client.area:
- area.broadcast_ooc(
- f"💢 [{client.id}] {client.showname} knocks for attention. 💢"
- )
+ area.broadcast_ooc(f"💢 [{client.id}] {client.showname} knocks for attention. 💢")
else:
- client.area.broadcast_ooc(
- f"[{client.id}] {client.showname} knocks on [{area.id}] {area.name}."
- )
- area.broadcast_ooc(
- f"💢 Someone is knocking from [{client.area.id}] {client.area.name} 💢"
- )
+ client.area.broadcast_ooc(f"[{client.id}] {client.showname} knocks on [{area.id}] {area.name}.")
+ area.broadcast_ooc(f"💢 Someone is knocking from [{client.area.id}] {client.area.name} 💢")
except ValueError:
- raise ArgumentError(
- "Failed to knock: you need to input an accessible area name or ID to knock!"
- )
+ raise ArgumentError("Failed to knock: you need to input an accessible area name or ID to knock!")
except (AreaError, ClientError):
raise
@@ -692,9 +575,7 @@ def ooc_cmd_peek(client, arg):
Usage: /peek
"""
if arg == "":
- raise ArgumentError(
- "You need to input an accessible area name or ID to peek into it!"
- )
+ raise ArgumentError("You need to input an accessible area name or ID to peek into it!")
if client.blinded:
raise ClientError("You are blinded!")
try:
@@ -720,12 +601,7 @@ def ooc_cmd_peek(client, arg):
if area.dark:
raise ClientError("Area is dark!")
except ClientError as ex:
- if (
- not client.area.dark
- and not client.sneaking
- and not client.hidden
- and "locked" in str(ex).lower()
- ):
+ if not client.area.dark and not client.sneaking and not client.hidden and "locked" in str(ex).lower():
client.area.broadcast_ooc(
f"[{client.id}] {client.showname} tried to peek into [{area.id}] {area.name} but {str(ex).lower()}"
)
@@ -733,8 +609,7 @@ def ooc_cmd_peek(client, arg):
area.broadcast_ooc(
f"Someone tried to enter from [{client.area.id}] {client.area.name} but {str(ex).lower()}"
)
- client.send_ooc(
- f"Failed to peek into [{area.id}] {area.name}: {ex}")
+ client.send_ooc(f"Failed to peek into [{area.id}] {area.name}: {ex}")
return
else:
sorted_clients = []
@@ -742,9 +617,7 @@ def ooc_cmd_peek(client, arg):
if not c.hidden and c not in area.owners and not c.is_mod: # pure IC
sorted_clients.append(c)
- _sort = [
- c.showname for c in sorted(sorted_clients, key=lambda x: x.showname)
- ]
+ _sort = [c.showname for c in sorted(sorted_clients, key=lambda x: x.showname)]
# this would be nice to be a separate "make human readable list" func
if len(_sort) == 2:
@@ -759,17 +632,12 @@ def ooc_cmd_peek(client, arg):
sorted_clients = "nobody"
if not client.sneaking and not client.hidden:
- client.area.broadcast_ooc(
- f"[{client.id}] {client.showname} peeks into [{area.id}] {area.name}..."
- )
+ client.area.broadcast_ooc(f"[{client.id}] {client.showname} peeks into [{area.id}] {area.name}...")
else:
- client.send_ooc(
- f"You silently peek into [{area.id}] {area.name}...")
+ client.send_ooc(f"You silently peek into [{area.id}] {area.name}...")
client.send_ooc(f"There's {sorted_clients}.")
except ValueError:
- raise ArgumentError(
- "Failed to peek: you need to input an accessible area name or ID to knock!"
- )
+ raise ArgumentError("Failed to peek: you need to input an accessible area name or ID to knock!")
except (AreaError, ClientError):
raise
@@ -781,9 +649,7 @@ def ooc_cmd_max_players(client, arg):
Usage: /max_players [num]
"""
if arg == "":
- client.send_ooc(
- f"Max amount of players for the area is {client.area.max_players}."
- )
+ client.send_ooc(f"Max amount of players for the area is {client.area.max_players}.")
return
try:
@@ -791,12 +657,9 @@ def ooc_cmd_max_players(client, arg):
if arg < -1 or arg > 99:
raise ClientError("The min-max values are -1 and 99!")
client.area.max_players = arg
- client.send_ooc(
- f"New max amount of players for the area is now {client.area.max_players}."
- )
+ client.send_ooc(f"New max amount of players for the area is now {client.area.max_players}.")
except ValueError:
- raise ArgumentError(
- "Area ID must be a name, abbreviation or a number.")
+ raise ArgumentError("Area ID must be a name, abbreviation or a number.")
except (AreaError, ClientError):
raise
@@ -817,18 +680,14 @@ def ooc_cmd_desc(client, arg):
else:
if client.area.cannot_ic_interact(client):
raise ClientError("You are not on the area's invite list!")
- if (
- not client.is_mod
- and not (client in client.area.owners)
- and client.char_id == -1
- ):
+ if not client.is_mod and client not in client.area.owners and client.char_id == -1:
raise ClientError("You may not do that while spectating!")
arg = arg.strip()
if arg == "":
ooc_cmd_desc_clear(client, "")
return
if client.area.dark:
- if not client.is_mod and not (client in client.area.owners):
+ if not client.is_mod and client not in client.area.owners:
raise ClientError("You must be authorized to do that.")
client.area.desc_dark = arg.strip()
else:
@@ -836,9 +695,7 @@ def ooc_cmd_desc(client, arg):
desc = arg[:128]
if len(arg) > len(desc):
desc += "... Use /desc to read the rest."
- client.area.broadcast_ooc(
- f"📃{client.showname} changed the area description to: {desc}."
- )
+ client.area.broadcast_ooc(f"📃{client.showname} changed the area description to: {desc}.")
client.area.broadcast_area_desc()
database.log_area("desc.change", client, client.area, message=arg)
@@ -852,24 +709,19 @@ def ooc_cmd_desc_clear(client, arg):
raise ClientError("You are blinded!")
if client.area.cannot_ic_interact(client):
raise ClientError("You are not on the area's invite list!")
- if (
- not client.is_mod
- and not (client in client.area.owners)
- and client.char_id == -1
- ):
+ if not client.is_mod and client not in client.area.owners and client.char_id == -1:
raise ClientError("You may not do that while spectating!")
if client.area.dark:
- if not client.is_mod and not (client in client.area.owners):
+ if not client.is_mod and client not in client.area.owners:
raise ClientError("You must be authorized to do that.")
client.area.desc_dark = ""
else:
client.area.desc = ""
- client.area.broadcast_ooc(
- f"📃{client.showname} cleared the area description."
- )
+ client.area.broadcast_ooc(f"📃{client.showname} cleared the area description.")
client.area.broadcast_area_desc()
database.log_area("desc.clear", client, client.area)
+
@mod_only(area_owners=True)
def ooc_cmd_edit_ambience(client, arg):
"""
@@ -878,9 +730,7 @@ def ooc_cmd_edit_ambience(client, arg):
Usage: /edit_ambience [tog]
"""
if len(arg.split()) > 1:
- raise ArgumentError(
- "This command can only take one argument ('on' or 'off') or no arguments at all!"
- )
+ raise ArgumentError("This command can only take one argument ('on' or 'off') or no arguments at all!")
if arg:
if arg == "on":
client.edit_ambience = True
@@ -906,9 +756,7 @@ def ooc_cmd_lights(client, arg):
Usage: /lights [tog]
"""
if len(arg.split()) > 1:
- raise ArgumentError(
- "This command can only take one argument ('on' or 'off') or no arguments at all!"
- )
+ raise ArgumentError("This command can only take one argument ('on' or 'off') or no arguments at all!")
if arg:
if arg == "on":
client.area.dark = False
@@ -979,4 +827,4 @@ def ooc_cmd_clear_area_broadcast(client, arg):
client.send_ooc("Current area broadcast list is already empty!")
return
client.area.broadcast_list.clear()
- client.send_ooc("Current area broadcast list has been cleared.")
\ No newline at end of file
+ client.send_ooc("Current area broadcast list has been cleared.")
diff --git a/server/commands/battle.py b/server/commands/battle.py
index 20231eb8..e52c455e 100644
--- a/server/commands/battle.py
+++ b/server/commands/battle.py
@@ -7,7 +7,6 @@
from server.constants import derelative
from . import mod_only
-from .. import commands
__all__ = [
"ooc_cmd_choose_fighter",
@@ -77,9 +76,9 @@ def send_info_fighter(client):
Prepare the message about fighter info
"""
msg = f"\n👤 {client.battle.fighter} 👤:\n"
- if client.battle.status != None:
+ if client.battle.status is not None:
msg += f"Status 🌈: {client.battle.status}\n"
- msg += f"\nHP 💗: {round(client.battle.hp,2)}/{client.battle.maxhp}\nMANA 💧: {round(client.battle.mana,2)}\nATK 🗡️: {round(client.battle.atk,2)}\nDEF 🛡️: {round(client.battle.defe,2)}\nSPA ✨: {round(client.battle.spa,2)}\nSPD 🔮: {round(client.battle.spd,2)}\nSPE 💨: {round(client.battle.spe,2)}\n\n"
+ msg += f"\nHP 💗: {round(client.battle.hp, 2)}/{client.battle.maxhp}\nMANA 💧: {round(client.battle.mana, 2)}\nATK 🗡️: {round(client.battle.atk, 2)}\nDEF 🛡️: {round(client.battle.defe, 2)}\nSPA ✨: {round(client.battle.spa, 2)}\nSPD 🔮: {round(client.battle.spd, 2)}\nSPE 💨: {round(client.battle.spe, 2)}\n\n"
for move in client.battle.moves:
move_id = client.battle.moves.index(move)
msg += f"🌠 [{move_id}]{move.name} 🌠:\nManaCost 💧: {move.cost}\nType 💠: {move.type}\nPower 💪: {move.power}\nAccuracy 🔎: {move.accuracy}%\n"
@@ -89,16 +88,16 @@ def send_info_fighter(client):
msg += f"- {effect}\n"
msg += "\n"
client.send_ooc(msg)
-
+
def send_stats_fighter(client):
"""
Prepare the message about fighter stats
"""
msg = f"\n👤 {client.battle.fighter} 👤:\n"
- if client.battle.status != None:
+ if client.battle.status is not None:
msg += f"Status 🌈: {client.battle.status}\n"
- msg += f"\nHP 💗: {round(client.battle.hp,2)}/{client.battle.maxhp}\nMANA 💧: {round(client.battle.mana,2)}\nATK 🗡️: {round(client.battle.atk,2)}\nDEF 🛡️: {round(client.battle.defe,2)}\nSPA ✨: {round(client.battle.spa,2)}\nSPD 🔮: {round(client.battle.spd,2)}\nSPE 💨: {round(client.battle.spe,2)}\n\n"
+ msg += f"\nHP 💗: {round(client.battle.hp, 2)}/{client.battle.maxhp}\nMANA 💧: {round(client.battle.mana, 2)}\nATK 🗡️: {round(client.battle.atk, 2)}\nDEF 🛡️: {round(client.battle.defe, 2)}\nSPA ✨: {round(client.battle.spa, 2)}\nSPD 🔮: {round(client.battle.spd, 2)}\nSPE 💨: {round(client.battle.spe, 2)}\n\n"
client.send_ooc(msg)
@@ -109,9 +108,7 @@ def ooc_cmd_choose_fighter(client, arg):
Usage: /choose_fighter NameFighter
"""
if f"{arg.lower()}.yaml" in os.listdir("storage/battlesystem"):
- with open(
- f"storage/battlesystem/{arg.lower()}.yaml", "r", encoding="utf-8"
- ) as c_load:
+ with open(f"storage/battlesystem/{arg.lower()}.yaml", "r", encoding="utf-8") as c_load:
char = yaml.safe_load(c_load)
client.battle = ClientManager.BattleChar(client, arg.lower(), char)
send_info_fighter(client)
@@ -138,15 +135,11 @@ def ooc_cmd_create_fighter(client, arg):
args = shlex.split(arg)
if len(args) > 8:
- client.send_ooc(
- "Too many arguments...\nUsage: /create_fighter FighterName HP MANA ATK DEF SPA SPD SPE"
- )
+ client.send_ooc("Too many arguments...\nUsage: /create_fighter FighterName HP MANA ATK DEF SPA SPD SPE")
return
if len(args) < 8:
- client.send_ooc(
- "Not enough arguments...\nUsage: /create_fighter FighterName HP MANA ATK DEF SPA SPD SPE"
- )
+ client.send_ooc("Not enough arguments...\nUsage: /create_fighter FighterName HP MANA ATK DEF SPA SPD SPE")
return
if (
@@ -197,9 +190,7 @@ def ooc_cmd_create_move(client, arg):
Usage: /create_move MoveName ManaCost MovesType Power Accuracy Effects
"""
if client.battle is None:
- client.send_ooc(
- "You have to choose a figher to create a move.\n /choose_fighter FighterName"
- )
+ client.send_ooc("You have to choose a figher to create a move.\n /choose_fighter FighterName")
return
args = shlex.split(arg)
@@ -234,9 +225,7 @@ def ooc_cmd_create_move(client, arg):
)
return
- with open(
- f"storage/battlesystem/{client.battle.fighter}.yaml", "r", encoding="utf-8"
- ) as c_load:
+ with open(f"storage/battlesystem/{client.battle.fighter}.yaml", "r", encoding="utf-8") as c_load:
char = yaml.safe_load(c_load)
move_list = []
@@ -282,35 +271,26 @@ def ooc_cmd_modify_stat(client, arg):
Usage: /modify_stat FighterName Stat Value
"""
args = shlex.split(arg)
-
-
+
path = derelative(args[0].lower())
if f"{path}.yaml" not in os.listdir("storage/battlesystem"):
client.send_ooc("No fighter has this name!")
return
if args[1].lower() not in ["hp", "mana", "atk", "def", "spa", "spd", "spe"]:
- client.send_ooc(
- "You could just modify this stats:\nhp, mana, atk, def, spa, spd, spe"
- )
+ client.send_ooc("You could just modify this stats:\nhp, mana, atk, def, spa, spd, spe")
return
if float(args[2]) < 0:
client.send_ooc("The value have to be a number greater than or equal to zero")
return
- with open(
- f"storage/battlesystem/{path}.yaml", "r", encoding="utf-8"
- ) as c_load:
+ with open(f"storage/battlesystem/{path}.yaml", "r", encoding="utf-8") as c_load:
char = yaml.safe_load(c_load)
char[args[1].upper()] = float(args[2])
- with open(
- f"storage/battlesystem/{path}.yaml", "w", encoding="utf-8"
- ) as c_save:
+ with open(f"storage/battlesystem/{path}.yaml", "w", encoding="utf-8") as c_save:
yaml.dump(char, c_save)
- client.send_ooc(
- f"{path}'s {args[1]} has been modified. To check the changes choose again this fighter"
- )
+ client.send_ooc(f"{path}'s {args[1]} has been modified. To check the changes choose again this fighter")
@mod_only(hub_owners=True)
@@ -333,14 +313,12 @@ def ooc_cmd_delete_move(client, arg):
You have to choose a fighter first!
Usage: /delete_move MoveName
"""
-
+
if client.battle is None:
client.send_ooc("You have to choose the fighter first")
return
-
- with open(
- f"storage/battlesystem/{client.battle.fighter}.yaml", "r", encoding="utf-8"
- ) as c_load:
+
+ with open(f"storage/battlesystem/{client.battle.fighter}.yaml", "r", encoding="utf-8") as c_load:
char = yaml.safe_load(c_load)
move_list = []
for i in range(0, len(char["Moves"])):
@@ -355,9 +333,7 @@ def ooc_cmd_delete_move(client, arg):
) as c_save:
yaml.dump(char, c_save)
- client.battle = ClientManager.BattleChar(
- client, client.battle.fighter, char
- )
+ client.battle = ClientManager.BattleChar(client, client.battle.fighter, char)
guild = None
for g in client.area.battle_guilds:
if client in client.area.battle_guilds[g]:
@@ -371,49 +347,49 @@ def ooc_cmd_delete_move(client, arg):
@mod_only(hub_owners=True)
def ooc_cmd_battle_config(client, arg):
- """
- Allow you to customize some battle settings.
- Usage: /custom_battle
- """
- if arg == "":
- client.send_ooc(
- "paralysis_rate, critical_rate, critical_bonus, bonus_malus, poison_damage, show_hp, min_multishot, max_multishot, burn_damage, freeze_damage, confusion_rate, enraged_bonus, stolen_stat"
- )
- return
- args = arg.split(" ")
- if args[0].lower() == "paralysis_rate":
- client.area.battle_paralysis_rate = int(args[1])
- elif args[0].lower() == "critical_rate":
- client.area.battle_critical_rate = int(args[1])
- elif args[0].lower() == "critical_bonus":
- client.area.battle_critical_bonus = float(args[1])
- elif args[0].lower() == "bonus_malus":
- client.area.battle_bonus_malus = float(args[1])
- elif args[0].lower() == "poison_damage":
- client.area.battle_poison_damage = float(args[1])
- elif args[0].lower() == "min_multishot":
- client.area.battle_min_multishot = int(args[1])
- elif args[0].lower() == "max_multishot":
- client.area.battle_max_multishot = int(args[1])
- elif args[0].lower() == "burn_damage":
- client.area.battle_burn_damage = float(args[1])
- elif args[0].lower() == "freeze_damage":
- client.area.battle_freeze_damage = float(args[1])
- elif args[0].lower() == "confusion_rate":
- client.area.battle_confusion_rate = int(args[1])
- elif args[0].lower() == "enraged_bonus":
- client.area.battle_enraged_bonus = float(args[1])
- elif args[0].lower() == "stolen_stat":
- client.area.battle_stolen_stat = float(args[1])
- elif args[1].lower() in ["true", "false"] and args[0].lower() == "show_hp":
- if args[1].lower() == "true":
- client.area.battle_show_hp = True
- else:
- client.area.battle_show_hp = False
- else:
- client.send_ooc("value is not valid")
- return
- client.send_ooc(f"{args[0].lower()} has been changed to {args[1]}")
+ """
+ Allow you to customize some battle settings.
+ Usage: /custom_battle
+ """
+ if arg == "":
+ client.send_ooc(
+ "paralysis_rate, critical_rate, critical_bonus, bonus_malus, poison_damage, show_hp, min_multishot, max_multishot, burn_damage, freeze_damage, confusion_rate, enraged_bonus, stolen_stat"
+ )
+ return
+ args = arg.split(" ")
+ if args[0].lower() == "paralysis_rate":
+ client.area.battle_paralysis_rate = int(args[1])
+ elif args[0].lower() == "critical_rate":
+ client.area.battle_critical_rate = int(args[1])
+ elif args[0].lower() == "critical_bonus":
+ client.area.battle_critical_bonus = float(args[1])
+ elif args[0].lower() == "bonus_malus":
+ client.area.battle_bonus_malus = float(args[1])
+ elif args[0].lower() == "poison_damage":
+ client.area.battle_poison_damage = float(args[1])
+ elif args[0].lower() == "min_multishot":
+ client.area.battle_min_multishot = int(args[1])
+ elif args[0].lower() == "max_multishot":
+ client.area.battle_max_multishot = int(args[1])
+ elif args[0].lower() == "burn_damage":
+ client.area.battle_burn_damage = float(args[1])
+ elif args[0].lower() == "freeze_damage":
+ client.area.battle_freeze_damage = float(args[1])
+ elif args[0].lower() == "confusion_rate":
+ client.area.battle_confusion_rate = int(args[1])
+ elif args[0].lower() == "enraged_bonus":
+ client.area.battle_enraged_bonus = float(args[1])
+ elif args[0].lower() == "stolen_stat":
+ client.area.battle_stolen_stat = float(args[1])
+ elif args[1].lower() in ["true", "false"] and args[0].lower() == "show_hp":
+ if args[1].lower() == "true":
+ client.area.battle_show_hp = True
+ else:
+ client.area.battle_show_hp = False
+ else:
+ client.send_ooc("value is not valid")
+ return
+ client.send_ooc(f"{args[0].lower()} has been changed to {args[1]}")
def send_battle_info(client):
@@ -433,7 +409,7 @@ def send_battle_info(client):
emoji = "⚔️"
if client.area.battle_show_hp:
- show_hp = f": {round(client.battle.hp*100/client.battle.maxhp,2)}%"
+ show_hp = f": {round(client.battle.hp * 100 / client.battle.maxhp, 2)}%"
else:
show_hp = ""
@@ -448,7 +424,7 @@ def send_battle_info(client):
emoji = "⚔️"
if client.area.battle_show_hp:
- show_hp = f": {round(client.battle.hp*100/client.battle.maxhp,2)}%"
+ show_hp = f": {round(client.battle.hp * 100 / client.battle.maxhp, 2)}%"
else:
show_hp = ""
@@ -474,11 +450,7 @@ def ooc_cmd_fight(client, arg):
Usage: /fight
"""
if len(client.area.fighters) > 0 and client.area.battle_started:
- free_fighters = {
- c.battle.fighter: c
- for c in client.area.fighters
- if c.battle.current_client is not None
- }
+ free_fighters = {c.battle.fighter: c for c in client.area.fighters if c.battle.current_client is not None}
if client in client.area.fighters:
index = client.area.fighters.index(client)
client.battle = client.area.fighters[index].battle
@@ -498,9 +470,7 @@ def ooc_cmd_fight(client, arg):
client.area.fighters.remove(target)
client.area.fighters.append(client)
msg = send_battle_info(client)
- battle_send_ic(
- client, msg=f"~{client.battle.fighter}~ is ready to fight (reconnected)"
- )
+ battle_send_ic(client, msg=f"~{client.battle.fighter}~ is ready to fight (reconnected)")
for client in client.area.fighters:
client.send_ooc(msg)
return
@@ -521,10 +491,8 @@ def ooc_cmd_fight(client, arg):
msg = send_battle_info(client)
for client in client.area.fighters:
client.send_ooc(msg)
- client.area.broadcast_ooc(
- f"⚔️{client.battle.fighter} ({client.showname}) is ready to fight!⚔️"
- )
- fighter_name = client.area.area_manager.char_list[client.char_id]
+ client.area.broadcast_ooc(f"⚔️{client.battle.fighter} ({client.showname}) is ready to fight!⚔️")
+ client.area.area_manager.char_list[client.char_id]
battle_send_ic(client, msg=f"~{client.battle.fighter}~ is ready to fight")
@@ -554,18 +522,14 @@ def ooc_cmd_surrender(client, arg):
client.battle.hp = 0
client.battle.selected_move = -1
client.battle.target = None
- battle_send_ic(
- client, msg=f"~{client.battle.fighter}~ decides to surrend", offset=100
- )
+ battle_send_ic(client, msg=f"~{client.battle.fighter}~ decides to surrend", offset=100)
with open(
f"storage/battlesystem/{client.battle.fighter}.yaml",
"r",
encoding="utf-8",
) as c_load:
char = yaml.safe_load(c_load)
- client.battle = ClientManager.BattleChar(
- client, client.battle.fighter, char
- )
+ client.battle = ClientManager.BattleChar(client, client.battle.fighter, char)
guild = None
for g in client.area.battle_guilds:
if client in client.area.battle_guilds[g]:
@@ -604,9 +568,7 @@ def ooc_cmd_remove_fighter(client, arg):
encoding="utf-8",
) as c_load:
char = yaml.safe_load(c_load)
- target.battle = ClientManager.BattleChar(
- target, target.battle.fighter, char
- )
+ target.battle = ClientManager.BattleChar(target, target.battle.fighter, char)
guild = None
for g in target.area.battle_guilds:
if target in target.area.battle_guilds[g]:
@@ -664,7 +626,7 @@ def ooc_cmd_skip_move(client, arg):
client.battle.selected_move = -2
client.area.num_selected_move += 1
- client.send_ooc(f"You have choosen to skip the turn")
+ client.send_ooc("You have choosen to skip the turn")
client.area.broadcast_ooc(f"{client.battle.fighter} has choosen a move")
if client.area.num_selected_move == len(client.area.fighters):
@@ -740,9 +702,7 @@ def ooc_cmd_leave_guild(client, arg):
else:
client.send_ooc("Target not found!")
elif client == client.area.battle_guilds[client.battle.guild][0]:
- guild_ids = {
- c.id: c for c in client.area.battle_guilds[client.battle.guild]
- }
+ guild_ids = {c.id: c for c in client.area.battle_guilds[client.battle.guild]}
if int(arg) in guild_ids:
target = guild_ids[int(arg)]
guild = target.battle.guild
@@ -774,9 +734,7 @@ def ooc_cmd_join_guild(client, arg):
guild = client.battle.guild
if client != client.area.battle_guilds[guild][0]:
- client.send_ooc(
- "You are not the guild leader, you cannot choose who can join to the guild."
- )
+ client.send_ooc("You are not the guild leader, you cannot choose who can join to the guild.")
return
area_ids = {c.id: c for c in client.area.clients}
@@ -854,9 +812,7 @@ def send_info_guild(client):
msg += "\n\n👤Members👤:\n\n"
for fighter in client.area.battle_guilds[guild]:
if fighter != guild_leader:
- msg += (
- f"⚔️[{fighter.id}]{fighter.battle.fighter} ({fighter.showname})⚔️\n"
- )
+ msg += f"⚔️[{fighter.id}]{fighter.battle.fighter} ({fighter.showname})⚔️\n"
client.send_ooc(msg)
@@ -997,25 +953,19 @@ def start_battle_animation(area):
if client.battle.hp > 0:
# check if a fighter skipped the turn
if client.battle.selected_move == -2:
- battle_send_ic(
- client, msg=f"~{client.battle.fighter}~ decides to skip the turn"
- )
+ battle_send_ic(client, msg=f"~{client.battle.fighter}~ decides to skip the turn")
continue
if client.battle.status == "stunned":
client.battle.status = None
- battle_send_ic(
- client, msg=f"~{client.battle.fighter}~ is stunned and cannot fight"
- )
+ battle_send_ic(client, msg=f"~{client.battle.fighter}~ is stunned and cannot fight")
continue
if client.battle.status == "confused":
confused = random.randint(1, client.area.battle_confusion_rate)
if confused == 1:
client.battle.status = None
- battle_send_ic(
- client, msg=f"~{client.battle.fighter}~ snaps out of confusion"
- )
+ battle_send_ic(client, msg=f"~{client.battle.fighter}~ snaps out of confusion")
elif confused == client.area.battle_confusion_rate:
battle_send_ic(
client,
@@ -1055,17 +1005,12 @@ def start_battle_animation(area):
# check if the fighter misses the move
miss = random.randint(1, 100)
if move.accuracy < miss:
- battle_send_ic(
- client, msg=f"~{client.battle.fighter}~ misses the target"
- )
+ battle_send_ic(client, msg=f"~{client.battle.fighter}~ misses the target")
continue
# check if the fighter is paralysed
paralysis = random.randint(1, area.battle_paralysis_rate)
- if (
- paralysis == area.battle_paralysis_rate
- and client.battle.status == "paralysis"
- ):
+ if paralysis == area.battle_paralysis_rate and client.battle.status == "paralysis":
battle_send_ic(
client,
msg=f"~{client.battle.fighter}~ is affected by paralysis and cannot fight",
@@ -1089,18 +1034,14 @@ def start_battle_animation(area):
targets = [c for c in client.area.fighters]
else:
targets = [
- c
- for c in client.area.battle_guilds[client.battle.guild]
- if c in client.area.fighters
+ c for c in client.area.battle_guilds[client.battle.guild] if c in client.area.fighters
]
else:
if client.battle.guild is None:
targets = [c for c in client.area.fighters if c != client]
else:
targets = [
- c
- for c in client.area.fighters
- if c not in client.area.battle_guilds[client.battle.guild]
+ c for c in client.area.fighters if c not in client.area.battle_guilds[client.battle.guild]
]
if "multishot" in move.effect:
shots = random.randint(
@@ -1109,9 +1050,7 @@ def start_battle_animation(area):
)
targets = random.choices(targets, shots)
elif "multishot" in move.effect and "atkall" not in move.effect:
- shots = random.randint(
- client.area.battle_min_multishot, client.area.battle_max_multishot
- )
+ shots = random.randint(client.area.battle_min_multishot, client.area.battle_max_multishot)
targets = []
for i in range(0, shots):
targets.append(client.battle.target)
@@ -1128,7 +1067,7 @@ def start_battle_animation(area):
if len(targets) == 1:
battle_send_ic(
client,
- msg=f"and tries to help but the target is already down",
+ msg="and tries to help but the target is already down",
)
continue
if "heal" in move.effect:
@@ -1157,7 +1096,7 @@ def start_battle_animation(area):
msg=f"and heals ~{target.battle.fighter}~ of ~{heal}~ hp",
effect="lifeup",
)
-
+
if "healstatus" in move.effect:
if target.battle.status is None:
battle_send_ic(
@@ -1174,12 +1113,8 @@ def start_battle_animation(area):
f"and removed {status} from ~{target.battle.fighter}~",
)
if status == "burn":
- target.battle.spd = (
- target.battle.spd * area.battle_bonus_malus
- )
- target.battle.defe = (
- target.battle.defe * area.battle_bonus_malus
- )
+ target.battle.spd = target.battle.spd * area.battle_bonus_malus
+ target.battle.defe = target.battle.defe * area.battle_bonus_malus
if "atkraiseally" in move.effect:
target.battle.atk = target.battle.atk * area.battle_bonus_malus
@@ -1190,9 +1125,7 @@ def start_battle_animation(area):
)
if "defraiseally" in move.effect:
- target.battle.defe = (
- target.battle.defe * area.battle_bonus_malus
- )
+ target.battle.defe = target.battle.defe * area.battle_bonus_malus
battle_send_ic(
target,
msg=f" and raises the defense of ~{target.battle.fighter}~",
@@ -1259,7 +1192,7 @@ def start_battle_animation(area):
if client.battle.status == "enraged":
client.battle.status = None
damage = damage * area.battle_enraged_bonus
- battle_send_ic(client, msg=f"focuses all strenght")
+ battle_send_ic(client, msg="focuses all strenght")
# send ic damage move
if damage == 0:
@@ -1393,9 +1326,7 @@ def start_battle_animation(area):
shake=1,
)
target.battle.spd = target.battle.spd / area.battle_bonus_malus
- target.battle.defe = (
- target.battle.defe / area.battle_bonus_malus
- )
+ target.battle.defe = target.battle.defe / area.battle_bonus_malus
battle_send_ic(
target,
msg=f"and ~{target.battle.fighter}~'s defensive statistics go down",
@@ -1491,7 +1422,7 @@ def start_battle_animation(area):
for client in area.fighters:
if client.battle.hp <= 0:
continue
- fighter_name = client.area.area_manager.char_list[client.char_id]
+ client.area.area_manager.char_list[client.char_id]
if client.battle.status == "poison" and client.battle.hp > 0:
client.battle.hp += -client.battle.maxhp / area.battle_poison_damage
battle_send_ic(
@@ -1527,9 +1458,7 @@ def start_battle_animation(area):
"burn",
"freeze",
]:
- battle_send_ic(
- client, msg=f"~{client.battle.fighter}~ ran out of hp!", offset=100
- )
+ battle_send_ic(client, msg=f"~{client.battle.fighter}~ ran out of hp!", offset=100)
# check dead fighters and unselect move and target
for client in list(area.fighters):
@@ -1546,9 +1475,7 @@ def start_battle_animation(area):
encoding="utf-8",
) as c_load:
char = yaml.safe_load(c_load)
- client.battle = ClientManager.BattleChar(
- client, client.battle.fighter, char
- )
+ client.battle = ClientManager.BattleChar(client, client.battle.fighter, char)
guild = None
for g in client.area.battle_guilds:
if client in client.area.battle_guilds[g]:
@@ -1560,13 +1487,9 @@ def start_battle_animation(area):
if len(area.fighters) == 1:
winner = area.fighters[0]
battle_send_ic(winner, msg=f"~{winner.battle.fighter}~ wins the battle!")
- with open(
- f"storage/battlesystem/{winner.battle.fighter}.yaml", "r", encoding="utf-8"
- ) as c_load:
+ with open(f"storage/battlesystem/{winner.battle.fighter}.yaml", "r", encoding="utf-8") as c_load:
char = yaml.safe_load(c_load)
- winner.battle = ClientManager.BattleChar(
- winner, winner.battle.fighter, char
- )
+ winner.battle = ClientManager.BattleChar(winner, winner.battle.fighter, char)
guild = None
for g in winner.area.battle_guilds:
if winner in winner.area.battle_guilds[g]:
@@ -1575,7 +1498,7 @@ def start_battle_animation(area):
winner.battle.guild = guild
area.fighters = []
elif len(area.fighters) == 0:
- battle_send_ic(client, msg=f"~Everyone~ is down...", offset=100)
+ battle_send_ic(client, msg="~Everyone~ is down...", offset=100)
area.fighters = []
else:
# check if there is a winner guild
@@ -1593,9 +1516,7 @@ def start_battle_animation(area):
encoding="utf-8",
) as c_load:
char = yaml.safe_load(c_load)
- winner.battle = ClientManager.BattleChar(
- winner, winner.battle.fighter, char
- )
+ winner.battle = ClientManager.BattleChar(winner, winner.battle.fighter, char)
guild = None
for g in winner.area.battle_guilds:
if winner in winner.area.battle_guilds[g]:
diff --git a/server/commands/casing.py b/server/commands/casing.py
index d0001a4e..396528e7 100644
--- a/server/commands/casing.py
+++ b/server/commands/casing.py
@@ -51,6 +51,7 @@
"ooc_cmd_evidence_lists",
]
+
def ooc_cmd_doc(client, arg):
"""
Show or change the link for the current case document.
@@ -62,16 +63,10 @@ def ooc_cmd_doc(client, arg):
else:
if client.area.cannot_ic_interact(client):
raise ClientError("You are not on the area's invite list!")
- if (
- not client.is_mod
- and not (client in client.area.owners)
- and client.char_id == -1
- ):
+ if not client.is_mod and client not in client.area.owners and client.char_id == -1:
raise ClientError("You may not do that while spectating!")
client.area.change_doc(arg)
- client.area.broadcast_ooc(
- f"{client.showname} changed the doc link to: {client.area.doc}"
- )
+ client.area.broadcast_ooc(f"{client.showname} changed the doc link to: {client.area.doc}")
database.log_area("doc.change", client, client.area, message=arg)
@@ -84,15 +79,10 @@ def ooc_cmd_cleardoc(client, arg):
raise ArgumentError("This command has no arguments.")
if client.area.cannot_ic_interact(client):
raise ClientError("You are not on the area's invite list!")
- if (
- not client.is_mod
- and not (client in client.area.owners)
- and client.char_id == -1
- ):
+ if not client.is_mod and client not in client.area.owners and client.char_id == -1:
raise ClientError("You may not do that while spectating!")
client.area.change_doc()
- client.area.broadcast_ooc(
- "{} cleared the doc link.".format(client.showname))
+ client.area.broadcast_ooc("{} cleared the doc link.".format(client.showname))
database.log_area("doc.clear", client, client.area)
@@ -111,7 +101,7 @@ def ooc_cmd_evidence(client, arg):
# 0 = name
# 1 = desc
# 2 = image
- evi_msg = f"\n💼[{i+1}]: '{evi[0]}'" # (🖼️{evi[2]})
+ evi_msg = f"\n💼[{i + 1}]: '{evi[0]}'" # (🖼️{evi[2]})
if arg == "" or arg.lower() in evi_msg.lower():
msg += evi_msg
msg += "\n\n|| Use /evidence [evi_name/id] to read specific evidence. ||"
@@ -126,10 +116,8 @@ def ooc_cmd_evidence(client, arg):
evidence = evi
break
if evidence is None:
- raise AreaError(
- f"Target evidence not found! (/evidence {arg})"
- )
- msg = f"==💼[{i+1}]: '{evidence[0]}=="
+ raise AreaError(f"Target evidence not found! (/evidence {arg})")
+ msg = f"==💼[{i + 1}]: '{evidence[0]}=="
msg += f"\n🖼️Image: {evidence[2]}"
msg += f"\n📃Desc:\n{evidence[1]}"
msg += "\n\n|| Use /evidence to read all evidence in the area ||"
@@ -152,7 +140,8 @@ def ooc_cmd_evidence_add(client, arg):
args = shlex.split(arg)
if len(args) > 3:
raise ArgumentError(
- f"Too many arguments! Make sure to surround your args in \"\"'s if there's spaces. (/evidence_add {arg})")
+ f"Too many arguments! Make sure to surround your args in \"\"'s if there's spaces. (/evidence_add {arg})"
+ )
# fill the rest of it with asterisk to fill to max_args
args = args + ([""] * (max_args - len(args)))
if args[0] == "":
@@ -162,12 +151,10 @@ def ooc_cmd_evidence_add(client, arg):
if args[2] == "":
args[2] = "empty.png"
except ValueError as ex:
- client.send_ooc(f'{ex} (/evidence_add {arg})')
+ client.send_ooc(f"{ex} (/evidence_add {arg})")
return
- client.area.evi_list.add_evidence(
- client, args[0], args[1], args[2]
- )
+ client.area.evi_list.add_evidence(client, args[0], args[1], args[2])
database.log_area("evidence.add", client, client.area)
client.area.broadcast_evidence_list()
client.send_ooc(f"You have added evidence '{args[0]}'.")
@@ -179,9 +166,7 @@ def ooc_cmd_evidence_remove(client, arg):
Usage: /evidence_remove
"""
if arg == "":
- raise ArgumentError(
- "Use /evidence_remove to remove that piece of evidence."
- )
+ raise ArgumentError("Use /evidence_remove to remove that piece of evidence.")
try:
evi_list = client.area.get_evidence_list(client)
evidence = None
@@ -190,9 +175,7 @@ def ooc_cmd_evidence_remove(client, arg):
evidence = evi
break
if evidence is None:
- raise AreaError(
- f"Target evidence not found! (/evidence_remove {arg})"
- )
+ raise AreaError(f"Target evidence not found! (/evidence_remove {arg})")
evi_name = evidence[0]
client.area.evi_list.del_evidence(client, i)
database.log_area("evidence.del", client, client.area)
@@ -212,9 +195,7 @@ def ooc_cmd_evidence_edit(client, arg):
Usage: /evidence_edit [name] [desc] [image]
"""
if arg == "":
- raise ArgumentError(
- "Use /evidence_edit [name] [desc] [image] to edit that piece of evidence."
- )
+ raise ArgumentError("Use /evidence_edit [name] [desc] [image] to edit that piece of evidence.")
try:
max_args = 4
@@ -222,11 +203,12 @@ def ooc_cmd_evidence_edit(client, arg):
args = shlex.split(arg)
if len(args) > 4:
raise ArgumentError(
- f"Too many arguments! Make sure to surround your args in \"\"'s if there's spaces. (/evidence_edit {arg})")
+ f"Too many arguments! Make sure to surround your args in \"\"'s if there's spaces. (/evidence_edit {arg})"
+ )
# fill the rest of it with asterisk to fill to max_args
args = args + (["*"] * (max_args - len(args)))
except ValueError as ex:
- client.send_ooc(f'{ex} (/evidence_edit {arg})')
+ client.send_ooc(f"{ex} (/evidence_edit {arg})")
return
try:
@@ -237,9 +219,7 @@ def ooc_cmd_evidence_edit(client, arg):
evidence = evi
break
if evidence is None:
- raise AreaError(
- f"Target evidence not found! (/evidence_edit {arg})"
- )
+ raise AreaError(f"Target evidence not found! (/evidence_edit {arg})")
evi_name = evidence[0]
evi = (args[1], args[2], args[3], "all")
@@ -247,8 +227,7 @@ def ooc_cmd_evidence_edit(client, arg):
database.log_area("evidence.edit", client, client.area)
client.area.broadcast_evidence_list()
if evi[0] != "*" and evi_name != evi[0]:
- client.send_ooc(
- f"You have edited evidence '{evi_name}' to '{evi[0]}'.")
+ client.send_ooc(f"You have edited evidence '{evi_name}' to '{evi[0]}'.")
else:
client.send_ooc(f"You have edited evidence '{evi_name}'.")
except ValueError:
@@ -278,12 +257,9 @@ def ooc_cmd_evidence_present(client, arg):
evidence = evi
break
if evidence is None:
- raise AreaError(
- f"Target evidence not found! (/evidence_present {arg})"
- )
+ raise AreaError(f"Target evidence not found! (/evidence_present {arg})")
client.presenting = i + 1
- client.send_ooc(
- f"Will now present evidence [{client.presenting}] {evidence[0]} on next IC message.")
+ client.send_ooc(f"Will now present evidence [{client.presenting}] {evidence[0]} on next IC message.")
except ValueError:
raise
except (AreaError, ClientError):
@@ -302,21 +278,15 @@ def ooc_cmd_evidence_mod(client, arg):
elif arg in ["FFA", "Mods", "CM", "HiddenCM"]:
if not client.is_mod:
if client.area.evidence_mod == "Mods":
- raise ClientError(
- "You must be authorized to change this area's evidence mod from Mod-only."
- )
+ raise ClientError("You must be authorized to change this area's evidence mod from Mod-only.")
if arg == "Mods":
- raise ClientError(
- "You must be authorized to set the area's evidence to Mod-only."
- )
+ raise ClientError("You must be authorized to set the area's evidence to Mod-only.")
client.area.evidence_mod = arg
client.area.broadcast_evidence_list()
client.send_ooc(f"current evidence mod: {client.area.evidence_mod}")
database.log_area("evidence_mod", client, client.area, message=arg)
else:
- raise ArgumentError(
- "Wrong Argument. Use /evidence_mod . Possible values: FFA, CM, Mods, HiddenCM"
- )
+ raise ArgumentError("Wrong Argument. Use /evidence_mod . Possible values: FFA, CM, Mods, HiddenCM")
@mod_only(area_owners=True)
@@ -331,8 +301,7 @@ def ooc_cmd_evidence_swap(client, arg):
if len(args) != 2:
raise ClientError("you must specify 2 numbers")
try:
- client.area.evi_list.evidence_swap(
- client, int(args[0]) - 1, int(args[1]) - 1)
+ client.area.evi_list.evidence_swap(client, int(args[0]) - 1, int(args[1]) - 1)
client.area.broadcast_evidence_list()
except Exception:
raise ClientError("you must specify 2 numbers")
@@ -351,16 +320,13 @@ def ooc_cmd_cm(client, arg):
if arg != "":
# Nominate all self clients (Those not present in area will not be counted later)
if arg == "*":
- arg = [c.id for c in client.server.client_manager.get_multiclients(
- client.ipid, client.hdid)]
+ arg = [c.id for c in client.server.client_manager.get_multiclients(client.ipid, client.hdid)]
# CM the provided targets
else:
arg = arg.split(" ")
# Client is not a mod, not a CM and not a GM, meaning they're trying to nominate someone without being /cm first
if not client.is_mod and client not in client.area.owners:
- raise ArgumentError(
- "You cannot 'nominate' people to be CMs when you are not one."
- )
+ raise ArgumentError("You cannot 'nominate' people to be CMs when you are not one.")
else:
# Self CM
arg = [client.id]
@@ -368,16 +334,11 @@ def ooc_cmd_cm(client, arg):
for id in arg:
try:
id = int(id)
- c = client.server.client_manager.get_targets(
- client, TargetType.ID, id, False
- )[0]
+ c = client.server.client_manager.get_targets(client, TargetType.ID, id, False)[0]
if c not in client.area.clients:
- raise ArgumentError(
- "You can only 'nominate' people to be CMs when they are in the area."
- )
+ raise ArgumentError("You can only 'nominate' people to be CMs when they are in the area.")
elif c in client.area._owners:
- client.send_ooc(
- f"{c.showname} [{c.id}] is already a CM here.")
+ client.send_ooc(f"{c.showname} [{c.id}] is already a CM here.")
else:
client.area.add_owner(c)
database.log_area("cm.add", client, client.area, target=c)
@@ -403,16 +364,12 @@ def ooc_cmd_uncm(client, arg):
for _id in arg:
try:
_id = int(_id)
- c = client.server.client_manager.get_targets(
- client, TargetType.ID, _id, False
- )[0]
+ c = client.server.client_manager.get_targets(client, TargetType.ID, _id, False)[0]
if c in client.area._owners:
client.area.remove_owner(c)
database.log_area("cm.remove", client, client.area, target=c)
else:
- client.send_ooc(
- "You cannot remove someone from CMing when they aren't a CM."
- )
+ client.send_ooc("You cannot remove someone from CMing when they aren't a CM.")
except (ValueError, IndexError):
client.send_ooc(f"{_id} does not look like a valid ID.")
except (ClientError, ArgumentError):
@@ -448,15 +405,12 @@ def ooc_cmd_anncase(client, arg):
# XXX: Merge with aoprotocol.net_cmd_casea
if client in client.area.owners:
if not client.can_call_case():
- raise ClientError(
- "Please wait 60 seconds between case announcements!")
+ raise ClientError("Please wait 60 seconds between case announcements!")
args = re.findall(r'(?:[^\s,"]|"(?:\\.|[^"])*")+', arg)
if len(args) == 0:
raise ArgumentError("Please do not call this command manually!")
elif len(args) == 1:
- raise ArgumentError(
- "You should probably announce the case to at least one person."
- )
+ raise ArgumentError("You should probably announce the case to at least one person.")
else:
if (
not args[1] == "1"
@@ -465,9 +419,7 @@ def ooc_cmd_anncase(client, arg):
and not args[4] == "1"
and not args[5] == "1"
):
- raise ArgumentError(
- "You should probably announce the case to at least one person."
- )
+ raise ArgumentError("You should probably announce the case to at least one person.")
msg = "=== Case Announcement ===\r\n{} [{}] is hosting {}, looking for ".format(
client.showname, client.id, args[0]
)
@@ -483,21 +435,14 @@ def ooc_cmd_anncase(client, arg):
msg += ", ".join(lookingfor) + ".\r\n=================="
- client.server.send_all_cmd_pred(
- "CASEA", msg, args[1], args[2], args[3], args[4], args[5], "1"
- )
+ client.server.send_all_cmd_pred("CASEA", msg, args[1], args[2], args[3], args[4], args[5], "1")
client.set_case_call_delay()
- log_data = {
- k: v
- for k, v in zip(("message", "def", "pro", "jud", "jur", "steno"), args)
- }
+ log_data = {k: v for k, v in zip(("message", "def", "pro", "jud", "jur", "steno"), args)}
database.log_area("case", client, client.area, message=log_data)
else:
- raise ClientError(
- "You cannot announce a case in an area where you are not a CM!"
- )
+ raise ClientError("You cannot announce a case in an area where you are not a CM!")
@mod_only()
@@ -510,9 +455,7 @@ def ooc_cmd_blockwtce(client, arg):
if len(arg) == 0:
raise ArgumentError("You must specify a target. Use /blockwtce .")
try:
- targets = client.server.client_manager.get_targets(
- client, TargetType.ID, int(arg), False
- )
+ targets = client.server.client_manager.get_targets(client, TargetType.ID, int(arg), False)
except Exception:
raise ArgumentError("You must enter a number. Use /blockwtce .")
if not targets:
@@ -531,12 +474,9 @@ def ooc_cmd_unblockwtce(client, arg):
Usage: /unblockwtce
"""
if len(arg) == 0:
- raise ArgumentError(
- "You must specify a target. Use /unblockwtce .")
+ raise ArgumentError("You must specify a target. Use /unblockwtce .")
try:
- targets = client.server.client_manager.get_targets(
- client, TargetType.ID, int(arg), False
- )
+ targets = client.server.client_manager.get_targets(client, TargetType.ID, int(arg), False)
except Exception:
raise ArgumentError("You must enter a number. Use /unblockwtce .")
if not targets:
@@ -563,9 +503,7 @@ def ooc_cmd_judgelog(client, arg):
jlog_msg += f"\r\n{x}"
client.send_ooc(jlog_msg)
else:
- raise ServerError(
- "There have been no judge actions in this area since start of session."
- )
+ raise ServerError("There have been no judge actions in this area since start of session.")
def ooc_cmd_afk(client, arg):
@@ -590,9 +528,7 @@ def ooc_cmd_remote_listen(client, arg):
try:
client.remote_listen = options[arg.upper()]
except KeyError:
- raise ArgumentError(
- "Invalid option! Your options are NONE, IC, OOC or ALL."
- )
+ raise ArgumentError("Invalid option! Your options are NONE, IC, OOC or ALL.")
reversed_options = dict(map(reversed, options.items()))
opt = reversed_options[client.remote_listen]
client.send_ooc(f"Your current remote listen option is: {opt}")
@@ -615,9 +551,7 @@ def ooc_cmd_testimony(client, arg):
return
idx = int(args[0]) - 1
client.area.testimony_send(idx)
- client.area.broadcast_ooc(
- f"{client.showname} has moved to Statement {idx+1}."
- )
+ client.area.broadcast_ooc(f"{client.showname} has moved to Statement {idx + 1}.")
except ValueError:
raise ArgumentError("Index must be a number!")
except ClientError:
@@ -636,7 +570,7 @@ def ooc_cmd_testimony(client, arg):
here = " "
if i == client.area.testimony_index:
here = " >"
- msg += f"\n{here}{i+1}) {name}: {txt}"
+ msg += f"\n{here}{i + 1}) {name}: {txt}"
client.send_ooc(msg)
@@ -647,8 +581,7 @@ def ooc_cmd_testimony_start(client, arg):
Usage: /testimony_start
"""
if arg == "":
- raise ArgumentError(
- "You must provite a title! /testimony_start .")
+ raise ArgumentError("You must provite a title! /testimony_start .")
if len(arg) < 3:
raise ArgumentError("Title must contain at least 3 characters!")
client.area.testimony.clear()
@@ -687,8 +620,7 @@ def ooc_cmd_testimony_clear(client, arg):
raise ArgumentError("This command does not take any arguments.")
client.area.testimony.clear()
client.area.testimony_title = ""
- client.area.broadcast_ooc(
- f"{client.showname} cleared the current testimony.")
+ client.area.broadcast_ooc(f"{client.showname} cleared the current testimony.")
@mod_only(area_owners=True)
@@ -708,8 +640,7 @@ def ooc_cmd_testimony_remove(client, arg):
client.area.testimony.pop(idx)
if client.area.testimony_index == idx:
client.area.testimony_index = -1
- client.area.broadcast_ooc(
- f"{client.showname} has removed Statement {idx+1}.")
+ client.area.broadcast_ooc(f"{client.showname} has removed Statement {idx + 1}.")
except ValueError:
raise ArgumentError("Index must be a number!")
except IndexError:
@@ -735,8 +666,7 @@ def ooc_cmd_testimony_amend(client, arg):
lst = list(client.area.testimony[idx])
lst[4] = "}}}" + " ".join(args[1:])
client.area.testimony[idx] = tuple(lst)
- client.area.broadcast_ooc(
- f"{client.showname} has amended Statement {idx+1}.")
+ client.area.broadcast_ooc(f"{client.showname} has amended Statement {idx + 1}.")
except ValueError:
raise ArgumentError("Index must be a number!")
except IndexError:
@@ -764,9 +694,7 @@ def ooc_cmd_testimony_swap(client, arg):
client.area.testimony[idx1],
client.area.testimony[idx2],
)
- client.area.broadcast_ooc(
- f"{client.showname} has swapped Statements {idx1+1} and {idx2+1}."
- )
+ client.area.broadcast_ooc(f"{client.showname} has swapped Statements {idx1 + 1} and {idx2 + 1}.")
except ValueError:
raise ArgumentError("Index must be a number!")
except IndexError:
@@ -793,9 +721,7 @@ def ooc_cmd_testimony_insert(client, arg):
statement = client.area.testimony.pop(idx1)
client.area.testimony.insert(idx2, statement)
- client.area.broadcast_ooc(
- f"{client.showname} has inserted Statement {idx1+1} into {idx2+1}."
- )
+ client.area.broadcast_ooc(f"{client.showname} has inserted Statement {idx1 + 1} into {idx2 + 1}.")
except ValueError:
raise ArgumentError("Index must be a number!")
except IndexError:
@@ -813,10 +739,7 @@ def ooc_cmd_cs(client, arg):
Usage: /cs
"""
if arg == "":
- if (
- client.area.minigame_schedule
- and not client.area.minigame_schedule.cancelled()
- ):
+ if client.area.minigame_schedule and not client.area.minigame_schedule.cancelled():
msg = f"Current minigame is {client.area.minigame}!\n"
red = []
for cid in client.area.red_team:
@@ -842,9 +765,7 @@ def ooc_cmd_cs(client, arg):
return
args = arg.split()
try:
- target = client.server.client_manager.get_targets(
- client, TargetType.ID, int(args[0]), True
- )[0]
+ target = client.server.client_manager.get_targets(client, TargetType.ID, int(args[0]), True)[0]
except Exception:
raise ArgumentError("Target not found.")
else:
@@ -920,15 +841,13 @@ def set_minigame_song(client, minigame="", song="", condition=0):
client.area.panic_talk_action_song_end = song
elif condition == 2:
client.area.panic_talk_action_song_concede = song
- client.send_ooc(
- f"Setting the {minigame} {condition_str} song to {song}.")
+ client.send_ooc(f"Setting the {minigame} {condition_str} song to {song}.")
return
# Songname is not provided
client.editing_minigame_song = minigame
client.editing_minigame_song_condition = condition
- client.send_ooc(
- f"Play a song to set the {minigame} {condition_str} song to...")
+ client.send_ooc(f"Play a song to set the {minigame} {condition_str} song to...")
@mod_only(area_owners=True)
@@ -976,22 +895,17 @@ def ooc_cmd_concede(client, arg):
if client.area.minigame != "":
try:
if arg.lower() == "not-pta" and client.area.minigame == "Panic Talk Action":
- client.send_ooc(
- "Current minigame is Panic Talk Action - not conceding this one."
- )
+ client.send_ooc("Current minigame is Panic Talk Action - not conceding this one.")
return
# CM's end the minigame automatically using /concede
if client in client.area.owners:
client.area.end_minigame("Forcibly ended.")
- client.area.broadcast_ooc(
- "The minigame has been forcibly ended.")
+ client.area.broadcast_ooc("The minigame has been forcibly ended.")
return
if client.char_id not in client.area.blue_team and client.char_id not in client.area.red_team:
client.area.vote_end_minigame(client)
return
- client.area.start_debate(
- client, client
- ) # starting a debate against yourself is a concede
+ client.area.start_debate(client, client) # starting a debate against yourself is a concede
except AreaError as ex:
raise ex
else:
@@ -1007,9 +921,7 @@ def ooc_cmd_subtheme(client, arg):
client.area.area_manager.subtheme = arg.strip()
# Set everyone's subthemes
client.area.area_manager.broadcast_subtheme()
- client.send_ooc(
- f"Setting hub subtheme to {arg}."
- )
+ client.send_ooc(f"Setting hub subtheme to {arg}.")
@mod_only(hub_owners=True)
@@ -1021,9 +933,7 @@ def ooc_cmd_time_of_day(client, arg):
client.area.area_manager.time_of_day = arg.strip()
# Set everyone's time_of_day
client.area.area_manager.broadcast_subtheme()
- client.send_ooc(
- f"Setting hub time_of_day to {arg}."
- )
+ client.send_ooc(f"Setting hub time_of_day to {arg}.")
@mod_only(hub_owners=True)
@@ -1040,7 +950,7 @@ def ooc_cmd_evidence_lists(client, arg):
client.send_ooc(msg)
-def evidence_load(client, name, overlay = False):
+def evidence_load(client, name, overlay=False):
if f"{name}.yaml" not in os.listdir("storage/evidence"):
client.send_ooc(f"Evidence List {name} not found!")
return
@@ -1080,7 +990,7 @@ def ooc_cmd_evidence_overlay(client, arg):
if arg == "":
client.send_ooc("Usage: /evidence_overlay ")
return
- evidence_load(client, derelative(arg), overlay = True)
+ evidence_load(client, derelative(arg), overlay=True)
@mod_only(area_owners=True)
@@ -1102,12 +1012,8 @@ def ooc_cmd_evidence_save(client, arg):
with open(arg, "r", encoding="utf-8") as stream:
evi_list = yaml.safe_load(stream)
if "read_only" in evi_list and evi_list["read_only"] is True:
- raise ArgumentError(
- f"Evidence List {arg} already exists and it is read-only!"
- )
+ raise ArgumentError(f"Evidence List {arg} already exists and it is read-only!")
with open(arg, "w", encoding="utf-8") as yaml_save:
yaml.dump(evidence, yaml_save)
- database.log_area(f"evidence.save", client, client.area, arg)
- client.send_ooc(
- f"Evidence has been saved as '{arg}' on the server."
- )
+ database.log_area("evidence.save", client, client.area, arg)
+ client.send_ooc(f"Evidence has been saved as '{arg}' on the server.")
diff --git a/server/commands/character.py b/server/commands/character.py
index 36fd2fc1..cf117a28 100644
--- a/server/commands/character.py
+++ b/server/commands/character.py
@@ -77,6 +77,7 @@ def ooc_cmd_set_url(client, arg):
client.send_ooc(f"URL set to {arg_strip}")
client.char_url = arg_strip
+
def ooc_cmd_get_urls(client, arg):
"""
This command returns the server's URL List.
@@ -87,6 +88,7 @@ def ooc_cmd_get_urls(client, arg):
f_server_links += f"{name}: {url} \n"
client.send_ooc(f_server_links)
+
def ooc_cmd_switch(client, arg):
"""
Switch to another character. If moderator and the specified character is
@@ -108,8 +110,7 @@ def ooc_cmd_switch(client, arg):
except ServerError:
raise
try:
- client.change_character(
- cid, client.is_mod or client in client.area.owners)
+ client.change_character(cid, client.is_mod or client in client.area.owners)
except ClientError:
raise
client.send_ooc("Character changed.")
@@ -145,9 +146,7 @@ def ooc_cmd_pair(client, arg):
return
if arg.isdigit():
- targets = client.server.client_manager.get_targets(
- client, TargetType.ID, int(arg), True
- )
+ targets = client.server.client_manager.get_targets(client, TargetType.ID, int(arg), True)
if len(targets) > 0:
client.charid_pair = targets[0].char_id
client.charid_pair_override = True
@@ -161,7 +160,9 @@ def ooc_cmd_pair(client, arg):
char = client.charid_pair
if client.charid_pair in range(0, len(client.area.area_manager.char_list)):
char = client.area.area_manager.char_list[client.charid_pair]
- client.send_ooc(f"Successfully paired with '{char}'! Ask them to pair with you back, and show up on the same /pos for it to work.")
+ client.send_ooc(
+ f"Successfully paired with '{char}'! Ask them to pair with you back, and show up on the same /pos for it to work."
+ )
else:
client.send_ooc("Pairing target not found!")
@@ -186,11 +187,11 @@ def ooc_cmd_pair_order(client, arg):
Usage: /pair_order [order]
"""
if client.charid_pair_override:
- msg = ['in front of', 'behind']
+ msg = ["in front of", "behind"]
if arg:
- if arg.lower() == 'front':
+ if arg.lower() == "front":
client.pair_order = 0
- elif arg.lower() == 'behind':
+ elif arg.lower() == "behind":
client.pair_order = 1
elif arg.isdigit() and int(arg) in [0, 1]:
client.pair_order = int(arg)
@@ -220,17 +221,11 @@ def ooc_cmd_forcepos(client, arg):
pos = args[0]
if len(args) > 1:
- targets = client.server.client_manager.get_targets(
- client, TargetType.CHAR_NAME, " ".join(args[1:]), True
- )
+ targets = client.server.client_manager.get_targets(client, TargetType.CHAR_NAME, " ".join(args[1:]), True)
if len(targets) == 0 and args[1].isdigit():
- targets = client.server.client_manager.get_targets(
- client, TargetType.ID, int(args[1]), True
- )
+ targets = client.server.client_manager.get_targets(client, TargetType.ID, int(args[1]), True)
if len(targets) == 0:
- targets = client.server.client_manager.get_targets(
- client, TargetType.OOC_NAME, " ".join(args[1:]), True
- )
+ targets = client.server.client_manager.get_targets(client, TargetType.OOC_NAME, " ".join(args[1:]), True)
if len(targets) == 0:
raise ArgumentError("No targets found.")
else:
@@ -258,8 +253,7 @@ def ooc_cmd_forcepos(client, arg):
t.area.broadcast_evidence_list()
t.send_ooc(f"Forced into /pos {_pos}.")
client.send_ooc(f"Forced [{t.id}] {t.showname} into /pos {_pos}.")
- database.log_area("forcepos", client, client.area,
- target=t, message=pos)
+ database.log_area("forcepos", client, client.area, target=t, message=pos)
except ClientError:
raise
@@ -271,18 +265,13 @@ def ooc_cmd_force_switch(client, arg):
Usage: /force_switch [char]
"""
if not arg:
- raise ArgumentError(
- 'Not enough arguments. Usage: /force_switch [char]')
+ raise ArgumentError("Not enough arguments. Usage: /force_switch [char]")
args = shlex.split(arg)
try:
if args[0].isnumeric():
- targets = client.server.client_manager.get_targets(
- client, TargetType.ID, int(args[0]), False
- )
+ targets = client.server.client_manager.get_targets(client, TargetType.ID, int(args[0]), False)
else:
- targets = client.server.client_manager.get_targets(
- client, TargetType.CHAR_NAME, args[0], False
- )
+ targets = client.server.client_manager.get_targets(client, TargetType.CHAR_NAME, args[0], False)
for target in targets:
force_switch(client, target, " ".join(args[1:]))
except Exception as ex:
@@ -293,7 +282,7 @@ def ooc_cmd_force_switch(client, arg):
def force_switch(client, target, char=""):
if not client.is_mod and client not in target.area.owners:
- raise ClientError(f'Insufficient permissions for {char}')
+ raise ClientError(f"Insufficient permissions for {char}")
if char != "":
try:
if char == "-1" or char.lower() == "spectator":
@@ -314,7 +303,7 @@ def force_switch(client, target, char=""):
except ClientError:
raise
else:
- target.send_ooc(f"You've been forced into character select screen.")
+ target.send_ooc("You've been forced into character select screen.")
target.char_select()
@@ -330,9 +319,7 @@ def ooc_cmd_kill(client, arg):
targets = []
ids = [int(s) for s in arg.split(" ")]
for targ_id in ids:
- c = client.server.client_manager.get_targets(
- client, TargetType.ID, targ_id, False
- )
+ c = client.server.client_manager.get_targets(client, TargetType.ID, targ_id, False)
if c:
targets = targets + c
except Exception:
@@ -341,11 +328,10 @@ def ooc_cmd_kill(client, arg):
try:
for target in targets:
force_switch(client, target, "-1")
- target.send_ooc(f"💀You are dead!💀")
+ target.send_ooc("💀You are dead!💀")
except Exception as ex:
- raise ArgumentError(
- f"Error encountered: {ex}. Use /kill as a mod or area owner."
- )
+ raise ArgumentError(f"Error encountered: {ex}. Use /kill as a mod or area owner.")
+
def ooc_cmd_randomchar(client, arg):
"""
@@ -379,18 +365,12 @@ def ooc_cmd_charcurse(client, arg):
"You must specify a target (an ID) and at least one character ID. Consult /charids for the character IDs."
)
elif len(arg) == 1:
- raise ArgumentError(
- "You must specific at least one character ID. Consult /charids for the character IDs."
- )
+ raise ArgumentError("You must specific at least one character ID. Consult /charids for the character IDs.")
args = arg.split()
try:
- targets = client.server.client_manager.get_targets(
- client, TargetType.ID, int(args[0]), False
- )
+ targets = client.server.client_manager.get_targets(client, TargetType.ID, int(args[0]), False)
except Exception:
- raise ArgumentError(
- "You must specify a valid target! Make sure it is a valid ID."
- )
+ raise ArgumentError("You must specify a valid target! Make sure it is a valid ID.")
if targets:
for c in targets:
log_msg = ""
@@ -399,22 +379,15 @@ def ooc_cmd_charcurse(client, arg):
try:
cid = int(raw_cid)
c.charcurse.append(cid)
- part_msg += " " + \
- str(client.area.area_manager.char_list[cid]) + ","
- log_msg += " " + \
- str(client.area.area_manager.char_list[cid]) + ","
- except:
- ArgumentError(
- "" + str(raw_cid) +
- " does not look like a valid character ID."
- )
+ part_msg += " " + str(client.area.area_manager.char_list[cid]) + ","
+ log_msg += " " + str(client.area.area_manager.char_list[cid]) + ","
+ except Exception:
+ raise ArgumentError("" + str(raw_cid) + " does not look like a valid character ID.")
part_msg = part_msg[:-1]
part_msg += "."
log_msg = log_msg[:-1]
c.char_select()
- database.log_area(
- "charcurse", client, client.area, target=c, message=log_msg
- )
+ database.log_area("charcurse", client, client.area, target=c, message=log_msg)
client.send_ooc("Charcursed" + part_msg)
else:
client.send_ooc("No targets found.")
@@ -430,13 +403,9 @@ def ooc_cmd_uncharcurse(client, arg):
raise ArgumentError("You must specify a target (an ID).")
args = arg.split()
try:
- targets = client.server.client_manager.get_targets(
- client, TargetType.ID, int(args[0]), False
- )
+ targets = client.server.client_manager.get_targets(client, TargetType.ID, int(args[0]), False)
except Exception:
- raise ArgumentError(
- "You must specify a valid target! Make sure it is a valid ID."
- )
+ raise ArgumentError("You must specify a valid target! Make sure it is a valid ID.")
if targets:
for c in targets:
if len(c.charcurse) > 0:
@@ -489,9 +458,7 @@ def ooc_cmd_blind(client, arg):
targets = []
ids = [int(s) for s in arg.split(" ")]
for targ_id in ids:
- c = client.server.client_manager.get_targets(
- client, TargetType.ID, targ_id, False
- )
+ c = client.server.client_manager.get_targets(client, TargetType.ID, targ_id, False)
if c:
targets = targets + c
except Exception:
@@ -522,9 +489,7 @@ def ooc_cmd_unblind(client, arg):
targets = []
ids = [int(s) for s in arg.split(" ")]
for targ_id in ids:
- c = client.server.client_manager.get_targets(
- client, TargetType.ID, targ_id, False
- )
+ c = client.server.client_manager.get_targets(client, TargetType.ID, targ_id, False)
if c:
targets = targets + c
except Exception:
@@ -549,42 +514,28 @@ def ooc_cmd_player_move_delay(client, arg):
"""
args = shlex.split(arg)
try:
- if len(args) > 0 and (
- client.is_mod or client in client.area.area_manager.owners
- ):
+ if len(args) > 0 and (client.is_mod or client in client.area.area_manager.owners):
# Try to find by char name first
- targets = client.server.client_manager.get_targets(
- client, TargetType.CHAR_NAME, args[0]
- )
+ targets = client.server.client_manager.get_targets(client, TargetType.CHAR_NAME, args[0])
# If that doesn't work, find by client ID
if len(targets) == 0 and args[0].isdigit():
- targets = client.server.client_manager.get_targets(
- client, TargetType.ID, int(args[0])
- )
+ targets = client.server.client_manager.get_targets(client, TargetType.ID, int(args[0]))
# If that doesn't work, find by OOC Name
if len(targets) == 0:
- targets = client.server.client_manager.get_targets(
- client, TargetType.OOC_NAME, args[0]
- )
+ targets = client.server.client_manager.get_targets(client, TargetType.OOC_NAME, args[0])
c = targets[0]
if len(args) > 1:
- move_delay = min(
- 1800, max(-1800, int(args[1]))
- ) # Move delay is limited between -1800 and 1800
+ move_delay = min(1800, max(-1800, int(args[1]))) # Move delay is limited between -1800 and 1800
c.move_delay = move_delay
- client.send_ooc(
- f"Set move delay for {c.char_name} to {c.move_delay}.")
+ client.send_ooc(f"Set move delay for {c.char_name} to {c.move_delay}.")
else:
- client.send_ooc(
- f"Move delay for {c.char_name} is {c.move_delay}.")
+ client.send_ooc(f"Move delay for {c.char_name} is {c.move_delay}.")
else:
client.send_ooc(f"Your current move delay is {client.move_delay}.")
except ValueError:
raise ArgumentError("Delay must be an integer between -1800 and 1800.")
except IndexError:
- raise ArgumentError(
- "Target client not found. Use /player_move_delay [delay]."
- )
+ raise ArgumentError("Target client not found. Use /player_move_delay [delay].")
except (AreaError, ClientError):
raise
@@ -600,32 +551,23 @@ def ooc_cmd_player_hide(client, arg):
raise ArgumentError("You must specify a target.")
args = arg.split()
if args[0] == "*":
- targets = [
- c for c in client.area.clients if c != client and c != client.area.owners
- ]
+ targets = [c for c in client.area.clients if c != client and c != client.area.owners]
else:
try:
targets = []
ids = [int(s) for s in args]
for targ_id in ids:
- c = client.server.client_manager.get_targets(
- client, TargetType.ID, targ_id, False
- )
+ c = client.server.client_manager.get_targets(client, TargetType.ID, targ_id, False)
if c:
targets = targets + c
except Exception:
- raise ArgumentError(
- "You must specify a target. Use /player_unhide [id(s)]."
- )
+ raise ArgumentError("You must specify a target. Use /player_unhide [id(s)].")
if targets:
for c in targets:
if c.hidden:
- raise ClientError(
- f"Client [{c.id}] {c.showname} already hidden!")
+ raise ClientError(f"Client [{c.id}] {c.showname} already hidden!")
c.hide(True)
- client.send_ooc(
- f"You have hidden [{c.id}] {c.showname} from /getarea and playercounts."
- )
+ client.send_ooc(f"You have hidden [{c.id}] {c.showname} from /getarea and playercounts.")
else:
client.send_ooc("No targets found.")
@@ -641,32 +583,23 @@ def ooc_cmd_player_unhide(client, arg):
raise ArgumentError("You must specify a target.")
args = arg.split()
if args[0] == "*":
- targets = [
- c for c in client.area.clients if c != client and c != client.area.owners
- ]
+ targets = [c for c in client.area.clients if c != client and c != client.area.owners]
else:
try:
targets = []
ids = [int(s) for s in args]
for targ_id in ids:
- c = client.server.client_manager.get_targets(
- client, TargetType.ID, targ_id, False
- )
+ c = client.server.client_manager.get_targets(client, TargetType.ID, targ_id, False)
if c:
targets = targets + c
except Exception:
- raise ArgumentError(
- "You must specify a target. Use /player_unhide [id(s)]."
- )
+ raise ArgumentError("You must specify a target. Use /player_unhide [id(s)].")
if targets:
for c in targets:
if not c.hidden:
- raise ClientError(
- f"Client [{c.id}] {c.showname} already revealed!")
+ raise ClientError(f"Client [{c.id}] {c.showname} already revealed!")
c.hide(False)
- client.send_ooc(
- f"You have revealed [{c.id}] {c.showname} for /getarea and playercounts."
- )
+ client.send_ooc(f"You have revealed [{c.id}] {c.showname} for /getarea and playercounts.")
else:
client.send_ooc("No targets found.")
@@ -677,9 +610,7 @@ def ooc_cmd_hide(client, arg):
Usage: /hide
"""
if arg == "":
- raise ArgumentError(
- "Use /hide to hide in evidence, or /unhide to stop hiding."
- )
+ raise ArgumentError("Use /hide to hide in evidence, or /unhide to stop hiding.")
try:
if arg.isnumeric():
arg = str(int(arg) - 1)
@@ -708,25 +639,19 @@ def ooc_cmd_sneak(client, arg):
"""
if not arg:
if client.sneaking:
- raise ClientError(
- "You are already sneaking! Use /unsneak to stop sneaking.")
+ raise ClientError("You are already sneaking! Use /unsneak to stop sneaking.")
client.sneak(True)
else:
args = shlex.split(arg)
try:
if args[0].isnumeric():
- targets = client.server.client_manager.get_targets(
- client, TargetType.ID, int(args[0]), False
- )
+ targets = client.server.client_manager.get_targets(client, TargetType.ID, int(args[0]), False)
else:
- targets = client.server.client_manager.get_targets(
- client, TargetType.CHAR_NAME, args[0], False
- )
+ targets = client.server.client_manager.get_targets(client, TargetType.CHAR_NAME, args[0], False)
for x in targets:
force_sneak(client, x)
except Exception as ex:
- raise ArgumentError(
- f"Error encountered: {ex}. Use /sneak [id]")
+ raise ArgumentError(f"Error encountered: {ex}. Use /sneak [id]")
def ooc_cmd_unsneak(client, arg):
@@ -737,25 +662,19 @@ def ooc_cmd_unsneak(client, arg):
"""
if not arg:
if not client.sneaking:
- raise ClientError(
- "You are not sneaking! Use /sneak to start sneaking.")
+ raise ClientError("You are not sneaking! Use /sneak to start sneaking.")
client.sneak(False)
else:
args = shlex.split(arg)
try:
if args[0].isnumeric():
- targets = client.server.client_manager.get_targets(
- client, TargetType.ID, int(args[0]), False
- )
+ targets = client.server.client_manager.get_targets(client, TargetType.ID, int(args[0]), False)
else:
- targets = client.server.client_manager.get_targets(
- client, TargetType.CHAR_NAME, args[0], False
- )
+ targets = client.server.client_manager.get_targets(client, TargetType.CHAR_NAME, args[0], False)
for x in targets:
force_unsneak(client, x)
except Exception as ex:
- raise ArgumentError(
- f"Error encountered: {ex}. Use /unsneak [id]")
+ raise ArgumentError(f"Error encountered: {ex}. Use /unsneak [id]")
@mod_only(area_owners=True)
@@ -780,9 +699,7 @@ def ooc_cmd_freeze(client, arg):
targets = []
ids = [int(s) for s in arg.split(" ")]
for targ_id in ids:
- c = client.server.client_manager.get_targets(
- client, TargetType.ID, targ_id, False
- )
+ c = client.server.client_manager.get_targets(client, TargetType.ID, targ_id, False)
if c:
targets = targets + c
except Exception:
@@ -794,9 +711,7 @@ def ooc_cmd_freeze(client, arg):
client.send_ooc(f"Client [{c.id}] {c.name} already frozen! Use /unfreeze {c.id} to undo.")
continue
c.freeze(True)
- client.send_ooc(
- f"You have frozen [{c.id}] {c.name} from being able to move between areas."
- )
+ client.send_ooc(f"You have frozen [{c.id}] {c.name} from being able to move between areas.")
else:
raise ArgumentError("No targets found.")
@@ -813,9 +728,7 @@ def ooc_cmd_unfreeze(client, arg):
targets = []
ids = [int(s) for s in arg.split(" ")]
for targ_id in ids:
- c = client.server.client_manager.get_targets(
- client, TargetType.ID, targ_id, False
- )
+ c = client.server.client_manager.get_targets(client, TargetType.ID, targ_id, False)
if c:
targets = targets + c
except Exception:
@@ -861,9 +774,7 @@ def ooc_cmd_unlisten_pos(client, arg):
if client.listen_pos is None:
raise ClientError("You are not listening to any pos at the moment!")
client.listen_pos = None
- client.send_ooc(
- "You re no longer listening to any pos (All IC messages will appear as normal)."
- )
+ client.send_ooc("You re no longer listening to any pos (All IC messages will appear as normal).")
@mod_only(hub_owners=True)
@@ -909,14 +820,10 @@ def mod_keys(client, arg, mod=0):
"""
args = arg.split()
if len(args) <= 1 and mod != 0:
- raise ArgumentError(
- "Please provide the key(s) to set. Keys must be a number 5 or a link eg. 1-5."
- )
+ raise ArgumentError("Please provide the key(s) to set. Keys must be a number 5 or a link eg. 1-5.")
try:
if args[0].isnumeric():
- target = client.server.client_manager.get_targets(
- client, TargetType.ID, int(args[0]), False
- )
+ target = client.server.client_manager.get_targets(client, TargetType.ID, int(args[0]), False)
if target:
target = target[0].char_id
else:
@@ -925,7 +832,7 @@ def mod_keys(client, arg, mod=0):
else:
try:
target = client.area.area_manager.get_char_id_by_name(arg)
- except (ServerError):
+ except ServerError:
raise
if len(args) > 1:
@@ -939,16 +846,13 @@ def mod_keys(client, arg, mod=0):
# make sure all the keys are integers
key = int(key)
if mod in (1, 2):
- keys = client.area.area_manager.get_character_data(
- target, "keys", [])
+ keys = client.area.area_manager.get_character_data(target, "keys", [])
if a in keys and mod == 2:
keys.remove(a)
- elif not (a in keys):
+ elif a not in keys:
keys.append(a)
client.area.area_manager.set_character_data(target, "keys", keys)
- client.send_ooc(
- f"Character folder {client.area.area_manager.char_list[target]}'s keys are updated: {keys}"
- )
+ client.send_ooc(f"Character folder {client.area.area_manager.char_list[target]}'s keys are updated: {keys}")
except ValueError:
raise ArgumentError("Keys must be a number like 5 or a link eg. 1-5.")
except (AreaError, ClientError):
@@ -986,9 +890,7 @@ def ooc_cmd_keys_remove(client, arg):
Usage: /keys_remove [key(s)]
"""
if not arg:
- raise ArgumentError(
- "Usage: /keys_remove [area id(s)]. Removes the selected 'keys' from the user."
- )
+ raise ArgumentError("Usage: /keys_remove [area id(s)]. Removes the selected 'keys' from the user.")
mod_keys(client, arg, 2)
@@ -1004,14 +906,12 @@ def ooc_cmd_keys(client, arg):
if len(args) < 1:
client.send_ooc(f"Your current keys are {client.keys}")
return
- if not client.is_mod and not (client in client.area.area_manager.owners):
+ if not client.is_mod and client not in client.area.area_manager.owners:
raise ClientError("Only mods and GMs can check other people's keys.")
if len(args) == 1:
try:
if args[0].isnumeric():
- target = client.server.client_manager.get_targets(
- client, TargetType.ID, int(args[0]), False
- )
+ target = client.server.client_manager.get_targets(client, TargetType.ID, int(args[0]), False)
if target:
target = target[0].char_id
else:
@@ -1020,13 +920,10 @@ def ooc_cmd_keys(client, arg):
else:
try:
target = client.area.area_manager.get_char_id_by_name(arg)
- except (ServerError):
+ except ServerError:
raise
- keys = client.area.area_manager.get_character_data(
- target, "keys", [])
- client.send_ooc(
- f"{client.area.area_manager.char_list[target]} current keys are {keys}"
- )
+ keys = client.area.area_manager.get_character_data(target, "keys", [])
+ client.send_ooc(f"{client.area.area_manager.char_list[target]} current keys are {keys}")
except Exception:
raise ArgumentError("Target not found.")
else:
@@ -1041,9 +938,7 @@ def ooc_cmd_kms(client, arg):
"""
if arg != "":
raise ArgumentError("This command takes no arguments!")
- for target in client.server.client_manager.get_multiclients(
- client.ipid, client.hdid
- ):
+ for target in client.server.client_manager.get_multiclients(client.ipid, client.hdid):
if target != client:
target.disconnect()
client.send_ooc("Kicked other instances of client.")
@@ -1072,15 +967,11 @@ def ooc_cmd_chardesc(client, arg):
if arg.isnumeric():
try:
- target = client.server.client_manager.get_targets(
- client, TargetType.ID, int(arg), True
- )[0].char_id
- desc = client.area.area_manager.get_character_data(
- target, "desc", "")
+ target = client.server.client_manager.get_targets(client, TargetType.ID, int(arg), True)[0].char_id
+ desc = client.area.area_manager.get_character_data(target, "desc", "")
target = client.area.area_manager.char_list[target]
client.send_ooc(f"📜{target} Description: {desc}")
- database.log_area("chardesc.request", client,
- client.area, message=target)
+ database.log_area("chardesc.request", client, client.area, message=target)
except Exception:
raise ArgumentError("Target not found.")
else:
@@ -1093,9 +984,7 @@ def ooc_cmd_chardesc(client, arg):
desc = arg[:128]
if len(arg) > len(desc):
desc += f"... Use /chardesc {client.id} to read the rest."
- client.area.broadcast_ooc(
- f"{client.showname} changed their character description to: {desc}."
- )
+ client.area.broadcast_ooc(f"{client.showname} changed their character description to: {desc}.")
client.area.broadcast_player_list()
database.log_area("chardesc.change", client, client.area, message=arg)
@@ -1107,15 +996,11 @@ def ooc_cmd_chardesc_clear(client, arg):
"""
client.area.area_manager.set_character_data(client.char_id, "desc", "")
if not client.hidden and not client.sneaking:
- client.area.broadcast_ooc(
- f"{client.showname} cleared their character description."
- )
+ client.area.broadcast_ooc(f"{client.showname} cleared their character description.")
client.area.broadcast_player_list()
else:
- client.send_ooc(f"You cleared your character description.")
- database.log_area(
- "chardesc.clear", client, client.area
- )
+ client.send_ooc("You cleared your character description.")
+ database.log_area("chardesc.clear", client, client.area)
@mod_only(hub_owners=True)
@@ -1126,13 +1011,10 @@ def ooc_cmd_chardesc_set(client, arg):
"""
args = arg.split(" ")
if len(args) < 1:
- raise ArgumentError(
- "Not enough arguments. Usage: /chardesc_set [desc]")
+ raise ArgumentError("Not enough arguments. Usage: /chardesc_set [desc]")
try:
if args[0].isnumeric():
- target = client.server.client_manager.get_targets(
- client, TargetType.ID, int(args[0]), False
- )
+ target = client.server.client_manager.get_targets(client, TargetType.ID, int(args[0]), False)
if target:
target = target[0].char_id
else:
@@ -1141,7 +1023,7 @@ def ooc_cmd_chardesc_set(client, arg):
else:
try:
target = client.area.area_manager.get_char_id_by_name(arg)
- except (ServerError):
+ except ServerError:
raise
desc = ""
if len(args) > 1:
@@ -1149,9 +1031,7 @@ def ooc_cmd_chardesc_set(client, arg):
client.area.area_manager.set_character_data(target, "desc", desc)
target = client.area.area_manager.char_list[target]
client.send_ooc(f"📜{target} Description: {desc}")
- database.log_area(
- "chardesc.set", client, client.area, message=f"{target}: {desc}"
- )
+ database.log_area("chardesc.set", client, client.area, message=f"{target}: {desc}")
if not client.hidden and not client.sneaking:
client.area.broadcast_player_list()
except Exception:
@@ -1166,9 +1046,7 @@ def ooc_cmd_chardesc_get(client, arg):
"""
try:
if arg.isnumeric():
- target = client.server.client_manager.get_targets(
- client, TargetType.ID, int(arg), False
- )
+ target = client.server.client_manager.get_targets(client, TargetType.ID, int(arg), False)
if target:
target = target[0].char_id
else:
@@ -1177,14 +1055,12 @@ def ooc_cmd_chardesc_get(client, arg):
else:
try:
target = client.area.area_manager.get_char_id_by_name(arg)
- except (ServerError):
+ except ServerError:
raise
desc = client.area.area_manager.get_character_data(target, "desc", "")
target = client.area.area_manager.char_list[target]
client.send_ooc(f"📜{target} Description: {desc}")
- database.log_area(
- "chardesc.get", client, client.area, message=f"{target}: {desc}"
- )
+ database.log_area("chardesc.get", client, client.area, message=f"{target}: {desc}")
except Exception:
raise ArgumentError("Target not found.")
@@ -1197,9 +1073,7 @@ def ooc_cmd_narrate(client, arg):
Usage: /narrate [tog]
"""
if len(arg.split()) > 1:
- raise ArgumentError(
- "This command can only take one argument ('on' or 'off') or no arguments at all!"
- )
+ raise ArgumentError("This command can only take one argument ('on' or 'off') or no arguments at all!")
if arg:
if arg == "on":
client.narrator = True
@@ -1211,9 +1085,7 @@ def ooc_cmd_narrate(client, arg):
client.narrator = not client.narrator
if client.blankpost is True:
client.blankpost = False
- client.send_ooc(
- "You cannot be a narrator and blankposting at the same time. Blankposting disabled!"
- )
+ client.send_ooc("You cannot be a narrator and blankposting at the same time. Blankposting disabled!")
stat = "no longer be narrating"
if client.narrator:
stat = "be narrating now"
@@ -1227,9 +1099,7 @@ def ooc_cmd_blankpost(client, arg):
Usage: /blankpost [tog]
"""
if len(arg.split()) > 1:
- raise ArgumentError(
- "This command can only take one argument ('on' or 'off') or no arguments at all!"
- )
+ raise ArgumentError("This command can only take one argument ('on' or 'off') or no arguments at all!")
if arg:
if arg == "on":
client.blankpost = True
@@ -1241,9 +1111,7 @@ def ooc_cmd_blankpost(client, arg):
client.blankpost = not client.blankpost
if client.narrator is True:
client.narrator = False
- client.send_ooc(
- "You cannot be a narrator and blankposting at the same time. Narrating disabled!"
- )
+ client.send_ooc("You cannot be a narrator and blankposting at the same time. Narrating disabled!")
stat = "no longer be blankposting"
if client.blankpost:
stat = "be blankposting now"
@@ -1258,9 +1126,7 @@ def ooc_cmd_firstperson(client, arg):
Usage: /firstperson [tog]
"""
if len(arg.split()) > 1:
- raise ArgumentError(
- "This command can only take one argument ('on' or 'off') or no arguments at all!"
- )
+ raise ArgumentError("This command can only take one argument ('on' or 'off') or no arguments at all!")
if arg:
if arg == "on":
client.firstperson = True
@@ -1272,9 +1138,7 @@ def ooc_cmd_firstperson(client, arg):
client.firstperson = not client.firstperson
if client.narrator is True:
client.narrator = False
- client.send_ooc(
- "You cannot be a narrator and firstperson at the same time. Narrating disabled!"
- )
+ client.send_ooc("You cannot be a narrator and firstperson at the same time. Narrating disabled!")
stat = "no longer be firstperson"
if client.firstperson:
stat = "be firstperson now"
@@ -1298,8 +1162,7 @@ def ooc_cmd_showname(client, arg):
client.send_ooc("Your IC showname is way too long!")
return
if not client.is_mod and arg.lstrip().lower().startswith("[m"):
- client.send_ooc(
- "Nice try! You may not spoof [M] tag in your showname.")
+ client.send_ooc("Nice try! You may not spoof [M] tag in your showname.")
return
client.used_showname_command = True
client.showname = arg
@@ -1332,21 +1195,17 @@ def ooc_cmd_webfiles(client, arg):
try:
if args[0] == "*":
- targets = [
- c
- for c in client.area.clients
- if c != client and c != client.area.owners
- ]
+ targets = [c for c in client.area.clients if c != client and c != client.area.owners]
else:
- targets = client.server.client_manager.get_targets(
- client, TargetType.ID, int(args[0]), False
- )
+ targets = client.server.client_manager.get_targets(client, TargetType.ID, int(args[0]), False)
except ValueError:
raise ArgumentError("Target ID must be a number or *.")
try:
for c in targets:
- client.send_ooc(f"To download the files, visit https://attorneyonline.github.io/webDownloader/index.html?char={c.iniswap}")
+ client.send_ooc(
+ f"To download the files, visit https://attorneyonline.github.io/webDownloader/index.html?char={c.iniswap}"
+ )
except Exception:
raise ClientError("You must specify a target. Use /webfiles ")
@@ -1384,9 +1243,7 @@ def ooc_cmd_triple_pair(client, arg):
return
if arg.isdigit():
- targets = client.server.client_manager.get_targets(
- client, TargetType.ID, int(arg), True
- )
+ targets = client.server.client_manager.get_targets(client, TargetType.ID, int(arg), True)
if len(targets) > 0:
client.third_charid = targets[0].char_id
else:
@@ -1397,18 +1254,21 @@ def ooc_cmd_triple_pair(client, arg):
char = client.third_charid
if client.third_charid in range(0, len(client.area.area_manager.char_list)):
char = client.area.area_manager.char_list[client.third_charid]
- client.send_ooc(f"Successfully paired with '{char}'! Ask them to pair with you back, and show up on the same /pos for it to work.")
+ client.send_ooc(
+ f"Successfully paired with '{char}'! Ask them to pair with you back, and show up on the same /pos for it to work."
+ )
+
def get_latest_area(client, char_id: int):
char_folder = None
if char_id in range(0, len(client.area.area_manager.char_list)):
char_folder = client.area.area_manager.char_list[char_id]
- if char_folder == None:
- print(char_folder, ' ', char_id)
- client.send_ooc(f"Can't get latest area when spectating!")
+ if char_folder is None:
+ print(char_folder, " ", char_id)
+ client.send_ooc("Can't get latest area when spectating!")
return None
latest_area_id = client.area.area_manager.get_character_data(char_id, "latest_area", None)
- if latest_area_id == None:
+ if latest_area_id is None:
client.send_ooc(f"{char_folder} has no latest occupied area defined!")
return None
target_area = None
@@ -1419,6 +1279,7 @@ def get_latest_area(client, char_id: int):
return None
return target_area
+
@mod_only(hub_owners=True)
def ooc_cmd_get_latest_area(client, arg):
"""
@@ -1430,21 +1291,22 @@ def ooc_cmd_get_latest_area(client, arg):
if len(arg) == 0:
target_charid = client.char_id
elif arg.isdigit():
- targets = client.server.client_manager.get_targets(
- client, TargetType.ID, int(arg), True
- )
+ targets = client.server.client_manager.get_targets(client, TargetType.ID, int(arg), True)
if len(targets) > 0:
target_charid = targets[0].char_id
else:
- arg = arg.replace("\"", "").lower()
+ arg = arg.replace('"', "").lower()
for i in range(0, len(client.area.area_manager.char_list)):
if arg == client.area.area_manager.char_list[i].lower():
target_charid = i
area = get_latest_area(client, target_charid)
if area:
- client.send_ooc(f"{client.area.area_manager.char_list[target_charid]} latest occupied area is [{area.id}] {area.name}.")
- else:
- client.send_ooc(f"Area not found!")
+ client.send_ooc(
+ f"{client.area.area_manager.char_list[target_charid]} latest occupied area is [{area.id}] {area.name}."
+ )
+ else:
+ client.send_ooc("Area not found!")
+
@mod_only(hub_owners=True)
def ooc_cmd_kick_to_latest_area(client, arg):
@@ -1458,13 +1320,11 @@ def ooc_cmd_kick_to_latest_area(client, arg):
target_charid = client.char_id
targets = [client]
elif arg.isdigit():
- targets = client.server.client_manager.get_targets(
- client, TargetType.ID, int(arg), True
- )
+ targets = client.server.client_manager.get_targets(client, TargetType.ID, int(arg), True)
if len(targets) > 0:
target_charid = targets[0].char_id
else:
- arg = arg.replace("\"", "").lower()
+ arg = arg.replace('"', "").lower()
for i in range(0, len(client.area.area_manager.char_list)):
if arg == client.area.area_manager.char_list[i].lower():
target_charid = i
@@ -1477,12 +1337,8 @@ def ooc_cmd_kick_to_latest_area(client, arg):
for target in targets:
old_area = target.area
target.set_area(area)
- target.send_ooc(
- f"You were kicked from [{old_area.id}] {old_area.name} to [{area.id}] {area.name}."
- )
- database.log_area(
- "kick_to_latest_area", client, client.area, target=target, message=area.id
- )
+ target.send_ooc(f"You were kicked from [{old_area.id}] {old_area.name} to [{area.id}] {area.name}.")
+ database.log_area("kick_to_latest_area", client, client.area, target=target, message=area.id)
client.area.invite_list.discard(target.id)
client.send_ooc(
f"Kicked [{target.id}] {target.showname} from [{old_area.id}] {old_area.name} to [{area.id}] {area.name}."
@@ -1492,6 +1348,7 @@ def ooc_cmd_kick_to_latest_area(client, arg):
except ClientError:
raise
+
@mod_only(hub_owners=True)
def ooc_cmd_set_latest_area(client, arg):
"""
@@ -1501,16 +1358,12 @@ def ooc_cmd_set_latest_area(client, arg):
"""
args = shlex.split(arg)
if len(args) == 0:
- raise ArgumentError(
- "Not enough args. Usage: /set_latest_area [area_id]"
- )
+ raise ArgumentError("Not enough args. Usage: /set_latest_area [area_id]")
target_charid = -1
if len(args) == 1:
target_charid = client.char_id
elif args[0].isdigit():
- targets = client.server.client_manager.get_targets(
- client, TargetType.ID, int(args[1]), True
- )
+ targets = client.server.client_manager.get_targets(client, TargetType.ID, int(args[1]), True)
if len(targets) > 0:
target_charid = targets[0].char_id
else:
@@ -1521,7 +1374,7 @@ def ooc_cmd_set_latest_area(client, arg):
if target_charid in range(0, len(client.area.area_manager.char_list)):
char_folder = client.area.area_manager.char_list[target_charid]
if not char_folder:
- client.send_ooc(f"Invalid character id!")
+ client.send_ooc("Invalid character id!")
return None
if len(args) >= 2:
to_area = int(args[1])
@@ -1532,4 +1385,6 @@ def ooc_cmd_set_latest_area(client, arg):
target_area = client.area.area_manager.get_area_by_id(to_area)
client.send_ooc(f"Successfuly set {char_folder} latest occupied area to [{target_area.id}] {target_area.name}.")
except Exception:
- client.send_ooc(f"Warning: setting {char_folder} latest occupied area to an invalid area for current hub. Area ID: [{to_area}].")
\ No newline at end of file
+ client.send_ooc(
+ f"Warning: setting {char_folder} latest occupied area to an invalid area for current hub. Area ID: [{to_area}]."
+ )
diff --git a/server/commands/fun.py b/server/commands/fun.py
index e5ae955c..2aa27ad1 100644
--- a/server/commands/fun.py
+++ b/server/commands/fun.py
@@ -1,6 +1,6 @@
from server import database
from server.constants import TargetType
-from server.exceptions import ClientError, ArgumentError
+from server.exceptions import ArgumentError
from . import mod_only
@@ -22,9 +22,7 @@ def ooc_cmd_disemvowel(client, arg):
if len(arg) == 0:
raise ArgumentError("You must specify a target.")
try:
- targets = client.server.client_manager.get_targets(
- client, TargetType.ID, int(arg), False
- )
+ targets = client.server.client_manager.get_targets(client, TargetType.ID, int(arg), False)
except Exception:
raise ArgumentError("You must specify a target. Use /disemvowel .")
if targets:
@@ -45,12 +43,9 @@ def ooc_cmd_undisemvowel(client, arg):
if len(arg) == 0:
raise ArgumentError("You must specify a target.")
try:
- targets = client.server.client_manager.get_targets(
- client, TargetType.ID, int(arg), False
- )
+ targets = client.server.client_manager.get_targets(client, TargetType.ID, int(arg), False)
except Exception:
- raise ArgumentError(
- "You must specify a target. Use /undisemvowel .")
+ raise ArgumentError("You must specify a target. Use /undisemvowel .")
if targets:
for c in targets:
database.log_area("undisemvowel", client, client.area, target=c)
@@ -69,9 +64,7 @@ def ooc_cmd_shake(client, arg):
if len(arg) == 0:
raise ArgumentError("You must specify a target.")
try:
- targets = client.server.client_manager.get_targets(
- client, TargetType.ID, int(arg), False
- )
+ targets = client.server.client_manager.get_targets(client, TargetType.ID, int(arg), False)
except Exception:
raise ArgumentError("You must specify a target. Use /shake .")
if targets:
@@ -92,9 +85,7 @@ def ooc_cmd_unshake(client, arg):
if len(arg) == 0:
raise ArgumentError("You must specify a target.")
try:
- targets = client.server.client_manager.get_targets(
- client, TargetType.ID, int(arg), False
- )
+ targets = client.server.client_manager.get_targets(client, TargetType.ID, int(arg), False)
except Exception:
raise ArgumentError("You must specify a target. Use /unshake .")
if targets:
@@ -113,6 +104,4 @@ def ooc_cmd_rainbow(client, arg):
"""
client.rainbow = not client.rainbow
toggle = "now" if client.rainbow else "no longer"
- client.send_ooc(
- f"You will {toggle} have rainbowtext."
- )
+ client.send_ooc(f"You will {toggle} have rainbowtext.")
diff --git a/server/commands/hubs.py b/server/commands/hubs.py
index 64b620e2..5a9da146 100644
--- a/server/commands/hubs.py
+++ b/server/commands/hubs.py
@@ -66,12 +66,7 @@ def ooc_cmd_hub(client, arg):
h = arg.split(" ")[0]
hid = h.strip("[]")
if (
- (
- h.startswith("[")
- and h.endswith("]")
- and hid.isdigit()
- and hub.id == int(hid)
- )
+ (h.startswith("[") and h.endswith("]") and hid.isdigit() and hub.id == int(hid))
or hub.name.lower() == arg.lower()
or hub.abbreviation == arg
or (arg.isdigit() and hub.id == int(arg))
@@ -107,8 +102,7 @@ def ooc_cmd_save_hub(client, arg):
args = shlex.split(arg)
if not client.is_mod:
if arg == "":
- raise ArgumentError(
- "You must be authorized to save the default hub!")
+ raise ArgumentError("You must be authorized to save the default hub!")
if len(args[0]) < 3:
raise ArgumentError("Filename must be at least 3 symbols long!")
try:
@@ -118,21 +112,16 @@ def ooc_cmd_save_hub(client, arg):
path = "storage/hubs/read_only"
else:
path = "storage/hubs"
- num_files = len(
- [f for f in os.listdir(path) if os.path.isfile(
- os.path.join(path, f))]
- )
+ num_files = len([f for f in os.listdir(path) if os.path.isfile(os.path.join(path, f))])
if num_files >= 1000: # yikes
- raise AreaError(
- "Server storage full! Please contact the server host to resolve this issue."
- )
+ raise AreaError("Server storage full! Please contact the server host to resolve this issue.")
try:
if os.path.isfile(f"storage/hubs/read_only/{name}.yaml"):
raise ArgumentError(f"Hub {name} already exists and it is read-only!")
if os.path.isfile(f"storage/hubs/{name}.yaml") and len(args) > 2 and args[1].lower() == "read_only":
try:
os.remove(f"storage/hubs/{name}.yaml")
- except:
+ except OSError:
raise AreaError(f"{name} hasn't been removed from write and read folder!")
name = f"{path}/{name}.yaml"
hub = client.area.area_manager.save(ignore=["can_gm", "max_areas"])
@@ -156,9 +145,7 @@ def ooc_cmd_save_hub(client, arg):
client.send_ooc(f"Saving as {name}...")
else:
client.server.hub_manager.save("config/areas_new.yaml")
- client.send_ooc(
- "Saving all Hubs to areas_new.yaml. Contact the server owner to apply the changes."
- )
+ client.send_ooc("Saving all Hubs to areas_new.yaml. Contact the server owner to apply the changes.")
except AreaError:
raise
@@ -187,8 +174,7 @@ def ooc_cmd_load_hub(client, arg):
client.area.area_manager.send_arup_status()
client.area.area_manager.send_arup_cms()
client.area.area_manager.send_arup_lock()
- client.server.client_manager.refresh_music(
- client.area.area_manager.clients)
+ client.server.client_manager.refresh_music(client.area.area_manager.clients)
client.send_ooc("Success, sending ARUP and refreshing music...")
else:
client.server.hub_manager.load(hub_id=client.area.area_manager.id)
@@ -226,8 +212,7 @@ def ooc_cmd_overlay_hub(client, arg):
client.area.area_manager.send_arup_status()
client.area.area_manager.send_arup_cms()
client.area.area_manager.send_arup_lock()
- client.server.client_manager.refresh_music(
- client.area.area_manager.clients)
+ client.server.client_manager.refresh_music(client.area.area_manager.clients)
client.send_ooc("Success, sending ARUP and refreshing music...")
else:
client.server.hub_manager.load()
@@ -253,14 +238,14 @@ def ooc_cmd_list_hubs(client, arg):
try:
if F.lower().endswith(".yaml"):
hubs_read_only.append(F[:-5])
- except:
+ except Exception:
continue
for F in os.listdir("storage/hubs/"):
try:
if F.lower().endswith(".yaml"):
hubs_editable.append(F[:-5])
- except:
+ except Exception:
continue
hubs_read_only.sort()
@@ -288,8 +273,7 @@ def ooc_cmd_clear_hub(client, arg):
try:
client.server.hub_manager.load(hub_id=client.area.area_manager.id)
client.area.area_manager.broadcast_ooc("Hub clearing initiated...")
- client.server.client_manager.refresh_music(
- client.area.area_manager.clients)
+ client.server.client_manager.refresh_music(client.area.area_manager.clients)
client.send_ooc("Success, sending ARUP and refreshing music...")
except AreaError:
raise
@@ -303,12 +287,9 @@ def ooc_cmd_rename_hub(client, arg):
"""
if arg != "":
client.area.area_manager.name = dezalgo(arg)[:64]
- client.send_ooc(
- f"Renamed hub [{client.area.area_manager.id}] to {client.area.area_manager.name}."
- )
+ client.send_ooc(f"Renamed hub [{client.area.area_manager.id}] to {client.area.area_manager.name}.")
else:
- raise ArgumentError(
- "Invalid number of arguments. Use /rename_hub .")
+ raise ArgumentError("Invalid number of arguments. Use /rename_hub .")
@mod_only(hub_owners=True)
@@ -354,8 +335,7 @@ def ooc_cmd_area_remove(client, arg):
except (AreaError, ClientError):
raise
else:
- raise ArgumentError(
- "Invalid number of arguments. Use /area_remove .")
+ raise ArgumentError("Invalid number of arguments. Use /area_remove .")
@mod_only(hub_owners=True)
@@ -380,8 +360,7 @@ def ooc_cmd_area_duplicate(client, arg):
except (AreaError, ClientError):
raise
else:
- raise ArgumentError(
- "Invalid number of arguments. Use /area_duplicate .")
+ raise ArgumentError("Invalid number of arguments. Use /area_duplicate .")
@mod_only(area_owners=True)
@@ -396,17 +375,13 @@ def ooc_cmd_area_rename(client, arg):
args = arg.split(maxsplit=1)
if len(args) <= 0:
- raise ArgumentError(
- "Invalid number of arguments. Use /area_rename [aid] ."
- )
+ raise ArgumentError("Invalid number of arguments. Use /area_rename [aid] .")
# Test if we want to target an area
if args[0].isnumeric():
if len(args) == 1:
# Can't set the area name to just a number only
- raise ArgumentError(
- "Only Area ID was provided with no name. Use /area_rename [aid] ."
- )
+ raise ArgumentError("Only Area ID was provided with no name. Use /area_rename [aid] .")
try:
area = client.area.area_manager.get_area_by_id(int(args[0]))
name = args[1]
@@ -439,8 +414,7 @@ def ooc_cmd_area_swap(client, arg):
area2 = client.area.area_manager.get_area_by_id(int(args[1]))
client.area.area_manager.swap_area(area1, area2, True)
client.area.area_manager.broadcast_area_list()
- client.send_ooc(
- f"Area {area1.name} has been swapped with Area {area2.name}!")
+ client.send_ooc(f"Area {area1.name} has been swapped with Area {area2.name}!")
except ValueError:
raise ArgumentError("Area IDs must be a number.")
except (AreaError, ClientError):
@@ -461,8 +435,7 @@ def ooc_cmd_area_switch(client, arg):
area2 = client.area.area_manager.get_area_by_id(int(args[1]))
client.area.area_manager.swap_area(area1, area2, False)
client.area.area_manager.broadcast_area_list()
- client.send_ooc(
- f"Area {area1.name} has been switched with Area {area2.name}!")
+ client.send_ooc(f"Area {area1.name} has been switched with Area {area2.name}!")
except ValueError:
raise ArgumentError("Area IDs must be a number.")
except (AreaError, ClientError):
@@ -507,29 +480,23 @@ def ooc_cmd_area_pref(client, arg):
msg = "Current preferences:"
for attri in client.area.__dict__.keys():
value = getattr(client.area, attri)
- if not (type(value) is bool):
+ if type(value) is not bool:
continue
- mod = "[gm] " if not (attri in cm_allowed) else ""
+ mod = "[gm] " if attri not in cm_allowed else ""
msg += f"\n* {mod}{attri}={value}"
client.send_ooc(msg)
return
args = arg.split()
if len(args) > 2:
- raise ArgumentError(
- "Usage: /area_pref | /area_pref | /area_pref "
- )
+ raise ArgumentError("Usage: /area_pref | /area_pref | /area_pref ")
try:
cmd = args[0].lower()
attri = getattr(client.area, cmd)
- if not (type(attri) is bool):
+ if type(attri) is not bool:
raise ArgumentError("Preference is not a boolean.")
- if (
- not client.is_mod
- and client not in client.area.area_manager.owners
- and not (cmd in cm_allowed)
- ):
+ if not client.is_mod and client not in client.area.area_manager.owners and cmd not in cm_allowed:
raise ClientError("You need to be a GM to modify this preference.")
tog = not attri
if len(args) > 1:
@@ -563,16 +530,11 @@ def ooc_cmd_area_move_delay(client, arg):
args = arg.split()
try:
if len(args) > 0:
- move_delay = min(
- 1800, max(-1800, int(args[0]))
- ) # Move delay is limited between -1800 and 1800
+ move_delay = min(1800, max(-1800, int(args[0]))) # Move delay is limited between -1800 and 1800
client.area.move_delay = move_delay
- client.send_ooc(
- f"Set {client.area.name} movement delay to {move_delay}.")
+ client.send_ooc(f"Set {client.area.name} movement delay to {move_delay}.")
else:
- client.send_ooc(
- f"Current move delay for {client.area.name} is {client.area.move_delay}."
- )
+ client.send_ooc(f"Current move delay for {client.area.name} is {client.area.move_delay}.")
except ValueError:
raise ArgumentError("Delay must be an integer between -1800 and 1800.")
except (AreaError, ClientError):
@@ -589,13 +551,9 @@ def ooc_cmd_hub_move_delay(client, arg):
args = arg.split()
try:
if len(args) > 0:
- move_delay = min(
- 1800, max(-1800, int(args[0]))
- ) # Move delay is limited between -1800 and 1800
+ move_delay = min(1800, max(-1800, int(args[0]))) # Move delay is limited between -1800 and 1800
client.area.area_manager.move_delay = move_delay
- client.send_ooc(
- f"Set {client.area.area_manager.name} movement delay to {move_delay}."
- )
+ client.send_ooc(f"Set {client.area.area_manager.name} movement delay to {move_delay}.")
else:
client.send_ooc(
f"Current move delay for {client.area.area_manager.name} is {client.area.area_manager.move_delay}."
@@ -617,11 +575,8 @@ def ooc_cmd_toggle_replace_music(client, arg):
boolean = arg in ["true", "on", "1"]
client.area.area_manager.replace_music = boolean
toggle = "now" if client.area.area_manager.replace_music else "no longer"
- client.server.client_manager.refresh_music(
- client.area.area_manager.clients)
- client.area.area_manager.broadcast_ooc(
- f"Hub music list will {toggle} replace server music list."
- )
+ client.server.client_manager.refresh_music(client.area.area_manager.clients)
+ client.area.area_manager.broadcast_ooc(f"Hub music list will {toggle} replace server music list.")
@mod_only(hub_owners=True)
@@ -635,9 +590,7 @@ def ooc_cmd_toggle_passing_ic(client, arg):
boolean = arg in ["true", "on", "1"]
client.area.area_manager.passing_msg = boolean
toggle = "enabled" if client.area.area_manager.passing_msg else "disabled"
- client.area.area_manager.broadcast_ooc(
- f"IC area passing messages are now {toggle} for this hub."
- )
+ client.area.area_manager.broadcast_ooc(f"IC area passing messages are now {toggle} for this hub.")
@mod_only(hub_owners=True)
@@ -648,15 +601,11 @@ def ooc_cmd_arup_enable(client, arg):
Usage: /arup_enable
"""
if client.area.area_manager.arup_enabled:
- raise ClientError(
- "ARUP system is already enabled! Use /arup_disable to disable it."
- )
+ raise ClientError("ARUP system is already enabled! Use /arup_disable to disable it.")
client.area.area_manager.arup_enabled = True
- client.area.area_manager.send_command(
- "FL", client.server.supported_features)
+ client.area.area_manager.send_command("FL", client.server.supported_features)
client.area.area_manager.broadcast_area_list(refresh=True)
- client.area.area_manager.broadcast_ooc(
- "ARUP system has been enabled for this hub.")
+ client.area.area_manager.broadcast_ooc("ARUP system has been enabled for this hub.")
@mod_only(hub_owners=True)
@@ -666,17 +615,13 @@ def ooc_cmd_arup_disable(client, arg):
Usage: /arup_disable
"""
if not client.area.area_manager.arup_enabled:
- raise ClientError(
- "ARUP system is already disabled! Use /arup_enable to enable it."
- )
+ raise ClientError("ARUP system is already disabled! Use /arup_enable to enable it.")
client.area.area_manager.arup_enabled = False
preflist = client.server.supported_features.copy()
preflist.remove("arup")
client.area.area_manager.send_command("FL", *preflist)
client.area.area_manager.broadcast_area_list(refresh=True)
- client.area.area_manager.broadcast_ooc(
- "ARUP system has been disabled for this hub."
- )
+ client.area.area_manager.broadcast_ooc("ARUP system has been disabled for this hub.")
@mod_only(hub_owners=True)
@@ -690,9 +635,7 @@ def ooc_cmd_toggle_getareas(client, arg):
boolean = arg in ["true", "on", "1"]
client.area.area_manager.can_getareas = boolean
toggle = "enabled" if client.area.area_manager.can_getareas else "disabled"
- client.area.area_manager.broadcast_ooc(
- f"Use of /getareas has been {toggle} for this hub."
- )
+ client.area.area_manager.broadcast_ooc(f"Use of /getareas has been {toggle} for this hub.")
@mod_only(hub_owners=True)
@@ -706,9 +649,7 @@ def ooc_cmd_toggle_spectate(client, arg):
boolean = arg in ["true", "on", "1"]
client.area.area_manager.can_spectate = boolean
toggle = "enabled" if client.area.area_manager.can_spectate else "disabled"
- client.area.area_manager.broadcast_ooc(
- f"Spectating has been {toggle} for this hub."
- )
+ client.area.area_manager.broadcast_ooc(f"Spectating has been {toggle} for this hub.")
@mod_only(hub_owners=True)
@@ -718,14 +659,10 @@ def ooc_cmd_hide_clients(client, arg):
Usage: /hide_clients
"""
if client.area.area_manager.hide_clients:
- raise ClientError(
- "Client playercounts already hidden! Use /unhide_clients to unhide."
- )
+ raise ClientError("Client playercounts already hidden! Use /unhide_clients to unhide.")
client.area.area_manager.hide_clients = True
client.area.area_manager.broadcast_area_list()
- client.area.area_manager.broadcast_ooc(
- "Client playercounts are now hidden for this hub."
- )
+ client.area.area_manager.broadcast_ooc("Client playercounts are now hidden for this hub.")
@mod_only(hub_owners=True)
@@ -735,14 +672,10 @@ def ooc_cmd_unhide_clients(client, arg):
Usage: /unhide_clients
"""
if not client.area.area_manager.hide_clients:
- raise ClientError(
- "Client playercounts already revealed! Use /hide_clients to hide."
- )
+ raise ClientError("Client playercounts already revealed! Use /hide_clients to hide.")
client.area.area_manager.hide_clients = False
client.area.area_manager.broadcast_area_list()
- client.area.area_manager.broadcast_ooc(
- "Client playercounts are no longer hidden for this hub."
- )
+ client.area.area_manager.broadcast_ooc("Client playercounts are no longer hidden for this hub.")
@mod_only(hub_owners=True)
@@ -753,37 +686,29 @@ def ooc_cmd_force_follow(client, arg):
"""
arg = arg.split()
if len(arg) == 0:
- raise ArgumentError(
- "You must specify a victim. Usage: /force_follow [target_id]")
+ raise ArgumentError("You must specify a victim. Usage: /force_follow [target_id]")
try:
- victims = client.server.client_manager.get_targets(
- client, TargetType.ID, int(arg[0]), False
- )
+ victims = client.server.client_manager.get_targets(client, TargetType.ID, int(arg[0]), False)
except Exception:
- raise ArgumentError(
- "You must specify a victim. Usage: /force_follow [target_id]")
+ raise ArgumentError("You must specify a victim. Usage: /force_follow [target_id]")
target = client
if len(arg) >= 2:
try:
- target = client.server.client_manager.get_targets(
- client, TargetType.ID, int(arg[1]), False
- )
+ target = client.server.client_manager.get_targets(client, TargetType.ID, int(arg[1]), False)
except Exception:
- raise ArgumentError(
- "Invalid target! Usage: /force_follow [target_id]")
+ raise ArgumentError("Invalid target! Usage: /force_follow [target_id]")
if victims:
for c in victims:
if client == c:
- raise ClientError(
- "You are already forced to follow yourself because you are yourself!"
- )
+ raise ClientError("You are already forced to follow yourself because you are yourself!")
c.following = client
c.forced_to_follow = True
c.send_ooc(f"You've been forced to follow {client.showname}!")
if c.area != client.area:
c.set_area(client.area)
client.send_ooc(
- f"Forced {len(victims)} client(s) to follow [{target.id}] {target.showname}. Use /unfollow {target.id} to free them.")
+ f"Forced {len(victims)} client(s) to follow [{target.id}] {target.showname}. Use /unfollow {target.id} to free them."
+ )
else:
client.send_ooc("No targets found.")
@@ -795,9 +720,7 @@ def ooc_cmd_follow(client, arg):
"""
if len(arg) == 0:
try:
- client.send_ooc(
- f"You are currently following [{client.following.id}] {client.following.showname}."
- )
+ client.send_ooc(f"You are currently following [{client.following.id}] {client.following.showname}.")
except Exception:
raise ArgumentError("Not following anybody. Use /follow .")
return
@@ -807,27 +730,17 @@ def ooc_cmd_follow(client, arg):
and client not in client.area.area_manager.owners
and client.following is not None
):
- raise ClientError(
- "You can't change follow targets while being forced to follow!"
- )
+ raise ClientError("You can't change follow targets while being forced to follow!")
try:
- targets = client.server.client_manager.get_targets(
- client, TargetType.ID, int(arg), False
- )
+ targets = client.server.client_manager.get_targets(client, TargetType.ID, int(arg), False)
except Exception:
raise ArgumentError("You must specify a target. Use /follow .")
if targets:
c = targets[0]
if client == c:
raise ClientError("Can't follow yourself!")
- if (
- c not in client.area.clients
- and not client.is_mod
- and client not in client.area.area_manager.owners
- ):
- raise ClientError(
- "You are not a mod/GM - Target must be present in your area!"
- )
+ if c not in client.area.clients and not client.is_mod and client not in client.area.area_manager.owners:
+ raise ClientError("You are not a mod/GM - Target must be present in your area!")
if client.following and client.following.id == c.id:
ooc_cmd_unfollow(client, "")
return
@@ -849,16 +762,10 @@ def ooc_cmd_unfollow(client, arg):
"""
allowed = client.is_mod or client in client.area.area_manager.owners
if len(arg) == 0:
- if (
- client.forced_to_follow
- and not allowed
- and client.following is not None
- ):
+ if client.forced_to_follow and not allowed and client.following is not None:
raise ClientError("You can't escape being forced to follow!")
try:
- client.send_ooc(
- f"You are no longer following [{client.following.id}] {client.following.showname}."
- )
+ client.send_ooc(f"You are no longer following [{client.following.id}] {client.following.showname}.")
client.following = None
client.forced_to_follow = False
except Exception:
@@ -884,27 +791,21 @@ def ooc_cmd_unfollow(client, arg):
if client.is_mod or client in client.area.area_manager.owners:
try:
- targets = client.server.client_manager.get_targets(
- client, TargetType.ID, int(arg), False
- )
+ targets = client.server.client_manager.get_targets(client, TargetType.ID, int(arg), False)
except Exception:
- raise ArgumentError(
- "You must specify a target. Use /follow_me .")
+ raise ArgumentError("You must specify a target. Use /follow_me .")
if targets:
count = 0
for c in targets:
if c.forced_to_follow:
c.following = None
c.forced_to_follow = False
- c.send_ooc(
- "You've been freed from having to follow someone.")
+ c.send_ooc("You've been freed from having to follow someone.")
count += 1
if count == 0:
client.send_ooc("No valid targets found.")
else:
- client.send_ooc(
- f"Freed {count} existing client(s) from having to follow someone."
- )
+ client.send_ooc(f"Freed {count} existing client(s) from having to follow someone.")
else:
client.send_ooc("No targets found.")
else:
@@ -923,9 +824,7 @@ def ooc_cmd_info(client, arg):
if not client.is_mod and client not in client.area.area_manager.owners:
raise ClientError("You must be a GM of the Hub to do that.")
client.area.area_manager.info = arg
- client.area.area_manager.broadcast_ooc(
- "{} changed the Hub info.".format(client.showname)
- )
+ client.area.area_manager.broadcast_ooc("{} changed the Hub info.".format(client.showname))
database.log_area("info.change", client, client.area, message=arg)
@@ -942,16 +841,13 @@ def ooc_cmd_gm(client, arg):
if arg != "":
# GM all self clients
if arg == "*":
- arg = [c.id for c in client.server.client_manager.get_multiclients(
- client.ipid, client.hdid)]
+ arg = [c.id for c in client.server.client_manager.get_multiclients(client.ipid, client.hdid)]
# GM the targets
else:
arg = arg.split(" ")
# Client is not a mod and not a GM, meaning they're trying to nominate someone without being /gm first
if not client.is_mod and client not in client.area.area_manager.owners:
- raise ArgumentError(
- "You cannot 'nominate' people to be GMs when you are not one."
- )
+ raise ArgumentError("You cannot 'nominate' people to be GMs when you are not one.")
else:
# Self GM
arg = [client.id]
@@ -959,25 +855,15 @@ def ooc_cmd_gm(client, arg):
for id in arg:
try:
id = int(id)
- c = client.server.client_manager.get_targets(
- client, TargetType.ID, id, False
- )[0]
+ c = client.server.client_manager.get_targets(client, TargetType.ID, id, False)[0]
if c not in client.area.area_manager.clients:
- raise ArgumentError(
- "You can only 'nominate' people to be GMs when they are in the hub."
- )
+ raise ArgumentError("You can only 'nominate' people to be GMs when they are in the hub.")
elif c in client.area.area_manager.owners:
- client.send_ooc(
- f"{c.showname} [{c.id}] is already a GM here.")
+ client.send_ooc(f"{c.showname} [{c.id}] is already a GM here.")
else:
for mc in c.server.client_manager.get_multiclients(c.ipid, c.hdid):
- if (
- mc in mc.area.area_manager.owners
- and mc.area.area_manager != c.area.area_manager
- ):
- raise ClientError(
- f"One of {c.showname} [{c.id}]'s clients is already a GM in another hub!"
- )
+ if mc in mc.area.area_manager.owners and mc.area.area_manager != c.area.area_manager:
+ raise ClientError(f"One of {c.showname} [{c.id}]'s clients is already a GM in another hub!")
client.area.area_manager.add_owner(c)
database.log_area("gm.add", client, client.area, target=c)
except (ValueError, IndexError):
@@ -1002,16 +888,12 @@ def ooc_cmd_ungm(client, arg):
for _id in arg:
try:
_id = int(_id)
- c = client.server.client_manager.get_targets(
- client, TargetType.ID, _id, False
- )[0]
+ c = client.server.client_manager.get_targets(client, TargetType.ID, _id, False)[0]
if c in client.area.area_manager.owners:
client.area.area_manager.remove_owner(c)
database.log_area("gm.remove", client, client.area, target=c)
else:
- client.send_ooc(
- "You cannot remove someone from GMing when they aren't a GM."
- )
+ client.send_ooc("You cannot remove someone from GMing when they aren't a GM.")
except (ValueError, IndexError):
client.send_ooc(f"{id} does not look like a valid ID.")
except (ClientError, ArgumentError):
@@ -1064,19 +946,16 @@ def ooc_cmd_hpset(client, arg):
"""
args = shlex.split(arg)
if len(args) == 0:
- raise ArgumentError(
- "You must specify a position and HP. Use /hpset [area]")
+ raise ArgumentError("You must specify a position and HP. Use /hpset [area]")
elif len(args) == 1:
- raise ArgumentError(
- "You must specify HP. Use /hpset [area]")
+ raise ArgumentError("You must specify HP. Use /hpset [area]")
if args[0] == "def":
side = 1
elif args[0] == "pro":
side = 2
else:
- raise ArgumentError(
- "Invalid position. Use \"pro\" or \"def\"")
+ raise ArgumentError('Invalid position. Use "pro" or "def"')
area_list = [client.area]
if len(args > 2):
diff --git a/server/commands/inventory.py b/server/commands/inventory.py
index ccf99b62..b8816645 100644
--- a/server/commands/inventory.py
+++ b/server/commands/inventory.py
@@ -1,11 +1,8 @@
import shlex
-import yaml
-import os
-import re
from server import database
-from server.constants import TargetType, derelative
+from server.constants import TargetType
from server.exceptions import ClientError, ServerError, ArgumentError, AreaError
from . import mod_only
@@ -28,7 +25,7 @@ def get_inventory(evi_list, arg):
# 0 = name
# 1 = desc
# 2 = image
- evi_msg = f"\n💼[{i+1}]: '{evi[0]}'" # (🖼️{evi[2]})
+ evi_msg = f"\n💼[{i + 1}]: '{evi[0]}'" # (🖼️{evi[2]})
if arg == "" or arg.lower() in evi_msg.lower():
msg += evi_msg
msg += "\n\n|| Use /inventory [evi_name/id] to read specific evidence. ||"
@@ -42,10 +39,8 @@ def get_inventory(evi_list, arg):
evidence = evi
break
if evidence is None:
- raise AreaError(
- f"Target evidence not found! (/inventory {arg})"
- )
- msg = f"==💼[{i+1}]: '{evidence[0]}=="
+ raise AreaError(f"Target evidence not found! (/inventory {arg})")
+ msg = f"==💼[{i + 1}]: '{evidence[0]}=="
msg += f"\n🖼️Image: {evidence[2]}"
msg += f"\n📃Desc:\n{evidence[1]}"
msg += f"\n\n|| Use /inventory_drop {i} to drop this into the area ||"
@@ -86,12 +81,8 @@ def ooc_cmd_inventory_drop(client, arg):
evidence = evi
break
if evidence is None:
- raise AreaError(
- f"Target evidence not found! (/inventory_drop {arg})"
- )
- client.area.evi_list.add_evidence(
- client, evidence[0], evidence[1], evidence[2]
- )
+ raise AreaError(f"Target evidence not found! (/inventory_drop {arg})")
+ client.area.evi_list.add_evidence(client, evidence[0], evidence[1], evidence[2])
client.remove_inventory_evidence(i)
client.area.broadcast_evidence_list()
msg = f"You drop '{evidence[0]}' evidence into [{client.id}] {client.area.name}."
@@ -104,9 +95,7 @@ def ooc_cmd_inventory_drop(client, arg):
def get_inventory_target(client, arg):
if arg.isnumeric():
- target = client.server.client_manager.get_targets(
- client, TargetType.ID, int(arg), False
- )
+ target = client.server.client_manager.get_targets(client, TargetType.ID, int(arg), False)
if target:
target = target[0].char_id
else:
@@ -115,7 +104,7 @@ def get_inventory_target(client, arg):
else:
try:
target = client.area.area_manager.get_char_id_by_name(arg)
- except (ServerError):
+ except ServerError:
raise
return target
@@ -129,19 +118,17 @@ def ooc_cmd_inventory_get(client, arg):
try:
# Get the user input
args = shlex.split(arg)
-
+
target = get_inventory_target(client, args.pop(0))
-
+
inventory = client.area.area_manager.get_character_data(target, "inventory", "")
charname = client.area.area_manager.char_list[target]
inventory_list = get_inventory(inventory, " ".join(args))
msg = f"==Evidence in '{charname}' inventory==\n{inventory_list}"
client.send_ooc(msg)
- database.log_area(
- "inventory.get", client, client.area, message=charname
- )
+ database.log_area("inventory.get", client, client.area, message=charname)
except ValueError as ex:
- client.send_ooc(f'{ex} (/inventory_get {arg})')
+ client.send_ooc(f"{ex} (/inventory_get {arg})")
return
@@ -154,13 +141,14 @@ def ooc_cmd_inventory_add(client, arg):
try:
# Get the user input
args = shlex.split(arg)
-
+
target = get_inventory_target(client, args.pop(0))
max_args = 3
if len(args) > max_args:
raise ArgumentError(
- f"Too many arguments! Make sure to surround your args in \"\"'s if there's spaces. (/inventory_add {arg})")
+ f"Too many arguments! Make sure to surround your args in \"\"'s if there's spaces. (/inventory_add {arg})"
+ )
# fill the rest of it with asterisk to fill to max_args
args = args + ([""] * (max_args - len(args)))
if args[0] == "":
@@ -170,7 +158,7 @@ def ooc_cmd_inventory_add(client, arg):
if args[2] == "":
args[2] = "empty.png"
except ValueError as ex:
- client.send_ooc(f'{ex} (/inventory_add {arg})')
+ client.send_ooc(f"{ex} (/inventory_add {arg})")
return
inventory = client.area.area_manager.get_character_data(target, "inventory", list())
@@ -191,10 +179,11 @@ def ooc_cmd_inventory_remove(client, arg):
target = get_inventory_target(client, args.pop(0))
if len(args) > 1:
raise ArgumentError(
- f"Too many arguments! Make sure to surround your args in \"\"'s if there's spaces. (/inventory_remove {arg})")
+ f"Too many arguments! Make sure to surround your args in \"\"'s if there's spaces. (/inventory_remove {arg})"
+ )
inventory = client.area.area_manager.get_character_data(target, "inventory", list())
-
+
arg = " ".join(args)
evidence = None
for i, evi in enumerate(inventory):
@@ -202,13 +191,11 @@ def ooc_cmd_inventory_remove(client, arg):
evidence = evi
break
if evidence is None:
- raise AreaError(
- f"Target evidence not found! (/inventory_remove {arg})"
- )
+ raise AreaError(f"Target evidence not found! (/inventory_remove {arg})")
inventory.pop(i)
client.area.area_manager.set_character_data(target, "inventory", inventory)
except ValueError as ex:
- client.send_ooc(f'{ex} (/inventory_remove {arg})')
+ client.send_ooc(f"{ex} (/inventory_remove {arg})")
return
@@ -234,11 +221,12 @@ def ooc_cmd_inventory_edit(client, arg):
max_args = 3
if len(args) > max_args:
raise ArgumentError(
- f"Too many arguments! Make sure to surround your args in \"\"'s if there's spaces. (/inventory_edit {arg})")
+ f"Too many arguments! Make sure to surround your args in \"\"'s if there's spaces. (/inventory_edit {arg})"
+ )
# fill the rest of it with asterisk to fill to max_args
args = args + (["*"] * (max_args - len(args)))
except ValueError as ex:
- client.send_ooc(f'{ex} (/inventory_edit {arg})')
+ client.send_ooc(f"{ex} (/inventory_edit {arg})")
return
try:
@@ -249,17 +237,14 @@ def ooc_cmd_inventory_edit(client, arg):
evidence = evi
break
if evidence is None:
- raise AreaError(
- f"Target evidence not found! (/inventory_edit {arg})"
- )
+ raise AreaError(f"Target evidence not found! (/inventory_edit {arg})")
evi_name = evidence[0]
inventory[i] = [args[0], args[1], args[2]]
client.area.area_manager.set_character_data(target, "inventory", inventory)
database.log_area("inventory.edit", client, client.area)
charname = client.area.area_manager.char_list[target]
if args[0] != "*" and target_evi != args[0]:
- client.send_ooc(
- f"You have edited evidence '{evi_name}' to '{args[0]}' in {charname}'s inventory.")
+ client.send_ooc(f"You have edited evidence '{evi_name}' to '{args[0]}' in {charname}'s inventory.")
else:
client.send_ooc(f"You have edited evidence '{evi_name}' in {charname}'s inventory.")
except ValueError:
diff --git a/server/commands/messaging.py b/server/commands/messaging.py
index 1990c542..99b8b247 100644
--- a/server/commands/messaging.py
+++ b/server/commands/messaging.py
@@ -1,6 +1,6 @@
from server import database
from server.constants import TargetType
-from server.exceptions import ClientError, ArgumentError, AreaError
+from server.exceptions import ClientError, ArgumentError
from . import mod_only
@@ -155,19 +155,13 @@ def ooc_cmd_pm(client, arg):
raise ArgumentError(
'Not enough arguments. use /pm . Target should be ID, OOC-name or char-name. Use /getarea for getting info like "[ID] char-name".'
)
- targets = client.server.client_manager.get_targets(
- client, TargetType.CHAR_NAME, arg, local=True
- )
+ targets = client.server.client_manager.get_targets(client, TargetType.CHAR_NAME, arg, local=True)
key = TargetType.CHAR_NAME
if len(targets) == 0 and args[0].isdigit():
- targets = client.server.client_manager.get_targets(
- client, TargetType.ID, int(args[0]), all_hub=True
- )
+ targets = client.server.client_manager.get_targets(client, TargetType.ID, int(args[0]), all_hub=True)
key = TargetType.ID
if len(targets) == 0:
- targets = client.server.client_manager.get_targets(
- client, TargetType.OOC_NAME, arg, local=True
- )
+ targets = client.server.client_manager.get_targets(client, TargetType.OOC_NAME, arg, local=True)
key = TargetType.OOC_NAME
if len(targets) == 0:
raise ArgumentError("No targets found.")
@@ -176,12 +170,11 @@ def ooc_cmd_pm(client, arg):
msg = " ".join(args[1:])
else:
if key == TargetType.CHAR_NAME:
- msg = arg[len(targets[0].char_name) + 1:]
+ msg = arg[len(targets[0].char_name) + 1 :]
if key == TargetType.OOC_NAME:
- msg = arg[len(targets[0].name) + 1:]
+ msg = arg[len(targets[0].name) + 1 :]
except Exception:
- raise ArgumentError(
- "Not enough arguments. Use /pm .")
+ raise ArgumentError("Not enough arguments. Use /pm .")
c = targets[0]
if c.pm_mute:
raise ClientError("This user muted all pm conversation")
@@ -214,6 +207,4 @@ def ooc_cmd_mutepm(client, arg):
if len(arg) != 0:
raise ArgumentError("This command doesn't take any arguments")
client.pm_mute = not client.pm_mute
- client.send_ooc(
- "You stopped receiving PMs" if client.pm_mute else "You are now receiving PMs"
- )
+ client.send_ooc("You stopped receiving PMs" if client.pm_mute else "You are now receiving PMs")
diff --git a/server/commands/music.py b/server/commands/music.py
index 546ae92d..b608e38b 100644
--- a/server/commands/music.py
+++ b/server/commands/music.py
@@ -4,8 +4,8 @@
import yaml
from server import database
-from server.constants import TargetType, derelative, contains_URL
-from server.exceptions import ClientError, ServerError, ArgumentError, AreaError
+from server.constants import TargetType, derelative
+from server.exceptions import ClientError, ArgumentError, AreaError
from . import mod_only
@@ -49,9 +49,7 @@ def ooc_cmd_currentmusic(client, arg):
)
else:
client.send_ooc(
- "The current music is '{}' and was played by {}.".format(
- client.area.music, client.area.music_player
- )
+ "The current music is '{}' and was played by {}.".format(client.area.music, client.area.music_player)
)
@@ -88,13 +86,9 @@ def ooc_cmd_jukebox_toggle(client, arg):
client.area.jukebox = not client.area.jukebox
client.area.jukebox_votes = []
client.area.broadcast_ooc(
- "{} [{}] has set the jukebox to {}.".format(
- client.showname, client.id, client.area.jukebox
- )
- )
- database.log_area(
- "jukebox_toggle", client, client.area, message=client.area.jukebox
+ "{} [{}] has set the jukebox to {}.".format(client.showname, client.id, client.area.jukebox)
)
+ database.log_area("jukebox_toggle", client, client.area, message=client.area.jukebox)
@mod_only(area_owners=True)
@@ -108,20 +102,15 @@ def ooc_cmd_jukebox_skip(client, arg):
if not client.area.jukebox:
raise ClientError("This area does not have a jukebox.")
if len(client.area.jukebox_votes) == 0:
- raise ClientError(
- "There is no song playing right now, skipping is pointless.")
+ raise ClientError("There is no song playing right now, skipping is pointless.")
client.area.start_jukebox()
if len(client.area.jukebox_votes) == 1:
client.area.broadcast_ooc(
- "{} [{}] has forced a skip, restarting the only jukebox song.".format(
- client.showname, client.id
- )
+ "{} [{}] has forced a skip, restarting the only jukebox song.".format(client.showname, client.id)
)
else:
client.area.broadcast_ooc(
- "{} [{}] has forced a skip to the next jukebox song.".format(
- client.showname, client.id
- )
+ "{} [{}] has forced a skip to the next jukebox song.".format(client.showname, client.id)
)
database.log_area("jukebox_skip", client, client.area)
@@ -172,8 +161,7 @@ def ooc_cmd_jukebox(client, arg):
if total == 0:
message += "-- CHANCE: 100"
else:
- message += "-- CHANCE: " + \
- str(round(chance[song] / total * 100))
+ message += "-- CHANCE: " + str(round(chance[song] / total * 100))
client.send_ooc(f"The jukebox has the following songs in it:{message}")
@@ -185,8 +173,7 @@ def ooc_cmd_play(client, arg):
"""
if len(arg) == 0:
raise ArgumentError("You must specify a song.")
- client.change_music(arg, client.char_id, "", 2,
- True) # looped change music
+ client.change_music(arg, client.char_id, "", 2, True) # looped change music
def ooc_cmd_play_once(client, arg):
@@ -196,8 +183,7 @@ def ooc_cmd_play_once(client, arg):
"""
if len(arg) == 0:
raise ArgumentError("You must specify a song.")
- client.change_music(arg, client.char_id, "", 2,
- False) # non-looped change music
+ client.change_music(arg, client.char_id, "", 2, False) # non-looped change music
@mod_only()
@@ -209,9 +195,7 @@ def ooc_cmd_blockdj(client, arg):
if len(arg) == 0:
raise ArgumentError("You must specify a target. Use /blockdj .")
try:
- targets = client.server.client_manager.get_targets(
- client, TargetType.ID, int(arg), False
- )
+ targets = client.server.client_manager.get_targets(client, TargetType.ID, int(arg), False)
except Exception:
raise ArgumentError("You must enter a number. Use /blockdj .")
if not targets:
@@ -233,9 +217,7 @@ def ooc_cmd_unblockdj(client, arg):
if len(arg) == 0:
raise ArgumentError("You must specify a target. Use /unblockdj .")
try:
- targets = client.server.client_manager.get_targets(
- client, TargetType.ID, int(arg), False
- )
+ targets = client.server.client_manager.get_targets(client, TargetType.ID, int(arg), False)
except Exception:
raise ArgumentError("You must enter a number. Use /unblockdj .")
if not targets:
@@ -259,14 +241,14 @@ def ooc_cmd_musiclists(client, arg):
try:
if F.lower().endswith(".yaml"):
musiclist_read_only.append(F[:-5])
- except:
+ except Exception:
continue
for F in os.listdir("storage/musiclists/"):
try:
if F.lower().endswith(".yaml"):
musiclist_editable.append(F[:-5])
- except:
+ except Exception:
continue
musiclist_read_only.sort()
@@ -353,8 +335,7 @@ def ooc_cmd_hub_musiclist(client, arg):
client.area.area_manager.load_music(f"storage/musiclists/{arg}.yaml")
client.area.area_manager.music_ref = arg
client.send_ooc(f"Loading hub musiclist {arg}...")
- client.server.client_manager.refresh_music(
- client.area.area_manager.clients)
+ client.server.client_manager.refresh_music(client.area.area_manager.clients)
except AreaError:
raise
except Exception:
@@ -368,14 +349,11 @@ def ooc_cmd_random_music(client, arg):
"""
songs = []
for c in client.local_music_list:
- if "category" in c and (
- arg == "" or c["category"].strip("==").lower() == arg.lower()
- ):
+ if "category" in c and (arg == "" or c["category"].strip("==").lower() == arg.lower()):
if "songs" in c:
songs = songs + c["songs"]
if len(songs) <= 0:
- raise ArgumentError(
- "Could not find a single song that fit the criteria!")
+ raise ArgumentError("Could not find a single song that fit the criteria!")
song_name = songs[random.randint(0, len(songs) - 1)]["name"]
client.change_music(song_name, client.char_id, "", 2)
@@ -383,19 +361,15 @@ def ooc_cmd_random_music(client, arg):
def musiclist_rebuild(musiclist, path):
prepath = ""
for item in musiclist:
- if (
- "use_unique_folder" in item
- and item["use_unique_folder"] is True
- ):
- prepath = os.path.splitext(
- os.path.basename(f"storage/musiclists/{path}"))[0] + "/"
+ if "use_unique_folder" in item and item["use_unique_folder"] is True:
+ prepath = os.path.splitext(os.path.basename(f"storage/musiclists/{path}"))[0] + "/"
if "category" not in item:
continue
for song in item["songs"]:
song["name"] = prepath + song["name"]
-
+
return musiclist
@@ -443,9 +417,9 @@ def ooc_cmd_musiclist_save(client, arg):
if os.path.isfile(f"storage/musiclists/{name}.yaml") and len(args) > 2 and args[1].lower() == "read_only":
try:
os.remove(f"storage/musiclists/{name}.yaml")
- except:
+ except OSError:
raise AreaError(f"{args[0]} hasn't been removed from write and read folder!")
-
+
with open(filepath, "w", encoding="utf-8") as yaml_save:
yaml.dump(musiclist, yaml_save)
client.send_ooc(f"Musiclist '{name}' saved on server list!")
@@ -458,22 +432,20 @@ def ooc_cmd_musiclist_remove(client, arg):
Usage: /musiclist_remove
"""
if arg == "":
- client.send_ooc(
- "Usage: /musiclist_remove "
- )
+ client.send_ooc("Usage: /musiclist_remove ")
return
args = shlex.split(arg)
if len(args) != 3:
- client.send_ooc(
- "Usage: /musiclist_remove "
- )
+ client.send_ooc("Usage: /musiclist_remove ")
return
if args[0] not in ["local", "area", "hub"]:
- client.send_ooc("You can add a song if musiclist is loaded in local or in area or in hub.\nUsage: /musiclist_add ")
+ client.send_ooc(
+ "You can add a song if musiclist is loaded in local or in area or in hub.\nUsage: /musiclist_add "
+ )
return
-
+
if args[0] == "local":
targets = [client]
musiclist = client.music_list
@@ -489,7 +461,7 @@ def ooc_cmd_musiclist_remove(client, arg):
return
targets = client.area.area_manager.clients
musiclist = client.area.area_manager.music_list
-
+
if musiclist == []:
client.send_ooc("You cannot remove a song, if there aren't songs in the musiclist.")
return
@@ -507,10 +479,7 @@ def ooc_cmd_musiclist_remove(client, arg):
category_id = categories.index(args[1])
- songs = [
- musiclist[category_id]["songs"][i]["name"]
- for i in range(0, len(musiclist[category_id]["songs"]))
- ]
+ songs = [musiclist[category_id]["songs"][i]["name"] for i in range(0, len(musiclist[category_id]["songs"]))]
if args[2] not in songs:
client.send_ooc("Song has not been found!")
@@ -530,7 +499,7 @@ def ooc_cmd_musiclist_remove(client, arg):
else:
path = client.area.area_manager.music_ref
client.area.area_manager.music_list = musiclist_rebuild(musiclist, path)
-
+
client.server.client_manager.refresh_music(targets, True)
client.send_ooc(f"'{args[2]}' song has been removed to '{path}' musiclist.")
@@ -543,24 +512,20 @@ def ooc_cmd_musiclist_add(client, arg):
Usage: /musiclist_add [Length] [Path]
"""
if arg == "":
- client.send_ooc(
- "Usage: /musiclist_add [Length] [Path]"
- )
+ client.send_ooc("Usage: /musiclist_add [Length] [Path]")
return
args = shlex.split(arg)
if len(args) < 3:
- client.send_ooc(
- "Usage: /musiclist_add [Length] [Path]"
- )
+ client.send_ooc("Usage: /musiclist_add [Length] [Path]")
return
-
+
if args[0] not in ["local", "area", "hub"]:
client.send_ooc(
"You can add a song if musiclist is loaded in local or in area or in hub.\nUsage: /musiclist_add [Length] [Path]"
)
return
-
+
if args[0] == "local":
targets = [client]
musiclist = client.music_list
@@ -576,7 +541,7 @@ def ooc_cmd_musiclist_add(client, arg):
return
targets = client.area.area_manager.clients
musiclist = client.area.area_manager.music_list
-
+
if musiclist == []:
musiclist.append({})
musiclist[0]["use_unique_folder"] = False
@@ -586,7 +551,7 @@ def ooc_cmd_musiclist_add(client, arg):
client.area.music_ref = "unsaved"
else:
client.area.area_manager.music_ref = "unsaved"
-
+
categories = []
for i in range(0, len(musiclist)):
if "category" in musiclist[i]:
@@ -606,8 +571,8 @@ def ooc_cmd_musiclist_add(client, arg):
song_id = len(musiclist[category_id]["songs"]) - 1
name = args[2]
- if not name.endswith(('.mp3', '.ogg', '.opus', '.wav', '.m4a')):
- name += '.music'
+ if not name.endswith((".mp3", ".ogg", ".opus", ".wav", ".m4a")):
+ name += ".music"
musiclist[category_id]["songs"][song_id]["name"] = name
length = -1
@@ -631,6 +596,6 @@ def ooc_cmd_musiclist_add(client, arg):
else:
path = client.area.area_manager.music_ref
client.area.area_manager.music_list = musiclist_rebuild(musiclist, path)
-
+
client.server.client_manager.refresh_music(targets, True)
client.send_ooc(f"'{args[2]}' song has been added to '{path}' musiclist.")
diff --git a/server/commands/roleplay.py b/server/commands/roleplay.py
index 84cff861..0dfe5c00 100644
--- a/server/commands/roleplay.py
+++ b/server/commands/roleplay.py
@@ -57,9 +57,7 @@ def rtd(arg):
if arg_length == 2:
dice_type, modifiers = args
if len(modifiers) > MODIFIER_LENGTH_MAX:
- raise ArgumentError(
- "The given modifier is too long to compute. Please try a shorter one"
- )
+ raise ArgumentError("The given modifier is too long to compute. Please try a shorter one")
elif arg_length == 1:
dice_type, modifiers = arg, ""
else:
@@ -76,31 +74,20 @@ def rtd(arg):
try:
num_dice, chosen_max = int(dice_type[0]), int(dice_type[1])
except ValueError:
- raise ArgumentError(
- "Expected integer value for number of rolls and max value of dice"
- )
+ raise ArgumentError("Expected integer value for number of rolls and max value of dice")
if not 1 <= num_dice <= NUMDICE_MAX:
- raise ArgumentError(
- "Number of rolls must be between 1 and {}".format(NUMDICE_MAX)
- )
+ raise ArgumentError("Number of rolls must be between 1 and {}".format(NUMDICE_MAX))
if not 1 <= chosen_max <= DICE_MAX:
- raise ArgumentError(
- "Dice value must be between 1 and {}".format(DICE_MAX))
+ raise ArgumentError("Dice value must be between 1 and {}".format(DICE_MAX))
for char in modifiers:
if char not in ACCEPTABLE_IN_MODIFIER:
- raise ArgumentError(
- "Expected numbers and standard mathematical operations in modifier"
- )
+ raise ArgumentError("Expected numbers and standard mathematical operations in modifier")
if char == "r":
special_calculation = True
- if (
- "**" in modifiers
- ): # Exponentiation manually disabled, it can be pretty dangerous
- raise ArgumentError(
- "Expected numbers and standard mathematical operations in modifier"
- )
+ if "**" in modifiers: # Exponentiation manually disabled, it can be pretty dangerous
+ raise ArgumentError("Expected numbers and standard mathematical operations in modifier")
else:
num_dice, chosen_max, modifiers = 1, 6, "" # Default
@@ -134,22 +121,14 @@ def rtd(arg):
"Given mathematical formula takes numbers past the server's computation limit"
)
except ValueError:
- raise ArgumentError(
- "Given mathematical formula has a syntax error and cannot be computed"
- )
+ raise ArgumentError("Given mathematical formula has a syntax error and cannot be computed")
try:
- mid_roll = round(
- eval(aux_modifier[:-1])
- ) # By this point it should be 'safe' to run eval
+ mid_roll = round(eval(aux_modifier[:-1])) # By this point it should be 'safe' to run eval
except SyntaxError:
- raise ArgumentError(
- "Given mathematical formula has a syntax error and cannot be computed"
- )
+ raise ArgumentError("Given mathematical formula has a syntax error and cannot be computed")
except TypeError: # Deals with inputs like 3(r-1)
- raise ArgumentError(
- "Given mathematical formula has a syntax error and cannot be computed"
- )
+ raise ArgumentError("Given mathematical formula has a syntax error and cannot be computed")
except ZeroDivisionError:
divzero_attempts += 1
if divzero_attempts == MAXDIVZERO_ATTEMPTS:
@@ -191,9 +170,7 @@ def ooc_cmd_roll(client, arg):
f"[👉🎲] [{client.id}] {client.showname} rolled:\n {roll} out of {chosen_max}."
+ (f"\nThe total sum is {Sum}." if num_dice > 1 else "")
)
- database.log_area(
- "roll", client, client.area, message=f"{roll} out of {chosen_max}"
- )
+ database.log_area("roll", client, client.area, message=f"{roll} out of {chosen_max}")
def ooc_cmd_rollp(client, arg):
@@ -207,20 +184,15 @@ def ooc_cmd_rollp(client, arg):
roll, num_dice, chosen_max, _modifiers, Sum = rtd(arg)
client.send_ooc(
- f"[Hidden] You rolled {roll} out of {chosen_max}."
- + (f"\nThe total sum is {Sum}." if num_dice > 1 else "")
+ f"[Hidden] You rolled {roll} out of {chosen_max}." + (f"\nThe total sum is {Sum}." if num_dice > 1 else "")
)
for c in client.area.owners:
- c.send_ooc(
- f"[{client.area.id}]{client.showname} secretly rolled {roll} out of {chosen_max}."
- )
+ c.send_ooc(f"[{client.area.id}]{client.showname} secretly rolled {roll} out of {chosen_max}.")
client.area.send_owner_command(
f"[👉🎲] [{client.id}] {client.showname} secretly rolled:\n {roll} out of {chosen_max}."
+ (f"\nThe total sum is {Sum}." if num_dice > 1 else "")
)
- database.log_area(
- "rollp", client, client.area, message=f"{roll} out of {chosen_max}"
- )
+ database.log_area("rollp", client, client.area, message=f"{roll} out of {chosen_max}")
def ooc_cmd_notecard(client, arg):
@@ -248,9 +220,7 @@ def ooc_cmd_notecard_clear(client, arg):
Usage: /notecard_clear
"""
client.area.cards.clear()
- client.area.broadcast_ooc(
- f"[{client.id}] {client.showname} has cleared all the note cards in this area."
- )
+ client.area.broadcast_ooc(f"[{client.id}] {client.showname} has cleared all the note cards in this area.")
database.log_area("notecard_clear", client, client.area)
@@ -268,14 +238,12 @@ def ooc_cmd_notecard_reveal(client, arg):
card_showname = card_data[0]
card_msg = card_data[1]
card_owner_display = f"[DC] {card_showname}"
- card_owner = client.server.client_manager.get_targets(
- client, TargetType.CHAR_NAME, card_charname, False
- )
+ card_owner = client.server.client_manager.get_targets(client, TargetType.CHAR_NAME, card_charname, False)
if len(card_owner) > 0:
card_owner = card_owner[0]
card_owner_display = f"[{card_owner.id}] {card_owner.showname}"
msg += f"\n{card_owner_display}: {card_msg}"
-
+
# Reveal the notecards in OOC!
client.area.broadcast_ooc(msg)
@@ -284,9 +252,7 @@ def ooc_cmd_notecard_reveal(client, arg):
client.send_ooc("Use /notecard_clear for clearing.")
else:
client.area.cards.clear()
- client.area.broadcast_ooc(
- f"Notecards have been cleared."
- )
+ client.area.broadcast_ooc("Notecards have been cleared.")
database.log_area("notecard_reveal", client, client.area)
@@ -299,26 +265,20 @@ def ooc_cmd_notecard_check(client, arg):
"""
if len(client.area.cards) == 0:
raise ClientError("There are no notecards to check in this area.")
- client.area.broadcast_ooc(
- f"[{client.id}] {client.showname} has checked the notecards in this area."
- )
+ client.area.broadcast_ooc(f"[{client.id}] {client.showname} has checked the notecards in this area.")
msg = "Notecards in this area:"
for card_charname, card_data in client.area.cards.items():
card_showname = card_data[0]
card_msg = card_data[1]
card_owner_display = f"[DC] {card_showname}"
- card_owner = client.server.client_manager.get_targets(
- client, TargetType.CHAR_NAME, card_charname, False
- )
+ card_owner = client.server.client_manager.get_targets(client, TargetType.CHAR_NAME, card_charname, False)
if len(card_owner) > 0:
card_owner = card_owner[0]
card_owner_display = f"[{card_owner.id}] {card_owner.showname}"
msg += f"\n{card_owner_display}: {card_msg}"
client.send_ooc(msg)
- client.send_ooc(
- "Use /notecard_clear for clearing, or /notecard_reveal to reveal the results publicly."
- )
+ client.send_ooc("Use /notecard_clear for clearing, or /notecard_reveal to reveal the results publicly.")
database.log_area("notecard_check", client, client.area)
@@ -331,12 +291,8 @@ def ooc_cmd_vote(client, arg):
if len(args) == 0:
raise ArgumentError("Please provide a client ID. Usage: /vote .")
if client.char_name in [y for x in client.area.votes.values() for y in x]:
- raise ArgumentError(
- "You already cast your vote! Wait on the CM to /vote_clear."
- )
- target = client.server.client_manager.get_targets(
- client, TargetType.ID, int(args[0]), False
- )[0]
+ raise ArgumentError("You already cast your vote! Wait on the CM to /vote_clear.")
+ target = client.server.client_manager.get_targets(client, TargetType.ID, int(args[0]), False)[0]
client.area.votes.setdefault(target.char_name, []).append(client.char_name)
client.area.broadcast_ooc(f"[{client.id}] {client.showname} cast a vote.")
database.log_area("vote", client, client.area)
@@ -353,26 +309,20 @@ def ooc_cmd_vote_clear(client, arg):
for value in client.area.votes.values():
if arg in value:
value.remove(arg)
- client.area.broadcast_ooc(
- f"[{client.id}] {client.showname} has cleared {arg}'s vote."
- )
+ client.area.broadcast_ooc(f"[{client.id}] {client.showname} has cleared {arg}'s vote.")
return
raise ClientError(
f"No vote was cast by {arg}! (This is case-sensitive - are you sure you spelled the voter character folder right?)"
)
client.area.votes.clear()
- client.area.broadcast_ooc(
- f"[{client.id}] {client.showname} has cleared all the votes in this area."
- )
+ client.area.broadcast_ooc(f"[{client.id}] {client.showname} has cleared all the votes in this area.")
database.log_area("vote_clear", client, client.area)
def get_vote_results(client, votes):
def get_showname(target_name):
"""Helper function to convert a charname to showname format."""
- owners = client.server.client_manager.get_targets(
- client, TargetType.CHAR_NAME, target_name, False
- )
+ owners = client.server.client_manager.get_targets(client, TargetType.CHAR_NAME, target_name, False)
if owners:
owner = owners[0]
return f"[{owner.id}] {owner.showname}"
@@ -380,38 +330,36 @@ def get_showname(target_name):
# Sort votes by count (ascending)
sorted_votes = sorted(votes.items(), key=lambda x: len(x[1]))
-
+
msg_lines = []
max_votes = 0
-
+
for candidate, voters in sorted_votes:
# Process voters
voter_names = [get_showname(voter) for voter in voters]
voters_str = ", ".join(voter_names)
-
+
# Process candidate
candidate_name = get_showname(candidate)
-
+
# Build vote line
vote_count = len(voters)
plural = "s" if vote_count > 1 else ""
- msg_lines.append(
- f"🗳️{vote_count} vote{plural} for {candidate_name}\n ◽ Voted by {voters_str}."
- )
-
+ msg_lines.append(f"🗳️{vote_count} vote{plural} for {candidate_name}\n ◽ Voted by {voters_str}.")
+
# Track max votes
if vote_count > max_votes:
max_votes = vote_count
-
+
# Find winners
winners = [get_showname(k) for k, v in sorted_votes if len(v) == max_votes]
-
+
# Add winner/tie message
if len(winners) > 1:
msg_lines.append(f"{', '.join(winners)} have tied for most votes.")
else:
msg_lines.append(f"{winners[0]} has most votes.")
-
+
return "\n".join(msg_lines)
@@ -432,9 +380,7 @@ def ooc_cmd_vote_reveal(client, arg):
client.send_ooc("Use /vote_clear for clearing.")
else:
client.area.votes.clear()
- client.area.broadcast_ooc(
- f"Votes have been cleared."
- )
+ client.area.broadcast_ooc("Votes have been cleared.")
database.log_area("vote_reveal", client, client.area)
@@ -447,15 +393,11 @@ def ooc_cmd_vote_check(client, arg):
"""
if len(client.area.votes) == 0:
raise ClientError("There are no votes to check in this area.")
- client.area.broadcast_ooc(
- f"[{client.id}] {client.showname} has checked the votes in this area."
- )
+ client.area.broadcast_ooc(f"[{client.id}] {client.showname} has checked the votes in this area.")
msg = "Votes in this area:\n"
msg += get_vote_results(client, client.area.votes)
client.send_ooc(msg)
- client.send_ooc(
- "Use /vote_clear for clearing, or /vote_reveal to reveal the results publicly."
- )
+ client.send_ooc("Use /vote_clear for clearing, or /vote_reveal to reveal the results publicly.")
database.log_area("vote_check", client, client.area)
@@ -477,9 +419,7 @@ def rolla_reload(area):
with open("config/dice.yaml", "r") as dice:
area.ability_dice = yaml.safe_load(dice)
except Exception:
- raise ServerError(
- "There was an error parsing the ability dice configuration. Check your syntax."
- )
+ raise ServerError("There was an error parsing the ability dice configuration. Check your syntax.")
def ooc_cmd_rolla_set(client, arg):
@@ -491,13 +431,9 @@ def ooc_cmd_rolla_set(client, arg):
rolla_reload(client.area)
available_sets = ", ".join(client.area.ability_dice.keys())
if len(arg) == 0:
- raise ArgumentError(
- f"You must specify the ability set name.\nAvailable sets: {available_sets}"
- )
+ raise ArgumentError(f"You must specify the ability set name.\nAvailable sets: {available_sets}")
elif arg not in client.area.ability_dice:
- raise ArgumentError(
- f"Invalid ability set '{arg}'.\nAvailable sets: {available_sets}"
- )
+ raise ArgumentError(f"Invalid ability set '{arg}'.\nAvailable sets: {available_sets}")
client.ability_dice_set = arg
client.send_ooc(f"Set ability set to {arg}.")
@@ -517,16 +453,11 @@ def ooc_cmd_rolla(client, arg):
if not hasattr(client.area, "ability_dice"):
rolla_reload(client.area)
if not hasattr(client, "ability_dice_set"):
- raise ClientError(
- "You must set your ability set using /rolla_set .")
+ raise ClientError("You must set your ability set using /rolla_set .")
ability_dice = client.area.ability_dice[client.ability_dice_set]
roll, max_roll, ability = rolla(ability_dice)
- client.area.broadcast_ooc(
- f"[{client.id}] {client.showname} rolled a {roll} (out of {max_roll}): {ability}."
- )
- database.log_area(
- "rolla", client, client.area, message=f"{roll} out of {max_roll}: {ability}"
- )
+ client.area.broadcast_ooc(f"[{client.id}] {client.showname} rolled a {roll} (out of {max_roll}): {ability}.")
+ database.log_area("rolla", client, client.area, message=f"{roll} out of {max_roll}: {ability}")
def ooc_cmd_coinflip(client, arg):
@@ -538,9 +469,7 @@ def ooc_cmd_coinflip(client, arg):
raise ArgumentError("This command has no arguments.")
coin = ["heads", "tails"]
flip = random.choice(coin)
- client.area.broadcast_ooc(
- f"[{client.id}] {client.showname} flipped a coin and got {flip}."
- )
+ client.area.broadcast_ooc(f"[{client.id}] {client.showname} flipped a coin and got {flip}.")
database.log_area("coinflip", client, client.area, message=flip)
@@ -576,27 +505,29 @@ def ooc_cmd_rps(client, arg):
rps_rules = client.area.area_manager.rps_rules
- # Strip the input of blank spaces on edges
+ # Strip the input of blank spaces on edges
arg = arg.strip()
-
+
# If doing /rps by itself, simply tell the user the rules.
if not arg:
msg = "RPS rules:"
for i, rule in enumerate(rps_rules):
- msg += f"\n {i+1}) "
+ msg += f"\n {i + 1}) "
choice = rule[0]
msg += choice
if len(choice) > 1:
- losers = ', '.join(rule[1:])
+ losers = ", ".join(rule[1:])
msg += f" beats {losers}"
client.send_ooc(msg)
return
if arg.lower() in ["clear", "cancel"]:
if client.rps_choice:
- client.area.broadcast_ooc(f'[{client.id}] {client.showname} no longer wants to play 🎲Rock Paper Scissors🎲... 🙁')
+ client.area.broadcast_ooc(
+ f"[{client.id}] {client.showname} no longer wants to play 🎲Rock Paper Scissors🎲... 🙁"
+ )
client.rps_choice = ""
- client.send_ooc('You cleared your choice.')
+ client.send_ooc("You cleared your choice.")
return
# List of our available choices
@@ -614,16 +545,16 @@ def ooc_cmd_rps(client, arg):
# Fuzzy match, queue up our pick but look if we can get something better
if arg.lower() in choice:
picked = choice
-
+
if picked not in choices:
raise ArgumentError(f"Invalid choice! Available choices are: {', '.join(choices)}")
-
+
# If we already have made a rps choice before, simply silently swap our choice.
if client.rps_choice:
client.rps_choice = picked
- client.send_ooc(f'Swapped your choice to {client.rps_choice}!')
+ client.send_ooc(f"Swapped your choice to {client.rps_choice}!")
return
-
+
# Set our Rock Paper Scissors choice
client.rps_choice = picked
@@ -639,16 +570,16 @@ def ooc_cmd_rps(client, arg):
# Look for our opponent if none is present
if not target:
- msg = f'[{client.id}] {client.showname} wants to play 🎲Rock Paper Scissors🎲!\n❕ Do /rps [choice] to challenge them! ❕'
+ msg = f"[{client.id}] {client.showname} wants to play 🎲Rock Paper Scissors🎲!\n❕ Do /rps [choice] to challenge them! ❕"
client.area.broadcast_ooc(msg)
- client.send_ooc(f'You picked {client.rps_choice}!')
+ client.send_ooc(f"You picked {client.rps_choice}!")
return
# Start constructing our output message
- msg = '🎲Rock Paper Scissors🎲'
- msg += f'\n ◽ [{target.id}] {target.showname} picks {target.rps_choice}!'
- msg += f'\n ◽ [{client.id}] {client.showname} picks {client.rps_choice}!'
-
+ msg = "🎲Rock Paper Scissors🎲"
+ msg += f"\n ◽ [{target.id}] {target.showname} picks {target.rps_choice}!"
+ msg += f"\n ◽ [{client.id}] {client.showname} picks {client.rps_choice}!"
+
# Calculate our winner
a = target.rps_choice.lower()
b = client.rps_choice.lower()
@@ -670,7 +601,7 @@ def ooc_cmd_rps(client, arg):
if winner:
msg += f"\n 🏆[{winner.id}] {winner.showname} WINS!!!🏆"
else:
- msg += f"\n 👔It's a tie!👔"
+ msg += "\n 👔It's a tie!👔"
# Announce the message!
client.area.broadcast_ooc(msg)
@@ -689,16 +620,16 @@ def ooc_cmd_rps_rules(client, arg):
/rps_rules [index] - delete a rule at index
/rps_rules - wipe all current rules
"""
- #client.area.area_manager.rps_rules
+ # client.area.area_manager.rps_rules
- # Strip the input of blank spaces on edges
+ # Strip the input of blank spaces on edges
arg = arg.strip()
-
+
# If doing /rps_rules by itself, simply tell the user the rules.
if not arg:
ooc_cmd_rps(client, "")
return
-
+
try:
args = arg.split(maxsplit=1)
action = args[0]
@@ -714,24 +645,18 @@ def ooc_cmd_rps_rules(client, arg):
client.area.area_manager.rps_rules.append(newrule)
client.send_ooc(f"Added a new rule: {rule}")
elif action.lower() in ["del", "remove", "-"]:
- index = int(param)-1
+ index = int(param) - 1
if index < 0 or index >= len(client.area.area_manager.rps_rules):
- raise ArgumentError(
- "Invalid index!"
- )
+ raise ArgumentError("Invalid index!")
client.send_ooc(f"Deleted a rule: {client.area.area_manager.rps_rules[index]}")
client.area.area_manager.rps_rules.pop(index)
elif action.lower() in ["clear", "clean", "reset", "wipe"]:
client.send_ooc("Deleted all rules.")
client.area.area_manager.rps_rules.clear()
else:
- raise ArgumentError(
- "Invalid action!"
- )
+ raise ArgumentError("Invalid action!")
except ValueError:
- raise ArgumentError(
- "Invalid parameter!"
- )
+ raise ArgumentError("Invalid parameter!")
def ooc_cmd_timer(client, arg):
@@ -765,9 +690,9 @@ def ooc_cmd_timer(client, arg):
for timer_id, timer in enumerate(client.area.timers):
if timer.set:
if timer.started:
- msg += f"\nTimer {timer_id+1} is at {timer.target - arrow.get()}"
+ msg += f"\nTimer {timer_id + 1} is at {timer.target - arrow.get()}"
else:
- msg += f"\nTimer {timer_id+1} is at {timer.static}"
+ msg += f"\nTimer {timer_id + 1} is at {timer.static}"
client.send_ooc(msg)
return
# TI packet specification:
@@ -788,24 +713,17 @@ def ooc_cmd_timer(client, arg):
if len(args) < 2:
if timer.set:
if timer.started:
- client.send_ooc(
- f"Timer {timer_id} is at {timer.target - arrow.get()}")
+ client.send_ooc(f"Timer {timer_id} is at {timer.target - arrow.get()}")
else:
client.send_ooc(f"Timer {timer_id} is at {timer.static}")
else:
client.send_ooc(f"Timer {timer_id} is unset.")
return
- if not (client in client.area.owners) and not client.is_mod:
- raise ArgumentError(
- "Only CMs or GMs can modify timers. Usage: /timer ")
- if (
- timer_id == 0
- and not (client in client.area.area_manager.owners)
- and not client.is_mod
- ):
- raise ArgumentError(
- "Only GMs can set hub-wide timer ID 0. Usage: /timer ")
+ if client not in client.area.owners and not client.is_mod:
+ raise ArgumentError("Only CMs or GMs can modify timers. Usage: /timer ")
+ if timer_id == 0 and client not in client.area.area_manager.owners and not client.is_mod:
+ raise ArgumentError("Only GMs can set hub-wide timer ID 0. Usage: /timer ")
command_arg = args[1]
@@ -869,15 +787,11 @@ def ooc_cmd_timer(client, arg):
cmd = full.split(" ")[0]
called_function = f"ooc_cmd_{cmd}"
- if len(client.server.command_aliases) > 0 and not hasattr(
- commands, called_function
- ):
+ if len(client.server.command_aliases) > 0 and not hasattr(commands, called_function):
if cmd in client.server.command_aliases:
called_function = f"ooc_cmd_{client.server.command_aliases[cmd]}"
if not hasattr(commands, called_function):
- client.send_ooc(
- f"[Timer {timer_id}] Invalid command: {cmd}. Use /help to find up-to-date commands."
- )
+ client.send_ooc(f"[Timer {timer_id}] Invalid command: {cmd}. Use /help to find up-to-date commands.")
return
timer.commands.append(full)
client.send_ooc(f"Adding command to Timer {timer_id}: /{full}")
@@ -885,7 +799,7 @@ def ooc_cmd_timer(client, arg):
# Send static time if applicable
if timer.set:
- s = int(not timer.started)
+ int(not timer.started)
static_time = int(timer.static.total_seconds()) * 1000
if timer_id == 0:
client.area.area_manager.send_timer_set_time(timer_id, static_time, timer.started)
@@ -934,12 +848,7 @@ def ooc_cmd_demo(client, arg):
client.last_demo_call = time.time() * 1000
client.area.demo.clear()
- desc = (
- evidence.desc.replace("", "#")
- .replace("", "&")
- .replace("", "%")
- .replace("", "$")
- )
+ desc = evidence.desc.replace("", "#").replace("", "&").replace("", "%").replace("", "$")
packets = desc.split("%")
for packet in packets:
p_args = packet.split("#")
@@ -952,8 +861,7 @@ def ooc_cmd_demo(client, arg):
client.area.demo += [p_args]
for c in client.area.clients:
if c in client.area.owners:
- c.send_ooc(
- f"Starting demo playback using evidence '{evidence.name}'...")
+ c.send_ooc(f"Starting demo playback using evidence '{evidence.name}'...")
client.area.play_demo(client)
@@ -997,8 +905,7 @@ def ooc_cmd_trigger(client, arg):
if not evidence:
raise ArgumentError("Target evidence not found!")
if len(args) <= 2:
- client.send_ooc(
- f'Call "{evidence.triggers[trig]}" on trigger "{trig}"')
+ client.send_ooc(f'Call "{evidence.triggers[trig]}" on trigger "{trig}"')
return
val = args[2]
evidence.triggers[trig] = val
@@ -1009,8 +916,7 @@ def ooc_cmd_trigger(client, arg):
if trig not in client.area.triggers:
raise ArgumentError(f"Invalid trigger: {trig}")
if len(args) <= 1:
- client.send_ooc(
- f'Call "{client.area.triggers[trig]}" on trigger "{trig}"')
+ client.send_ooc(f'Call "{client.area.triggers[trig]}" on trigger "{trig}"')
return
val = args[1]
client.area.triggers[trig] = val
@@ -1027,7 +933,7 @@ def ooc_cmd_format_timer(client, arg):
args = shlex.split(arg)
try:
args[0] = int(args[0])
- except:
+ except (ValueError, IndexError):
return
if args[0] == 0:
if client.is_mod or client in client.area.area_manager.owners:
@@ -1036,16 +942,12 @@ def ooc_cmd_format_timer(client, arg):
client.send_ooc("You cannot change timer 0 format if you are not GM")
return
else:
- if (
- client.is_mod
- or client in client.area.area_manager.owners
- or client in client.area.owners
- ):
+ if client.is_mod or client in client.area.area_manager.owners or client in client.area.owners:
timer = client.area.timers[args[0] - 1]
else:
client.send_ooc("You cannot change timer format if you are at least CM")
return
- timer.format = ' '.join(args[1:])
+ timer.format = " ".join(args[1:])
if timer.format == "":
timer.format = "hh:mm:ss.zzz"
client.send_ooc("Resetting timer format to default.")
@@ -1072,7 +974,7 @@ def ooc_cmd_timer_interval(client, arg):
args = shlex.split(arg)
try:
args[0] = int(args[0])
- except:
+ except (ValueError, IndexError):
raise ArgumentError("Timer ID should be an integer")
if args[0] == 0:
if client.is_mod or client in client.area.area_manager.owners:
@@ -1081,26 +983,23 @@ def ooc_cmd_timer_interval(client, arg):
client.send_ooc("You cannot change timer 0 interval if you are not GM")
return
else:
- if (
- client.is_mod
- or client in client.area.area_manager.owners
- or client in client.area.owners
- ):
+ if client.is_mod or client in client.area.area_manager.owners or client in client.area.owners:
timer = client.area.timers[args[0] - 1]
else:
client.send_ooc("You cannot change timer interval if you are at least CM")
return
try:
if len(args) == 1:
- timer.interval = 16
+ timer.interval = 16
else:
timer.interval = pytimeparse.parse(args[1]) * 1000
- except:
+ except (TypeError, ValueError):
raise ArgumentError("Interval value not valid!")
if timer.set:
client.send_timer_set_interval(args[0], timer)
client.send_ooc(f"Timer {args[0]} interval is set to '{args[1]}'")
+
def ooc_cmd_ooc_actions(client, arg):
"""
Enable or disable IC actions being broadcast to OOC as well.
@@ -1108,9 +1007,7 @@ def ooc_cmd_ooc_actions(client, arg):
Usage: /ooc_actions [tog]
"""
if len(arg.split()) > 1:
- raise ArgumentError(
- "This command can only take one argument ('on' or 'off') or no arguments at all!"
- )
+ raise ArgumentError("This command can only take one argument ('on' or 'off') or no arguments at all!")
if arg:
if arg == "on":
client.ooc_actions = True
diff --git a/server/constants.py b/server/constants.py
index ca42708f..c4fba3ac 100644
--- a/server/constants.py
+++ b/server/constants.py
@@ -22,10 +22,10 @@ class MusicEffect(IntFlag):
class ReportCardReason(IntFlag):
- Nothing = 0,
- Blackout = 1,
- PendingLook = 2,
- Blinded = 3,
+ Nothing = 0
+ Blackout = 1
+ PendingLook = 2
+ Blinded = 3
NoPlayerList = 4
@@ -70,8 +70,7 @@ def censor(text, censor_list=[], replace="*", whole_words=True):
if whole_words:
regex = r"\b%s\b"
for word in censor_list:
- text = re.sub(regex % word, len(word) * replace,
- text, flags=re.IGNORECASE)
+ text = re.sub(regex % word, len(word) * replace, text, flags=re.IGNORECASE)
return text
@@ -86,31 +85,19 @@ def contains_URL(sample):
def encode_ao_packet(params):
+ def escape(s):
+ return str(s).replace("#", "").replace("%", "").replace("$", "").replace("&", "")
+
new_params = []
for arg in params:
if type(arg) is tuple:
- encoded = []
- for tup in arg:
- encoded.append(
- str(tup)
- .replace("#", "")
- .replace("%", "")
- .replace("$", "")
- .replace("&", "")
- )
- new_params.append(tuple(encoded))
+ new_params.append(tuple(escape(tup) for tup in arg))
else:
- new_params.append(
- str(arg)
- .replace("#", "")
- .replace("%", "")
- .replace("$", "