# Colors BLACK = '\033[30m' RED = '\033[31m' GREEN = '\033[32m' YELLOW = '\033[33m' # orange on some systems BLUE = '\033[34m' MAGENTA = '\033[35m' CYAN = '\033[36m' LIGHT_GRAY = '\033[37m' DARK_GRAY = '\033[90m' BRIGHT_RED = '\033[91m' BRIGHT_GREEN = '\033[92m' BRIGHT_YELLOW = '\033[93m' BRIGHT_BLUE = '\033[94m' BRIGHT_MAGENTA = '\033[95m' BRIGHT_CYAN = '\033[96m' WHITE = '\033[97m' RESET = '\033[0m' print("[" + BLUE + "..." + RESET + "] Importing Guilded.py...") import guilded print("[" + BLUE + "..." + RESET + "] Importing System modules...") import traceback from time import sleep from requests import get from random import randint, choice import os import sys print("[" + BLUE + "..." + RESET + "] Importing Platform & distro...") import platform import distro print("[" + BLUE + "..." + RESET + "] Importing DuckDuckGo search...") from duckduckgo_search import DDGS import subprocess import nmap import re client = guilded.Client() # Help document documentation = """$help - Shows this message. $ping - Test if bot is online. $version - Get version of SweeBot and the system it's running on $whoami - Gets your user ID $perms - Gets your permissions $search - Preform a websearch via DuckDuckGo """ meows = ['Meow!', 'Nyaa~', 'Mrow.', 'Prr! :3', 'Hiss!', "Mrrp?", "Mreow.", "!woeM", "3: !rrP", "!ssiH", "~aayN", "Mew!", "Moew!"] version = "0.0.1 (rollback)" # user permissions def getperms(userID): if not os.path.isfile(str(userID)): open(str(userID),'w').write("") return [] else: if open(str(userID)).read().replace("\n", "").split(",") == ['']: return [] return open(str(userID)).read().replace("\n", "").split(",") class SweeBotTestException(Exception): pass class SweeBotSystemException(Exception): pass # Client itself @client.event async def on_ready(): print('[' + GREEN + 'OK' + RESET + '] Ready') @client.event async def on_message(message): if message.author.name != client.user.name: if message.content == "": return print(YELLOW + "<"+message.author.name if message.author != None else "Gil" +" ("+message.channel.name+"@"+message.server.name+ " {" + message.server.id +"})> "+RESET+message.content) if message.author.name == client.user.name or message.author.bot: return elif message.content[0] == "$": try: command=message.content[1:].split(" ") if command[0] == "help": await message.reply(embed=guilded.Embed(title=":sweebot-success: SweeBot usage:",description=documentation)) print("[" + GREEN + "OK" + RESET + "] '$help' executed successfully.") elif command[0] == "ping": if randint(0,2) == 1: print("[" + MAGENTA + "DBG" + RESET + "] Pnog easter egg.") mess = await message.reply(embed=guilded.Embed(title=":sweebot-success: Command complete.",description="Pnog.")) else: mess = await message.reply(embed=guilded.Embed(title=":sweebot-success: Command complete.",description="Pong.")) print("[" + GREEN + "OK" + RESET + "] '$ping' executed successfully.") elif command[0] == "version": if platform.system() == "Windows": print("[" + MAGENTA + "DBG" + RESET + "] Host runs Windows.") mess = await message.reply(embed=guilded.Embed(title=":sweebot: for :guilded: " + version +" running on:",description=":desktop_computer: " + platform.node() + "\n:sweedows: " + platform.system() + " " + platform.release() + " Version " + platform.version() + "\n:guilded: Guilded.py version " + guilded.__version__ + "\n:gear: Python " + sys.version.split(" ")[0])) else: print("[" + MAGENTA + "DBG" + RESET + "] Host runs Linux.") if "ubuntu" in distro.name().lower(): emoticon = ":ubuntu:" elif "debian" in distro.name().lower(): emoticon = ":debian:" else: emoticon = ":tux-linux:" mess = await message.reply(embed=guilded.Embed(title=":sweebot: for :guilded: " + version +" running on:",description=":desktop_computer: " + platform.node() + "\n" + emoticon + " " + distro.name(pretty=True) + "\n:guilded: Guilded.py version " + guilded.__version__ + "\n:gear: Python " + sys.version.split(" ")[0])) print("[" + GREEN + "OK" + RESET + "] '$version' executed successfully.") elif command[0] == "restart": if "restart" in getperms(message.author.id) or "full" in getperms(message.author.id): mess = await message.reply(embed=guilded.Embed(title=":sweebot-success: Command complete.",description="Restarting bot...")) print("[" + BLUE + "..." + RESET + "] Restarting script... (initiated by " + message.author.name + ")") if os.path.isfile("/home/swee/.config/systemd/user/guild.service"): os.system("systemctl --user restart guild.service") else: subprocess.Popen(["py"] + sys.argv) exit() else: mess = await message.reply(embed=guilded.Embed(title=":sweebot-fail: Permission denied.")) print("[" + RED + "FAIL" + RESET + "] Not restarting script, Permission Denied for " + message.author.name) elif command[0] == "shell": if "full" in getperms(message.author.id): mess = await message.reply("```No output (yet)```") print("[" + BLUE + "..." + RESET + "] Running shell... (initiated by " + message.author.name + ")") sleep(1) p = subprocess.Popen(command[1:], stdout=subprocess.PIPE, stderr=subprocess.STDOUT) output = "" for line in iter(p.stdout.readline, b''): output+=line.decode() await mess.edit("```\n" + output +"```") p.stdout.close() p.wait() await mess.edit("```\n" + output +"```\n\n**Finished.**") else: mess = await message.reply(embed=guilded.Embed(title=":sweebot-fail: Permission denied.")) print("[" + RED + "FAIL" + RESET + "] Not restarting script, Permission Denied for " + message.author.name) elif command[0] == "pull": if "full" in getperms(message.author.id): mess = await message.reply(embed=guilded.Embed(title=":sweebot-loading: Pulling from Git...", description="```[Starting, please stand by...]```")) print("[" + BLUE + "..." + RESET + "] Pulling from git... (initiated by " + message.author.name + ")") sleep(1) p = subprocess.Popen("/home/swee/update-sb4g.sh", stdout=subprocess.PIPE, stderr=subprocess.STDOUT) output = "" for line in iter(p.stdout.readline, b''): output+=line.decode() await mess.edit(embed=guilded.Embed(title=":sweebot-loading: Pulling from Git...", description="```\n" + output + "```")) p.stdout.close() p.wait() await mess.edit(embed=guilded.Embed(title=":sweebot-success: Done, restarting bot...", description="```\n" + output + "```")) else: mess = await message.reply(embed=guilded.Embed(title=":sweebot-fail: Permission denied.")) print("[" + RED + "FAIL" + RESET + "] Not restarting script, Permission Denied for " + message.author.name) #elif command[0] == "spammy-shell": # if "full" in getperms(message.author.id): # mess = await message.reply("```No output (yet)```") # print("[" + BLUE + "..." + RESET + "] Running shell... (initiated by " + message.author.name + ")") # sleep(1) # p = subprocess.Popen(command[1:], stdout=subprocess.PIPE, stderr=subprocess.STDOUT) # output = "" # first = True # for line in iter(p.stdout.readline, b''): # if first: # await mess.edit("```" + line.decode().rstrip() +"```") # first = False # else: # await message.channel.send("```" + line.decode().rstrip() +"```") # p.stdout.close() # p.wait() # await message.channel.send("**Finished.**") # else: # mess = await message.reply(embed=guilded.Embed(title=":sweebot-fail: Permission denied.")) # print("[" + RED + "FAIL" + RESET + "] Not restarting script, Permission Denied for " + message.author.name) elif command[0] == "whoami": if getperms(message.author.id) != []: mess = await message.reply(embed=guilded.Embed(title=":sweebot-success: Command complete.",description=":gear: UserID: "+str(message.author.id)+"\n:warning: Your User ID has permissions, use `$perms` to see")) else: mess = await message.reply(embed=guilded.Embed(title=":sweebot-success: Command complete.",description=":gear: UserID: "+str(message.author.id))) print("[" + GREEN + "OK" + RESET + "] '$whoami' executed successfully.") elif command[0] == "perms": if getperms(message.author.id) != []: mess = await message.reply(embed=guilded.Embed(title=":sweebot-success: Command complete.",description="`"+",".join(getperms(message.author.id))+"`")) else: mess = await message.reply(embed=guilded.Embed(title=":sweebot-success: Command complete.",description=":question: No permissions")) print("[" + GREEN + "OK" + RESET + "] '$perms' executed successfully.") elif command[0] == "meow": mess = await message.reply(embed=guilded.Embed(title=choice(meows))) print("[" + GREEN + "OK" + RESET + "] '$meow' executed successfully.") elif command[0] == "figlet": result = subprocess.run(["figlet"] + command[1:], stdout=subprocess.PIPE, stderr=subprocess.PIPE) output = (result.stdout.decode('utf-8')+result.stderr.decode('utf-8')) mess = await message.reply("```\n" + output + "\n```") print("[" + GREEN + "OK" + RESET + "] '$figlet' executed successfully.") elif command[0] == "nmap": if len(command) == 2: result = subprocess.run(["nmap", "--noninteractive", command[1]], stdout=subprocess.PIPE, stderr=subprocess.STDOUT) output = result.stdout.decode('utf-8') ports = [] if output.split("\n")[1][:6] == "Failed": mess = await message.reply(embed=guilded.Embed(title=":sweebot-fail: Command Failed!",description="Nmap failed to resolve the domain!")) else: ending = False for i, j in enumerate(output.split("\n")): if not ending: if j[:4] == "PORT": ending = True pass else: temp = (re.sub(' +', ' ', j)).split(" ") print(temp) if j != "": ports.append(("🟢 " if temp[1] == "open" else "🔴 ") + temp[0] + " (" + temp[2] + ")") else: break mess = await message.reply(embed=guilded.Embed(title=":sweebot-success: Found " + str(len(ports)) +" ports",description="\n".join(ports))) print("[" + GREEN + "OK" + RESET + "] '$nmap' executed successfully.") else: mess = await message.reply(embed=guilded.Embed(title=":sweebot-fail: Invalid arguments",description="Only 1 argument is allowed: $nmap [hostname/IP]")) elif command[0] == "error": raise SweeBotTestException("Test Error for SweeBot") elif command[0] == "search": request = [] while request == []: request = DDGS().text(" ".join(command[1:])) result = [] print(request) for i in request: if len(result) != 3: result.append("") h = len(result) - 1 result[h] += "[" + i['title'] + '](' + i['href'] + ")\n\n" result[h] += "" + i['href'] result[h] += "\n\n" + i['body'] + "\n\n" else: break result.append("Please check out [UnnamedSearchEngine](https://swee.pythonanywhere.com/use) btw, it's a very lightweight and private search engine.") print(result) embeds = [] for i in result: embeds.append(guilded.Embed(description=i)) await message.reply("Search results:" ,embed=guilded.Embed(description="\n".join(result))) print("[" + GREEN + "OK" + RESET + "] '$search' executed successfully.") else: mess = await message.reply(embed=guilded.Embed(title=":sweebot-unknown: Command not found.")) except Exception as ex: mess = await message.reply(embed=guilded.Embed(title=":sweebot-fail: Command failed!",description=traceback.format_exc())) print("[" + RED + "FAIL" + RESET + "] Command failed, check chat for traceback.") else: print("[" + MAGENTA + "DBG" + RESET + "] No triggers in message, ignoring...") print("[" + BLUE + "..." + RESET + "] Now running the bot...") try: client.run(os.environ["SBtoken"]) except: print("[ERR] Client failed to run")