first commit

This commit is contained in:
onyx-and-iris 2026-03-21 00:25:40 +00:00
commit 48bf6f6728
19 changed files with 806 additions and 0 deletions

212
.gitignore vendored Normal file
View File

@ -0,0 +1,212 @@
# Generated by ignr: github.com/onyx-and-iris/ignr
## Python ##
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[codz]
*$py.class
# C extensions
*.so
# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py.cover
.hypothesis/
.pytest_cache/
cover/
# Translations
*.mo
*.pot
# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal
# Flask stuff:
instance/
.webassets-cache
# Scrapy stuff:
.scrapy
# Sphinx documentation
docs/_build/
# PyBuilder
.pybuilder/
target/
# Jupyter Notebook
.ipynb_checkpoints
# IPython
profile_default/
ipython_config.py
# pyenv
# For a library or package, you might want to ignore these files since the code is
# intended to run in multiple environments; otherwise, check them in:
# .python-version
# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock
# UV
# Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.
# This is especially recommended for binary packages to ensure reproducibility, and is more
# commonly ignored for libraries.
#uv.lock
# poetry
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
# This is especially recommended for binary packages to ensure reproducibility, and is more
# commonly ignored for libraries.
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
#poetry.lock
#poetry.toml
# pdm
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
# pdm recommends including project-wide configuration in pdm.toml, but excluding .pdm-python.
# https://pdm-project.org/en/latest/usage/project/#working-with-version-control
#pdm.lock
#pdm.toml
.pdm-python
.pdm-build/
# pixi
# Similar to Pipfile.lock, it is generally recommended to include pixi.lock in version control.
#pixi.lock
# Pixi creates a virtual environment in the .pixi directory, just like venv module creates one
# in the .venv directory. It is recommended not to include this directory in version control.
.pixi
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
__pypackages__/
# Celery stuff
celerybeat-schedule
celerybeat.pid
# SageMath parsed files
*.sage.py
# Environments
.env
.envrc
.venv
env/
venv/
ENV/
env.bak/
venv.bak/
# Spyder project settings
.spyderproject
.spyproject
# Rope project settings
.ropeproject
# mkdocs documentation
/site
# mypy
.mypy_cache/
.dmypy.json
dmypy.json
# Pyre type checker
.pyre/
# pytype static type analyzer
.pytype/
# Cython debug symbols
cython_debug/
# PyCharm
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
# and can be added to the global gitignore or merged into this file. For a more nuclear
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
#.idea/
# Abstra
# Abstra is an AI-powered process automation framework.
# Ignore directories containing user credentials, local state, and settings.
# Learn more at https://abstra.io/docs
.abstra/
# Visual Studio Code
# Visual Studio Code specific template is maintained in a separate VisualStudioCode.gitignore
# that can be found at https://github.com/github/gitignore/blob/main/Global/VisualStudioCode.gitignore
# and can be added to the global gitignore or merged into this file. However, if you prefer,
# you could uncomment the following to ignore the entire vscode folder
# .vscode/
# Ruff stuff:
.ruff_cache/
# PyPI configuration file
.pypirc
# Cursor
# Cursor is an AI-powered code editor. `.cursorignore` specifies files/directories to
# exclude from AI features like autocomplete and code analysis. Recommended for sensitive data
# refer to https://docs.cursor.com/context/ignore-files
.cursorignore
.cursorindexingignore
# Marimo
marimo/_static/
marimo/_lsp/
__marimo__/
# End of ignr

9
LICENSE.txt Normal file
View File

@ -0,0 +1,9 @@
MIT License
Copyright (c) 2026-present onyx-and-iris <code@onyxandiris.online>
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

21
README.md Normal file
View File

@ -0,0 +1,21 @@
# q3rcon-cli
[![PyPI - Version](https://img.shields.io/pypi/v/q3rcon-cli.svg)](https://pypi.org/project/q3rcon-cli)
[![PyPI - Python Version](https://img.shields.io/pypi/pyversions/q3rcon-cli.svg)](https://pypi.org/project/q3rcon-cli)
-----
## Table of Contents
- [Installation](#installation)
- [License](#license)
## Installation
```console
pip install q3rcon-cli
```
## License
`q3rcon-cli` is distributed under the terms of the [MIT](https://spdx.org/licenses/MIT.html) license.

54
pyproject.toml Normal file
View File

@ -0,0 +1,54 @@
[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"
[project]
name = "q3rcon-cli"
dynamic = ["version"]
description = ''
readme = "README.md"
requires-python = ">=3.8"
license = "MIT"
keywords = []
authors = [{ name = "onyx-and-iris", email = "code@onyxandiris.online" }]
classifiers = [
"Development Status :: 4 - Beta",
"Programming Language :: Python",
"Programming Language :: Python :: 3.8",
"Programming Language :: Python :: 3.9",
"Programming Language :: Python :: 3.10",
"Programming Language :: Python :: 3.11",
"Programming Language :: Python :: 3.12",
"Programming Language :: Python :: Implementation :: CPython",
"Programming Language :: Python :: Implementation :: PyPy",
]
dependencies = ["aio-q3-rcon>=1.0.0", "clypi>=1.8.2"]
[project.scripts]
q3rcon-cli = "q3rcon_cli.cli:main"
[project.urls]
Documentation = "https://github.com/onyx-and-iris/q3rcon-cli#readme"
Issues = "https://github.com/onyx-and-iris/q3rcon-cli/issues"
Source = "https://github.com/onyx-and-iris/q3rcon-cli"
[tool.hatch.version]
path = "src/q3rcon_cli/__about__.py"
[tool.hatch.envs.types]
extra-dependencies = ["mypy>=1.0.0"]
[tool.hatch.envs.types.scripts]
check = "mypy --install-types --non-interactive {args:src/q3rcon_cli tests}"
[tool.coverage.run]
source_pkgs = ["q3rcon_cli", "tests"]
branch = true
parallel = true
omit = ["src/q3rcon_cli/__about__.py"]
[tool.coverage.paths]
q3rcon_cli = ["src/q3rcon_cli", "*/q3rcon-cli/src/q3rcon_cli"]
tests = ["tests", "*/q3rcon-cli/tests"]
[tool.coverage.report]
exclude_lines = ["no cov", "if __name__ == .__main__.:", "if TYPE_CHECKING:"]

77
ruff.toml Normal file
View File

@ -0,0 +1,77 @@
# Exclude a variety of commonly ignored directories.
exclude = [
".bzr",
".direnv",
".eggs",
".git",
".git-rewrite",
".hg",
".ipynb_checkpoints",
".mypy_cache",
".nox",
".pants.d",
".pyenv",
".pytest_cache",
".pytype",
".ruff_cache",
".svn",
".tox",
".venv",
".vscode",
"__pypackages__",
"_build",
"buck-out",
"build",
"dist",
"node_modules",
"site-packages",
"venv",
]
# Same as Black.
line-length = 88
indent-width = 4
# Assume Python 3.10
target-version = "py310"
[lint]
# Enable Pyflakes (`F`) and a subset of the pycodestyle (`E`) codes by default.
# Unlike Flake8, Ruff doesn't enable pycodestyle warnings (`W`) or
# McCabe complexity (`C901`) by default.
select = ["E4", "E7", "E9", "F"]
ignore = []
# Allow fix for all enabled rules (when `--fix`) is provided.
fixable = ["ALL"]
unfixable = []
# Allow unused variables when underscore-prefixed.
dummy-variable-rgx = "^(_+|(_+[a-zA-Z0-9_]*[a-zA-Z0-9]+?))$"
[format]
# Unlike Black, use single quotes for strings.
quote-style = "single"
# Like Black, indent with spaces, rather than tabs.
indent-style = "space"
# Like Black, respect magic trailing commas.
skip-magic-trailing-comma = false
# Like Black, automatically detect the appropriate line ending.
line-ending = "auto"
# Enable auto-formatting of code examples in docstrings. Markdown,
# reStructuredText code/literal blocks and doctests are all supported.
#
# This is currently disabled by default, but it is planned for this
# to be opt-out in the future.
docstring-code-format = false
# Set the line length limit used when formatting code snippets in
# docstrings.
#
# This only has an effect when the `docstring-code-format` setting is
# enabled.
docstring-code-line-length = "dynamic"

View File

@ -0,0 +1,4 @@
# SPDX-FileCopyrightText: 2026-present onyx-and-iris <code@onyxandiris.online>
#
# SPDX-License-Identifier: MIT
__version__ = "0.0.1"

View File

@ -0,0 +1,3 @@
# SPDX-FileCopyrightText: 2026-present onyx-and-iris <code@onyxandiris.online>
#
# SPDX-License-Identifier: MIT

102
src/q3rcon_cli/cli.py Normal file
View File

@ -0,0 +1,102 @@
import clypi
from aioq3rcon import Client
from clypi import Command, arg
from typing_extensions import override
from .commands import (
Fastrestart,
Gametype,
Hostname,
Map,
Mapname,
Maprotate,
Plugins,
Status,
)
from .console import Console
Subcommands = (
Status | Mapname | Maprotate | Fastrestart | Gametype | Hostname | Map | Plugins
)
class Q3rconCli(Command):
subcommand: Subcommands | None = None
host: str = arg(
'localhost',
short='h',
help='The host to connect to',
env='Q3RCON_CLI_HOST',
group='Connection',
)
port: int = arg(
27960,
short='p',
help='The port to connect to',
env='Q3RCON_CLI_PORT',
group='Connection',
)
password: str = arg(
'',
short='P',
help='The password for authentication',
env='Q3RCON_CLI_PASSWORD',
group='Connection',
)
interactive: bool = arg(
False,
short='i',
help='Whether to start in interactive mode (defaults to false)',
)
@override
async def run(self):
if self.interactive:
await self.run_interactive()
else:
await Status.run(self)
async def run_interactive(self):
print(
clypi.style('Entering interactive mode. Type', fg='blue'),
clypi.style("'Q'", fg='red'),
clypi.style('to quit.', fg='blue'),
)
DEFAULT_FRAGMENT_READ_TIMEOUT = 0.25
while command := input(clypi.style('cmd: ', fg='green')):
if command.lower() == 'q':
break
fragment_read_timeout = None
if command in (
'status',
'fast_restart',
'map_restart',
'map',
'map_rotate',
):
fragment_read_timeout = 1
async with Client(
self.host,
self.port,
self.password,
fragment_read_timeout=fragment_read_timeout
or DEFAULT_FRAGMENT_READ_TIMEOUT,
) as client:
try:
if response := await client.send_command(command):
Console.print_response(response)
except TimeoutError:
print(
clypi.style(
'Timeout waiting for response for command:', fg='red'
),
clypi.style(command, fg='yellow'),
)
def main():
cli = Q3rconCli().parse()
cli.start()

View File

@ -0,0 +1,19 @@
from .fastrestart import Fastrestart
from .gametype import Gametype
from .hostname import Hostname
from .map import Map
from .mapname import Mapname
from .maprotate import Maprotate
from .plugins import Plugins
from .status import Status
__all__ = [
'Status',
'Mapname',
'Maprotate',
'Fastrestart',
'Gametype',
'Hostname',
'Map',
'Plugins',
]

View File

@ -0,0 +1,19 @@
from aioq3rcon import Client
from clypi import Command, arg
from typing_extensions import override
from q3rcon_cli.console import Console
class Fastrestart(Command):
"""Executes a fast restart of the server."""
host: str = arg(inherited=True)
port: int = arg(inherited=True)
password: str = arg(inherited=True)
@override
async def run(self):
async with Client(self.host, self.port, self.password) as client:
if response := await client.send_command('fast_restart'):
Console.print_response(response)

View File

@ -0,0 +1,43 @@
from aioq3rcon import Client
from clypi import Command, Positional, Spinner, arg
from typing_extensions import override
from q3rcon_cli.console import Console
class Gametype(Command):
"""Get or set the current gametype of the server."""
new_gametype: Positional[str] = arg(
help='The new gametype to change to (optional). If not provided, the current gametype will be printed.',
default='',
)
host: str = arg(inherited=True)
port: int = arg(inherited=True)
password: str = arg(inherited=True)
force: bool = arg(
False,
short='f',
help='Whether to force the gametype change even if players are currently in the server.',
)
@override
async def run(self):
if not Gametype.new_gametype:
async with Client(self.host, self.port, self.password) as client:
if response := await client.send_command('g_gametype'):
Console.print_cvar(response)
return
async with Client(self.host, self.port, self.password) as client:
DEFAULT_FRAGMENT_READ_TIMEOUT = client.fragment_read_timeout
await client.send_command(f'g_gametype {self.new_gametype}')
if self.force:
async with Spinner('Forcing gametype change...'):
client.fragment_read_timeout = 1
await client.send_command('map_restart')
client.fragment_read_timeout = DEFAULT_FRAGMENT_READ_TIMEOUT
if response := await client.send_command('g_gametype'):
Console.print_cvar(response)

View File

@ -0,0 +1,30 @@
from aioq3rcon import Client
from clypi import Command, Positional, arg
from typing_extensions import override
from q3rcon_cli.console import Console
class Hostname(Command):
"""Get or set the current hostname of the server."""
new_hostname: Positional[str] = arg(
help='The new hostname to change to (optional). If not provided, the current hostname will be printed.',
default='',
)
host: str = arg(inherited=True)
port: int = arg(inherited=True)
password: str = arg(inherited=True)
@override
async def run(self):
if not self.new_hostname:
async with Client(self.host, self.port, self.password) as client:
if response := await client.send_command('sv_hostname'):
Console.print_cvar(response)
return
async with Client(self.host, self.port, self.password) as client:
await client.send_command(f'sv_hostname {self.new_hostname}')
if response := await client.send_command('sv_hostname'):
Console.print_cvar(response)

View File

@ -0,0 +1,33 @@
from aioq3rcon import Client
from clypi import Command, Positional, Spinner, arg
from typing_extensions import override
from q3rcon_cli.console import Console
class Map(Command):
"""Get the current map or change to a new one."""
new_map: Positional[str] = arg(
help='The new map to change to (optional). If not provided, the current map will be printed.',
default='',
)
host: str = arg(inherited=True)
port: int = arg(inherited=True)
password: str = arg(inherited=True)
@override
async def run(self):
if not self.new_map:
async with Client(self.host, self.port, self.password) as client:
if response := await client.send_command('mapname'):
Console.print_cvar(response)
return
async with Spinner('Changing map...'):
async with Client(
self.host, self.port, self.password, fragment_read_timeout=1
) as client:
await client.send_command(f'map mp_{self.new_map.removeprefix("mp_")}')
if response := await client.send_command('mapname'):
Console.print_cvar(response)

View File

@ -0,0 +1,19 @@
from aioq3rcon import Client
from clypi import Command, arg
from typing_extensions import override
from q3rcon_cli.console import Console
class Mapname(Command):
"""Prints the current map name of the server."""
host: str = arg(inherited=True)
port: int = arg(inherited=True)
password: str = arg(inherited=True)
@override
async def run(self):
async with Client(self.host, self.port, self.password) as client:
if response := await client.send_command('mapname'):
Console.print_cvar(response)

View File

@ -0,0 +1,22 @@
from aioq3rcon import Client
from clypi import Command, Spinner, arg
from typing_extensions import override
from q3rcon_cli.console import Console
class Maprotate(Command):
"""Rotates the map to the next one in the map rotation list."""
host: str = arg(inherited=True)
port: int = arg(inherited=True)
password: str = arg(inherited=True)
@override
async def run(self):
async with Spinner('Rotating map...'):
async with Client(
self.host, self.port, self.password, fragment_read_timeout=1
) as client:
if response := await client.send_command('map_rotate'):
Console.print_response(response)

View File

@ -0,0 +1,19 @@
from aioq3rcon import Client
from clypi import Command, arg
from typing_extensions import override
from q3rcon_cli.console import Console
class Plugins(Command):
"""Prints the currently loaded plugins of the server."""
host: str = arg(inherited=True)
port: int = arg(inherited=True)
password: str = arg(inherited=True)
@override
async def run(self):
async with Client(self.host, self.port, self.password) as client:
if response := await client.send_command('plugins'):
Console.print_response(response)

View File

@ -0,0 +1,22 @@
from aioq3rcon import Client
from clypi import Command, Spinner, arg
from typing_extensions import override
from q3rcon_cli.console import Console
class Status(Command):
"""Prints the status of the server."""
host: str = arg(inherited=True)
port: int = arg(inherited=True)
password: str = arg(inherited=True)
@override
async def run(self):
async with Spinner('Fetching status...'):
async with Client(
self.host, self.port, self.password, fragment_read_timeout=0.5
) as client:
if response := await client.send_command('status'):
Console.print_status(response)

95
src/q3rcon_cli/console.py Normal file
View File

@ -0,0 +1,95 @@
import re
import clypi
from clypi import cprint
class Console:
COLOUR_CODE_REGEX = re.compile(r'\^[0-9]')
STATUS_PLAYER_REGEX = re.compile(
r'^\s*(?P<slot>[0-9]+)\s+'
r'(?P<score>[0-9-]+)\s+'
r'(?P<ping>[0-9]+)\s+'
r'(?P<guid>[0-9a-f]+)\s+'
r'(?P<name>.*?)\s+'
r'(?P<last>[0-9]+?)\s*'
r'(?P<ip>(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.){3}'
r'(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])):?'
r'(?P<port>-?[0-9]{1,5})\s*'
r'(?P<qport>-?[0-9]{1,5})\s+'
r'(?P<rate>[0-9]+)$',
re.IGNORECASE | re.VERBOSE,
)
CVAR_REGEX = re.compile(
r'^["](?P<name>[a-z_]+)["]\sis[:]\s'
r'["](?P<value>.*?)["]\s'
r'default[:]\s'
r'["](?P<default>.*?)["]\s'
r'info[:]\s'
r'["](?P<info>.*?)["]$'
)
@staticmethod
def remove_colour_codes(s: str) -> str:
"""Remove Quake 3 colour codes from a string."""
return Console.COLOUR_CODE_REGEX.sub('', s)
@staticmethod
def print_response(response: str):
response = Console.remove_colour_codes(response).removeprefix('print\n')
cprint(f'\n{response}\n', fg='yellow')
@staticmethod
def print_status(response: str):
_slots = []
_scores = []
_pings = []
_guids = []
_names = []
_ips = []
lines = response.splitlines()
for line in lines:
if m := Console.STATUS_PLAYER_REGEX.match(line):
_slots.append(m.group('slot'))
_scores.append(m.group('score'))
_pings.append(m.group('ping'))
_guids.append(m.group('guid'))
_names.append(m.group('name'))
_ips.append(m.group('ip'))
if not _slots:
cprint('\nNo players connected.\n', fg='yellow')
return
slots = clypi.boxed(_slots, title='Slot', width=15)
scores = clypi.boxed(_scores, title='Score', width=15)
pings = clypi.boxed(_pings, title='Ping', width=15)
guids = clypi.boxed(_guids, title='GUID', width=40)
names = clypi.boxed(_names, title='Name', width=30)
ips = clypi.boxed(_ips, title='IP', width=30)
print(f'\n{clypi.stack(slots, scores, pings, guids, names, ips, padding=0)}')
@staticmethod
def print_cvar(response: str):
response = Console.remove_colour_codes(response).removeprefix('print\n')
if m := Console.CVAR_REGEX.match(response):
name = clypi.boxed(
[m.group('name')], title='Name', width=max(len(m.group('name')) + 4, 30)
)
value = clypi.boxed(
[m.group('value')],
title='Value',
width=max(len(m.group('value')) + 4, 30),
)
default = clypi.boxed(
[m.group('default')],
title='Default',
width=max(len(m.group('default')) + 4, 30),
)
info = clypi.boxed(
[m.group('info')], title='Info', width=max(len(m.group('info')) + 4, 30)
)
print(f'\n{clypi.stack(name, value, default, info, padding=0)}')

3
tests/__init__.py Normal file
View File

@ -0,0 +1,3 @@
# SPDX-FileCopyrightText: 2026-present onyx-and-iris <code@onyxandiris.online>
#
# SPDX-License-Identifier: MIT