From c0cc81dd7c80d2a78eaab102c366ec312b4777da Mon Sep 17 00:00:00 2001 From: Little Monkey <106759534+PlaceReporter99@users.noreply.github.com> Date: Tue, 3 Sep 2024 15:11:19 +0100 Subject: [PATCH] So I'm thinking we can do this to handle connection issues --- main.py | 407 ++++++++++++++++++++++++++++---------------------------- 1 file changed, 206 insertions(+), 201 deletions(-) diff --git a/main.py b/main.py index c4381da..becd91a 100644 --- a/main.py +++ b/main.py @@ -41,8 +41,8 @@ def page(): main_ = __name__ == "__main__" -def onn(room): - room.on(Events.MESSAGE, roomer(room)) +def onn(room, bot): + room.on(Events.MESSAGE, roomer(room, bot)) def indent(text): @@ -98,230 +98,235 @@ def f(*args, **kwargs): return default return f -def roomer(r): +def roomer(r, bot): def msg(event): - rid = r.roomID - nofish = [146039] - if (result := re.match( - r"🐟 (.*)'s line quivers\.<\/i>", - html.unescape(event.content), - re.UNICODE, - )) and event.user_id == 375672: - if result.group(1) == "Utility Bot" and rid not in nofish: - r.send("/fish again") - else: - settingr = dataread("settings", result.group(1), "fishping") - if settingr == None: - datawrite("settings", result.group(1), "fishping", False) - elif settingr: + try: + rid = r.roomID + nofish = [146039] + if (result := re.match( + r"🐟 (.*)'s line quivers\.<\/i>", + html.unescape(event.content), + re.UNICODE, + )) and event.user_id == 375672: + if result.group(1) == "Utility Bot" and rid not in nofish: + r.send("/fish again") + else: + settingr = dataread("settings", result.group(1), "fishping") + if settingr == None: + datawrite("settings", result.group(1), "fishping", False) + elif settingr: + r.send( + f"@{result.group(1).replace(' ', '')} your fish is ready!") + elif event.content[:5] == "echo ": + if event.user_id == 540406 or event.content[5:10] != "/fish": + r.send(html.unescape(event.content[5:])) + else: r.send( - f"@{result.group(1).replace(' ', '')} your fish is ready!") - elif event.content[:5] == "echo ": - if event.user_id == 540406 or event.content[5:10] != "/fish": - r.send(html.unescape(event.content[5:])) - else: - r.send( - r.buildReply(event.message_id, "Sorry, I cannot do that.")) - elif event.content[:8] == "echochr ": - r.send(html.unescape(chr(int(event.content[8:])))) - elif event.content[:5] == "calc ": - string = html.unescape(event.content[5:]) - r.send( - r.buildReply( - event.message_id, - "\n" + urlopen(f"https://safe-exec.onrender.com/{quote(string, safe='')}").read().decode("utf-8") - )) - elif event.content[:5] == "ping ": - r.send("@" + re.sub(" ", "", html.unescape(event.content[5:]))) - elif event.content[:10] == "remotesay ": - com = html.unescape(event.content[10:]) - li = com.partition(",") - if li[1] == "": - li = ("147516", ",", li[0]) - - if li[0] == "147571": + r.buildReply(event.message_id, "Sorry, I cannot do that.")) + elif event.content[:8] == "echochr ": + r.send(html.unescape(chr(int(event.content[8:])))) + elif event.content[:5] == "calc ": + string = html.unescape(event.content[5:]) r.send( - r.buildReply(event.message_id, - "Sorry, I'm afraid I can't do that.")) - else: - global g # skipcq: PYL-W0601 - g = bot.joinRoom(int(li[0])) - g.send(event.user_name + ": " + li[2]) - g.on(Events.MESSAGE, remote) - r.send(r.buildReply(event.message_id, "Message sent.")) - elif event.content == "getsource": - r.send( - r.buildReply( - event.message_id, - "https://github.com/SE-Utility-Bot/utility-bot/blob/main/main.py", - )) - elif event.content[:6] == "getcmd": - commands = { - "echo ": - " Sends the message given to it.", - "echochr ": - " Sends the unicode character with the codepoint of the number given to it. Must be in base 10.", - "calc ": - " Sends the answer to the given Python expression. Times out after 10 seconds.", - "ping ": - " Pings the person with the username that was passed to it.", - "remotesay , ": - " Sends a message in the specified room ID. If no room ID is given, the room defaults to Sandbox 2.", - "getsource": - " Sends a link to the source code.", - "getcmd ": - " Sends the command description. If no command is given, it lists the commands with their descriptions instead.", - "emptystring": - " Sends a picture of an empty string.", - "help": - " Shows some information.", - "op / status": - " Replies with a random message from statuses.txt. Exists to quickly check whether the bot is running.", - "webscrape ": - " Sends the HTML content of the specified URL.", - "random , , ": - " Sends the specified number of random numbers in the inclusive range (using secrets.choice). 1 argument uses the range 0 to 255, and 2 arguments uses the range 0 to . Maximum argument value is 1000 for and 9 * 10 ** 18 for all other arguments.", - "translate | | ": - " Translates from the language code in (automatically detects language if none is given) to the language code in (translates to English if none is given). See https://utility-bot.streamlit.app/Supported_translation_languages for supported languages and their language codes.", - "fishinv": - " Get's the bot's fishing inventory, with the fishing game being run by OakBot.", - "setting , ": - " Changes the specified setting to the specified boolean value", - - } - if len(event.content) > 6: - try: - r.send( - r.buildReply( - event.message_id, - "`" + (result := [ - x for x in commands if re.match( - event.content.partition(" ")[2], x) - ][0]) + "`: " + commands[result], - )) - except IndexError: + r.buildReply( + event.message_id, + "\n" + urlopen(f"https://safe-exec.onrender.com/{quote(string, safe='')}").read().decode("utf-8") + )) + elif event.content[:5] == "ping ": + r.send("@" + re.sub(" ", "", html.unescape(event.content[5:]))) + elif event.content[:10] == "remotesay ": + com = html.unescape(event.content[10:]) + li = com.partition(",") + if li[1] == "": + li = ("147516", ",", li[0]) + + if li[0] == "147571": r.send( r.buildReply(event.message_id, - "Command does not exist.")) - else: - r.send( - indent( - f"@{event.user_name.replace(' ', '')}\nHere are the available commands for this bot and their structures:\n\n" - + ("\n".join(f"{chr(8226)} {x}: {commands[x]}" - for x in commands)), )) - elif event.content == "emptystring": - r.send( - r.buildReply(event.message_id, - "https://i.stack.imgur.com/Fh2Cq.png")) - elif event.content == "help": - r.send( - r.buildReply( - event.message_id, - 'Type in "getcmd" (without the quotes) for a list of commands and their descriptions.\n\nRepo: https://github.com/SE-Utility-Bot/utility-bot\nWebsite: https://utility-bot.streamlit.app/\nCalculation Module: https://github.com/SE-Utility-Bot/safe-exec', - )) - elif event.content in ("op", "status"): - with open("status.txt") as f, open(__file__) as g: + "Sorry, I'm afraid I can't do that.")) + else: + global g # skipcq: PYL-W0601 + g = bot.joinRoom(int(li[0])) + g.send(event.user_name + ": " + li[2]) + g.on(Events.MESSAGE, remote) + r.send(r.buildReply(event.message_id, "Message sent.")) + elif event.content == "getsource": r.send( r.buildReply( event.message_id, - secrets.choice(f.read().split("\n")).replace("\\n", "\n").replace( - "[prog_rand]", - secrets.choice(g.read().split("\n"))), + "https://github.com/SE-Utility-Bot/utility-bot/blob/main/main.py", )) - elif event.content[:10] == "webscrape ": - try: + elif event.content[:6] == "getcmd": + commands = { + "echo ": + " Sends the message given to it.", + "echochr ": + " Sends the unicode character with the codepoint of the number given to it. Must be in base 10.", + "calc ": + " Sends the answer to the given Python expression. Times out after 10 seconds.", + "ping ": + " Pings the person with the username that was passed to it.", + "remotesay , ": + " Sends a message in the specified room ID. If no room ID is given, the room defaults to Sandbox 2.", + "getsource": + " Sends a link to the source code.", + "getcmd ": + " Sends the command description. If no command is given, it lists the commands with their descriptions instead.", + "emptystring": + " Sends a picture of an empty string.", + "help": + " Shows some information.", + "op / status": + " Replies with a random message from statuses.txt. Exists to quickly check whether the bot is running.", + "webscrape ": + " Sends the HTML content of the specified URL.", + "random , , ": + " Sends the specified number of random numbers in the inclusive range (using secrets.choice). 1 argument uses the range 0 to 255, and 2 arguments uses the range 0 to . Maximum argument value is 1000 for and 9 * 10 ** 18 for all other arguments.", + "translate | | ": + " Translates from the language code in (automatically detects language if none is given) to the language code in (translates to English if none is given). See https://utility-bot.streamlit.app/Supported_translation_languages for supported languages and their language codes.", + "fishinv": + " Get's the bot's fishing inventory, with the fishing game being run by OakBot.", + "setting , ": + " Changes the specified setting to the specified boolean value", + + } + if len(event.content) > 6: + try: + r.send( + r.buildReply( + event.message_id, + "`" + (result := [ + x for x in commands if re.match( + event.content.partition(" ")[2], x) + ][0]) + "`: " + commands[result], + )) + except IndexError: + r.send( + r.buildReply(event.message_id, + "Command does not exist.")) + else: + r.send( + indent( + f"@{event.user_name.replace(' ', '')}\nHere are the available commands for this bot and their structures:\n\n" + + ("\n".join(f"{chr(8226)} {x}: {commands[x]}" + for x in commands)), )) + elif event.content == "emptystring": r.send( - indent( - f"@{event.user_name.replace(' ', '')}" + - "\nHere is the source code of the HTML webpage:\n\n" + - urlopen(event.content[10:]).read().decode("utf-8"))) - except Exception as err: # skipcq: PYL-W0703 - r.send(r.buildReply(event.message_id, f"`{repr(err)}`")) - - elif event.content[:7] == "random ": - args = [int(x) for x in event.content[7:].split(",")] - if len(args) == 1: - args.append(0) - args.append(255) - elif len(args) == 2: - args.insert(1, 0) - if args[0] > 1000 or any(x > 9 * 10**18 for x in args): + r.buildReply(event.message_id, + "https://i.stack.imgur.com/Fh2Cq.png")) + elif event.content == "help": r.send( r.buildReply( event.message_id, - "Sorry, that will probably take me too long.")) - else: - numbers = [ - secrets.choice(range(args[1], args[2] + 1)) - for x in range(args[0]) + 'Type in "getcmd" (without the quotes) for a list of commands and their descriptions.\n\nRepo: https://github.com/SE-Utility-Bot/utility-bot\nWebsite: https://utility-bot.streamlit.app/\nCalculation Module: https://github.com/SE-Utility-Bot/safe-exec', + )) + elif event.content in ("op", "status"): + with open("status.txt") as f, open(__file__) as g: + r.send( + r.buildReply( + event.message_id, + secrets.choice(f.read().split("\n")).replace("\\n", "\n").replace( + "[prog_rand]", + secrets.choice(g.read().split("\n"))), + )) + elif event.content[:10] == "webscrape ": + try: + r.send( + indent( + f"@{event.user_name.replace(' ', '')}" + + "\nHere is the source code of the HTML webpage:\n\n" + + urlopen(event.content[10:]).read().decode("utf-8"))) + except Exception as err: # skipcq: PYL-W0703 + r.send(r.buildReply(event.message_id, f"`{repr(err)}`")) + + elif event.content[:7] == "random ": + args = [int(x) for x in event.content[7:].split(",")] + if len(args) == 1: + args.append(0) + args.append(255) + elif len(args) == 2: + args.insert(1, 0) + if args[0] > 1000 or any(x > 9 * 10**18 for x in args): + r.send( + r.buildReply( + event.message_id, + "Sorry, that will probably take me too long.")) + else: + numbers = [ + secrets.choice(range(args[1], args[2] + 1)) + for x in range(args[0]) + ] + r.send( + r.buildReply(event.message_id, + f"Here are your random numbers:\n{numbers}")) + elif event.content[:10] == "translate ": + arguments = [ + remove_space(x) + for x in html.unescape(event.content[10:]).split("|") ] + while len(arguments) < 3: + arguments.append("auto") r.send( - r.buildReply(event.message_id, - f"Here are your random numbers:\n{numbers}")) - elif event.content[:10] == "translate ": - arguments = [ - remove_space(x) - for x in html.unescape(event.content[10:]).split("|") - ] - while len(arguments) < 3: - arguments.append("auto") - r.send( - r.buildReply( - event.message_id, - GoogleTranslator(**dict( - zip( - ["target", "source"], - [ - a if (a := arguments[1]) != "auto" else "en", - arguments[2], - ], - ))).translate(arguments[0]), - )) - elif event.content == "fishinv": - r.send("/fish inv") - - elif event.content[:6] == "shell ": - if event.user_id == 540406: + r.buildReply( + event.message_id, + GoogleTranslator(**dict( + zip( + ["target", "source"], + [ + a if (a := arguments[1]) != "auto" else "en", + arguments[2], + ], + ))).translate(arguments[0]), + )) + elif event.content == "fishinv": + r.send("/fish inv") + + elif event.content[:6] == "shell ": + if event.user_id == 540406: + try: + output = subprocess.getoutput(event.content[6:]) + r.send(indent(r.buildReply(event.message_id, '\n' + output))) + except: + r.send(r.buildReply(event.message_id, "An error occured while executing the command.")) + else: + r.send(r.buildReply(event.message_id, "You don't have permission, sorry!")) + + elif event.content[:8] == "setting ": + setting, value = map(remove_space, event.content[8:].split(",")) + bool_settings = ["fishping"] + int_settings = [] + if setting in bool_settings: + value = tobool(value) + if value == None: + r.send(r.buildReply(event.message_id, "The provided value isn't a recognised boolean.")) + return + elif setting in int_settings: + value = errortodefault(int)(value) + if value == None: + r.send(r.buildReply(event.message_id, "The provided value isn't a recognised number.")) + return try: - output = subprocess.getoutput(event.content[6:]) - r.send(indent(r.buildReply(event.message_id, '\n' + output))) + datawrite("settings", event.user_name, setting, value) except: - r.send(r.buildReply(event.message_id, "An error occured while executing the command.")) - else: - r.send(r.buildReply(event.message_id, "You don't have permission, sorry!")) - - elif event.content[:8] == "setting ": - setting, value = map(remove_space, event.content[8:].split(",")) - bool_settings = ["fishping"] - int_settings = [] - if setting in bool_settings: - value = tobool(value) - if value == None: - r.send(r.buildReply(event.message_id, "The provided value isn't a recognised boolean.")) - return - elif setting in int_settings: - value = errortodefault(int)(value) - if value == None: - r.send(r.buildReply(event.message_id, "The provided value isn't a recognised number.")) - return - try: - datawrite("settings", event.user_name, setting, value) - except: - r.send(r.buildReply(event.message_id, "Setting could not be saved.")) - else: - r.send(r.buildReply(event.message_id, "Setting changed!")) + r.send(r.buildReply(event.message_id, "Setting could not be saved.")) + else: + r.send(r.buildReply(event.message_id, "Setting changed!")) + except ConnectionError: + bot.leaveAllRooms() + mainf() return msg - -if main_: +def mainf(): bot = sechat.Bot() bot.login(os.environ["BOT_EMAIL"], os.environ["BOT_PASSWORD"]) [r, baso, ubot] = map(bot.joinRoom, [1, 146039, 154629]) for room in [r, baso, ubot]: - onn(room) - + onn(room, bot) + +if main_: + mainf() try: app.run(host='0.0.0.0', port=5000) while True: