be more restrictive with stuff

This commit is contained in:
Nexus 2024-09-12 01:45:38 +01:00
parent 46f5320f58
commit 4764d8cd2a
5 changed files with 28 additions and 19 deletions

View file

@ -58,16 +58,6 @@ class AIModule(niobot.Module):
with open(p, "w") as _fd: with open(p, "w") as _fd:
json.dump(users, _fd) json.dump(users, _fd)
@niobot.command("ping")
async def ping_command(self, ctx: niobot.Context):
"""Checks the bot is running."""
reply = await ctx.respond("Pong!")
server = await self.find_server(gpu_only=False)
if not server:
await reply.edit("Pong :(\nNo servers available.")
return
await reply.edit(f"Pong!\nSelected server: {server['name']}")
@niobot.command("whitelist.add") @niobot.command("whitelist.add")
@niobot.is_owner() @niobot.is_owner()
async def whitelist_add(self, ctx: niobot.Context, user_id: str, model: str = "llama3:latest"): async def whitelist_add(self, ctx: niobot.Context, user_id: str, model: str = "llama3:latest"):
@ -100,6 +90,7 @@ class AIModule(niobot.Module):
await ctx.respond(f"Removed {user_id} from the whitelist.") await ctx.respond(f"Removed {user_id} from the whitelist.")
@niobot.command("ollama.set-model") @niobot.command("ollama.set-model")
@niobot.from_homeserver("nexy7574.co.uk", "nicroxio.co.uk", "shronk.net")
async def set_model(self, ctx: niobot.Context, model: str): async def set_model(self, ctx: niobot.Context, model: str):
"""Sets the model you want to use.""" """Sets the model you want to use."""
users = self.read_users() users = self.read_users()
@ -111,6 +102,7 @@ class AIModule(niobot.Module):
await ctx.respond(f"Set model to {model}. Don't forget to pull it with `h!ollama.pull`.") await ctx.respond(f"Set model to {model}. Don't forget to pull it with `h!ollama.pull`.")
@niobot.command("ollama.pull") @niobot.command("ollama.pull")
@niobot.from_homeserver("nexy7574.co.uk", "nicroxio.co.uk", "shronk.net")
async def pull_model(self, ctx: niobot.Context): async def pull_model(self, ctx: niobot.Context):
"""Pulls the model you set.""" """Pulls the model you set."""
users = self.read_users() users = self.read_users()
@ -128,6 +120,7 @@ class AIModule(niobot.Module):
await msg.edit(f"Pulled model {model}.") await msg.edit(f"Pulled model {model}.")
@niobot.command("ollama.chat", greedy=True) @niobot.command("ollama.chat", greedy=True)
@niobot.from_homeserver("nexy7574.co.uk", "nicroxio.co.uk", "shronk.net")
async def chat(self, ctx: niobot.Context): async def chat(self, ctx: niobot.Context):
"""Chat with the model.""" """Chat with the model."""
if "--gpu" in ctx.args: if "--gpu" in ctx.args:
@ -158,7 +151,8 @@ class AIModule(niobot.Module):
logging.exception(e) logging.exception(e)
await ctx.respond(content="An error occurred.") await ctx.respond(content="An error occurred.")
@niobot.command("ollama.status") @niobot.command("ollama.status", aliases=["ollama.ping"])
@niobot.from_homeserver("nexy7574.co.uk", "nicroxio.co.uk", "shronk.net")
async def status(self, ctx: niobot.Context, gpu_only: bool = False): async def status(self, ctx: niobot.Context, gpu_only: bool = False):
"""Checks which servers are online.""" """Checks which servers are online."""
lines: dict[str, dict[str, str | None | bool]] = {} lines: dict[str, dict[str, str | None | bool]] = {}

View file

@ -38,13 +38,16 @@ class EvalModule(niobot.Module):
"""Removes any code block syntax from the given string.""" """Removes any code block syntax from the given string."""
code = code.strip() code = code.strip()
lines = code.splitlines(False) lines = code.splitlines(False)
if len(lines[0]) == 2 or lines[0] in ("py", "python", "python3"): # likely a codeblock language identifier if len(lines[0]) == 2 or lines[0] in ("py", "python", "python3", "sh", "shell", "bash"):
# likely a codeblock language identifier
lines = lines[1:] lines = lines[1:]
return "\n".join(lines) return "\n".join(lines)
@niobot.command("eval") @niobot.command("eval")
@niobot.is_owner()
async def python_eval(self, ctx: niobot.Context, code: str): async def python_eval(self, ctx: niobot.Context, code: str):
"""Evaluates python code. """
Evaluates python code.
All code is automatically wrapped in an async function, so you can do top-level awaits. All code is automatically wrapped in an async function, so you can do top-level awaits.
You must return a value for it to be printed, or manually print() it. You must return a value for it to be printed, or manually print() it.
@ -67,6 +70,7 @@ class EvalModule(niobot.Module):
g = { g = {
**globals().copy(), **globals().copy(),
**locals().copy(), **locals().copy(),
"bot": ctx.bot,
"ctx": ctx, "ctx": ctx,
"loop": asyncio.get_event_loop(), "loop": asyncio.get_event_loop(),
"stdout": stdout, "stdout": stdout,
@ -119,6 +123,7 @@ class EvalModule(niobot.Module):
await msg.edit(f"Error:\n```py\n{traceback.format_exc()}```") await msg.edit(f"Error:\n```py\n{traceback.format_exc()}```")
@niobot.command("shell") @niobot.command("shell")
@niobot.is_owner()
async def shell(self, ctx: niobot.Context, command: str): async def shell(self, ctx: niobot.Context, command: str):
"""Runs a shell command in a subprocess. Does not output live.""" """Runs a shell command in a subprocess. Does not output live."""
if command.startswith("sh\n"): if command.startswith("sh\n"):
@ -200,8 +205,9 @@ class EvalModule(niobot.Module):
@niobot.command() @niobot.command()
@niobot.is_owner() @niobot.is_owner()
async def runas(self, ctx: niobot.Context, user: str, command: str, *args: str): async def runas(self, ctx: niobot.Context, user: str, command: str, *args):
"""Run a command as another user.""" """Run a command as another user."""
args = args or []
if args and args[0] == "%null%": if args and args[0] == "%null%":
args = tuple() args = tuple()
event = ctx.event event = ctx.event

View file

@ -6,9 +6,14 @@ import httpx
class LatencyModule(niobot.Module): class LatencyModule(niobot.Module):
@niobot.command("latency")
@niobot.command("latency", aliases=["ping"])
async def latency(self, ctx: niobot.Context, homeserver: str = None): async def latency(self, ctx: niobot.Context, homeserver: str = None):
"""See the bot's latency.""" """
See the bot's latency.
If you supply a homeserver, it will also show the federation latency to that homeserver.
"""
latency = ctx.latency latency = ctx.latency
homeserver = homeserver or ctx.message.sender.split(":")[1] homeserver = homeserver or ctx.message.sender.split(":")[1]

View file

@ -185,6 +185,7 @@ class TruthSocialTranscode(niobot.Module):
return ctx.message.sender.split(":", 1)[1] in {"shronk.net", "nicroxio.co.uk", "nexy7574.co.uk"} return ctx.message.sender.split(":", 1)[1] in {"shronk.net", "nicroxio.co.uk", "nexy7574.co.uk"}
@niobot.command("transcode") @niobot.command("transcode")
@niobot.from_homeserver("nexy7574.co.uk", "shronk.net", "nicroxio.co.uk", "transgender.ing")
async def do_transcode(self, ctx: niobot.Context, message_link: typing.Annotated[niobot.RoomMessage, niobot.EventParser("m.room.message")]): async def do_transcode(self, ctx: niobot.Context, message_link: typing.Annotated[niobot.RoomMessage, niobot.EventParser("m.room.message")]):
""" """
Transcodes a video to H264/AAC. Transcodes a video to H264/AAC.

View file

@ -122,7 +122,12 @@ class YoutubeDLModule(niobot.Module):
async def ytdl( async def ytdl(
self, ctx: niobot.Context, url: str, snip: Optional[str] = None, download_format: Optional[str] = None self, ctx: niobot.Context, url: str, snip: Optional[str] = None, download_format: Optional[str] = None
): ):
"""Downloads a video from YouTube or other source""" """
Downloads a video from YouTube or other source
snip: an optional timestamp to snip the video to, in the format `start-end`. e.g. `1:30-2:00`
download_format: the format to download the video in. e.g. `1080p`, or a specific ID (e.g. `22`)
"""
response = await ctx.respond("Preparing...") response = await ctx.respond("Preparing...")
options = self.default_options.copy() options = self.default_options.copy()
@ -216,8 +221,6 @@ class YoutubeDLModule(niobot.Module):
f"# {title}\n\n{description}\n\nProgress: `0% [..........]`\n\nDownloading (step 2/10)" f"# {title}\n\n{description}\n\nProgress: `0% [..........]`\n\nDownloading (step 2/10)"
) )
last_edit = time.time()
try: try:
await asyncio.to_thread(functools.partial(downloader.download, [url])) await asyncio.to_thread(functools.partial(downloader.download, [url]))
except DownloadError as e: except DownloadError as e: