Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
74 changes: 0 additions & 74 deletions app.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,7 @@
from twisted.spread import pb
from twisted.internet import endpoints
from os import environ
import functools
import json
import sqlite3
import simple_eval
from twisted.logger import textFileLogObserver, globalLogPublisher, Logger

log = Logger()
Expand All @@ -30,82 +27,11 @@ def remote_handlePublicMessage(self, protocol, user, channel, message,
max_line_length, timestamp):
if self._staleness_check(timestamp):
return
try:
callback = functools.partial(
protocol.callRemote, "msg", channel)
roles = resolveRoles(user)
if "ignored" in roles:
return
if message.startswith("!"):
return handleCommand(protocol, user, roles, channel, message[1:],
max_line_length, callback)
except Exception:
log.failure("FIXME, runaway exception")

def remote_handlePrivateMessage(self, protocol, user, channel, message,
max_line_length, timestamp):
if self._staleness_check(timestamp):
return
channel, _, _ = user.partition("!")
return self.remote_handlePublicMessage(protocol, user, channel,
message,
max_line_length,
timestamp)


user_query = ("select roles.name from roles where roles.oid in "
"(select userroles.oid from (users natural join usermask)"
"natural join userroles where usermask.mask=?);")


def resolveRoles(user):
with sqlite3.connect(config["core"]["db"]) as conn:
cur = conn.cursor()
res = cur.execute(user_query, (user,))
return [role[0] for role in res.fetchmany()]


def handleCommand(protocol, user, roles, channel, message, max_line_length,
callback):
command, _, suffix = message.partition(" ")
if command == "reincarnate":
if "superadmin" in roles:
log.info("Restarting app")
reactor.stop()
else:
log.info("User {user} tried to do code reload", user=user)
elif command == "eval":
truth, expr = suffix.split(":")
truth = [s.strip() for s in truth.split(",")]
try:
ret = simple_eval.eval_bool(expr, truth)
except simple_eval.EvalError as e:
callback(str(e))
else:
callback("Result: %s" % ret)
elif command == "join":
channel, _, password = suffix.partition(" ")
if not password:
password = None
if "superadmin" in roles:
if password:
log.info(f"Joining {channel} ({password})")
else:
log.info(f"Joining {channel}")
return protocol.callRemote("join", channel, password)
elif command == "leave":
channel, _, reason = suffix.partition(" ")
if not reason:
reason = None
if "superadmin" in roles:
if reason:
log.info("Leaving {channel} ({reason})",
channel=channel, reason=reason)
else:
log.info(f"Leaving {channel}")
return protocol.callRemote("leave", channel, reason)
else:
log.info(f"Unrecognized command {command}")


def log_and_exit(ret, reactor):
Expand Down
10 changes: 10 additions & 0 deletions config.json.example
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,16 @@
"keywords": ["hello", "hi"],
"response": "Hey! How can I help?"
}
},
{
"name": "eval",
"module": "plugins.eval_plugin",
"enabled": true
},
{
"name": "admin",
"module": "plugins.admin_plugin",
"enabled": true
}
]
}
Expand Down
114 changes: 114 additions & 0 deletions plugins/admin_plugin.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
# -*- coding: utf-8 -*-
"""
Admin plugin for nanobot.

Handles admin commands: !reincarnate, !join, !leave.
Role-based access is resolved via the configured SQLite database.
"""
import sqlite3
from plugin import Plugin
from twisted.logger import Logger

log = Logger()

_user_query = (
"select roles.name from roles where roles.oid in "
"(select userroles.oid from (users natural join usermask)"
"natural join userroles where usermask.mask=?);"
)


class AdminPlugin(Plugin):
"""Plugin that handles admin commands with role-based access control."""

def load(self):
"""Load the plugin and register handlers."""
log.info(f"Loading {self.name} plugin")
self._db = self.registry.config.get('core', {}).get('db')
self.register_handler('privmsg', self.on_privmsg)
log.info(f"{self.name} plugin loaded successfully")

def _resolve_roles(self, user):
"""
Resolve roles for a user from the database.

Args:
user: User mask (nick!user@host)

Returns:
List of role names for the user
"""
if not self._db:
return []
with sqlite3.connect(self._db) as conn:
cur = conn.cursor()
res = cur.execute(_user_query, (user,))
return [role[0] for role in res.fetchall()]

def on_privmsg(self, protocol, user, channel, message):
"""
Handle privmsg events, responding to admin commands.

Args:
protocol: NanoBotProtocol instance
user: User who sent the message (nick!user@host)
channel: Channel name or bot nickname (for private messages)
message: Message text
"""
if not message.startswith("!"):
return

command, _, suffix = message[1:].partition(" ")
if command not in ("reincarnate", "join", "leave"):
return

roles = self._resolve_roles(user)
if "ignored" in roles:
return

if command == "reincarnate":
if "superadmin" in roles:
log.info("Restarting app")
if protocol.bot._proc:
protocol.bot._proc.signalProcess('KILL')
else:
log.info("User {user} tried to do code reload", user=user)
elif command == "join":
chan, _, password = suffix.partition(" ")
if not password:
password = None
if "superadmin" in roles:
if password:
log.info(f"Joining {chan} ({password})")
else:
log.info(f"Joining {chan}")
protocol.join(chan, password)
elif command == "leave":
chan, _, reason = suffix.partition(" ")
if not reason:
reason = None
if "superadmin" in roles:
if reason:
log.info("Leaving {channel} ({reason})",
channel=chan, reason=reason)
else:
log.info(f"Leaving {chan}")
protocol.leave(chan, reason)


def load(registry, config):
"""
Plugin entry point called by PluginRegistry when loading the plugin.

Args:
registry: PluginRegistry instance
config: Plugin configuration dictionary

Returns:
AdminPlugin instance
"""
plugin_name = config.get('name', 'admin')
plugin_config = config.get('config', {})
plugin = AdminPlugin(plugin_name, registry, plugin_config)
plugin.load()
return plugin
67 changes: 67 additions & 0 deletions plugins/eval_plugin.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
# -*- coding: utf-8 -*-
"""
Eval plugin for nanobot.

Handles the !eval command for boolean expression evaluation.
"""
import simple_eval
from plugin import Plugin
from twisted.logger import Logger

log = Logger()


class EvalPlugin(Plugin):
"""Plugin that handles the !eval command for boolean expression evaluation."""

def load(self):
"""Load the plugin and register handlers."""
log.info(f"Loading {self.name} plugin")
self.register_handler('privmsg', self.on_privmsg)
log.info(f"{self.name} plugin loaded successfully")

def on_privmsg(self, protocol, user, channel, message):
"""
Handle privmsg events, responding to !eval commands.

Args:
protocol: NanoBotProtocol instance
user: User who sent the message (nick!user@host)
channel: Channel name or bot nickname (for private messages)
message: Message text
"""
if not message.startswith("!eval "):
return

suffix = message[len("!eval "):]
if channel == protocol.nickname:
target = user.split('!')[0]
else:
target = channel

truth, _, expr = suffix.partition(":")
truth = [s.strip() for s in truth.split(",")]
try:
ret = simple_eval.eval_bool(expr, truth)
except simple_eval.EvalError as e:
protocol.msg(target, str(e))
else:
protocol.msg(target, "Result: %s" % ret)


def load(registry, config):
"""
Plugin entry point called by PluginRegistry when loading the plugin.

Args:
registry: PluginRegistry instance
config: Plugin configuration dictionary

Returns:
EvalPlugin instance
"""
plugin_name = config.get('name', 'eval')
plugin_config = config.get('config', {})
plugin = EvalPlugin(plugin_name, registry, plugin_config)
plugin.load()
return plugin
Loading