Formatting

This commit is contained in:
Firepup Sixfifty 2024-05-24 12:06:41 -05:00
parent ce6dc597ef
commit b720b5edf8
Signed by: Firepup650
GPG key ID: 7C92E2ABBBFAB9BA
4 changed files with 135 additions and 91 deletions

69
bot.py
View file

@ -53,7 +53,7 @@ class bot(bare.bot):
else "FireBot" else "FireBot"
) )
self.queue: list[bbytes] = [] # pyright: ignore [reportInvalidTypeForm] self.queue: list[bbytes] = [] # pyright: ignore [reportInvalidTypeForm]
self.statuses = {'firepup': {}} self.statuses = {"firepup": {}}
self.ops = {} self.ops = {}
self.sock = socket(AF_INET, SOCK_STREAM) self.sock = socket(AF_INET, SOCK_STREAM)
self.current = "user" self.current = "user"
@ -318,38 +318,41 @@ class bot(bare.bot):
if action in handlers.handles: if action in handlers.handles:
res, chan = handlers.handles[action](self, ircmsg) res, chan = handlers.handles[action](self, ircmsg)
if res == "reload" and type(chan) == str: if res == "reload" and type(chan) == str:
try: try:
reload(conf) reload(conf)
self.adminnames = ( self.adminnames = (
conf.servers[self.server]["admins"] conf.servers[self.server]["admins"]
if "admins" in conf.servers[self.server] if "admins" in conf.servers[self.server]
else [] else []
) )
self.ignores = ( self.ignores = (
conf.servers[self.server]["ignores"] conf.servers[self.server]["ignores"]
if "ignores" in conf.servers[self.server] if "ignores" in conf.servers[self.server]
else [] else []
) )
self.__version__ = conf.__version__ self.__version__ = conf.__version__
self.npallowed = conf.npallowed self.npallowed = conf.npallowed
self.interval = ( self.interval = (
conf.servers[self.server]["interval"] conf.servers[self.server]["interval"]
if "interval" in conf.servers[self.server] if "interval" in conf.servers[self.server]
else 50 else 50
) )
conf.prefix = ( conf.prefix = (
conf.servers[self.server]["prefix"] conf.servers[self.server]["prefix"]
if "prefix" in conf.servers[self.server] if "prefix" in conf.servers[self.server]
else "." else "."
) )
reload(cmds) reload(cmds)
reload(handlers) reload(handlers)
self.msg("Reloaded successfully", chan) self.msg("Reloaded successfully", chan)
except Exception: except Exception:
Err = format_exc() Err = format_exc()
for line in Err.split("\n"): for line in Err.split("\n"):
self.log(line, "ERROR") self.log(line, "ERROR")
self.msg("Reload failed, likely partially reloaded. Please check error logs.", chan) self.msg(
"Reload failed, likely partially reloaded. Please check error logs.",
chan,
)
else: else:
if ircmsg.startswith("PING "): if ircmsg.startswith("PING "):
self.ping(ircmsg) self.ping(ircmsg)

View file

@ -155,19 +155,19 @@ def debug(bot: bare.bot, chan: str, name: str, message: str) -> None:
def debugInternal(bot: bare.bot, chan: str, name: str, message: str) -> None: def debugInternal(bot: bare.bot, chan: str, name: str, message: str) -> None:
things = dir(bot) things = dir(bot)
try: try:
thing = message.split(' ', 1)[1] thing = message.split(" ", 1)[1]
except IndexError: except IndexError:
bot.msg("You can't just ask me to lookup nothing.", chan) bot.msg("You can't just ask me to lookup nothing.", chan)
return return
if thing in things: if thing in things:
bot.msg(f"self.{thing} = {getattr(bot, thing)}", chan) bot.msg(f"self.{thing} = {getattr(bot, thing)}", chan)
else: else:
bot.msg(f"I have nothing called \"{thing}\"", chan) bot.msg(f'I have nothing called "{thing}"', chan)
def debugEval(bot: bare.bot, chan: str, name: str, message: str) -> None: def debugEval(bot: bare.bot, chan: str, name: str, message: str) -> None:
try: try:
bot.msg(str(eval(message.split(' ', 1)[1])), chan) bot.msg(str(eval(message.split(" ", 1)[1])), chan)
except Exception as E: except Exception as E:
bot.msg(f"Exception: {E}", chan) bot.msg(f"Exception: {E}", chan)
@ -234,17 +234,23 @@ def markov(bot: bare.bot, chan: str, name: str, message: str) -> None:
def setStatus(bot: bare.bot, chan: str, name: str, message: str) -> None: def setStatus(bot: bare.bot, chan: str, name: str, message: str) -> None:
user, stat, reas = ('', 0, '') user, stat, reas = ("", 0, "")
try: try:
if message.split(' ')[1] == "help": if message.split(" ")[1] == "help":
bot.msg("Assuming you want help with status codes. 1 is Available, 2 is Busy, 3 is Unavailable, anything else is Unknown.", chan) bot.msg(
"Assuming you want help with status codes. 1 is Available, 2 is Busy, 3 is Unavailable, anything else is Unknown.",
chan,
)
return return
message = message.split(' ', 1)[1] message = message.split(" ", 1)[1]
user = message.split(' ')[0].lower() user = message.split(" ")[0].lower()
stat = int(message.split(' ')[1]) stat = int(message.split(" ")[1])
reas = message.split(' ', 2)[2] reas = message.split(" ", 2)[2]
except IndexError: except IndexError:
bot.msg(f"Insufficent information to set a status. Only got {len(message.split(' ')) - (1 if '.sS' in message else 0)}/3 expected args.", chan) bot.msg(
f"Insufficent information to set a status. Only got {len(message.split(' ')) - (1 if '.sS' in message else 0)}/3 expected args.",
chan,
)
return return
except ValueError: except ValueError:
bot.msg("Status parameter must be an int.", chan) bot.msg("Status parameter must be an int.", chan)
@ -259,28 +265,31 @@ def setStatus(bot: bare.bot, chan: str, name: str, message: str) -> None:
case _: case _:
stat = "Unknown" stat = "Unknown"
if user in ["me", "my", "I"]: if user in ["me", "my", "I"]:
user = 'firepup' user = "firepup"
bot.statuses[user] = {'status': stat, 'reason': reas} bot.statuses[user] = {"status": stat, "reason": reas}
bot.msg(f"Status set for '{user}'. Raw data: {bot.statuses[user]}", chan) bot.msg(f"Status set for '{user}'. Raw data: {bot.statuses[user]}", chan)
def getStatus(bot: bare.bot, chan: str, name: str, message: str) -> None: def getStatus(bot: bare.bot, chan: str, name: str, message: str) -> None:
user = '' user = ""
try: try:
user = message.split(' ')[1] user = message.split(" ")[1]
except IndexError: except IndexError:
user = 'firepup' user = "firepup"
if bot.statuses.get(user) is None: if bot.statuses.get(user) is None:
bot.msg("You've gotta provide a nick I actually recognize.", chan) bot.msg("You've gotta provide a nick I actually recognize.", chan)
return return
bot.msg(f"{user}'s status: {'Unknown' if not bot.statuses[user].get('status') else bot.statuses[user]['status']} - {'Reason unset' if not bot.statuses[user].get('reason') else bot.statuses[user]['reason']}", chan) bot.msg(
f"{user}'s status: {'Unknown' if not bot.statuses[user].get('status') else bot.statuses[user]['status']} - {'Reason unset' if not bot.statuses[user].get('reason') else bot.statuses[user]['reason']}",
chan,
)
def check(bot: bare.bot, chan: str, name: str, message: str) -> None: def check(bot: bare.bot, chan: str, name: str, message: str) -> None:
try: try:
msg = message.split(' ', 1)[1] msg = message.split(" ", 1)[1]
nick = msg.split('!')[0] nick = msg.split("!")[0]
host = msg.split('@', 1)[1] host = msg.split("@", 1)[1]
dnsbl, raws = conf.dnsblHandler(bot, nick, host, chan) dnsbl, raws = conf.dnsblHandler(bot, nick, host, chan)
bot.msg(f"Blacklist check: {dnsbl if dnsbl else 'Safe.'} ({raws})", chan) bot.msg(f"Blacklist check: {dnsbl if dnsbl else 'Safe.'} ({raws})", chan)
except Exception as E: except Exception as E:
@ -301,7 +310,11 @@ data: dict[str, dict[str, Any]] = {
"uptime": {"prefix": True, "aliases": []}, "uptime": {"prefix": True, "aliases": []},
"raw": {"prefix": True, "aliases": ["cmd "], "check": checks.admin}, "raw": {"prefix": True, "aliases": ["cmd "], "check": checks.admin},
"debug": {"prefix": True, "aliases": ["dbg", "d"], "check": checks.admin}, "debug": {"prefix": True, "aliases": ["dbg", "d"], "check": checks.admin},
"debugInternal": {"prefix": True, "aliases": ["dbgInt", "dI"], "check": checks.admin}, "debugInternal": {
"prefix": True,
"aliases": ["dbgInt", "dI"],
"check": checks.admin,
},
"debugEval": {"prefix": True, "aliases": ["dbgEval", "dE"], "check": checks.admin}, "debugEval": {"prefix": True, "aliases": ["dbgEval", "dE"], "check": checks.admin},
"8ball": {"prefix": True, "aliases": ["eightball", "8b"]}, "8ball": {"prefix": True, "aliases": ["eightball", "8b"]},
"join": {"prefix": True, "aliases": ["j"], "check": checks.admin}, "join": {"prefix": True, "aliases": ["j"], "check": checks.admin},

View file

@ -6,25 +6,27 @@ from typing import Optional, Any, Union
import bare, pylast import bare, pylast
from pydnsbl import DNSBLIpChecker, DNSBLDomainChecker, providers as BL from pydnsbl import DNSBLIpChecker, DNSBLDomainChecker, providers as BL
class droneBL(BL.Provider): class droneBL(BL.Provider):
def process_response(self, response): def process_response(self, response):
reasons = set() reasons = set()
for result in response: for result in response:
reason = result.host reason = result.host
if reason in ['127.0.0.3']: if reason in ["127.0.0.3"]:
reasons.add('IRC Spambot') reasons.add("IRC Spambot")
elif reason in ['127.0.0.19']: elif reason in ["127.0.0.19"]:
reasons.add('Abused VPN') reasons.add("Abused VPN")
elif reason in ['127.0.0.9', '127.0.0.8']: elif reason in ["127.0.0.9", "127.0.0.8"]:
reasons.add('Open Proxy') reasons.add("Open Proxy")
elif reason in ['127.0.0.13']: elif reason in ["127.0.0.13"]:
reasons.add('Automated Attacks') reasons.add("Automated Attacks")
else: else:
print('Unknown dnsbl reason: ' + reason, flush=True) print("Unknown dnsbl reason: " + reason, flush=True)
reasons.add('unknown') reasons.add("unknown")
return reasons return reasons
providers = BL.BASE_PROVIDERS + [droneBL('dnsbl.dronebl.org')]
providers = BL.BASE_PROVIDERS + [droneBL("dnsbl.dronebl.org")]
ipbl = DNSBLIpChecker(providers=providers) ipbl = DNSBLIpChecker(providers=providers)
hsbl = DNSBLDomainChecker(providers=providers) hsbl = DNSBLDomainChecker(providers=providers)
@ -44,7 +46,7 @@ servers: dict[str, dict[str, Any]] = {
"channels": {"#random": 0, "#dice": 0, "#offtopic": 0, "#main/replirc": 0}, "channels": {"#random": 0, "#dice": 0, "#offtopic": 0, "#main/replirc": 0},
"ignores": ["#main/replirc"], "ignores": ["#main/replirc"],
"hosts": ["9pfs.repl.co"], "hosts": ["9pfs.repl.co"],
"dnsblMode": "kickban" "dnsblMode": "kickban",
}, },
"efnet": { "efnet": {
"address": "irc.underworld.no", "address": "irc.underworld.no",
@ -126,8 +128,9 @@ def decode_escapes(s: str) -> str:
def cmdFind(message: str, find: list, usePrefix: bool = True) -> bool: def cmdFind(message: str, find: list, usePrefix: bool = True) -> bool:
cmd = None cmd = None
try: try:
cmd = message.split(' ', 1)[0] cmd = message.split(" ", 1)[0]
except IndexError: ... except IndexError:
...
if not cmd: if not cmd:
return False return False
if usePrefix: if usePrefix:
@ -136,7 +139,6 @@ def cmdFind(message: str, find: list, usePrefix: bool = True) -> bool:
return any(cmd == match for match in find) return any(cmd == match for match in find)
def mfind(message: str, find: list, usePrefix: bool = True) -> bool: def mfind(message: str, find: list, usePrefix: bool = True) -> bool:
if usePrefix: if usePrefix:
return any(message[: len(match) + 1] == prefix + match for match in find) return any(message[: len(match) + 1] == prefix + match for match in find)
@ -172,34 +174,53 @@ def dnsbl(hostname: str) -> tuple[str, dict[str, list[str]]]:
if hstDT[host] != ["unknown"]: if hstDT[host] != ["unknown"]:
hosts.append(host) hosts.append(host)
if not hosts: if not hosts:
return "", hstDT return "", hstDT
hostStr = None hostStr = None
if len(hosts) >= 3: if len(hosts) >= 3:
hostStr = ', and '.join((', '.join(hosts)).rsplit(", ", 1)) hostStr = ", and ".join((", ".join(hosts)).rsplit(", ", 1))
else: else:
hostStr = ' and '.join(hosts) hostStr = " and ".join(hosts)
return hostStr, hstDT return hostStr, hstDT
def dnsblHandler(bot: bare.bot, nick: str, hostname: str, chan: str) -> tuple[str, dict[str, list[str]]]:
dnsblStatus = 'Not enabled' def dnsblHandler(
bot: bare.bot, nick: str, hostname: str, chan: str
) -> tuple[str, dict[str, list[str]]]:
dnsblStatus = "Not enabled"
dnsblResps = {} dnsblResps = {}
if bot.dnsblMode != "none": if bot.dnsblMode != "none":
dnsblStatus, dnsblResps = dnsbl(hostname) dnsblStatus, dnsblResps = dnsbl(hostname)
if dnsblStatus: if dnsblStatus:
match bot.dnsblMode: match bot.dnsblMode:
case "kickban": case "kickban":
bot.sendraw(f"KICK #{chan} {nick} :Sorry, but you're on the {dnsblStatus} blacklist(s).") bot.sendraw(
f"KICK #{chan} {nick} :Sorry, but you're on the {dnsblStatus} blacklist(s)."
)
bot.sendraw(f"MODE #{chan} +b *!*@{hostname}") bot.sendraw(f"MODE #{chan} +b *!*@{hostname}")
case "akill": case "akill":
bot.sendraw(f"OS AKILL ADD *@{hostname} !P Sorry, but you're on the {dnsblStatus} blacklist(s).") bot.sendraw(
f"OS AKILL ADD *@{hostname} !P Sorry, but you're on the {dnsblStatus} blacklist(s)."
)
case "kline": case "kline":
bot.sendraw(f"KILL {nick} :Sorry, but you're on the {dnsblStatus} blacklist(s).") bot.sendraw(
bot.sendraw(f"KLINE 524160 *@{hostname} :Sorry, but you're on the {dnsblStatus} blacklist(s).") f"KILL {nick} :Sorry, but you're on the {dnsblStatus} blacklist(s)."
bot.sendraw(f"KLINE *@{hostname} :Sorry, but you're on the {dnsblStatus} blacklist(s).") )
bot.sendraw(
f"KLINE 524160 *@{hostname} :Sorry, but you're on the {dnsblStatus} blacklist(s)."
)
bot.sendraw(
f"KLINE *@{hostname} :Sorry, but you're on the {dnsblStatus} blacklist(s)."
)
case "gline": case "gline":
bot.sendraw(f"KILL {nick} :Sorry, but you're on the {dnsblStatus} blacklist(s).") bot.sendraw(
bot.sendraw(f"GLINE *@{hostname} 524160 :Sorry, but you're on the {dnsblStatus} blacklist(s).") f"KILL {nick} :Sorry, but you're on the {dnsblStatus} blacklist(s)."
bot.sendraw(f"GLINE *@{hostname} :Sorry, but you're on the {dnsblStatus} blacklist(s).") )
bot.sendraw(
f"GLINE *@{hostname} 524160 :Sorry, but you're on the {dnsblStatus} blacklist(s)."
)
bot.sendraw(
f"GLINE *@{hostname} :Sorry, but you're on the {dnsblStatus} blacklist(s)."
)
case _: case _:
bot.log(f'Unknown dnsbl Mode "{bot.dnsblMode}"!', "WARN") bot.log(f'Unknown dnsbl Mode "{bot.dnsblMode}"!', "WARN")
return dnsblStatus, dnsblResps return dnsblStatus, dnsblResps

View file

@ -117,15 +117,21 @@ def PRIVMSG(bot: bare.bot, msg: str) -> Union[tuple[None, None], tuple[str, str]
Err = format_exc() Err = format_exc()
for line in Err.split("\n"): for line in Err.split("\n"):
bot.log(line, "ERROR") bot.log(line, "ERROR")
bot.msg("Sorry, I had an error trying to execute that command. Please check error logs.", chan) bot.msg(
"Sorry, I had an error trying to execute that command. Please check error logs.",
chan,
)
else: else:
try: try:
cmds.call[cmd](bot, chan, name, message) cmds.call[cmd](bot, chan, name, message)
except Exception: except Exception:
Err = format_exc() Err = format_exc()
for line in Err.split("\n"): for line in Err.split("\n"):
bot.log(line, "ERROR") bot.log(line, "ERROR")
bot.msg("Sorry, I had an error trying to execute that command. Please check error logs.", chan) bot.msg(
"Sorry, I had an error trying to execute that command. Please check error logs.",
chan,
)
handled = True handled = True
break break
if not handled: if not handled:
@ -213,7 +219,8 @@ def MODE(bot: bare.bot, msg: str) -> tuple[None, None]:
users = "" users = ""
try: try:
users = msg.split("#", 1)[1].split(" ", 2)[2].split() users = msg.split("#", 1)[1].split(" ", 2)[2].split()
except IndexError: ... except IndexError:
...
if len(modes) != len(users): if len(modes) != len(users):
bot.log("Refusing to handle modes that do not have corresponding users.") bot.log("Refusing to handle modes that do not have corresponding users.")
return None, None return None, None