Compare commits

..

1 commit

Author SHA1 Message Date
db7217fe66 Update cc/honest_opinion 2024-12-04 13:21:48 -08:00
13 changed files with 214 additions and 385 deletions

View file

@ -1,10 +0,0 @@
name: Check syntax
on: [push,workflow_dispatch]
jobs:
check:
runs-on: debian-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
- run: python -m py_compile sweebot.py
- run: jshint script.js

17
cc/give
View file

@ -1,28 +1,21 @@
from sys import argv from sys import argv
import sqlite3 import sqlite3
import re
conn = sqlite3.connect("/home/sweebotirc/sbirc.db") conn = sqlite3.connect("/home/sweebotirc/sbirc.db")
database = conn.cursor() database = conn.cursor()
def getperms(mask: str): def getperms(cloak: str):
try: try:
database.execute(f"SELECT * FROM users;") database.execute("SELECT * FROM users WHERE username = '"+ cloak + "';")
output = database.fetchall() output = database.fetchall()
for i in output: return output[0][1]
if re.match(i[0].replace("*", ".+"), mask):
return i[1]
return ''
except: except:
print(traceback.format_exc())
return '' return ''
if argv[2] == "full": if getperms(argv[2]) == "full":
if len(argv) == 5: if len(argv) == 5:
if argv[3] == argv[2]: if argv[3] == argv[2]:
print(argv[1] + ": You wanna give yourself permissions!?") print(argv[1] + ": You wanna give yourself permissions!?")
else: else:
perms = getperms(argv[3]) perms = getperms(argv[3])
if argv[4] in perms: if perms != "":
print("The specified user already has these permissions.")
elif perms != "":
database.execute("UPDATE users SET perms = '" + perms + "," + argv[4] + "' WHERE username = '" + argv[3] + "';") database.execute("UPDATE users SET perms = '" + perms + "," + argv[4] + "' WHERE username = '" + argv[3] + "';")
print(argv[1] + ": Successfully appended '" + argv[4] + "' to the permissions of " + argv[3]) print(argv[1] + ": Successfully appended '" + argv[4] + "' to the permissions of " + argv[3])
else: else:

View file

@ -1,4 +1,4 @@
#!/usr/bin/python3 #!/usr/bin/python3
from random import choice from random import choice
opinions = ["Oreos are better than Chips Ahoy!", "Human baka, be furry!", "Cereal goes before milk!", "Cereal goes before milk, but what if I pour cereal before bowl? Answer: Chaos!", "Protogens don't run on swap, 1TB of physical RAM!", "Generative AI sucks.", "Y'know, we've all fought about cereal going before milk, but nobody discussed about if choccy powder goes before milk!! ;-;"] opinions = ["Oreos are better than Chips Ahoy!", "Human baka, be furry!", "Cereal goes before milk!", "Cereal goes before milk, but what if I pour cereal before bowl? Answer: Chaos!", "Protogens don't run on swap, 1TB of physical RAM!", "Generative AI sucks."]
print(choice(opinions)) print(choice(opinions))

View file

@ -1,7 +1,4 @@
#!/usr/bin/python3 #!/usr/bin/python3
import sweecrypt import sweecrypt
from sys import argv from sys import argv
if argv[3][:2] == "-s": print(sweecrypt.decrypt(" ".join(argv[3:])))
print(sweecrypt.decrypt(" ".join(argv[4:]), int(argv[3][2:])))
else:
print(sweecrypt.decrypt(" ".join(argv[3:])))

View file

@ -1,7 +1,4 @@
#!/usr/bin/python3 #!/usr/bin/python3
import sweecrypt import sweecrypt
from sys import argv from sys import argv
if argv[3][:2] == "-s": print(sweecrypt.encrypt(" ".join(argv[3:])))
print(sweecrypt.encrypt(" ".join(argv[4:]), int(argv[3][2:])))
else:
print(sweecrypt.encrypt(" ".join(argv[3:])))

View file

@ -1,21 +0,0 @@
<title>MeowNexUS IRC - Dashboard</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://swee.codes/style.css" type="text/css">
<body>
<center>
<h1>MeowNexUS IRC</h1>
<noscript>Requires JS, sorry.<br></noscript>
<a class="softcard" style="display: inline-block;" title="Commands run" href="#"><span id="run">...</span><br><img src="https://swee.codes/icons/up.svg"></a>
<a class="softcard" style="display: inline-block;" title="Commands refused" href="#"><span id="blocked">...</span><br><img src="https://swee.codes/icons/down.svg"></a>
<a class="softcard" style="display: inline-block;" title="Links parsed" href="#"><span id="links">...</span><br><img width="25px" src="https://swee.codes/icons/links.svg"></a>
<br>
<br>
<a class="download" style="background: #027ef9;" title="Refresh stats" onclick="refresh();"><img src="https://swee.codes/icons/refresh.svg"></a>
<hr>
<h1>Last AI Request:</h1>
<br>
<br>
<div width="100%" id="aichat">...</div>
</center>
<script src="script.js"></script>
</body>

View file

@ -1,22 +0,0 @@
Configure the bot for the channel. Requires the "full" perms. (will be allowed by chanops soon)
Use +FLAG to enable a disabled-by-default, and -FLAG vice versa.
Available flags:
* multiline - be able to print multiline output (enabled default)
* colonthree - make the bot say ":3" when someone's message starts with ":3" (enabled default)
* :3c - oh weawwy? :3c (DISABLED default, overriden by colonthree)
* links - parse titles of links sent by users (DISABLED default)
* sed - parse sed expressions without the need of $sed command (DISABLED default)
* config - placeholder, do not modify.
---
Syntax:
```
$config [FLAG] [FLAG] - Apply one or more flags
$config clear - Clear all flags
$config - list all flags in the channel
```

View file

@ -1 +1,11 @@
Documentation for $config can now be found in https://irc-bot.swee.codes/docs/config Configure the bot for the channel. Requires the "full" perms. (will be allowed by chanops soon)
Use +FLAG to enable a disabled-by-default, and -FLAG vice versa.
Available flags:
multiline - be able to print multiline output (enabled default)
colonthree - make the bot say ":3" when someone's message starts with ":3" (enabled default)
links - parse titles of links sent by users (DISABLED default)
(the config flag is a placeholder, do not change it)
syntax:
> $config [FLAG] [FLAG] - Apply one or more flags
> $config clear - Clear all flags
> $config - list all flags in the channel

View file

@ -1 +1 @@
Pulls the latest version of MeowNexUS IRC from its Git repository. requires the "git" permissions. Pulls the latest version of sweeBot from its Git repository. requires the "git" permissions.

View file

@ -1,35 +1,32 @@
/*jshint esversion: 8 */ var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'))
// Fetching the run value for the first time var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
return new bootstrap.Tooltip(tooltipTriggerEl)
})
const delay = ms => new Promise(res => setTimeout(res, ms));
fetch ("run.txt") fetch ("run.txt")
.then(x => x.text()) .then(x => x.text())
.then(y => document.getElementById("run").innerHTML = y); .then(y => document.getElementById("run").innerHTML = y);
// Fetching the block value for the first time
fetch ("block.txt") fetch ("block.txt")
.then(x => x.text())
.then(y => document.getElementById("blocked").innerHTML = y);
async function reboot(){
document.getElementById("rebooticon").innerHTML = "<i class=\"fas fa-power-off fa-fade\"></i>"
fetch ("reboot.run")
.then(x => x.text()) .then(x => x.text())
.then(y => document.getElementById("blocked").innerHTML = y); .then(y => document.getElementById("rebooticon").innerHTML = y);
fetch ("link.txt") await delay(2000)
.then(x => x.text()) document.getElementById("rebooticon").innerHTML = "<i class=\"fas fa-power-off\"></i>"
.then(y => document.getElementById("links").innerHTML = y); }
fetch ("lastquery.txt") async function refresh(){
.then(x => x.text()) document.getElementById("refresh").innerHTML = "<i class=\"fas fa-sync fa-spin\"></i>"
.then(y => document.getElementById("aichat").innerHTML = y); document.getElementById("run").innerHTML = "<span class=\"spinner-grow\"></span>"
async function refresh(){ document.getElementById("blocked").innerHTML = "<span class=\"spinner-grow\"></span>"
// Refresh the HTML to show the spinners fetch ("run.txt")
document.getElementById("run").innerHTML = "..."; .then(x => x.text())
document.getElementById("blocked").innerHTML = "..."; .then(y => document.getElementById("run").innerHTML = y)
document.getElementById("links").innerHTML = "..."; fetch ("block.txt")
document.getElementById("aichat").innerHTML = "..."; .then(x => x.text())
// Then fetch the values the same way as on the first part of the script. .then(y => document.getElementById("blocked").innerHTML = y);
fetch ("run.txt") await delay(2000)
.then(x => x.text()) document.getElementById("refresh").innerHTML = "<i class=\"fas fa-refresh\"></i>"
.then(y => document.getElementById("run").innerHTML = y);
fetch ("block.txt")
.then(x => x.text())
.then(y => document.getElementById("blocked").innerHTML = y);
fetch ("link.txt")
.then(x => x.text())
.then(y => document.getElementById("links").innerHTML = y);
fetch ("lastquery.txt")
.then(x => x.text())
.then(y => document.getElementById("aichat").innerHTML = y);
} }

30
sweebot-dashboard.py Normal file
View file

@ -0,0 +1,30 @@
from flask import Flask
from flask import send_file
from flask import request
from flask import redirect
import os
from pathlib import Path
from time import sleep as wait
app = Flask(__name__)
@app.route('/')
def index():
return send_file("sweebot.html", mimetype='text/html')
@app.route('/run.txt')
def run():
wait(2)
return send_file(str(Path.home()) + "/run.txt", mimetype='text/html')
@app.route('/block.txt')
def block():
wait(2)
return send_file(str(Path.home()) + "/block.txt", mimetype='text/html')
@app.route('/script.js')
def script():
return send_file("script.js", mimetype='application/javascript')
if __name__ == '__main__':
# run() method of Flask class runs the application
# on the local development server.
app.run(host='0.0.0.0',port=2001)

17
sweebot.html Normal file
View file

@ -0,0 +1,17 @@
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>SweeBot dashboard</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://kit.fontawesome.com/30bde606c1.js" crossorigin="anonymous"></script>
<body class="container text-white bg-dark">
<center>
<h1>SweeBot Dashboard</h1>
<a class="btn btn-success" data-bs-toggle="tooltip" title="Commands run" href="#"><h3 id="run"><span class="spinner-grow"></span></h3><i class="fas fa-comments"></i></a>
<a class="btn btn-danger" data-bs-toggle="tooltip" title="Commands refused" href="#"><h3 id="blocked"><span class="spinner-grow"></span></h3><i class="fas fa-ban"></i></a>
<br>
<br>
<a class="btn btn-primary" data-bs-toggle="tooltip" title="Refresh stats" onclick="refresh();" id="refresh"><i class="fas fa-sync"></i></a>
</center>
<script src="script.js"></script>
</body>

View file

@ -1,4 +1,4 @@
__version__ = "0.0.2 Funni update" + ". https://git.swee.codes/swee/MeowNex" __version__ = "0.0.2 Funni update"
import socket import socket
import subprocess import subprocess
from time import sleep, time, ctime from time import sleep, time, ctime
@ -10,90 +10,23 @@ from random import choice, randint as random, randrange
import traceback import traceback
import threading import threading
from pathlib import Path from pathlib import Path
from urllib.parse import urlparse, parse_qs
from requests import get, exceptions as rex from requests import get, exceptions as rex
from bs4 import BeautifulSoup from bs4 import BeautifulSoup
from googleapiclient.discovery import build from googleapiclient.discovery import build
from characterai import pycai
import uuid
CAItoken = environ["CAItoken"]
CAImodel = environ["CAIchara"]
try:
cai = pycai.Client(CAItoken)
me = cai.get_me()
chats = []
except:
print(traceback.format_exc())
run = 0
block = 0
parsed = 0
lastquery = "None yet."
# Dashboard thread
from flask import Flask, send_file, abort as abrt, redirect as redir
app = Flask(__name__)
responses_ai = {} # {uuid: response}
@app.route('/')
def index_html():
return send_file("dashboard.html", mimetype='text/html')
@app.route('/run.txt')
def runs():
return str(run)
@app.route('/block.txt')
def blocks():
return str(block)
@app.route('/link.txt')
def parses():
return str(parsed)
@app.route('/script.js')
def script_js():
return send_file("script.js", mimetype='application/javascript')
@app.route('/lastquery.txt')
def lastquery_txt():
return str(lastquery)
@app.route('/docs/config')
def config_docs():
return redir("https://git.swee.codes/swee/MeowNex/src/branch/main/docs/config.md")
@app.route('/response/<uuidd>')
def ai_response_truncate(uuidd):
if uuidd in responses_ai:
res = responses_ai[uuidd]
return f'<title>AI response {uuidd}</title>\n<meta name="viewport" content="width=device-width, initial-scale=1.0">\n<link rel="stylesheet" href="https://swee.codes/style.css" type="text/css">\n<body><center><h1>AI response {uuidd}</h1><br><br><div class=code width="100%" style="word-wrap: break-word;white-space: pre;text-align: left;">' + res
else:
abrt(404)
threading.Thread(target=app.run, daemon=True, kwargs={"port": 2005}).start()
# YouTube API
DEVELOPER_KEY = environ["ytapi"] DEVELOPER_KEY = environ["ytapi"]
headers = { headers = {
'User-Agent': 'MeowNexUS IRC ' + __version__ 'User-Agent': 'SweeBot IRC ' + __version__
} }
def get_yt_id(url):
query = urlparse(url)
# youtu.be already contains the ID in the path
if query.hostname == 'youtu.be': return query.path[1:]
if query.hostname in {'www.youtube.com', 'youtube.com', 'music.youtube.com'}:
# URLs that have the ID in the path instead of the query.
integrated_in_url = ["watch", "embed", "v", "shorts"]
try:
# The regular /watch path, which stores the ID in the query.
if query.path == '/watch': return parse_qs(query.query)['v'][0]
# Alternatively, it will get the ID in the path if the path was in the list above.
elif query.path.split('/')[1] in integrated_in_url: return query.path.split('/')[2]
except:
return None
class config: class config:
def __init__(self): def __init__(self):
self.conn = sqlite3.connect(environ["SBconfig"]) self.conn = sqlite3.connect(environ["SBconfig"])
self.database = self.conn.cursor() self.database = self.conn.cursor()
def perms(self, mask: str): def perms(self, cloak: str):
try: try:
self.database.execute(f"SELECT * FROM users;") self.database.execute(f"SELECT * FROM users WHERE username = ?;", [cloak])
output = self.database.fetchall() output = self.database.fetchall()
for i in output: return output[0][1]
if re.match(i[0].replace("*", ".+"), mask):
return i[1]
return ''
except: except:
print(traceback.format_exc()) print(traceback.format_exc())
return '' return ''
@ -163,11 +96,6 @@ def humanbytes(B):
return '{0:.2f}GB'.format(B / GB) return '{0:.2f}GB'.format(B / GB)
elif TB <= B: elif TB <= B:
return '{0:.2f}TB'.format(B / TB) return '{0:.2f}TB'.format(B / TB)
def rplce(text, old, new, n):
parts = text.split(old)
if len(parts) <= n:
return text # Not enough occurrences to replace
return old.join(parts[:n]) + new + old.join(parts[n:])
def replace_color_codes(text): def replace_color_codes(text):
def replacer(match): def replacer(match):
code = match.group(0) code = match.group(0)
@ -218,7 +146,7 @@ class bot_irc:
self.irc_socket.send( self.irc_socket.send(
bytes( bytes(
"USER " + bot_nick + " " + bot_nick + " " + bot_nick + " :MeowNexUS, a very cool bot made by Swee :3\n", "USER " + bot_nick + " " + bot_nick + " " + bot_nick + " :SweeBot, a very cool bot made by Swee :3\n",
"UTF-8", "UTF-8",
) )
) )
@ -251,7 +179,7 @@ class bot_irc:
server_irc = "127.0.0.1" # Use 127.0.0.1 for local ZNC server_irc = "127.0.0.1" # Use 127.0.0.1 for local ZNC
port_irc = 5000 # NO SSL FOR YOU port_irc = 6667 # NO SSL FOR YOU
channel_irc = ["##sweezero"] channel_irc = ["##sweezero"]
botnick_irc = environ.get('SBnick') botnick_irc = environ.get('SBnick')
botnickpass_irc =environ.get('SBuser') botnickpass_irc =environ.get('SBuser')
@ -270,13 +198,16 @@ baps = ["T-T", "Ow!", "Beep!"]
pats = ["-w-", "Meep...", "Prr!"] pats = ["-w-", "Meep...", "Prr!"]
meows_happy = ['Meow!', 'Nyaa~', 'Mrow.', 'Prr! :3', "Mrrp?", "Mreow.", "!woeM", "3: !rrP", "~aayN", "Mew!", "Moew!"] meows_happy = ['Meow!', 'Nyaa~', 'Mrow.', 'Prr! :3', "Mrrp?", "Mreow.", "!woeM", "3: !rrP", "~aayN", "Mew!", "Moew!"]
meows_upset = ['Hiss!', "!ssiH", "Grrr..."] meows_upset = ['Hiss!', "!ssiH", "Grrr..."]
my_self = ["MeowNexUS", "MeowNexU5", "MeowN3xUS"]
logs = {} # {channel: [line, line]} max 10 lines
happiness = 5 happiness = 5
run = 0
block = 0
global times global times
times = 0 times = 0
ai_storage = {} def update():
emoticons = {";3": "I think you forgot to press shift", ":#": "Wait no, don't hold shift THAT long!"} open(str(Path.home()) + "/run.txt", 'w').write(str(run))
open(str(Path.home()) + "/block.txt", 'w').write(str(block))
update()
def irci2(): def irci2():
irc2.connect_irc( irc2.connect_irc(
server_irc, port_irc, channel_irc, "sweeB0t", botpass_irc, botnickpass_irc + "/B" server_irc, port_irc, channel_irc, "sweeB0t", botpass_irc, botnickpass_irc + "/B"
@ -318,24 +249,18 @@ def restart():
irc2.irc_socket.close() irc2.irc_socket.close()
irc3.irc_socket.close() irc3.irc_socket.close()
exit(0) exit(0)
def system(cmd, chan, rstrip=False): def system(cmd, chan):
try: try:
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
outpp = ""
for line in iter(p.stdout.readline, b''): for line in iter(p.stdout.readline, b''):
if text != "" and text != " ": if text != "" and text != " ":
if not rstrip: multiline(line.rstrip(), chan)
multiline(line.rstrip(), chan)
else:
outpp += line.decode().rstrip() + " "
if rstrip:
multiline(outpp[:-1], chan)
p.stdout.close() p.stdout.close()
p.wait() p.wait()
except FileNotFoundError: except FileNotFoundError:
multiline(cmd[0] + " not found", chan) multiline(cmd[0] + " not found", chan)
except: except:
multiline(traceback.format_exc(), chan) multiline(traceback.format_exc())
irl2 = threading.Thread(target=irci2, daemon=True) irl2 = threading.Thread(target=irci2, daemon=True)
irl2.start() irl2.start()
irl3 = threading.Thread(target=irci3, daemon=True) irl3 = threading.Thread(target=irci3, daemon=True)
@ -354,9 +279,8 @@ while True:
channel = text.split("PRIVMSG")[1].split(" ")[1] channel = text.split("PRIVMSG")[1].split(" ")[1]
nick = text.split(" ")[0][1:].split("!")[0] nick = text.split(" ")[0][1:].split("!")[0]
username = text.split(" ")[0][1:].split("@")[1] username = text.split(" ")[0][1:].split("@")[1]
mask = text.split(" ")[0][1:]
try: try:
perms = sbconfig.perms(mask) perms = sbconfig.perms(username)
except: except:
perms = "" perms = ""
print(command) print(command)
@ -364,66 +288,17 @@ while True:
print(nick) print(nick)
print(username) print(username)
print(perms) print(perms)
cont = " ".join(command)
if not channel in logs:
logs[channel] = [{"nick": nick, "content": cont}]
else:
logs[channel].append({"nick": nick, "content": cont})
if len(logs[channel]) > 128: logs[channel] = logs[channel][::-1][:128][::-1]
#open("log-text-"+channel, "a").write(" ".join(command) + "\n") #open("log-text-"+channel, "a").write(" ".join(command) + "\n")
#open("log-name-"+channel, "a").write(nick + "\n") #open("log-name-"+channel, "a").write(nick + "\n")
except: except:
print(traceback.format_exc()) #print(traceback.format_exc())
def replased(expression): pass
if channel in logs:
try:
if expression.split("/")[0].lower() != "s": raise IndexError()
find = expression.split("/")[1]
replace = expression.split("/")[2]
user = None
repeat = False
index = 1
try:
extraflags = expression.split("/")[3:]
for i in extraflags:
if i.strip() == "":
pass
elif i.lower() == "g":
repeat = True
elif i.strip().isdigit():
print(f"index = {int(i)}")
index = int(i)
else:
print(f"user = {i.lower()}")
user = i.lower()
except: pass
cache = None
for i in logs[channel][::-1]:
if find in i["content"] and (user == None or i["nick"].lower() == user):
cache = i
break
if cache == None:
raise Exception("The specified text couldn't be found")
else:
if repeat:
cache["content"] = cache["content"].replace(find, replace)
else:
cache["content"] = rplce(cache["content"], find, replace, index)
cachenick = cache["nick"]
cachecontent = cache["content"]
multiline(f"[RPL] <{cachenick}> {cachecontent}", channel)
except IndexError:
irc.send_irc(channel, nick + ": [ERR] Sed expression might be incorrectly written!")
except Exception as ex:
irc.send_irc(channel, nick + ": [ERR] " + str(ex))
else:
irc.send_irc(channel, nick + ": [!!!] No logs saved in " + channel)
try: try:
#if True: #if True:
if "PRIVMSG" in text and not nick in my_self: if "PRIVMSG" in text:
if "PRIVMSG" in text and command[0][0] == "$": if "PRIVMSG" in text and command[0][0] == "$":
logs[channel] = logs[channel][:-1]
run+=1 run+=1
update()
if command[0] == "$ping": if command[0] == "$ping":
if random(1,2) == 1: if random(1,2) == 1:
irc.send_irc(channel, nick + ": Pnog") irc.send_irc(channel, nick + ": Pnog")
@ -436,7 +311,7 @@ while True:
irc.send_irc(channel, nick + ": Nice try") irc.send_irc(channel, nick + ": Nice try")
block+=1 block+=1
run-=1 run-=1
update()
else: else:
try: try:
if path.isfile(cwd + "/helps/" + " ".join(command[1:])): if path.isfile(cwd + "/helps/" + " ".join(command[1:])):
@ -450,13 +325,13 @@ while True:
irc.send_irc(channel, "tip, ping, whoami, perms, version, figlet, tdfiglet, cowsay, uptime, cc, joke, botsnack. (restart, join, part, shell, config, pull.) Use '$help (command)' for explanation.") irc.send_irc(channel, "tip, ping, whoami, perms, version, figlet, tdfiglet, cowsay, uptime, cc, joke, botsnack. (restart, join, part, shell, config, pull.) Use '$help (command)' for explanation.")
elif command[0] == "$tip": elif command[0] == "$tip":
system(["/usr/games/fortune", "debian-hints"], channel, True) system(["fortune"], channel)
elif command[0] == "$whoami": elif command[0] == "$whoami":
if perms != "": if perms != "":
irc.send_irc(channel, nick + ": " + mask + " (Your hostmask has permissions, use the 'perms' command to see)") irc.send_irc(channel, nick + ": " + username + " (Your cloak has permissions, use the 'perms' command to see)")
else: else:
irc.send_irc(channel, nick + ": " + mask) irc.send_irc(channel, nick + ": " + username)
elif command[0] == "$welcome": elif command[0] == "$welcome":
name = nick if not len(command) > 1 else " ".join(command[1:]) name = nick if not len(command) > 1 else " ".join(command[1:])
@ -468,9 +343,9 @@ while True:
elif command[0] == "$perms": elif command[0] == "$perms":
if len(command) == 2: if len(command) == 2:
if sbconfig.perms(command[1]) != "": if sbconfig.perms(command[1]) != "":
irc.send_irc(channel, nick + ": permissions of hostmask " + command[1] + ": " + sbconfig.perms(command[1])) irc.send_irc(channel, nick + ": permissions of cloak " + command[1] + ": " + sbconfig.perms(command[1]))
else: else:
irc.send_irc(channel, nick + ": The hostmask wildcard " + command[1] + " Doesn't have permissions.") irc.send_irc(channel, nick + ": The cloak " + command[1] + " Doesn't have permissions.")
else: else:
if perms != "": if perms != "":
irc.send_irc(channel, nick + ": " + perms) irc.send_irc(channel, nick + ": " + perms)
@ -486,19 +361,20 @@ while True:
irc.send_irc(channel, nick + ": Permission denied.") irc.send_irc(channel, nick + ": Permission denied.")
block+=1 block+=1
run-=1 run-=1
update()
elif command[0] == "$pull": elif command[0] == "$pull":
if perms == "full" or "git" in perms.split(","): if perms == "full" or "git" in perms.split(","):
ossystem("git fetch") ossystem("git fetch")
ossystem("git pull") ossystem("git pull")
irc.send_irc(channel, nick + ": Pulled from Git, restarting bot...") irc.send_irc(channel, nick + ": Pulled from Git, restarting bot...")
restart() sleep(1)
ossystem("sudo systemctl restart sweebot")
else: else:
irc.send_irc(channel, nick + ": Permission denied.") irc.send_irc(channel, nick + ": Permission denied.")
block+=1 block+=1
run-=1 run-=1
update()
elif command[0] == "$join": elif command[0] == "$join":
if perms == "full" or "join" in perms.split(","): if perms == "full" or "join" in perms.split(","):
@ -517,7 +393,7 @@ while True:
irc.send_irc(channel, nick + ": Permission denied.") irc.send_irc(channel, nick + ": Permission denied.")
block+=1 block+=1
run-=1 run-=1
update()
elif command[0] == "$part": elif command[0] == "$part":
if perms == "full" or "part" in perms.split(","): if perms == "full" or "part" in perms.split(","):
@ -539,46 +415,8 @@ while True:
irc.send_irc(channel, nick + ": Permission denied.") irc.send_irc(channel, nick + ": Permission denied.")
block+=1 block+=1
run-=1 run-=1
update()
elif command[0] == "$ai-chat":
try:
aiconnector = cai.connect()
chatquery = f"--Listen Up--\nYour happiness level is {happiness} (Maximum 10), your emotion level will impact the conversation's tone.\n--END Listen Up--\n--IRC recieve--\n<{nick}> " + " ".join(command[1:])
if channel in ai_storage:
aimsg = aiconnector.send_message(CAImodel, ai_storage[channel], chatquery)
else:
new, answer = aiconnector.new_chat(
CAImodel, me.id
)
aimsg = aiconnector.send_message(CAImodel, new.chat_id, chatquery)
ai_storage[channel] = new.chat_id
randomname = str(uuid.uuid4())
responses_ai[randomname] = aimsg.text
mtline = ""
lastquery = f"<p>Channel: {channel}</p><p>Request:</p><br><br><textarea class=code width=100% spellcheck=\"false\" autocapitalize=\"off\" autocomplete=\"off\" autocorrect=\"off\" readonly=\"true\">{chatquery}</textarea><hr><p>Response</p><br><br><textarea class=code width=100% spellcheck=\"false\" autocapitalize=\"off\" autocomplete=\"off\" autocorrect=\"off\" readonly=\"true\">{aimsg.text}</textarea>"
broke = False
for num, i in enumerate(aimsg.text.split("\n")):
if num == 5:
broke = True
break
elif len(i) > 256:
mtline += "\n" + i[:256] + "..."
broke = True
else:
mtline += "\n" + i
if broke:
mtline += f"\nView full response: https://irc-bot.swee.codes/response/{randomname}"
multiline(mtline, channel)
except:
multiline("Something went wrong while connecting to Character.AI.", channel)
print(traceback.format_exc())
elif command[0] == "$ai-clear":
if channel in ai_storage:
del ai_storage[channel]
multiline("Done.", channel)
else:
multiline(f"There is no existing AI conversation in {channel}", channel)
elif command[0] == "$socket": elif command[0] == "$socket":
if perms == "full": if perms == "full":
if len(command) > 1: if len(command) > 1:
@ -592,28 +430,18 @@ while True:
irc.send_irc(channel, nick + ": Permission denied.") irc.send_irc(channel, nick + ": Permission denied.")
block+=1 block+=1
run-=1 run-=1
update()
elif command[0] == "$patpat" or command[0] == "$headpat": elif command[0] == "$patpat" or command[0] == "$headpat":
if len(command) == 2: if len(command) == 2:
if int(command[1]) < 50: for i in range(0,int(command[1])):
for i in range(0,int(command[1])): happiness += (1 if happiness != 10 else 0)
happiness += (1 if happiness != 10 else 0)
else:
happiness = 10
elif len(command) == 1: elif len(command) == 1:
happiness += (1 if happiness != 10 else 0) happiness += (1 if happiness != 10 else 0)
if len(command) != 2 or int(command[1]) < 50: multiline(choice(pats) + " (Emotion: Upset " +
multiline(choice(pats) + " (Emotion: Upset " + ("#" * int(happiness)) +
("#" * int(happiness)) + ("-" * int(10-happiness)) + " Happy)",
("-" * int(10-happiness)) + " Happy)", channel)
channel)
else:
multiline("Okay that's enough!!" + " (Emotion: Upset " +
("#" * int(happiness)) +
("-" * int(10-happiness)) + " Happy)",
channel)
elif command[0] == "$emotion": elif command[0] == "$emotion":
multiline("Emotion: Upset " + multiline("Emotion: Upset " +
("#" * int(happiness)) + ("#" * int(happiness)) +
@ -621,30 +449,20 @@ while True:
channel) channel)
elif command[0] == "$bap": elif command[0] == "$bap":
if len(command) == 2: if len(command) == 2:
if int(command[1]) < 50: for i in range(0,int(command[1])):
for i in range(0,int(command[1])): happiness -= (1 if happiness != 0 else 0)
happiness -= (1 if happiness != 0 else 0)
else:
happiness = 0
elif len(command) == 1: elif len(command) == 1:
happiness -= (1 if happiness != 0 else 0) happiness -= (1 if happiness != 0 else 0)
if len(command) != 2 or int(command[1]) < 50: multiline(choice(baps) + " (Emotion: Upset " +
multiline(choice(baps) + " (Emotion: Upset " + ("#" * int(happiness)) +
("#" * int(happiness)) + ("-" * int(10-happiness)) + " Happy)",
("-" * int(10-happiness)) + " Happy)", channel)
channel)
else:
multiline("Okay that's enough!!" + " (Emotion: Upset " +
("#" * int(happiness)) +
("-" * int(10-happiness)) + " Happy)",
channel)
elif command[0] == "$meow": elif command[0] == "$meow":
if random(1,100) > (happiness*10): if random(1,100) > (happiness*10):
multiline(choice(meows_upset), channel) multiline(choice(meows_upset), channel)
else: else:
multiline(choice(meows_happy), channel) multiline(choice(meows_happy), channel)
elif command[0] == "$stats":
multiline(f"{nick}: {run} command(s) run, {block} refused, and {parsed} link(s) parsed, check out https://irc-bot.swee.codes", channel)
elif command[0] == "$shell": elif command[0] == "$shell":
if perms == "full": if perms == "full":
#or "shell" in perms.split(",") #or "shell" in perms.split(",")
@ -659,10 +477,10 @@ while True:
irc.send_irc(channel, nick + ": Permission denied.") irc.send_irc(channel, nick + ": Permission denied.")
block+=1 block+=1
run-=1 run-=1
update()
elif command[0] == "$version": elif command[0] == "$version":
irc.send_irc(channel, "This is MeowNexUS IRC " + __version__) irc.send_irc(channel, "This is SweeBot " + __version__)
elif command[0] == "$figlet": elif command[0] == "$figlet":
if not sbconfig.cflagexist(channel, "-multiline"): if not sbconfig.cflagexist(channel, "-multiline"):
@ -719,11 +537,45 @@ while True:
multiline(f"\x01ACTION gives a hug to {name}\x01", channel) multiline(f"\x01ACTION gives a hug to {name}\x01", channel)
elif command[0] == "$sed":
if len(command) == 2: #elif command[0] == "$sed":
replased(" ".join(command[1:])) # if len(command) > 1:
else: #try:
irc.send_irc(channel, nick + ": [???] This command takes only one argument.") # if True:
# com = ['sed',"" + command[1] + ""]
# print(command[1])
# texte = open("log-text-"+channel).read().split("\n")
# texte.reverse()
# texte.pop(0)
# texte.pop(0)
# print(texte)
# texttoreplace = ""
# j = 0
# broken = False
# for i in texte:
# if command[1].split("/")[1] in i:
# texttoreplace = i
# broken = True
# break
# j+=1
# if not broken:
# irc.send_irc(channel, "Unable to correct: '" + command[1].split("/")[1] + "' not found in any chat message.")
# continue
# namee = open("log-name-"+channel).read().split("\n")
# namee.reverse()
# namee.pop(0)
# namee.pop(0)
# namee = namee[j]
# open("temp","w").write(texttoreplace)
# com.append("temp")
# print(com)
# result = subprocess.run(com, stdout=subprocess.PIPE)
# output = result.stdout.decode('utf-8').split("\n")
# irc.send_irc(channel, "Correction using sed: <" + namee + "> " + output[0])
# #except Exception as ex:
# #irc.send_irc(channel, nick + ": " + ex.__class__.__name__)
# else:
# irc.send_irc(channel, nick + ": What to correct?")
elif command[0] == "$config": elif command[0] == "$config":
@ -757,7 +609,7 @@ while True:
irc.send_irc(channel, nick + ": Permission denied") irc.send_irc(channel, nick + ": Permission denied")
block+=1 block+=1
run-=1 run-=1
update()
else: else:
multiline("Configuration for " + channel + ": " + " ".join(sbconfig.chansettings(channel)), channel) multiline("Configuration for " + channel + ": " + " ".join(sbconfig.chansettings(channel)), channel)
except ex: except ex:
@ -768,7 +620,7 @@ while True:
irc.send_irc(channel, nick + ": Nice try.") irc.send_irc(channel, nick + ": Nice try.")
block+=1 block+=1
run-=1 run-=1
update()
else: else:
if path.isfile("cc/" + command[0][1:]): if path.isfile("cc/" + command[0][1:]):
try: try:
@ -779,7 +631,7 @@ while True:
comm = command comm = command
com.append("cc/" + comm[0][1:]) com.append("cc/" + comm[0][1:])
com.append(nick) com.append(nick)
com.append(perms) com.append(username)
comm.pop(0) comm.pop(0)
for i in comm: for i in comm:
com.append(i) com.append(i)
@ -795,55 +647,44 @@ while True:
elif command[0] == ":3": elif command[0] == ":3":
if not sbconfig.cflagexist(channel, "-colonthree"): if not sbconfig.cflagexist(channel, "-colonthree"):
irc.send_irc(channel, ":3") irc.send_irc(channel, ":3")
elif command[0] in emoticons:
if not sbconfig.cflagexist(channel, "-colonthree"):
irc.send_irc(channel, emoticons[command[0]])
elif ":3c" in command: elif ":3c" in command:
if sbconfig.cflagexist(channel, "+:3c") or not sbconfig.cflagexist(channel, "-colonthree"): if not sbconfig.cflagexist(channel, "-colonthree"):
multiline(choice(threes), channel) multiline(channel, choice(threes))
elif command[0][:2].lower() == "s/":
logs[channel] = logs[channel][:-1]
if sbconfig.cflagexist(channel, "+sed"):
replased(" ".join(command))
# try to parse and find a link # try to parse and find a link
if sbconfig.cflagexist(channel, "+links"): if sbconfig.cflagexist(channel, "+links"):
try: try:
for i in command: for i in command:
parse = urlparse(i) if i[:8] == "https://":
if parse.scheme in ["http", "https"]:
try: try:
if parse.hostname in ["youtube.com", "youtu.be", "www.youtube.com", "m.youtube.com", "youtube-nocookie.com"] and get_yt_id(i) != None: e = get(i, headers=headers, timeout=10)
try: header = e.headers
video_id = get_yt_id(i) content_type = header.get('content-type').split(";")[0]
youtube = build('youtube', 'v3', developerKey=DEVELOPER_KEY) content_len = header.get('Content-length')
request = youtube.videos().list(part='snippet,statistics', id=video_id) if content_type in allowedparse:
details = request.execute() if e.ok:
title = details['items'][0]['snippet']['title'] soup = BeautifulSoup(e.text, 'html.parser')
channel_yt = details['items'][0]['snippet']['channelTitle'] multiline("(" + nick + ") " + (soup.title.string if soup.title != None else "[No title provided]"), channel)
views = details['items'][0]['statistics']['viewCount']
multiline(f"({nick}) [▶️ YouTube] {title} | Author: {channel_yt} | {views} Views", channel)
except Exception as ex:
multiline("(" + nick + ") [YouTube Error, is it a valid YouTube URL?]", channel)
print(traceback.format_exc())
else:
e = get(i, headers=headers, timeout=10)
header = e.headers
content_type = header.get('content-type').split(";")[0]
content_len = header.get('Content-length')
if content_type in allowedparse:
if e.ok:
soup = BeautifulSoup(e.text, 'html.parser')
multiline("(" + nick + ") " + (" ".join(soup.title.string.splitlines())[:100] if soup.title != None else "[No title provided]"), channel)
else:
multiline("(" + nick + ") [HTTP " + str(e.status_code) + "]", channel)
else: else:
multiline("(" + nick + ") [" + humanbytes(content_len) + " " + str(content_type) + "]", channel) multiline("(" + nick + ") [HTTP " + str(e.status_code) + "]", channel)
parsed += 1 else:
multiline("(" + nick + ") [" + humanbytes(content_len) + " " + str(content_type) + "]", channel)
except rex.SSLError as ex: except rex.SSLError as ex:
multiline("(" + nick + ") [SSL Error: " + str(ex.message) + "]", channel) multiline("(" + nick + ") [SSL Error: " + str(ex.message) + "]", channel)
except Exception as ex: except Exception as ex:
multiline("(" + nick + ") [Request error: " + str(ex.message) + "]", channel) multiline("(" + nick + ") [Request error: " + str(ex.message) + "]", channel)
elif i[:7] == "http://":
e = get(i, headers=headers, timeout=10)
header = e.headers
content_type = header.get('content-type').split(";")[0]
content_len = header.get('Content-length')
if content_type in allowedparse:
if e.ok:
soup = BeautifulSoup(e.text, 'html.parser')
multiline("(" + nick + ") " + (soup.title.string if soup.title != None else "[No title provided]"), channel)
else:
multiline("(" + nick + ") [HTTP " + str(e.status_code) + "]", channel)
else:
multiline("(" + nick + ") [" + humanbytes(content_len) + " " + str(content_type) + "]", channel)
except: except:
print(traceback.format_exc()) print(traceback.format_exc())
elif "JOIN" in text and "#nixsanctuary" in text: elif "JOIN" in text and "#nixsanctuary" in text: