Compare commits

...

2 commits

Author SHA1 Message Date
6940a194d0 Add global error handling for commands 2022-06-12 12:34:26 +02:00
83b7f55399 Reimplement XKCD Title lookup 2022-06-12 12:31:51 +02:00
2 changed files with 38 additions and 10 deletions

View file

@ -23,7 +23,7 @@
"help": "{prefix}help (command): Get information on commands",
"ping": "{prefix}ping {Host}: Ping the selfbot (or any host)",
"roll": "{prefix}roll (Number): Roll a dice (with number sides)",
"xkcd": "{prefix}xkcd (Number): Get an XKCD comic",
"xkcd": "{prefix}xkcd (Number/Title): Get an XKCD comic",
"shrug": "{prefix}shrug {text}: Append ¯\\_(ツ)_/¯ to the text",
"emoji_size": "{prefix}emoji_size {size}: Set the default emoji size",
"emoji_list": "{prefix}emoji_list: Get a list of usable custom emojis"

46
main.py
View file

@ -55,6 +55,14 @@ client = None
ratelimits = {}
# Common function definitions
# Filter a title for local lookup with XKCD
def filter_xkcd_title(title):
filtered_title = ""
for char in title.lower().split("(")[0]:
if (char.isdecimal() or char.isalpha()) and (not char == " "):
filtered_title += char
return filtered_title
# Grab a list of all emojis on disk
def list_emojis():
global settings
@ -221,15 +229,29 @@ async def xkcd(args, room, event):
comic = ""
if len(args) == 1 and args[0].isdecimal():
comic = args[0] + "/"
try:
r = requests.get(f"https://xkcd.com/{comic}info.0.json")
elif len(args) > 0:
lookup = {}
r = requests.get("https://xkcd.com/archive/")
for line in r.text.split("\n"):
if "<a href=\"" in line and "\" title=\"2" in line:
num = line.split("/")[1]
title = filter_xkcd_title(line.split(">")[1].split("<")[0])
lookup[title] = num
user_title = filter_xkcd_title(" ".join(args))
if user_title in lookup.keys():
comic = lookup[user_title] + "/"
r = requests.get(f"https://xkcd.com/{comic}info.0.json")
if settings["debug"]:
rj = json.loads(r.text)
filename = download_file(rj["img"], settings["cache_path"] + "/" + str(rj["num"]) + "." + rj["img"].split(".")[-1])
image = await send_file(filename)
await send_text(room.room_id, f"{rj['year']}/{rj['month']}/{rj['day']}, {str(rj['num'])}: <a href=\"https://xkcd.com/{str(rj['num'])}/\">{rj['safe_title']}</a>")
return await send_image(room.room_id, image, rj['alt'])
except Exception:
return await send_text(room.room_id, "Failed to get XKCD!")
else:
try:
rj = json.loads(r.text)
except Exception:
return await send_text(room.room_id, "Failed to get XKCD!")
filename = download_file(rj["img"], settings["cache_path"] + "/" + str(rj["num"]) + "." + rj["img"].split(".")[-1])
image = await send_file(filename)
await send_text(room.room_id, f"{rj['year']}/{rj['month']}/{rj['day']}, {str(rj['num'])}: <a href=\"https://xkcd.com/{str(rj['num'])}/\">{rj['safe_title']}</a>")
return await send_image(room.room_id, image, rj['alt'])
async def message_callback(room: nio.MatrixRoom, event: nio.RoomMessageText) -> None:
global client, settings, emojis
@ -250,7 +272,13 @@ async def message_callback(room: nio.MatrixRoom, event: nio.RoomMessageText) ->
ratelimits[event.sender] = int(datetime.datetime.utcnow().timestamp()) + settings["ratelimit"]
if command in settings["command_list"] or (admin and command in settings["admin_command_list"]):
command_function = globals()[command]
await command_function(args, room, event)
if debug:
await command_function(args, room, event)
else:
try:
await command_function(args, room, event)
except Exception:
await send_text(room.room_id, "Something went wrong processing the command!")
return
if admin:
# If it is not a command, process regular message parsing.