fix
This commit is contained in:
159
.gitignore
vendored
Normal file
159
.gitignore
vendored
Normal file
@ -0,0 +1,159 @@
|
||||
# ---> Python
|
||||
# Byte-compiled / optimized / DLL files
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
*$py.class
|
||||
|
||||
# C extensions
|
||||
*.so
|
||||
|
||||
# Distribution / packaging
|
||||
.Python
|
||||
build/
|
||||
develop-eggs/
|
||||
dist/
|
||||
downloads/
|
||||
eggs/
|
||||
.eggs/
|
||||
lib/
|
||||
lib64/
|
||||
parts/
|
||||
sdist/
|
||||
var/
|
||||
wheels/
|
||||
share/python-wheels/
|
||||
*.egg-info/
|
||||
.installed.cfg
|
||||
*.egg
|
||||
MANIFEST
|
||||
|
||||
# PyInstaller
|
||||
# Usually these files are written by a python script from a template
|
||||
# before PyInstaller builds the exe, so as to inject date/other infos into it.
|
||||
*.manifest
|
||||
*.spec
|
||||
|
||||
# Installer logs
|
||||
pip-log.txt
|
||||
pip-delete-this-directory.txt
|
||||
|
||||
# Unit test / coverage reports
|
||||
htmlcov/
|
||||
.tox/
|
||||
.nox/
|
||||
.coverage
|
||||
.coverage.*
|
||||
.cache
|
||||
nosetests.xml
|
||||
coverage.xml
|
||||
*.cover
|
||||
*.py,cover
|
||||
.hypothesis/
|
||||
.pytest_cache/
|
||||
cover/
|
||||
|
||||
# Translations
|
||||
*.mo
|
||||
*.pot
|
||||
|
||||
# Django stuff:
|
||||
*.log
|
||||
local_settings.py
|
||||
db.sqlite3
|
||||
db.sqlite3-journal
|
||||
|
||||
# Flask stuff:
|
||||
instance/
|
||||
.webassets-cache
|
||||
|
||||
# Scrapy stuff:
|
||||
.scrapy
|
||||
|
||||
# Sphinx documentation
|
||||
docs/_build/
|
||||
|
||||
# PyBuilder
|
||||
.pybuilder/
|
||||
target/
|
||||
|
||||
# Jupyter Notebook
|
||||
.ipynb_checkpoints
|
||||
|
||||
# IPython
|
||||
profile_default/
|
||||
ipython_config.py
|
||||
|
||||
# pyenv
|
||||
# For a library or package, you might want to ignore these files since the code is
|
||||
# intended to run in multiple environments; otherwise, check them in:
|
||||
# .python-version
|
||||
|
||||
# pipenv
|
||||
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
|
||||
# However, in case of collaboration, if having platform-specific dependencies or dependencies
|
||||
# having no cross-platform support, pipenv may install dependencies that don't work, or not
|
||||
# install all needed dependencies.
|
||||
#Pipfile.lock
|
||||
|
||||
# poetry
|
||||
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
|
||||
# This is especially recommended for binary packages to ensure reproducibility, and is more
|
||||
# commonly ignored for libraries.
|
||||
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
|
||||
#poetry.lock
|
||||
|
||||
# PEP 582; used by e.g. github.com/David-OConnor/pyflow
|
||||
__pypackages__/
|
||||
|
||||
# Celery stuff
|
||||
celerybeat-schedule
|
||||
celerybeat.pid
|
||||
|
||||
# SageMath parsed files
|
||||
*.sage.py
|
||||
|
||||
# Environments
|
||||
.env
|
||||
.venv
|
||||
env/
|
||||
venv/
|
||||
ENV/
|
||||
env.bak/
|
||||
venv.bak/
|
||||
|
||||
# Spyder project settings
|
||||
.spyderproject
|
||||
.spyproject
|
||||
|
||||
# Rope project settings
|
||||
.ropeproject
|
||||
|
||||
# mkdocs documentation
|
||||
/site
|
||||
|
||||
# mypy
|
||||
.mypy_cache/
|
||||
.dmypy.json
|
||||
dmypy.json
|
||||
|
||||
# Pyre type checker
|
||||
.pyre/
|
||||
|
||||
# pytype static type analyzer
|
||||
.pytype/
|
||||
|
||||
# Cython debug symbols
|
||||
cython_debug/
|
||||
|
||||
# PyCharm
|
||||
# JetBrains specific template is maintainted in a separate JetBrains.gitignore that can
|
||||
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
|
||||
# and can be added to the global gitignore or merged into this file. For a more nuclear
|
||||
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
|
||||
#.idea/
|
||||
|
||||
saves
|
||||
|
||||
discord_edukun.log
|
||||
|
||||
.config
|
3
README.md
Normal file
3
README.md
Normal file
@ -0,0 +1,3 @@
|
||||
# edukun
|
||||
Edupage info forked from Untriextv and Tucan444
|
||||
|
110
bot.py
Normal file
110
bot.py
Normal file
@ -0,0 +1,110 @@
|
||||
import os #hi there
|
||||
def write_pid():
|
||||
pid = os.getpid()
|
||||
with open('/tmp/edu.pid', 'w') as f:
|
||||
f.write(str(pid))
|
||||
print('Hello my(i \'m edukun) pid is ' + str(pid))
|
||||
write_pid()
|
||||
|
||||
import discord
|
||||
import random
|
||||
import json
|
||||
import os
|
||||
from discord.ext import commands
|
||||
from discord.ext import tasks
|
||||
|
||||
|
||||
intents = discord.Intents.default()
|
||||
intents.members = True
|
||||
|
||||
|
||||
def get_prefix(clientX, message):
|
||||
with open("saves/prefixes", "r") as f:
|
||||
prefixes = json.load(f)
|
||||
|
||||
return prefixes[str(message.guild.id)]
|
||||
|
||||
|
||||
client = commands.Bot(command_prefix=get_prefix, intents=intents)
|
||||
|
||||
|
||||
@client.event
|
||||
async def on_ready():
|
||||
print("Edu is ready.")
|
||||
await client.change_presence(status=discord.Status.online, activity=discord.Game("Awake"))
|
||||
|
||||
|
||||
@client.command()
|
||||
@commands.has_permissions(administrator=True)
|
||||
async def load(ctx, *, extension="all"):
|
||||
if str(extension) not in ["all", "All"]:
|
||||
client.load_extension(f"extensions.{extension}")
|
||||
await ctx.send(f"Reloaded extension {extension}.")
|
||||
else:
|
||||
try:
|
||||
for ext in os.listdir("extensions"):
|
||||
if ext.endswith(".py"):
|
||||
try:
|
||||
client.load_extension(f"extensions.{ext[:-3]}")
|
||||
except:
|
||||
pass
|
||||
await ctx.send(f"Reloaded all extensions successfully.")
|
||||
except:
|
||||
await ctx.send("Error")
|
||||
|
||||
|
||||
@client.command()
|
||||
@commands.has_permissions(administrator=True)
|
||||
async def unload(ctx, *, extension="all"):
|
||||
if str(extension) not in ["all", "All"]:
|
||||
client.unload_extension(f"extensions.{extension}")
|
||||
await ctx.send(f"Reloaded extension {extension}.")
|
||||
else:
|
||||
try:
|
||||
for ext in os.listdir("extensions"):
|
||||
if ext.endswith(".py"):
|
||||
try:
|
||||
client.unload_extension(f"extensions.{ext[:-3]}")
|
||||
except:
|
||||
pass
|
||||
await ctx.send(f"Reloaded all extensions successfully.")
|
||||
except:
|
||||
await ctx.send("Error")
|
||||
|
||||
|
||||
@client.command()
|
||||
@commands.has_permissions(administrator=True)
|
||||
async def reload(ctx, *, extension="all"):
|
||||
if str(extension) not in ["all", "All"]:
|
||||
try:
|
||||
client.unload_extension(f"extensions.{extension}")
|
||||
client.load_extension(f"extensions.{extension}")
|
||||
await ctx.send(f"Reloaded extension {extension}.")
|
||||
except Exception as e:
|
||||
with open("saves/error_log.txt", "w+") as f:
|
||||
f.write(str(e))
|
||||
f.close()
|
||||
await ctx.send("Error")
|
||||
else:
|
||||
try:
|
||||
for ext in os.listdir("extensions"):
|
||||
if ext.endswith(".py"):
|
||||
try:
|
||||
client.unload_extension(f"extensions.{ext[:-3]}")
|
||||
except:
|
||||
pass
|
||||
client.load_extension(f"extensions.{ext[:-3]}")
|
||||
await ctx.send(f"Reloaded all extensions successfully.")
|
||||
except Exception as e:
|
||||
with open("saves/error_log.txt", "w+") as f:
|
||||
f.write(str(e))
|
||||
f.close()
|
||||
await ctx.send("Error")
|
||||
|
||||
|
||||
for ext in os.listdir("extensions"):
|
||||
if ext.endswith(".py"):
|
||||
client.load_extension(f"extensions.{ext[:-3]}")
|
||||
|
||||
with open("/home/edukun/edu_tkn") as tkn:
|
||||
client.run(tkn.read())
|
BIN
edu-kun_pfp.png
Normal file
BIN
edu-kun_pfp.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 1.8 KiB |
173
extensions/Edu_info.py
Normal file
173
extensions/Edu_info.py
Normal file
@ -0,0 +1,173 @@
|
||||
import json
|
||||
import time
|
||||
import requests
|
||||
import discord
|
||||
from discord.ext import commands
|
||||
|
||||
|
||||
class Edu_Info(commands.Cog):
|
||||
|
||||
def __init__(self, client):
|
||||
self.client = client
|
||||
|
||||
@commands.command()
|
||||
@commands.has_permissions(administrator=True)
|
||||
async def teachers(self, ctx):
|
||||
update_database(ctx)
|
||||
|
||||
with open("saves/edu.json", "r") as f:
|
||||
edu = json.load(f)
|
||||
edu = edu[str(ctx.guild.id)]
|
||||
|
||||
for teacher in edu["dbi"]["teachers"].keys():
|
||||
t = edu['dbi']['teachers'][teacher]
|
||||
teacher = discord.Embed(title=f"{t['firstname']} {t['lastname']}",
|
||||
description="profile")
|
||||
teacher.add_field(name="Gender",
|
||||
value=f"{t['gender']}")
|
||||
teacher.add_field(name="Started",
|
||||
value=f"{t['datefrom']}")
|
||||
|
||||
await ctx.send(content=None, embed=teacher)
|
||||
|
||||
@commands.command()
|
||||
@commands.has_permissions(administrator=True)
|
||||
async def classes(self, ctx):
|
||||
update_database(ctx)
|
||||
|
||||
with open("saves/edu.json", "r") as f:
|
||||
edu = json.load(f)
|
||||
edu = edu[str(ctx.guild.id)]
|
||||
|
||||
for classroom in edu["dbi"]["classes"].keys():
|
||||
cr = edu["dbi"]["classes"][classroom]
|
||||
teacher_id = cr["teacherid"]
|
||||
teach = "None"
|
||||
|
||||
# getting the teacher
|
||||
for teacher in edu["dbi"]["teachers"].keys():
|
||||
t = edu['dbi']['teachers'][teacher]
|
||||
|
||||
if t["id"] == teacher_id:
|
||||
teach = f"{t['firstname']} {t['lastname']}"
|
||||
|
||||
embed = discord.Embed(title=f"{cr['name']}",
|
||||
description="info")
|
||||
embed.add_field(name="Teacher",
|
||||
value=teach)
|
||||
|
||||
await ctx.send(content=None, embed=embed)
|
||||
|
||||
@commands.command()
|
||||
async def periods(self, ctx):
|
||||
update_database(ctx)
|
||||
|
||||
with open("saves/edu.json", "r") as f:
|
||||
edu = json.load(f)
|
||||
edu = edu[str(ctx.guild.id)]
|
||||
|
||||
periods = edu["dbi"]["periods"]
|
||||
|
||||
periodX = discord.Embed(title="Periods",
|
||||
description="hours")
|
||||
|
||||
for period in periods:
|
||||
|
||||
periodX.add_field(name=f"{period['name']}",
|
||||
value=f"{period['starttime']} - {period['endtime']}")
|
||||
|
||||
await ctx.send(content=None, embed=periodX)
|
||||
|
||||
@commands.command()
|
||||
async def authors(self, ctx):
|
||||
authors = discord.Embed(title="Authors",
|
||||
description="Tucan444, UntriexTv")
|
||||
|
||||
authors.add_field(name="Tucan444",
|
||||
value="https://tucan444.itch.io/")
|
||||
authors.add_field(name="UntriexTv",
|
||||
value="https://github.com/UntriexTv")
|
||||
await ctx.send(content=None, embed=authors)
|
||||
|
||||
|
||||
def update_database(ctx):
|
||||
# getting accounts
|
||||
with open("saves/accounts.json") as f:
|
||||
accounts = json.load(f)[str(ctx.guild.id)]
|
||||
|
||||
for account in accounts.keys():
|
||||
for i in range(6):
|
||||
try:
|
||||
url = 'https://zshorovaba.edupage.org/login/edubarLogin.php'
|
||||
headers = {
|
||||
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:82.0) Gecko/20100101 Firefox/82.0"}
|
||||
values = {'username': f"{accounts[account]['name']}",
|
||||
'password': f"{weird_shuffle(accounts[account]['password'])}"}
|
||||
edupage = requests.session()
|
||||
edupage.post(url, data=values, headers=headers)
|
||||
r = edupage.get("https://zshorovaba.edupage.org/timeline/", headers=headers)
|
||||
x = r.text.split("\n")
|
||||
lines_to_del = []
|
||||
for line in x:
|
||||
if len(line) < 10000:
|
||||
lines_to_del.append(line)
|
||||
|
||||
for line in lines_to_del:
|
||||
del x[x.index(line)]
|
||||
|
||||
x = list(x[0])
|
||||
while x[0] != "{":
|
||||
del x[0]
|
||||
while x[-1] != "}":
|
||||
del x[-1]
|
||||
x = "".join(x)
|
||||
x = x.replace("false", "False").replace("true", "True").replace("null", "None")
|
||||
var = eval(x)
|
||||
|
||||
with open(f"saves/{accounts[account]['file']}", "r") as f:
|
||||
save = json.load(f)
|
||||
|
||||
save[str(ctx.guild.id)] = var
|
||||
|
||||
with open(f"saves/{accounts[account]['file']}", "w") as f:
|
||||
json.dump(save, f, indent=4)
|
||||
break
|
||||
except:
|
||||
time.sleep(0.5)
|
||||
|
||||
|
||||
def weird_shuffle(message):
|
||||
x = message
|
||||
o = []
|
||||
e = []
|
||||
ind = []
|
||||
gug = 0
|
||||
for i in x:
|
||||
o.append(i)
|
||||
f = len(x) / 2
|
||||
if f % 1 == 0:
|
||||
o.append(" ")
|
||||
gug = 1
|
||||
p = len(o)
|
||||
for u in range(0, p):
|
||||
ind.append(u)
|
||||
for ef in range(0, p):
|
||||
if max(ind) - ef * 2 < 0:
|
||||
break
|
||||
e.append(o[max(ind) - ef * 2])
|
||||
if min(ind) + 1 + (ef * 2) > max(ind):
|
||||
break
|
||||
e.append(o[min(ind) + 1 + (ef * 2)])
|
||||
zet = ["", p]
|
||||
if gug == 1:
|
||||
e.remove(e[0])
|
||||
zet[0] = " "
|
||||
zet[1] = p - 1
|
||||
gug = ""
|
||||
for ups in range(0, zet[1]):
|
||||
gug += e[ups]
|
||||
return zet[0] + gug
|
||||
|
||||
|
||||
def setup(client):
|
||||
client.add_cog(Edu_Info(client))
|
690
extensions/Edupage.py
Normal file
690
extensions/Edupage.py
Normal file
@ -0,0 +1,690 @@
|
||||
import json
|
||||
import time
|
||||
import requests
|
||||
from datetime import datetime, timedelta
|
||||
import copy
|
||||
import discord
|
||||
from discord.ext import commands
|
||||
from discord.ext import tasks
|
||||
import schedule
|
||||
import string
|
||||
|
||||
|
||||
class Edupage(commands.Cog):
|
||||
|
||||
def __init__(self, client):
|
||||
self.client = client
|
||||
self.update.start()
|
||||
|
||||
self.schedule_time = datetime.strptime("2020-11-10 7:00:00", '%Y-%m-%d %H:%M:%S')
|
||||
while self.schedule_time <= datetime.now():
|
||||
self.schedule_time += timedelta(hours=12)
|
||||
# self.schedule_time += timedelta(hours=-12) # turn this on to show deadlines on bot reset
|
||||
|
||||
@commands.command()
|
||||
@commands.has_permissions(administrator=True)
|
||||
async def mess(self, ctx, amount=1):
|
||||
try:
|
||||
update_database(ctx)
|
||||
|
||||
no_edu0 = False
|
||||
no_edu1 = False
|
||||
|
||||
with open("saves/edu.json", "r") as f:
|
||||
edu = json.load(f)
|
||||
edu = edu[str(ctx.guild.id)]
|
||||
with open("saves/edu0.json", "r") as f:
|
||||
try:
|
||||
edu0 = json.load(f)
|
||||
edu0 = edu0[str(ctx.guild.id)]
|
||||
if len(edu0.keys()) == 0:
|
||||
raise Exception("nothing inside")
|
||||
except:
|
||||
no_edu0 = True
|
||||
with open("saves/edu1.json", "r") as f:
|
||||
try:
|
||||
edu1 = json.load(f)
|
||||
edu1 = edu1[str(ctx.guild.id)]
|
||||
if len(edu1.keys()) == 0:
|
||||
raise Exception("nothing inside")
|
||||
except:
|
||||
no_edu1 = True
|
||||
|
||||
# going over edu
|
||||
messages = edu['timelineItems']
|
||||
to_show = []
|
||||
|
||||
for message in messages:
|
||||
if message["typ"] == "sprava":
|
||||
to_show.append(message)
|
||||
|
||||
# going over edu0
|
||||
to_show0 = []
|
||||
if no_edu0 is False:
|
||||
messages = edu0['timelineItems']
|
||||
|
||||
for message in messages:
|
||||
if message["typ"] == "sprava":
|
||||
to_show0.append(message)
|
||||
|
||||
# going over edu1
|
||||
to_show1 = []
|
||||
if no_edu1 is False:
|
||||
messages = edu1['timelineItems']
|
||||
|
||||
for message in messages:
|
||||
if message["typ"] == "sprava":
|
||||
to_show1.append(message)
|
||||
|
||||
# cutting the files to required size
|
||||
while len(to_show) > int(amount):
|
||||
del to_show[-1]
|
||||
|
||||
if no_edu0 is False:
|
||||
while len(to_show0) > int(amount):
|
||||
del to_show0[-1]
|
||||
|
||||
if no_edu1 is False:
|
||||
while len(to_show1) > int(amount):
|
||||
del to_show1[-1]
|
||||
|
||||
# merging them together
|
||||
merged = merge(to_show, to_show0, to_show1)
|
||||
|
||||
while len(merged) > int(amount):
|
||||
del merged[-1]
|
||||
|
||||
# displaying
|
||||
for message in merged:
|
||||
try:
|
||||
await ctx.send(f"```{message['cas_pridania']} {message['user_meno']}\n"
|
||||
f"{message['vlastnik_meno']}: {message['text']}```")
|
||||
except:
|
||||
mess = discord.Embed(title="Message",
|
||||
description=f"{message['user_meno']}")
|
||||
mess.add_field(name=f"{message['vlastnik_meno']}:",
|
||||
value=f"text way to long, will be displayed as string")
|
||||
await ctx.send(content=None, embed=mess)
|
||||
|
||||
# copying code from another bot i made
|
||||
message_content = message["text"].split("\n")
|
||||
lengths = list(map(len, message_content))
|
||||
|
||||
cur_length = lengths[0]
|
||||
low = 0
|
||||
for i in range(1, len(lengths)):
|
||||
if cur_length + lengths[i] > 1700: # space for 204 \n
|
||||
send_string = '\n'.join(message_content[low:i])
|
||||
try:
|
||||
await ctx.send(f"```{send_string}```")
|
||||
except:
|
||||
pass
|
||||
low = i
|
||||
cur_length = 0
|
||||
cur_length += lengths[i]
|
||||
except Exception as e:
|
||||
with open("saves/error_log.txt", "w+") as f:
|
||||
f.write(str(e))
|
||||
f.close()
|
||||
|
||||
@commands.command()
|
||||
@commands.has_permissions(administrator=True)
|
||||
async def homework(self, ctx, amount=1):
|
||||
try:
|
||||
update_database(ctx)
|
||||
|
||||
no_edu0 = False
|
||||
no_edu1 = False
|
||||
|
||||
with open("saves/edu.json", "r") as f:
|
||||
edu = json.load(f)
|
||||
edu = edu[str(ctx.guild.id)]
|
||||
with open("saves/edu0.json", "r") as f:
|
||||
try:
|
||||
edu0 = json.load(f)
|
||||
edu0 = edu0[str(ctx.guild.id)]
|
||||
if len(edu0.keys()) == 0:
|
||||
raise Exception("nothing inside")
|
||||
except:
|
||||
no_edu0 = True
|
||||
with open("saves/edu1.json", "r") as f:
|
||||
try:
|
||||
edu1 = json.load(f)
|
||||
edu1 = edu1[str(ctx.guild.id)]
|
||||
if len(edu1.keys()) == 0:
|
||||
raise Exception("nothing inside")
|
||||
except:
|
||||
no_edu1 = True
|
||||
|
||||
# going over edu
|
||||
messages = edu['homeworks']
|
||||
to_show = []
|
||||
|
||||
for message in messages:
|
||||
to_show.append(message)
|
||||
|
||||
# going over edu0
|
||||
to_show0 = []
|
||||
if no_edu0 is False:
|
||||
messages = edu0['homeworks']
|
||||
|
||||
for message in messages:
|
||||
to_show0.append(message)
|
||||
|
||||
# going over edu1
|
||||
to_show1 = []
|
||||
if no_edu1 is False:
|
||||
messages = edu1['homeworks']
|
||||
|
||||
for message in messages:
|
||||
to_show1.append(message)
|
||||
|
||||
# cutting the files to required size
|
||||
while len(to_show) > int(amount):
|
||||
del to_show[-1]
|
||||
|
||||
if no_edu0 is False:
|
||||
while len(to_show0) > int(amount):
|
||||
del to_show0[-1]
|
||||
|
||||
if no_edu1 is False:
|
||||
while len(to_show1) > int(amount):
|
||||
del to_show1[-1]
|
||||
|
||||
# merging them together
|
||||
merged = merge(to_show, to_show0, to_show1)
|
||||
|
||||
while len(merged) > int(amount):
|
||||
del merged[-1]
|
||||
|
||||
for message in merged:
|
||||
try:
|
||||
await ctx.send(f"```{message['datecreated']} {message['autor_meno']}\n"
|
||||
f"predmet: {message['predmet_meno']}:\n"
|
||||
f"text: {message['name']}\n"
|
||||
f"deadline: {message['datetimeto']}```")
|
||||
except:
|
||||
await ctx.send(f"```{message['datecreated']} {message['autor_meno']}\n"
|
||||
f"predmet: {message['predmet_meno']}:\n"
|
||||
f"text: {message['name']}\n"
|
||||
f"deadline: {message['dateto']}```")
|
||||
except Exception as e:
|
||||
with open("saves/error_log.txt", "w+") as f:
|
||||
f.write(str(e))
|
||||
f.close()
|
||||
|
||||
@commands.command()
|
||||
@commands.has_permissions(administrator=True)
|
||||
async def new(self, ctx): # not always context cause automation sometimes only channel is passed
|
||||
update_database(ctx)
|
||||
|
||||
no_edu0 = False
|
||||
no_edu1 = False
|
||||
|
||||
with open("saves/edu.json", "r") as f:
|
||||
edu = json.load(f)
|
||||
edu = edu[str(ctx.guild.id)]
|
||||
with open("saves/edu0.json", "r") as f:
|
||||
try:
|
||||
edu0 = json.load(f)
|
||||
edu0 = edu0[str(ctx.guild.id)]
|
||||
if len(edu0.keys()) == 0:
|
||||
raise Exception("nothing inside")
|
||||
except:
|
||||
no_edu0 = True
|
||||
with open("saves/edu1.json", "r") as f:
|
||||
try:
|
||||
edu1 = json.load(f)
|
||||
edu1 = edu1[str(ctx.guild.id)]
|
||||
if len(edu1.keys()) == 0:
|
||||
raise Exception("nothing inside")
|
||||
except:
|
||||
no_edu1 = True
|
||||
|
||||
with open("saves/old.json", "r") as f:
|
||||
oldMain = json.load(f)
|
||||
|
||||
old = oldMain[str(ctx.guild.id)]
|
||||
|
||||
new_e_superids = []
|
||||
new_timelineids = []
|
||||
|
||||
# handling homework
|
||||
messages = edu['homeworks']
|
||||
to_show = []
|
||||
for message in messages:
|
||||
try:
|
||||
if message["e_superid"] not in old["homework"].keys():
|
||||
to_show.append(message)
|
||||
new_e_superids.append(message["e_superid"])
|
||||
else:
|
||||
pass
|
||||
except:
|
||||
pass
|
||||
|
||||
to_show0 = []
|
||||
if no_edu0 is False:
|
||||
messages = edu0['homeworks']
|
||||
for message in messages:
|
||||
try:
|
||||
if message["e_superid"] not in old["homework"].keys():
|
||||
if message["e_superid"] not in new_e_superids:
|
||||
new_e_superids.append(message["e_superid"])
|
||||
to_show0.append(message)
|
||||
else:
|
||||
pass
|
||||
except:
|
||||
pass
|
||||
|
||||
to_show1 = []
|
||||
if no_edu1 is False:
|
||||
messages = edu1['homeworks']
|
||||
for message in messages:
|
||||
try:
|
||||
if message["e_superid"] not in old["homework"].keys():
|
||||
if message["e_superid"] not in new_e_superids:
|
||||
new_e_superids.append(message["e_superid"])
|
||||
to_show1.append(message)
|
||||
else:
|
||||
pass
|
||||
except:
|
||||
pass
|
||||
|
||||
# merged = merge(to_show, to_show0, to_show1)
|
||||
merged = to_show1 + to_show0 + to_show
|
||||
|
||||
# displaying
|
||||
if merged:
|
||||
for message in merged:
|
||||
try:
|
||||
homework = discord.Embed(title=f"Homework",
|
||||
description=f"{message['datecreated']} - {message['autor_meno']}")
|
||||
homework.add_field(name=f"Subject:",
|
||||
value=f"{message['predmet_meno']}")
|
||||
homework.add_field(name=f"Text:",
|
||||
value=f"{message['name']}")
|
||||
homework.add_field(name=f"Deadline:",
|
||||
value=f"{message['datetimeto']}")
|
||||
await ctx.send(content=None, embed=homework)
|
||||
except:
|
||||
homework = discord.Embed(title=f"Homework",
|
||||
description=f"{message['datecreated']} - {message['autor_meno']}")
|
||||
homework.add_field(name=f"Subject:",
|
||||
value=f"{message['predmet_meno']}")
|
||||
homework.add_field(name=f"Text:",
|
||||
value=f"{message['name']}")
|
||||
homework.add_field(name=f"Deadline:",
|
||||
value=f"{message['dateto']}")
|
||||
await ctx.send(content=None, embed=homework)
|
||||
|
||||
# handling messages
|
||||
# getting client names to remove private messages
|
||||
|
||||
with open("saves/accounts.json", "r") as f:
|
||||
accounts = json.load(f)
|
||||
accounts = accounts[str(ctx.guild.id)]
|
||||
|
||||
names = [accounts[x]["name"] for x in accounts.keys()]
|
||||
|
||||
for name in range(len(names)):
|
||||
i = 0
|
||||
li = 0
|
||||
for char in names[name]:
|
||||
if char in string.ascii_uppercase:
|
||||
i += 1
|
||||
if i == 2:
|
||||
names[name] = f"{names[name][:li]} {names[name][li:]}"
|
||||
li += 1
|
||||
|
||||
# getting names to filter from database
|
||||
|
||||
with open("saves/names.json", "r") as f:
|
||||
namesX = json.load(f)
|
||||
|
||||
try:
|
||||
names += namesX[str(ctx.guild.id)]
|
||||
except:
|
||||
pass
|
||||
|
||||
# looking for messages
|
||||
to_show = []
|
||||
messages = edu["timelineItems"]
|
||||
for message in messages:
|
||||
if message["timelineid"] not in old['messages'].keys():
|
||||
if message['typ'] == "sprava":
|
||||
if message["user_meno"] not in names:
|
||||
to_show.append(message)
|
||||
new_timelineids.append(message["timelineid"])
|
||||
else:
|
||||
pass
|
||||
|
||||
to_show0 = []
|
||||
if no_edu0 is False:
|
||||
messages = edu0["timelineItems"]
|
||||
for message in messages:
|
||||
if message["timelineid"] not in old['messages'].keys():
|
||||
if message["timelineid"] not in new_timelineids:
|
||||
if message['typ'] == "sprava":
|
||||
if message["user_meno"] not in names:
|
||||
to_show0.append(message)
|
||||
new_timelineids.append(message["timelineid"])
|
||||
else:
|
||||
pass
|
||||
|
||||
to_show1 = []
|
||||
if no_edu1 is False:
|
||||
messages = edu1["timelineItems"]
|
||||
for message in messages:
|
||||
if message["timelineid"] not in old['messages'].keys():
|
||||
if message["timelineid"] not in new_timelineids:
|
||||
if message['typ'] == "sprava":
|
||||
if message["user_meno"] not in names:
|
||||
to_show1.append(message)
|
||||
new_timelineids.append(message["timelineid"])
|
||||
else:
|
||||
pass
|
||||
|
||||
# merged = merge(to_show, to_show0, to_show1)
|
||||
merged = to_show1 + to_show0 + to_show
|
||||
|
||||
# displaying
|
||||
if merged:
|
||||
for message in merged:
|
||||
try:
|
||||
mess = discord.Embed(title="Message",
|
||||
description=f"{message['user_meno']}")
|
||||
mess.add_field(name=f"{message['vlastnik_meno']}:",
|
||||
value=f"{message['text']}")
|
||||
await ctx.send(content=None, embed=mess)
|
||||
except:
|
||||
mess = discord.Embed(title="Message",
|
||||
description=f"{message['user_meno']}")
|
||||
mess.add_field(name=f"{message['vlastnik_meno']}:",
|
||||
value=f"text way to long, will be displayed as string")
|
||||
await ctx.send(content=None, embed=mess)
|
||||
|
||||
# copying code from another bot i made
|
||||
message_content = message["text"].split("\n")
|
||||
lengths = list(map(len, message_content))
|
||||
|
||||
if sum(lengths) <= 1700:
|
||||
await ctx.send(f"```{message['text']}```")
|
||||
|
||||
cur_length = lengths[0]
|
||||
low = 0
|
||||
for i in range(1, len(lengths)):
|
||||
if cur_length + lengths[i] > 1700: # space for 204 \n
|
||||
send_string = '\n'.join(message_content[low:i])
|
||||
try:
|
||||
await ctx.send(f"```{send_string}```")
|
||||
except:
|
||||
pass
|
||||
low = i
|
||||
cur_length = 0
|
||||
cur_length += lengths[i]
|
||||
|
||||
# appending new messages to old ones
|
||||
for iD in new_e_superids:
|
||||
old["homework"][iD] = iD
|
||||
for iD in new_timelineids:
|
||||
old["messages"][iD] = iD
|
||||
|
||||
oldMain[str(ctx.guild.id)] = old
|
||||
|
||||
with open("saves/old.json", "w") as f:
|
||||
json.dump(oldMain, f, indent=4)
|
||||
|
||||
@commands.command()
|
||||
@commands.has_permissions(administrator=True)
|
||||
async def deadline(self, ctx):
|
||||
try:
|
||||
|
||||
no_edu0 = False
|
||||
no_edu1 = False
|
||||
|
||||
with open("saves/edu.json", "r") as f:
|
||||
edu = json.load(f)
|
||||
edu = edu[str(ctx.guild.id)]
|
||||
with open("saves/edu0.json", "r") as f:
|
||||
try:
|
||||
edu0 = json.load(f)
|
||||
edu0 = edu0[str(ctx.guild.id)]
|
||||
if len(edu0.keys()) == 0:
|
||||
raise Exception("nothing inside")
|
||||
except:
|
||||
no_edu0 = True
|
||||
with open("saves/edu1.json", "r") as f:
|
||||
try:
|
||||
edu1 = json.load(f)
|
||||
edu1 = edu1[str(ctx.guild.id)]
|
||||
if len(edu1.keys()) == 0:
|
||||
raise Exception("nothing inside")
|
||||
except:
|
||||
no_edu1 = True
|
||||
|
||||
edu = edu["homeworks"]
|
||||
if no_edu0 is False:
|
||||
edu0 = edu0["homeworks"]
|
||||
else:
|
||||
edu0 = []
|
||||
|
||||
if no_edu1 is False:
|
||||
edu1 = edu1["homeworks"]
|
||||
else:
|
||||
edu1 = []
|
||||
|
||||
merged = merge(edu, edu0, edu1)
|
||||
for message in merged:
|
||||
try:
|
||||
x = datetime.strptime(message["datetimeto"], '%Y-%m-%d %H:%M:%S')
|
||||
except:
|
||||
x = datetime.strptime(message["dateto"], '%Y-%m-%d')
|
||||
if datetime.now() + timedelta(days=1) > x > datetime.now():
|
||||
try:
|
||||
homework = discord.Embed(title=f"!!!DEADLINE!!!",
|
||||
description=f"{message['datecreated']} - {message['autor_meno']}")
|
||||
homework.add_field(name=f"Subject:",
|
||||
value=f"{message['predmet_meno']}")
|
||||
homework.add_field(name=f"Text:",
|
||||
value=f"{message['name']}")
|
||||
homework.add_field(name=f"Deadline:",
|
||||
value=f"{message['datetimeto']}")
|
||||
await ctx.send(content=None, embed=homework)
|
||||
except:
|
||||
homework = discord.Embed(title="!!!DEADLINE!!!",
|
||||
description=f"{message['datecreated']} - {message['autor_meno']}")
|
||||
homework.add_field(name=f"Subject:",
|
||||
value=f"{message['predmet_meno']}")
|
||||
homework.add_field(name=f"Text:",
|
||||
value=f"{message['name']}")
|
||||
homework.add_field(name=f"Deadline:",
|
||||
value=f"{message['dateto']}")
|
||||
await ctx.send(content=None, embed=homework)
|
||||
except Exception as e:
|
||||
with open("saves/error_log.txt", "w+") as f:
|
||||
f.write(str(e))
|
||||
f.close()
|
||||
|
||||
@tasks.loop(seconds=120.0)
|
||||
async def update(self):
|
||||
print("time for cycle")
|
||||
with open("saves/setup.json", "r") as f:
|
||||
setupX = json.load(f)
|
||||
|
||||
try:
|
||||
with open("saves/channels.json", "r") as f:
|
||||
channels = json.load(f)
|
||||
|
||||
for server in self.client.guilds:
|
||||
try:
|
||||
for channel in server.channels:
|
||||
if channel.name == channels[str(server.id)]:
|
||||
await self.new(channel)
|
||||
except Exception as e:
|
||||
if setupX[str(server.id)]['debug']:
|
||||
await server.channels[-1].send("A problem has occurred.")
|
||||
with open("saves/error_log.txt", "w+") as f:
|
||||
f.write(str(e))
|
||||
f.close()
|
||||
|
||||
now = datetime.now()
|
||||
if self.schedule_time <= now:
|
||||
for server in self.client.guilds:
|
||||
try:
|
||||
for channel in server.channels:
|
||||
if channel.name == channels[str(server.id)]:
|
||||
await self.deadline(channel)
|
||||
except:
|
||||
if setupX[str(server.id)]['debug']:
|
||||
await server.channels[-1].send("A problem has occurred.")
|
||||
self.schedule_time += timedelta(hours=12)
|
||||
except Exception as e:
|
||||
with open("saves/error_log.txt", "w+") as f:
|
||||
f.write(str(e))
|
||||
f.close()
|
||||
|
||||
|
||||
def update_database(ctx):
|
||||
# getting accounts
|
||||
with open("saves/accounts.json") as f:
|
||||
accounts = json.load(f)[str(ctx.guild.id)]
|
||||
|
||||
for account in accounts.keys():
|
||||
for i in range(6):
|
||||
try:
|
||||
url = 'https://zshorovaba.edupage.org/login/edubarLogin.php'
|
||||
headers = {
|
||||
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:82.0) Gecko/20100101 Firefox/82.0"}
|
||||
values = {'username': f"{accounts[account]['name']}",
|
||||
'password': f"{weird_shuffle(accounts[account]['password'])}"}
|
||||
if values['username'] == "JakubDuris":
|
||||
pass
|
||||
edupage = requests.session()
|
||||
edupage.post(url, data=values, headers=headers)
|
||||
r = edupage.get("https://zshorovaba.edupage.org/timeline/", headers=headers)
|
||||
x = r.text.split("\n")
|
||||
lines_to_del = []
|
||||
if values['username'] == "JakubDuris":
|
||||
pass
|
||||
for line in x:
|
||||
if len(line) < 10000:
|
||||
lines_to_del.append(line)
|
||||
|
||||
for line in lines_to_del:
|
||||
del x[x.index(line)]
|
||||
if values['username'] == "JakubDuris":
|
||||
pass
|
||||
|
||||
x = list(x[0])
|
||||
while x[0] != "{":
|
||||
del x[0]
|
||||
while x[-1] != "}":
|
||||
del x[-1]
|
||||
x = "".join(x)
|
||||
x = x.replace("false", "False").replace("true", "True").replace("null", "None")
|
||||
var = eval(x)
|
||||
|
||||
if values['username'] == "JakubDuris":
|
||||
pass
|
||||
with open(f"saves/{accounts[account]['file']}", "r") as f:
|
||||
save = json.load(f)
|
||||
|
||||
save[str(ctx.guild.id)] = var
|
||||
|
||||
with open(f"saves/{accounts[account]['file']}", "w") as f:
|
||||
json.dump(save, f, indent=4)
|
||||
break
|
||||
except Exception as e:
|
||||
time.sleep(0.5)
|
||||
print(accounts[account]['name'])
|
||||
print(str(e))
|
||||
|
||||
|
||||
def merge(list0, list1, *args):
|
||||
|
||||
try:
|
||||
if list0[0]['typ'] == "sprava":
|
||||
l0 = [[datetime.strptime(item['cas_pridania'], '%Y-%m-%d %H:%M:%S'), item] for item in list0]
|
||||
l1 = [[datetime.strptime(item['cas_pridania'], '%Y-%m-%d %H:%M:%S'), item] for item in list1]
|
||||
else:
|
||||
raise Exception
|
||||
except:
|
||||
l0 = [[datetime.strptime(item['datecreated'], '%Y-%m-%d %H:%M:%S'), item] for item in list0]
|
||||
l1 = [[datetime.strptime(item['datecreated'], '%Y-%m-%d %H:%M:%S'), item] for item in list1]
|
||||
|
||||
l2 = l0 + l1
|
||||
merged = copy.deepcopy(l2)
|
||||
|
||||
# remove duplicates
|
||||
|
||||
merged = unduplicate(merged)
|
||||
|
||||
skip = False
|
||||
if len(merged) < 2:
|
||||
skip = True
|
||||
|
||||
if skip is False:
|
||||
for i in range(1, len(merged)):
|
||||
while merged[i][0] < merged[i-1][0] and i > 0:
|
||||
c = merged[i]
|
||||
merged[i] = merged[i-1]
|
||||
merged[i-1] = c
|
||||
i -= 1
|
||||
|
||||
merged.reverse()
|
||||
merged = [item[1] for item in merged]
|
||||
|
||||
if len(args) > 0:
|
||||
for li in args:
|
||||
merged = merge(merged, li)
|
||||
|
||||
return merged
|
||||
|
||||
|
||||
def unduplicate(listX):
|
||||
for item in listX:
|
||||
l3 = copy.copy(listX)
|
||||
l3.remove(item)
|
||||
|
||||
for itemX in l3:
|
||||
if item[0] == itemX[0]:
|
||||
listX = unduplicate(l3)
|
||||
return listX
|
||||
return listX
|
||||
|
||||
|
||||
def weird_shuffle(message):
|
||||
x = message
|
||||
o = []
|
||||
e = []
|
||||
ind = []
|
||||
gug = 0
|
||||
for i in x:
|
||||
o.append(i)
|
||||
f = len(x) / 2
|
||||
if f % 1 == 0:
|
||||
o.append(" ")
|
||||
gug = 1
|
||||
p = len(o)
|
||||
for u in range(0, p):
|
||||
ind.append(u)
|
||||
for ef in range(0, p):
|
||||
if max(ind) - ef * 2 < 0:
|
||||
break
|
||||
e.append(o[max(ind) - ef * 2])
|
||||
if min(ind) + 1 + (ef * 2) > max(ind):
|
||||
break
|
||||
e.append(o[min(ind) + 1 + (ef * 2)])
|
||||
zet = ["", p]
|
||||
if gug == 1:
|
||||
e.remove(e[0])
|
||||
zet[0] = " "
|
||||
zet[1] = p - 1
|
||||
gug = ""
|
||||
for ups in range(0, zet[1]):
|
||||
gug += e[ups]
|
||||
return zet[0] + gug
|
||||
|
||||
|
||||
def setup(client):
|
||||
client.add_cog(Edupage(client))
|
253
extensions/Server_Management.py
Normal file
253
extensions/Server_Management.py
Normal file
@ -0,0 +1,253 @@
|
||||
import discord
|
||||
import random
|
||||
import json
|
||||
import time
|
||||
from discord.ext import commands
|
||||
|
||||
|
||||
class Server_Management(commands.Cog):
|
||||
|
||||
def __init__(self, client):
|
||||
self.client = client
|
||||
|
||||
@commands.Cog.listener()
|
||||
async def on_guild_join(self, guild):
|
||||
# adding prefix
|
||||
with open("saves/prefixes", "r") as f:
|
||||
prefixes = json.load(f)
|
||||
|
||||
try:
|
||||
prefixes[str(guild.id)]
|
||||
except:
|
||||
prefixes[str(guild.id)] = "&"
|
||||
|
||||
with open("saves/prefixes", "w") as f:
|
||||
json.dump(prefixes, f, indent=4)
|
||||
|
||||
# adding to setup.json
|
||||
|
||||
with open("saves/setup.json", "r") as f:
|
||||
setupX = json.load(f)
|
||||
|
||||
try:
|
||||
setupX[str(guild.id)]
|
||||
except:
|
||||
setupX[str(guild.id)] = {"save": False,
|
||||
"guild_name": guild.name,
|
||||
"debug": False}
|
||||
|
||||
with open("saves/setup.json", "w") as f:
|
||||
json.dump(setupX, f, indent=4)
|
||||
|
||||
# adding accounts
|
||||
|
||||
with open("saves/accounts.json", "r") as f:
|
||||
accounts = json.load(f)
|
||||
|
||||
try:
|
||||
accounts[str(guild.id)]
|
||||
except:
|
||||
accounts[str(guild.id)] = {}
|
||||
|
||||
with open("saves/accounts.json", "w") as f:
|
||||
json.dump(accounts, f, indent=4)
|
||||
|
||||
# adding channel
|
||||
|
||||
with open("saves/channels.json", "r") as f:
|
||||
channels = json.load(f)
|
||||
|
||||
try:
|
||||
channels[str(guild.id)]
|
||||
except:
|
||||
channels[str(guild.id)] = guild.text_channels[len(guild.text_channels)-1].name
|
||||
|
||||
await guild.text_channels[len(guild.text_channels)-1].send("This channel has been chosen by Edu-Kun by default "
|
||||
"as channel where bot sends messages(notifications)\n"
|
||||
"U can change this with command &set_channel "
|
||||
"<channel_name>\n "
|
||||
"\n\t\tuse &help to get more information")
|
||||
|
||||
with open("saves/channels.json", "w") as f:
|
||||
json.dump(channels, f, indent=4)
|
||||
|
||||
# adding to old messages file
|
||||
|
||||
with open("saves/old.json", "r") as f:
|
||||
old = json.load(f)
|
||||
|
||||
try:
|
||||
old[str(guild.id)]
|
||||
except:
|
||||
old[str(guild.id)] = {
|
||||
"homework": {},
|
||||
"messages": {}
|
||||
}
|
||||
|
||||
with open("saves/old.json", "w") as f:
|
||||
json.dump(old, f, indent=4)
|
||||
|
||||
@commands.command(hidden=True)
|
||||
async def secretxxx(self, ctx):
|
||||
for guild in self.client.guilds:
|
||||
await self.on_guild_join(guild)
|
||||
|
||||
@commands.Cog.listener()
|
||||
async def on_guild_remove(self, guild):
|
||||
gi = str(guild.id)
|
||||
|
||||
# checking if we want to delete or save the data
|
||||
with open("saves/setup.json", "r") as f:
|
||||
setupX = json.load(f)
|
||||
|
||||
if setupX[str(guild.id)]["save"] is False:
|
||||
# removing prefix
|
||||
with open("saves/prefixes", "r") as f:
|
||||
prefixes = json.load(f)
|
||||
|
||||
prefixes.pop(gi)
|
||||
|
||||
with open("saves/prefixes", "w") as f:
|
||||
json.dump(prefixes, f, indent=4)
|
||||
|
||||
# removing accounts
|
||||
with open("saves/accounts.json", "r") as f:
|
||||
accounts = json.load(f)
|
||||
|
||||
accounts.pop(gi)
|
||||
|
||||
with open("saves/accounts.json", "w") as f:
|
||||
json.dump(accounts, f, indent=4)
|
||||
|
||||
# removing channel
|
||||
with open("saves/channels.json", "r") as f:
|
||||
channels = json.load(f)
|
||||
|
||||
channels.pop(gi)
|
||||
|
||||
with open("saves/channels.json", "w") as f:
|
||||
json.dump(channels, f, indent=4)
|
||||
|
||||
# removing list of old messages
|
||||
with open("saves/old.json", "r") as f:
|
||||
old = json.load(f)
|
||||
|
||||
old.pop(gi)
|
||||
|
||||
with open("saves/old.json", "w") as f:
|
||||
json.dump(old, f, indent=4)
|
||||
|
||||
try:
|
||||
# removing accounts
|
||||
with open("saves/edu.json", "r") as f:
|
||||
save = json.load(f)
|
||||
|
||||
save.pop(gi)
|
||||
|
||||
with open("saves/edu.json", "w") as f:
|
||||
json.dump(save, f, indent=4)
|
||||
except:
|
||||
pass
|
||||
|
||||
try:
|
||||
# removing accounts
|
||||
with open("saves/edu0.json", "r") as f:
|
||||
save = json.load(f)
|
||||
|
||||
save.pop(gi)
|
||||
|
||||
with open("saves/edu0.json", "w") as f:
|
||||
json.dump(save, f, indent=4)
|
||||
except:
|
||||
pass
|
||||
|
||||
try:
|
||||
# removing accounts
|
||||
with open("saves/edu1.json", "r") as f:
|
||||
save = json.load(f)
|
||||
|
||||
save.pop(gi)
|
||||
|
||||
with open("saves/edu1.json", "w") as f:
|
||||
json.dump(save, f, indent=4)
|
||||
except:
|
||||
pass
|
||||
|
||||
with open("saves/setup.json", "r") as f:
|
||||
setupX = json.load(f)
|
||||
|
||||
setupX.pop(gi)
|
||||
|
||||
with open("saves/setup.json", "w") as f:
|
||||
json.dump(setupX, f, indent=4)
|
||||
|
||||
with open("saves/names.json", "r") as f:
|
||||
names = json.load(f)
|
||||
|
||||
try:
|
||||
names.pop(gi)
|
||||
except:
|
||||
pass
|
||||
|
||||
with open("saves/names.json", "w") as f:
|
||||
json.dump(names, f, indent=4)
|
||||
|
||||
@commands.Cog.listener()
|
||||
async def on_message(self, message):
|
||||
if message.author == self.client.user:
|
||||
return
|
||||
|
||||
# server management commands
|
||||
@commands.command()
|
||||
@commands.has_permissions(administrator=True)
|
||||
async def change_prefix(self, ctx, *, prefix):
|
||||
with open("saves/prefixes", "r") as f:
|
||||
prefixes = json.load(f)
|
||||
|
||||
prefixes[str(ctx.guild.id)] = prefix
|
||||
|
||||
with open("saves/prefixes", "w") as f:
|
||||
json.dump(prefixes, f, indent=4)
|
||||
|
||||
await ctx.send(f"Prefix changed to '{prefix}'.")
|
||||
|
||||
@commands.command()
|
||||
@commands.has_permissions(administrator=True)
|
||||
async def save_on_quit(self, ctx, *, bool_):
|
||||
if bool_ in ["False", "false", "no", "No"]:
|
||||
|
||||
with open("saves/setup.json", "r") as f:
|
||||
store = json.load(f)
|
||||
|
||||
store[str(ctx.guild.id)]["save"] = False
|
||||
|
||||
with open("saves/setup.json", "w") as f:
|
||||
json.dump(store, f, indent=4)
|
||||
|
||||
await ctx.send("Saving on quit is turned off.")
|
||||
|
||||
elif bool_ in ["True", "true", "yes", "Yes"]:
|
||||
|
||||
with open("saves/setup.json", "r") as f:
|
||||
store = json.load(f)
|
||||
|
||||
store[str(ctx.guild.id)]["save"] = True
|
||||
|
||||
with open("saves/setup.json", "w") as f:
|
||||
json.dump(store, f, indent=4)
|
||||
|
||||
await ctx.send("Saving on quit is turned on.")
|
||||
|
||||
@commands.command()
|
||||
@commands.has_permissions(manage_messages=True)
|
||||
async def clear(self, ctx, amount=5):
|
||||
amount = int(amount)
|
||||
if amount > 1000:
|
||||
amount = 1000
|
||||
amount += 1
|
||||
await ctx.channel.purge(limit=amount)
|
||||
await ctx.send(f"Cleared {amount - 1} messages.")
|
||||
|
||||
|
||||
def setup(client):
|
||||
client.add_cog(Server_Management(client))
|
407
extensions/Setup.py
Normal file
407
extensions/Setup.py
Normal file
@ -0,0 +1,407 @@
|
||||
import json
|
||||
import string
|
||||
import time
|
||||
import requests
|
||||
import discord
|
||||
from discord.ext import commands
|
||||
|
||||
|
||||
class Setup(commands.Cog):
|
||||
|
||||
def __init__(self, client):
|
||||
self.client = client
|
||||
|
||||
@commands.command()
|
||||
@commands.has_permissions(administrator=True)
|
||||
async def add_client(self, ctx, name, password, save_number_0_1_2):
|
||||
with open("saves/accounts.json", "r") as f:
|
||||
accounts = json.load(f)
|
||||
|
||||
save_num = int(save_number_0_1_2)-1
|
||||
if save_num == -1:
|
||||
save_num = ""
|
||||
|
||||
server_accounts = accounts[str(ctx.guild.id)]
|
||||
|
||||
server_accounts[name] = {"name": name,
|
||||
"password": weird_shuffle(password),
|
||||
"file": f"edu{save_num}.json"}
|
||||
|
||||
accounts[str(ctx.guild.id)] = server_accounts
|
||||
|
||||
await ctx.channel.purge(limit=1)
|
||||
|
||||
await ctx.send(f"Client for account {name} added.")
|
||||
|
||||
with open("saves/accounts.json", "w") as f:
|
||||
json.dump(accounts, f, indent=4)
|
||||
|
||||
await self.h_m(ctx)
|
||||
|
||||
@commands.command()
|
||||
@commands.has_permissions(administrator=True)
|
||||
async def clear_clients(self, ctx):
|
||||
with open("saves/accounts.json", "r") as f:
|
||||
accounts = json.load(f)
|
||||
|
||||
accounts[str(ctx.guild.id)] = {}
|
||||
|
||||
await ctx.send("Cleared clients.")
|
||||
|
||||
with open("saves/accounts.json", "w") as f:
|
||||
json.dump(accounts, f, indent=4)
|
||||
|
||||
# removing accounts
|
||||
with open("saves/edu.json", "r") as f:
|
||||
save = json.load(f)
|
||||
|
||||
save[str(ctx.guild.id)] = {}
|
||||
|
||||
with open("saves/edu.json", "w") as f:
|
||||
json.dump(save, f, indent=4)
|
||||
|
||||
# removing accounts
|
||||
with open("saves/edu0.json", "r") as f:
|
||||
save = json.load(f)
|
||||
|
||||
save[str(ctx.guild.id)] = {}
|
||||
|
||||
with open("saves/edu0.json", "w") as f:
|
||||
json.dump(save, f, indent=4)
|
||||
|
||||
# removing accounts
|
||||
with open("saves/edu1.json", "r") as f:
|
||||
save = json.load(f)
|
||||
|
||||
save[str(ctx.guild.id)] = {}
|
||||
|
||||
with open("saves/edu1.json", "w") as f:
|
||||
json.dump(save, f, indent=4)
|
||||
|
||||
@commands.command()
|
||||
@commands.has_permissions(administrator=True)
|
||||
async def set_channel(self, ctx, channel_name):
|
||||
with open("saves/channels.json", "r") as f:
|
||||
channels = json.load(f)
|
||||
|
||||
channels[str(ctx.guild.id)] = channel_name
|
||||
|
||||
for channel in ctx.guild.channels:
|
||||
if channel.name == channel_name:
|
||||
await channel.send("This channel is now set as the channel where bot sends messages(notifications).\n"
|
||||
f"<@{ctx.author.id}>")
|
||||
|
||||
with open("saves/channels.json", "w") as f:
|
||||
json.dump(channels, f, indent=4)
|
||||
|
||||
@commands.command()
|
||||
@commands.has_permissions(administrator=True)
|
||||
async def debug(self, ctx, True_False):
|
||||
if True_False in ["True", "true"]:
|
||||
|
||||
with open("saves/setup.json", "r") as f:
|
||||
setupX = json.load(f)
|
||||
|
||||
setupX[str(ctx.guild.id)]['debug'] = True
|
||||
|
||||
with open("saves/setup.json", "w") as f:
|
||||
json.dump(setupX, f, indent=4)
|
||||
|
||||
await ctx.send("Debug is now on.")
|
||||
elif True_False in ["False", "false"]:
|
||||
|
||||
with open("saves/setup.json", "r") as f:
|
||||
setupX = json.load(f)
|
||||
|
||||
setupX[str(ctx.guild.id)]['debug'] = False
|
||||
|
||||
with open("saves/setup.json", "w") as f:
|
||||
json.dump(setupX, f, indent=4)
|
||||
|
||||
await ctx.send("Debug is now off.")
|
||||
|
||||
@commands.command()
|
||||
@commands.has_permissions(administrator=True)
|
||||
async def h_m(self, ctx):
|
||||
update_database(ctx)
|
||||
|
||||
no_edu0 = False
|
||||
no_edu1 = False
|
||||
|
||||
with open("saves/edu.json", "r") as f:
|
||||
edu = json.load(f)
|
||||
edu = edu[str(ctx.guild.id)]
|
||||
with open("saves/edu0.json", "r") as f:
|
||||
try:
|
||||
edu0 = json.load(f)
|
||||
edu0 = edu0[str(ctx.guild.id)]
|
||||
if len(edu0.keys()) == 0:
|
||||
raise Exception("nothing inside")
|
||||
except:
|
||||
no_edu0 = True
|
||||
with open("saves/edu1.json", "r") as f:
|
||||
try:
|
||||
edu1 = json.load(f)
|
||||
edu1 = edu1[str(ctx.guild.id)]
|
||||
if len(edu1.keys()) == 0:
|
||||
raise Exception("nothing inside")
|
||||
except:
|
||||
no_edu1 = True
|
||||
|
||||
with open("saves/old.json", "r") as f:
|
||||
oldMain = json.load(f)
|
||||
|
||||
old = oldMain[str(ctx.guild.id)]
|
||||
|
||||
new_e_superids = []
|
||||
new_timelineids = []
|
||||
|
||||
# handling homework
|
||||
messages = edu['homeworks']
|
||||
to_show = []
|
||||
for message in messages:
|
||||
try:
|
||||
if message["e_superid"] not in old["homework"].keys():
|
||||
to_show.append(message)
|
||||
new_e_superids.append(message["e_superid"])
|
||||
else:
|
||||
pass
|
||||
except:
|
||||
pass
|
||||
|
||||
to_show0 = []
|
||||
if no_edu0 is False:
|
||||
messages = edu0['homeworks']
|
||||
for message in messages:
|
||||
try:
|
||||
if message["e_superid"] not in old["homework"].keys():
|
||||
if message["e_superid"] not in new_e_superids:
|
||||
new_e_superids.append(message["e_superid"])
|
||||
to_show0.append(message)
|
||||
else:
|
||||
pass
|
||||
except:
|
||||
pass
|
||||
|
||||
to_show1 = []
|
||||
if no_edu1 is False:
|
||||
messages = edu1['homeworks']
|
||||
for message in messages:
|
||||
try:
|
||||
if message["e_superid"] not in old["homework"].keys():
|
||||
if message["e_superid"] not in new_e_superids:
|
||||
new_e_superids.append(message["e_superid"])
|
||||
to_show1.append(message)
|
||||
else:
|
||||
pass
|
||||
except:
|
||||
pass
|
||||
|
||||
# handling messages
|
||||
# getting client names to remove private messages
|
||||
|
||||
with open("saves/accounts.json", "r") as f:
|
||||
accounts = json.load(f)
|
||||
accounts = accounts[str(ctx.guild.id)]
|
||||
|
||||
names = [accounts[x]["name"] for x in accounts.keys()]
|
||||
|
||||
for name in range(len(names)):
|
||||
i = 0
|
||||
li = 0
|
||||
for char in names[name]:
|
||||
if char in string.ascii_uppercase:
|
||||
i += 1
|
||||
if i == 2:
|
||||
names[name] = f"{names[name][:li]} {names[name][li:]}"
|
||||
li += 1
|
||||
|
||||
# looking for messages
|
||||
to_show = []
|
||||
messages = edu["timelineItems"]
|
||||
for message in messages:
|
||||
if message["timelineid"] not in old['messages'].keys():
|
||||
if message['typ'] == "sprava":
|
||||
if message["user_meno"] not in names:
|
||||
to_show.append(message)
|
||||
new_timelineids.append(message["timelineid"])
|
||||
else:
|
||||
pass
|
||||
|
||||
to_show0 = []
|
||||
if no_edu0 is False:
|
||||
messages = edu0["timelineItems"]
|
||||
for message in messages:
|
||||
if message["timelineid"] not in old['messages'].keys():
|
||||
if message["timelineid"] not in new_timelineids:
|
||||
if message['typ'] == "sprava":
|
||||
if message["user_meno"] not in names:
|
||||
to_show0.append(message)
|
||||
new_timelineids.append(message["timelineid"])
|
||||
else:
|
||||
pass
|
||||
|
||||
to_show1 = []
|
||||
if no_edu1 is False:
|
||||
messages = edu1["timelineItems"]
|
||||
for message in messages:
|
||||
if message["timelineid"] not in old['messages'].keys():
|
||||
if message["timelineid"] not in new_timelineids:
|
||||
if message['typ'] == "sprava":
|
||||
if message["user_meno"] not in names:
|
||||
to_show1.append(message)
|
||||
new_timelineids.append(message["timelineid"])
|
||||
else:
|
||||
pass
|
||||
|
||||
# appending new messages to old ones
|
||||
for iD in new_e_superids:
|
||||
old["homework"][iD] = iD
|
||||
for iD in new_timelineids:
|
||||
old["messages"][iD] = iD
|
||||
|
||||
oldMain[str(ctx.guild.id)] = old
|
||||
|
||||
with open("saves/old.json", "w") as f:
|
||||
json.dump(oldMain, f, indent=4)
|
||||
|
||||
await ctx.send("Done")
|
||||
|
||||
@commands.command()
|
||||
@commands.has_permissions(administrator=True)
|
||||
async def filter_name(self, ctx, *, name):
|
||||
with open("saves/names.json", "r") as f:
|
||||
names = json.load(f)
|
||||
|
||||
try:
|
||||
names[str(ctx.guild.id)]
|
||||
except Exception as e:
|
||||
names[str(ctx.guild.id)] = []
|
||||
|
||||
names[str(ctx.guild.id)].append(str(name))
|
||||
|
||||
with open("saves/names.json", "w") as f:
|
||||
json.dump(names, f, indent=4)
|
||||
|
||||
await ctx.send(f"Name {name} added to filter.")
|
||||
|
||||
@commands.command()
|
||||
@commands.has_permissions(administrator=True)
|
||||
async def clear_filter(self, ctx):
|
||||
with open("saves/names.json", "r") as f:
|
||||
names = json.load(f)
|
||||
|
||||
names.pop(str(ctx.guild.id))
|
||||
|
||||
with open("saves/names.json", "w") as f:
|
||||
json.dump(names, f, indent=4)
|
||||
|
||||
await ctx.send("Filter cleared.")
|
||||
|
||||
@commands.command()
|
||||
@commands.has_permissions(administrator=True)
|
||||
async def HOW_TO_SETUP(self, ctx):
|
||||
tutorial = discord.Embed(title="Tutorial")
|
||||
|
||||
tutorial.add_field(name="1. setting channel",
|
||||
value="use &set_channel <channel-name> to set channel where bot should send notifications.")
|
||||
tutorial.add_field(name="2. adding clients",
|
||||
value="use &add_client <username-on-edupage> <password-on-edupage> <number of save>\n"
|
||||
"Number of save can be either 0, 1 or 2, one save can have maximum of 1 account.\n"
|
||||
"If something isnt working u can use &clear_clients to reset.")
|
||||
tutorial.add_field(name="3. filtering",
|
||||
value="This is for special cases, normally personal messages are filtered automatically"
|
||||
" using edupage username but in some cases edupage uses different name than username"
|
||||
"for messages. \nTo fix this we use &filter_name <name_to_filter> that filters private "
|
||||
"messages with that name, parameter <name_to_filter> can contain spaces.\n"
|
||||
"If you made a mistake u can use &clear_filter to reset filtered names.")
|
||||
tutorial.add_field(name="4. not working",
|
||||
value="If bot starts spamming messages and isnt stopping(this shouldnt happen)\n"
|
||||
"try using &h_m.\n"
|
||||
"Lastly theres &debug <true/false>, use this if u want to know if bot is dead or u did"
|
||||
" a mistake while adding clients, if u did a mistake it should start sending message "
|
||||
"'A problem has occurred' somewhere.")
|
||||
await ctx.send(content=None, embed=tutorial)
|
||||
|
||||
|
||||
def update_database(ctx):
|
||||
# getting accounts
|
||||
with open("saves/accounts.json") as f:
|
||||
accounts = json.load(f)[str(ctx.guild.id)]
|
||||
|
||||
for account in accounts.keys():
|
||||
for i in range(6):
|
||||
try:
|
||||
url = 'https://zshorovaba.edupage.org/login/edubarLogin.php'
|
||||
headers = {
|
||||
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:82.0) Gecko/20100101 Firefox/82.0"}
|
||||
values = {'username': f"{accounts[account]['name']}",
|
||||
'password': f"{weird_shuffle(accounts[account]['password'])}"}
|
||||
edupage = requests.session()
|
||||
edupage.post(url, data=values, headers=headers)
|
||||
r = edupage.get("https://zshorovaba.edupage.org/timeline/", headers=headers)
|
||||
x = r.text.split("\n")
|
||||
lines_to_del = []
|
||||
for line in x:
|
||||
if len(line) < 10000:
|
||||
lines_to_del.append(line)
|
||||
|
||||
for line in lines_to_del:
|
||||
del x[x.index(line)]
|
||||
|
||||
x = list(x[0])
|
||||
while x[0] != "{":
|
||||
del x[0]
|
||||
while x[-1] != "}":
|
||||
del x[-1]
|
||||
x = "".join(x)
|
||||
x = x.replace("false", "False").replace("true", "True").replace("null", "None")
|
||||
var = eval(x)
|
||||
|
||||
with open(f"saves/{accounts[account]['file']}", "r") as f:
|
||||
save = json.load(f)
|
||||
|
||||
save[str(ctx.guild.id)] = var
|
||||
|
||||
with open(f"saves/{accounts[account]['file']}", "w") as f:
|
||||
json.dump(save, f, indent=4)
|
||||
break
|
||||
except:
|
||||
time.sleep(0.5)
|
||||
|
||||
|
||||
def weird_shuffle(message):
|
||||
x = message
|
||||
o = []
|
||||
e = []
|
||||
ind = []
|
||||
gug = 0
|
||||
for i in x:
|
||||
o.append(i)
|
||||
f = len(x) / 2
|
||||
if f % 1 == 0:
|
||||
o.append(" ")
|
||||
gug = 1
|
||||
p = len(o)
|
||||
for u in range(0, p):
|
||||
ind.append(u)
|
||||
for ef in range(0, p):
|
||||
if max(ind) - ef * 2 < 0:
|
||||
break
|
||||
e.append(o[max(ind) - ef * 2])
|
||||
if min(ind) + 1 + (ef * 2) > max(ind):
|
||||
break
|
||||
e.append(o[min(ind) + 1 + (ef * 2)])
|
||||
zet = ["", p]
|
||||
if gug == 1:
|
||||
e.remove(e[0])
|
||||
zet[0] = " "
|
||||
zet[1] = p - 1
|
||||
gug = ""
|
||||
for ups in range(0, zet[1]):
|
||||
gug += e[ups]
|
||||
return zet[0] + gug
|
||||
|
||||
|
||||
def setup(client):
|
||||
client.add_cog(Setup(client))
|
1
saves/accounts.json
Normal file
1
saves/accounts.json
Normal file
@ -0,0 +1 @@
|
||||
{}
|
1
saves/channels.json
Normal file
1
saves/channels.json
Normal file
@ -0,0 +1 @@
|
||||
{}
|
1
saves/edu.json
Normal file
1
saves/edu.json
Normal file
@ -0,0 +1 @@
|
||||
{}
|
1
saves/edu0.json
Normal file
1
saves/edu0.json
Normal file
@ -0,0 +1 @@
|
||||
{}
|
1
saves/edu1.json
Normal file
1
saves/edu1.json
Normal file
@ -0,0 +1 @@
|
||||
{}
|
0
saves/error_log.txt
Normal file
0
saves/error_log.txt
Normal file
1
saves/names.json
Normal file
1
saves/names.json
Normal file
@ -0,0 +1 @@
|
||||
{}
|
1
saves/old.json
Normal file
1
saves/old.json
Normal file
@ -0,0 +1 @@
|
||||
{}
|
1
saves/prefixes
Normal file
1
saves/prefixes
Normal file
@ -0,0 +1 @@
|
||||
{}
|
1
saves/setup.json
Normal file
1
saves/setup.json
Normal file
@ -0,0 +1 @@
|
||||
{}
|
Reference in New Issue
Block a user