1
0
Fork 0
MeowNexGuilded/guild2.py
2024-09-11 16:37:51 -07:00

270 lines
No EOL
15 KiB
Python

# 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
from characterai import pycai
client = guilded.Client()
#C.AI
caitoken = os.environ["CAItoken"]
caibot= os.environ["CAImodel"]
while True:
try:
cai = pycai.Client(caitoken)
me = cai.get_me()
chat = cai.connect()
chats = []
break
except:
pass
# 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
$ai-chat - Preform an AI chat powered by Character.AI
"""
meows = ['Meow!', 'Nyaa~', 'Mrow.', 'Prr! :3', 'Hiss!', "Mrrp?", "Mreow.", "!woeM", "3: !rrP", "!ssiH", "~aayN", "Mew!", "Moew!"]
version = "0.0.2 patch 2 (AI update) (Open-source patch)"
# 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
class SweeBotAIException(Exception):
pass
# Client itself
@client.event
async def on_ready():
print('[' + GREEN + 'OK' + RESET + '] Ready')
@client.event
async def on_message(message):
ai = False
ai_ = None
ai__ = 0
for i in message.replied_to:
h = 0
for j in chats:
print(i.id)
print(j['messages'])
if i.id in j['messages']:
ai = True
ai_ = j['cai']
ai__ = h
break
h+=1
if message.author.name != client.user.name:
if message.content == "":
return
if message.author == None:
print(YELLOW + "Gil ("+message.channel.name+"@"+message.server.name+")> "+RESET+message.content)
else:
print(YELLOW + "<"+message.author.name+" ("+message.channel.name+"@"+message.server.name+ " {" + message.server.id +"})> "+RESET+message.content)
if message.author.name == client.user.name or message.author.bot:
return
if ai:
try:
chat = cai.connect()
if message.content == "$more":
mess = await message.reply(embed=guilded.Embed(title=":sweebot-loading: Requesting more..."))
message2 = chat.send_message(
caibot, ai_.chat_id, ""
)
await mess.edit(embed=guilded.Embed(title=":sweebot-success: Requested more.", description=message2.text))
chats[ai__]['messages'].append(mess.id)
else:
mess = await message.reply(embed=guilded.Embed(title=":sweebot-loading: Replying..."))
message2 = chat.send_message(
caibot, ai_.chat_id, "--Guilded receive--\n" + "<" + message.author.name + "> " + message.content
)
await mess.edit(embed=guilded.Embed(title=":sweebot-success: Successfully replied.", description=message2.text))
chats[ai__]['messages'].append(mess.id)
except:
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.")
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() + " " + distro.version() + " " + distro.codename() + "\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] == "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] == "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.")
elif command[0] == "ai-chat":
chat = cai.connect()
mess = await message.reply(embed=guilded.Embed(title=":sweebot-loading: Creating new AI chat."))
new, answer = chat.new_chat(
caibot, me.id
)
text = " ".join(command[1:])
message2 = chat.send_message(
caibot, new.chat_id, "--Guilded receive--\n" + "<" + message.author.name + ">" + text
)
await mess.edit(embed=guilded.Embed(title=":sweebot-success: New AI chat created.", description=message2.text))
chats.append({"messages": [mess.id], "cai": new})
elif command[0] == "more":
raise SweeBotAIException("Please reply to an AI message with `$more` instead of calling it without a reply.")
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")