Skip to content

Commit

Permalink
Cleanup+bugfixes
Browse files Browse the repository at this point in the history
  • Loading branch information
LuminatiHD committed Dec 21, 2021
1 parent bfb0270 commit 87e9ec5
Show file tree
Hide file tree
Showing 13 changed files with 230 additions and 98 deletions.
59 changes: 59 additions & 0 deletions Briefing/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import sqlite3
import Buttons
from Buttons import ChooseWeekdays, ChooseTime, choose_EF, choose_KF, choose_SF, Confirm
from datetime import date, datetime, timedelta
import FuncLibrary
from Briefing import editsettings

Expand Down Expand Up @@ -71,3 +72,61 @@ async def briefing(self, ctx:Context):

def setup(client):
client.add_cog(Briefing(client))


def outputbriefing(user, ef, sf, kf, mint):
weekdays = FuncLibrary.weekdays
output = nextcord.Embed(title=f"{weekdays[date.today().weekday()]}, "
f"{date.today().day}.{date.today().month}.{str(date.today().year)[2:]} "
f"({datetime.now().hour}:{datetime.now().minute:02})")

timeset = date.today()+timedelta(days=7)
items = cs.execute(f"SELECT * FROM items WHERE datum <= ? AND (access = 'all' " \
f"OR access = ? OR access = ? " \
f"OR access = ? OR access = ?) ORDER BY datum",
(timeset, user.id, sf, ef, kf)).fetchall()

output.add_field(name="AUFGABEN UND TESTS DIESE WOCHE:",
value=f"(Bis {timeset.day}.{timeset.month}.{timeset.year})", inline=False)

if items:
for item in items:
desc = item[3]
if not desc: # Wenn man keine Lernziele angegeben hat, dann ist desc=None.
desc = "Keine Lernziele"

elif len(desc) > 20:
desc = item[3][:20] + "..." # wöu schüsch chasch du lernziele ha wo viu ds läng si.

(year, month, day) = item[0].split("-")
itemdate = date(int(year), int(month), int(day))
output.add_field(name=f" {item[1].capitalize()} {item[2]}",
value=f" {str(weekdays[itemdate.weekday()])}, "
f"{day}.{month}.{year}\n {desc}\n ",
inline=False)

else:
output.add_field(name="Es ist nichts zu tun", value="Du kannst mit !new etwas hinzufügen.", inline=False)

currdate = (datetime.now()+timedelta(hours=24-17)).date()
tag = currdate.weekday()
wochentage = ["Mo", "Di", "Mi", "Do", "Fr"]

if tag > 4:
tag = (currdate + (timedelta(7) - timedelta(tag))).weekday() # tag wird ufe mänti gsetzt
output.add_field(name=".", value="**DER STUNDENPLAN VON MONTAG:**")

elif currdate == date.today():
output.add_field(name=".", value="**DER STUNDENPLAN VON HEUTE:**")

else:
output.add_field(name=".", value="**DER STUNDENPLAN VON MORGEN**")

allitems = cs.execute(f"SELECT fach, time, room FROM Stundenplan_23b WHERE weekday = ?" \
" AND (access='all' OR access = ? OR access = ? OR access = ? OR access=?)", \
(wochentage[tag], ef, sf, kf, mint)).fetchall()

allitems.sort(key=lambda elem: elem[1])
for i in allitems:
output.add_field(name=i[0], value=f"{i[1]}\n{i[2]}", inline=False)
return output
6 changes: 6 additions & 0 deletions Buttons.py
Original file line number Diff line number Diff line change
Expand Up @@ -625,6 +625,12 @@ async def edit_time(self, button:nextcord.ui.Button, interaction:nextcord.Intera
self.choice = "time"
self.stop()

@nextcord.ui.button(label="o", style=nextcord.ButtonStyle.primary)
async def delmsg(self, button:nextcord.ui.Button, interaction:nextcord.Interaction):
if await testinter(interaction, self.ctx):
self.choice = None
self.stop()

@nextcord.ui.button(label="Fächer ändern", style=nextcord.ButtonStyle.primary)
async def edit_classes(self, button:nextcord.ui.Button, interaction:nextcord.Interaction):
if await testinter(interaction, self.ctx):
Expand Down
4 changes: 2 additions & 2 deletions FuncLibrary.py
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ def layout(items, footer):
tmrw = True

# week_1 teschtet öb ds scho isch vergäh worde, wenn nid de machter das häre
elif itemdate <= date.today() + timedelta(7) and not week_1:
elif date.today()+timedelta(1)< itemdate <= date.today() + timedelta(7) and not week_1:
zeit = date.today() + timedelta(7)
output.add_field(name="__\nBIS NÄCHSTE WOCHE:__",
value=f"(Bis zum {zeit.day}.{zeit.month}.{zeit.year})",
Expand Down Expand Up @@ -193,7 +193,7 @@ def outputbriefing(user, ef, sf, kf, mint):
inline=False)

else:
output.add_field(name="Es ist nichts zu tun", value="Du kannst mit !new etwas hinzufügen\n.", inline=False)
output.add_field(name="Es ist nichts zu tun", value="Du kannst mit !new etwas hinzufügen.", inline=False)

currdate = (datetime.now()+timedelta(hours=24-17)).date()
tag = currdate.weekday()
Expand Down
Binary file modified ItemFiles.db
Binary file not shown.
10 changes: 6 additions & 4 deletions Items/editItem.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,9 +46,10 @@ async def editItem(self, ctx, selecteditem, editor):
confirm = Buttons.Confirm(ctx)
await ctx.reply("Aufgabe: ")
newaufg = await self.bot.wait_for("message", check=lambda msg: msg.author == ctx.author)
await newaufg.reply(f"Alte Aufgabe: {selecteditem[3]}\nNeue Aufgabe: {newaufg.content}.\nBestätigen?",
confirmmsg = await newaufg.reply(f"Alte Aufgabe: {selecteditem[3]}\nNeue Aufgabe: {newaufg.content}.\nBestätigen?",
view=confirm)
await confirm.wait()
await confirmmsg.delete()
database.cursor().execute(
f"UPDATE {Itemtable} SET aufgabe = ? WHERE rowid = ?",
(newaufg.content, selecteditem[5]))
Expand All @@ -70,9 +71,10 @@ async def editItem(self, ctx, selecteditem, editor):
int(selecteditem[0].split("-")[1]),
int(selecteditem[0].split("-")[2]))

await dateraw.reply(f"Altes Datum: {olddatum.day}.{olddatum.month}.{olddatum.year}"
confirmmsg = await dateraw.reply(f"Altes Datum: {olddatum.day}.{olddatum.month}.{olddatum.year}"
f"\nNeues Datum: {datum.day}.{datum.month}.{datum.year}\nBestätigen?", view=confirm)
await confirm.wait()
await confirmmsg.delete()
error = False
except (ValueError, TypeError, IndexError):
await ctx.reply("ungültiges Datum")
Expand All @@ -88,14 +90,14 @@ async def editItem(self, ctx, selecteditem, editor):
await ctx.reply("Fach: ")
newfach = await self.bot.wait_for("message", check=lambda msg: msg.author == ctx.author)

await newfach.reply(f"Altes Fach: {selecteditem[2]}\nNeues Fach: "
confirmmsg = await newfach.reply(f"Altes Fach: {selecteditem[2]}\nNeues Fach: "
f"{FuncLibrary.changefachname(newfach.content)}.\nBestätigen?", view=confirm)
await confirm.wait()
await confirmmsg.delete()

database.cursor().execute(
f"UPDATE {Itemtable} SET fach = ? WHERE rowid = ?",
(FuncLibrary.changefachname(newfach.content), selecteditem[5]))

elif "access" in editorbtn.edit:
confirm = Buttons.Confirm(ctx)
while not confirm.confirm:
Expand Down
4 changes: 2 additions & 2 deletions Items/searchItem.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ async def todo(self, ctx: Context):

if results: # aaschiinend giut ä lääri lischte aus ä boolean, ka bro
buttons = Buttons.PageButtons(results, 0, ctx)
outputmsg = await ctx.reply(embed=FuncLibrary.layout(selection,
outputmsg = await ctx.channel.send(embed=FuncLibrary.layout(selection,
footer=f"Seite {1}/{int(len(results) / 5) + (len(results) % 5 > 0)}"),
view=buttons)

Expand Down Expand Up @@ -117,7 +117,7 @@ async def todo(self, ctx: Context):
selected = nextcord.Embed(title=f"{selecteditem[1]} {selecteditem[2]} ",
color=embedcolor)

selected.add_field(name="Aufgabe:", value=selecteditem[3], inline=False)
selected.add_field(name="Aufgabe:", value=selecteditem[3] if selecteditem[3] else "None", inline=False)
selected.add_field(name="Zugriff: ", value=access, inline=False)
(year, month, day) = selecteditem[0].split("-")
selected.set_footer(text=f"Fällig bis: "
Expand Down
51 changes: 16 additions & 35 deletions Items/specialcmds.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ async def recommend(self, ctx:Context):
else:
suggestion = ctx.message.content[ctx.message.content.index(" "):]

if not suggestion.lower() in ["ligma", "sugma", "you suck", "u suck"]:
if not suggestion.lower().replace(" ", "") in ["ligma", "sugma", "you suck", "u suck", "ligmaballs"]:
confirm = await ctx.channel.send("Wird eingetragen...")
time = datetime.now()
time = f"{time.hour:02}:{time.minute:02}:{time.second:02}, {time.day:02}.{time.month:02}.{str(time.year)[-2::]}"
Expand All @@ -40,47 +40,25 @@ async def recommend(self, ctx:Context):
else:
await ctx.reply("Bro häb frässe")

@commands.command(name="remindme", aliases=["remind"],
help="Stelle dir einen Reminder. Für die Zeitangabe, gib die Zeit bitte in der Form HH:MM an."
"Der Bot schickt dir dann um diese Uhrzeit einen Reminder.")
async def set_reminder(self, ctx:Context):
error = True
while error:
await ctx.reply("Wann willst du erinnert werden (Uhrzeit)?")
timemsg = await self.bot.wait_for("message", check=lambda msg: msg.author == ctx.author)

try:
minute = int(timemsg.content.split(':')[1])
hour = int(timemsg.content.split(":")[0])
zeit = time(hour=hour, minute=minute)
error = False

except IndexError:
await ctx.reply("Zeit muss in der Form HH:MM angegeben werden")

except ValueError:
await ctx.reply("Inkorrekte Eingabe")

await ctx.reply("An was willst du erinnert werden?")
reminder = await self.bot.wait_for("message", check=lambda msg: msg.author == ctx.author)

cs.execute(f"INSERT INTO reminder VALUES ({int(ctx.author.id)}, ?, ?)", (str(zeit), reminder.content))
database.commit()

await ctx.channel.send("Reminder wurde eingetragen")

@commands.command(name="poll", help="Mache Polls. Format ist: !poll [test verschieben] [nicht verschieben]")
@commands.command(name="poll", help="Mache Polls. Format ist: !poll statement (dauer) [option a] [option b]")
async def poll(self, ctx:Context):
try:
question = ctx.message.content.split("(")[0][len("!poll"):]
duration = ctx.message.content.split("(")[1].split(")")[0]
optiona = ctx.message.content.split("[")[1].replace("]", "")
optionb = ctx.message.content.split("[")[2].replace("]", "")

votebutton = Buttons.VoteButtons(240.0)
votebutton = Buttons.VoteButtons(float(duration))
votebutton.OptA.label=optiona
votebutton.OptB.label = optionb
vote = await ctx.channel.send("Vote time", view=votebutton)
vote = await ctx.channel.send(f"{question} ({duration} sekunden)", view=votebutton)
await votebutton.wait()

for i in votebutton.children:
i.disabled=True

await vote.edit(view=votebutton)

if votebutton.votes:
votecounta, votecountb = list(votebutton.votes.values()).count(optiona), list(votebutton.votes.values()).count(optionb)

Expand All @@ -91,7 +69,7 @@ async def poll(self, ctx:Context):
await vote.reply(f"'{optionb}' hat gewonnen mit {votecountb} zu {votecounta} Punkten!")

else:
await vote.reply(f"Es ist Gleichstand ({votecounta}:{votecountb}")
await vote.reply(f"Es ist Gleichstand ({votecounta}:{votecountb})")

else:
await vote.reply("Niemand hat gewählt")
Expand All @@ -100,7 +78,10 @@ async def poll(self, ctx:Context):
await ctx.reply("Invalide syntax. Optionen müssen in der form [A][B] angegeben werden")

except nextcord.errors.HTTPException:
await ctx.reply("Nachricht ist zu lang. Darf nur 80 zeichen lang sein.")
await ctx.reply("Nachricht ist zu lang. Darf nur 80 Zeichen lang sein.")

except ValueError:
await ctx.reply(f"'{ctx.message.content.split('(')[1].split(')')[0]}' ist keine Zahl")

@commands.command(name="!stcol")
async def stcol(self, ctx:Context):
Expand Down
54 changes: 21 additions & 33 deletions Mensa/Webscraping.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,50 +9,38 @@ def menuoutput(output):
req = requests.get(url, 'html.parser').text
weekday = date.today().weekday()
menuselect = 1
output = []

if datetime.now().time() > time(hour=14, minute=30):
menuselect=2
weekday = (date.today()+timedelta(1)).weekday()

if weekday< 8:
items = req.split(f"<div id=\"menu-plan-tab{menuselect}")[1].replace("\t", "")\
.split(f"<div id=\"menu-plan-tab{menuselect+1}")[0]\
.split('<div class="menu-item">')[1::]

for item in items:
title = item.split('<h2 class="menu-title">')[1].split("</h2>")[0]

desc = item.split('<p class="menu-description">')[1].split('</p>')[0]\
.replace("<br />\n", " ")\
.replace("&amp;", "&")
items = req.split(f"<div id=\"menu-plan-tab{menuselect}")[1].replace("\t", "")\
.split(f"<div id=\"menu-plan-tab{menuselect+1}")[0]\
.split('<div class="menu-item">')[1::]

label = item.split('<div class="menu-prices prices-3">')[1]\
.replace("\t", "")\
.split('class="menu')[1]
for item in items:
item = item.replace("&amp;", "&")
title = item.split('<h2 class="menu-title">')[1].split("</h2>")[0]

if label.startswith("-provenance"):
label = label.split('-provenance">')[1].split('</span>')[0]
desc = item.split('<p class="menu-description">')[1].split('</p>')[0]\
.replace("<br />\n", " ")\

else:
label = label.split('-labels">\n\n\n<span class="label label-')[1].split(' has-infobox">')[0]
yield {"title": title, "desc":desc, "label":label}
label = item.split('<div class="menu-prices prices-3">')[1]\
.replace("\t", "")\
.split('class="menu')[1]

if label.startswith("-provenance"):
label = label.split('-provenance">')[1].split('</span>')[0]

else:
allelements = req.split("\"menu-item\"")[1::]
for i in allelements:
dic = {"title": i.split("menu-title\">")[1].split("</h2>")[0]}
else:
label = label.split('-labels">\n\n\n<span class="label label-')[1].split(' has-infobox">')[0]
output.append({"title": title, "desc":desc, "label":label})

desc = i.split("menu-description\">")[1].split("</p")[0]\
.replace("<br />", "\n")\
.replace("inkl.", "inkl. ")\
.replace("&amp;", "&")
dic["desc"] = desc
if output[0]["label"] not in {"vegan", "vegetarian"}:
output[0], output[1] = output[1], output[0]

try:
dic["label"] = i.split("menu-labels")[1].split("<p>")[1].split(":<br />")[0]
except IndexError:
dic["label"] = ""
yield dic
return output


async def menuweekly(output):
Expand Down
Binary file modified Mensa/menu.pdf
Binary file not shown.
Binary file modified Mensa/menu.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
27 changes: 14 additions & 13 deletions Stundenplan/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,25 +70,26 @@ async def day(self, ctx:Context):
currdate = (datetime.now()+timedelta(hours=24-17)).date()
tag = currdate.weekday()

if tag<=4:
sf, ef, kf, mint = access(ctx.author)
if tag>4:
currdate = currdate+timedelta(days=7-tag)
tag = 0

allitems = cs.execute(f"SELECT fach, time, room FROM {table} WHERE weekday = ?"\
" AND (access='all' OR access = ? OR access = ? OR access = ? OR access=?)",\
(wochentage[tag], ef, sf, kf, mint)).fetchall()

allitems.sort(key=lambda elem:elem[1])
sf, ef, kf, mint = access(ctx.author)

output = nextcord.Embed(title=f"{week[currdate.weekday()]}, {currdate.day}.{currdate.month}.{currdate.year}",
color=weekcol[tag])
allitems = cs.execute(f"SELECT fach, time, room FROM {table} WHERE weekday = ?"\
" AND (access='all' OR access = ? OR access = ? OR access = ? OR access=?)",\
(wochentage[tag], ef, sf, kf, mint)).fetchall()

for i in allitems:
output.add_field(name=i[0], value=f"{i[1]}\n{i[2]}", inline=False)
allitems.sort(key=lambda elem:elem[1])

await ctx.channel.send(embed=output)
output = nextcord.Embed(title=f"{week[currdate.weekday()]}, {currdate.day}.{currdate.month}.{currdate.year}",
color=weekcol[tag])

else:
await ctx.channel.send("Es ist Wochenende.")
for i in allitems:
output.add_field(name=i[0], value=f"{i[1]}\n{i[2]}", inline=False)

await ctx.channel.send(embed=output)


def setup(client):
Expand Down
Loading

0 comments on commit 87e9ec5

Please sign in to comment.