Several Changes

Remove XKCD lookup by title
Fix edits losing formatting
Fix edited replies
Generate help without args message
Remove poll command
Change Source URL to gitea instance
This commit is contained in:
deadcade 2022-06-12 06:01:49 +02:00
parent 0b6dc050e3
commit e3ac2c9006
2 changed files with 25 additions and 76 deletions

View file

@ -17,18 +17,16 @@
"ping",
"roll",
"xkcd",
"poll",
"help"
],
"help_messages": {
"help": "Admin commands:\n{prefix}shrug: Append shrug to the message\n{prefix}emoji_size {size}: Set default emoji size\n{prefix}emoji_list: Get a list of usable custom emojis\nUser commands:\n{prefix}ping: Ping the selfbot (or as admin, any host)\n{prefix}roll: Roll a dice, provide a number to select dice sides\n{prefix}xkcd: Get an XKCD comic\n{prefix}poll: Create a poll\n{prefix}help: Get information on commands\n\nArguments: (optional) [required] {admin only, optional} {[admin only, required]}\nDo {prefix}help (command) to see command help.",
"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/Title): Get an XKCD comic",
"xkcd": "{prefix}xkcd (Number): 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",
"poll": "{prefix}poll \"[Question]\" \"[Answer 1]\" \"[Answer 2]\" \"(Answer 3+)\": Create a poll"
"emoji_list": "{prefix}emoji_list: Get a list of usable custom emojis"
},
"source_url": "https://github.com/0xDEADCADE/Matrix-Selfbot"
"source_url": "https://g.deadca.de/deadcade/Matrix-Selfbot"
}

79
main.py
View file

@ -55,14 +55,6 @@ 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
@ -133,6 +125,7 @@ async def edit_message_unformatted(room_id, original_event, text):
# Edits a message (with HTML formatting)
async def edit_message(room_id, original_event, text):
global client
text = text.split("</mx-reply>")[-1]
unformatted, formatted = text, text
unformatted = "".join([part.split(">")[-1] for part in unformatted.split("<")])
unformatted = html.unescape(unformatted)
@ -153,10 +146,6 @@ async def send_text(room_id, text):
formatted = formatted.replace("\n", "<br>")
return await client.room_send(room_id=room_id, message_type="m.room.message", content={"msgtype": "m.text", "body": unformatted + " (SelfBot)", "format": "org.matrix.custom.html", "formatted_body": formatted + (f" (<a href=\"{settings['source_url']}\">SelfBot</a>)" if settings["source_url"] else " (SelfBot)")}, ignore_unverified_devices=True)
# Send a reaction
async def send_reaction(room_id, event_id, emoji):
return await client.room_send(room_id=room_id, message_type="m.reaction", content={"m.relates_to": {"rel_type": "m.annotation", "event_id": event_id, "key": emoji}}, ignore_unverified_devices=True)
# Commands definition
# Appends shrug to the end of the message
async def shrug(args, room, event):
@ -171,7 +160,14 @@ async def help(args, room, event):
if len(args) == 0:
# No command specified, send command list
source_text = f"\n<a href=\"{settings['source_url']}\">Source Code</a>" if settings["source_url"] else ""
return await send_text(room.room_id, settings["help_messages"]["help"].replace("{prefix}", settings["prefix"]) + source_text)
helptext = "Admin Commands:\n"
for command in settings["admin_command_list"].keys():
helptext += settings["help_messages"][command] + "\n"
helptext += "\nUser Commands:\n"
for command in settings["command_list"].keys():
helptext += settings["help_messages"][command] + "\n"
helptext += "\n\nArguments: (optional) [required] {admin only, optional}"
return await send_text(room.room_id, helptext.replace("{prefix}", settings["prefix"]) + source_text)
else:
help_command = args[0].lower().split(settings["prefix"])[-1]
if help_command in settings["help_messages"].keys():
@ -225,63 +221,15 @@ async def xkcd(args, room, event):
comic = ""
if len(args) == 1 and args[0].isdecimal():
comic = args[0] + "/"
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)
else:
try:
r = requests.get(f"https://xkcd.com/{comic}info.0.json")
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'])
# Create a poll
async def poll(args, room, event):
parsed_args = []
base_offset_emoji = 127462
for arg in args:
if arg.startswith('"'):
if arg.endswith('"'):
parsed_args.append(arg[1:][:-1])
else:
parsed_args.append(arg[1:])
elif arg.endswith('"'):
parsed_args[-1] += " " + arg[:-1]
else:
parsed_args[-1] += " " + arg
if len(parsed_args) < 3:
return await send_text(room.room_id, "Please provide at least 2 options")
question = parsed_args[0]
options = parsed_args[1:]
message = f"Poll:\n{question}\n"
for n, option in enumerate(options):
message += chr(base_offset_emoji + n) + ": " + option + "\n"
if option.lower() == "yes":
message = message.replace(chr(base_offset_emoji + n), chr(9989))
elif option.lower() == "no":
message = message.replace(chr(base_offset_emoji + n), chr(10060))
poll_message = await send_text(room.room_id, message)
for n, option in enumerate(options):
reaction_emoji = chr(base_offset_emoji + n)
if option.lower() == "yes":
reaction_emoji = chr(9989)
elif option.lower() == "no":
reaction_emoji = chr(10060)
await send_reaction(room.room_id, poll_message.event_id, reaction_emoji)
except Exception:
return await send_text(room.room_id, "Failed to get XKCD!")
async def message_callback(room: nio.MatrixRoom, event: nio.RoomMessageText) -> None:
global client, settings, emojis
@ -306,6 +254,9 @@ async def message_callback(room: nio.MatrixRoom, event: nio.RoomMessageText) ->
return
if admin:
# If it is not a command, process regular message parsing.
if event.formatted_body:
new_body, orig_body = event.formatted_body, event.formatted_body
else:
new_body, orig_body = event.body, event.body
# Emoji processor
if event.body.count(":") > 1: # Reduce searching by a significant margin