Compare commits

..

40 commits
v1.1.0 ... main

Author SHA1 Message Date
Jannover5000r
8ed61f8b97 Update README and exampleENV 2026-08-25 23:50:58 +02:00
Jannover5000r
218916e831 fixed timeutil to set UTC zone correctly
UTC will actually be set new when nothing is inserted

moved initUpdate() to the top of main and finish as first order of operations
2026-08-25 23:40:18 +02:00
Jannover5000r
1f5f10f545 added initupdate as a go routine 2026-08-25 23:28:46 +02:00
Jannover5000r
d2a84a8435 Removed Fatalf
in order to prevent a huge amount of restarts i removed Fatalf and made it return normally

I also made GetTime load the timezone once and just return the correct value as well as default to utc

made the Auth function retry 3 times per account and send an error after that

put time.Sleep into the correct loop in main.go

initUpdate is in main now
2026-08-25 23:27:37 +02:00
Jannover5000r
1d57e8a867 made a lot of changes for the workflow of the bot
- Timezone handling got updated
- Logs have been deleted to avoid duplicates and clean up the terminal
- removed unused code
- fixed an issue where the updating time threw errors
- improvements to the updateting of timetable data, only using a single api call now
- improved init to intitialize all needed files (classrooms, subjects etc.)
2026-08-25 22:53:59 +02:00
Jannover5000r
ae5b1f7b28 Merge branch 'main' of https://github.com/Jannover5000r/Untis-Logger 2026-08-24 18:41:36 +02:00
Jannover5000r
fb503f6a9e added a few things to
ticker will now only update timetable not send all requests to avoid rate limiting

Untis.go Main() will only be used in initial startup

ticker cleanup in botstart since that isnt being used anymore
2026-08-24 18:37:25 +02:00
Jannover
0de661c88f
Merge pull request #15 from Jannover5000r/feature-UpdateAt2Am
fix 2
2026-08-24 01:10:14 +00:00
Jannover5000r
5f8f21732c fix 2 2026-08-24 03:09:29 +02:00
Jannover
5e247cc87c
Merge pull request #14 from Jannover5000r/feature-UpdateAt2Am
fix
2026-08-24 00:54:15 +00:00
Jannover5000r
6cfe550bed fix 2026-08-24 02:53:25 +02:00
Jannover
0444051dcf
Merge pull request #13 from Jannover5000r/feature-UpdateAt2Am
Feature update at2 am
2026-08-24 00:44:27 +00:00
Jannover5000r
7f3b8b2672 added the file since i forgot 2026-08-24 02:43:07 +02:00
Jannover5000r
ffd83811ab made update stop sending before 1am
since i fixed the update time i can make the deadline 1am
2026-08-24 02:39:26 +02:00
Jannover5000r
9357f7381b Fixed timezone management
timezones now get loaded by a function in /Untis
Should make fetching happen at 0 am
2026-08-24 02:36:41 +02:00
Jannover
3fc436fe93
Update README.md 2026-08-22 23:59:47 +00:00
Jannover
bf0b89e024
Merge pull request #12 from Jannover5000r/feature-newDayUpdate
added a new if clause to check if the time is past or before 3am before sending the class update message
2026-08-22 23:41:54 +00:00
Jannover5000r
2659237b3f added a new if clause to check if the time is past or before 3am before
sending the class update message

This will hopefully remove the spam everyday
2026-08-23 01:39:17 +02:00
Jannover
6051141d91
Merge branch 'main' into temp-timezoneFix 2026-08-22 22:01:19 +00:00
Jannover5000r
18f953e444 modified README 2026-08-22 23:52:44 +02:00
Jannover5000r
a62e91b30b added timezonemanagment to timezone fix 2026-04-13 07:58:48 +00:00
Jannover5000r
3bf0158260 WebHook command now also toggles Lesson update message 2026-01-28 09:47:06 +00:00
Jannover5000r
110e4a5104 manual timetable update with !update 2026-01-20 09:25:43 +01:00
Jannover5000r
b3628700ae new 2025-11-19 13:03:05 +01:00
Jannover5000r
c9a5dd2ff5 fixed the account creation 2025-11-14 09:10:35 +01:00
Jannover5000r
74297067d8 Accounts.json will now be saved in the accounts directory 2025-11-14 08:44:40 +01:00
Jannover5000r
c29389e8f2 new changes to notification system 2025-11-13 10:13:54 +01:00
Jannover5000r
6c07bd9d13 delete unused 2025-11-11 09:46:15 +01:00
Jannover5000r
f05157916d removed git error 2025-11-11 09:12:04 +01:00
Jannover5000r
b45ac423b0 detailed changed lessons message 2025-11-11 09:08:10 +01:00
Jannover5000r
a718e700c3
main.go aktualisieren 2025-11-03 14:34:34 +01:00
Jannover5000r
3ba05a64ce
main.go aktualisieren 2025-11-03 14:27:42 +01:00
Jannover5000r
3d64a4947d changed readme 2025-11-03 03:12:10 +01:00
Jannover5000r
c3f73b99d5 removed unnecessary else bracket 2025-11-03 03:05:33 +01:00
Jannover5000r
4d04da7f78 !WebHook works now 2025-10-31 10:16:47 +01:00
Jannover5000r
7646684136 changed message and added toggle for default message 2025-10-30 20:00:58 +01:00
Jannover5000r
f3636c15c9 changed -1 to +1 2025-10-29 14:22:04 +01:00
Jannover5000r
39de95e3ce changes to readme 2025-10-29 13:02:23 +01:00
Jannover5000r
68d358e1e4 timezone adjustment 2025-10-29 12:56:03 +01:00
Jannover5000r
0613d88b28 times for notification changed 2025-10-29 08:46:19 +01:00
12 changed files with 170 additions and 128 deletions

View file

@ -15,7 +15,6 @@ import (
"path/filepath" "path/filepath"
"sync" "sync"
"syscall" "syscall"
"time"
"untislogger/Untis" "untislogger/Untis"
@ -225,7 +224,6 @@ func checkAllUsersTimetables(s *discordgo.Session) {
accounts := loadAllAccounts() accounts := loadAllAccounts()
for _, user := range accounts { for _, user := range accounts {
decPwd, _ := decrypt(user.Password) decPwd, _ := decrypt(user.Password)
// You can use decPwd to fetch the timetable for this user
checkTimetableChangesForUser(user, decPwd, s) checkTimetableChangesForUser(user, decPwd, s)
} }
} }
@ -253,14 +251,6 @@ func Start() {
return return
} }
// Schedule timetable checks every minute (or hour as needed)
go func() {
ticker := time.NewTicker(1 * time.Minute)
for range ticker.C {
checkAllUsersTimetables(dg)
}
}()
fmt.Println("Bot is now running. Press CTRL+C to exit.") fmt.Println("Bot is now running. Press CTRL+C to exit.")
// Wait for CTRL+C or other term signal to exit. // Wait for CTRL+C or other term signal to exit.
sc := make(chan os.Signal, 1) sc := make(chan os.Signal, 1)

View file

@ -8,12 +8,13 @@
- DISCORD_BOT_TOKEN - DISCORD_BOT_TOKEN
- ENC_KEY (generated via head -c 32 /dev/urandom | base64) - ENC_KEY (generated via head -c 32 /dev/urandom | base64)
- URL - URL
- TIMEZONE (will default to UTC if empty)
### URL can be found by following this structure: "<https://[SchoolName].webuntis.com/WebUntis/jsonrpc.do?school=[SchholName]" while SchoolName can be found by visiting the official website, going to the login for your school and it will be: "<https://[SchoolName].webuntis.com/WebUntis/?school=[SchoolName]#/basic/login>" ### URL can be found by following this structure
# This is a project for me, issues will be resolved as i find the motivation to do so, improvements may follow in the future "<https://[SchoolName].webuntis.com/WebUntis/jsonrpc.do?school=[SchholName]"
while SchoolName can be found by visiting the official website, going to the login for your school and it will be:
## I will try to maintain this project as best as possible. Maybe add a better security to it than to trust the host but for now it is working and that was my goal. Please report any errors you find while using this bot "<https://[SchoolName].webuntis.com/WebUntis/?school=[SchoolName]#/basic/login>"
# Installation # Installation

View file

@ -32,55 +32,57 @@ func Classes(cookies []*http.Cookie) {
g := getClasses{"2023-05-06 15:44:22.215292", "getKlassen", map[string]interface{}{}, "2.0"} g := getClasses{"2023-05-06 15:44:22.215292", "getKlassen", map[string]interface{}{}, "2.0"}
ClassesJson, err := json.Marshal(g) ClassesJson, err := json.Marshal(g)
if err != nil { if err != nil {
log.Fatalf("Error marshaling login data: %v", err) log.Printf("Error marshaling login data: %v", err)
return return
} }
classes := bytes.NewReader(ClassesJson) classes := bytes.NewReader(ClassesJson)
prompt, err := http.NewRequest("POST", Url, classes) prompt, err := http.NewRequest("POST", Url, classes)
if err != nil { if err != nil {
log.Fatalf("Error creatingrequest: %v", err) log.Printf("Error creatingrequest: %v", err)
return return
} }
//log.Println("prompt without extra header or cookie ", prompt) // log.Println("prompt without extra header or cookie ", prompt)
//log.Println("Cookie: ", cookies) // log.Println("Cookie: ", cookies)
prompt.Header.Set("Content-Type", "application/json") prompt.Header.Set("Content-Type", "application/json")
prompt.Header.Set("User-Agent", "Webuntis Test") prompt.Header.Set("User-Agent", "Webuntis Test")
for _, cookie := range cookies { for _, cookie := range cookies {
//if cookie.Name == "JSESSIONID" { // if cookie.Name == "JSESSIONID" {
prompt.AddCookie(cookie) prompt.AddCookie(cookie)
//log.Printf("Added JSESSIONID cookie: %s=%s", cookie.Name, cookie.Value) //log.Printf("Added JSESSIONID cookie: %s=%s", cookie.Name, cookie.Value)
//} //}
} }
//log.Println("Request JSON:", string(ClassesJson)) // log.Println("Request JSON:", string(ClassesJson))
out, err := http.DefaultClient.Do(prompt) out, err := http.DefaultClient.Do(prompt)
if err != nil { if err != nil {
log.Printf("Error during request: %v", err) log.Printf("Error during request: %v", err)
return return
} }
defer out.Body.Close() defer out.Body.Close()
//log.Println(out.Status) // log.Println(out.Status)
response, err := io.ReadAll(out.Body) response, err := io.ReadAll(out.Body)
if err != nil { if err != nil {
log.Printf("Error reading response body: %v", err) log.Printf("Error reading response body: %v", err)
return return
} }
//responseString := string(response) // responseString := string(response)
//log.Println("Repsonse ", responseString) // log.Println("Repsonse ", responseString)
var Response ClassesResponse var Response ClassesResponse
err = json.Unmarshal(response, &Response) err = json.Unmarshal(response, &Response)
if err != nil { if err != nil {
log.Fatalf("Error unmarshaling response: %v", err) log.Printf("Error unmarshaling response: %v", err)
} }
data, err := json.MarshalIndent(Response.Result, "", " ") data, err := json.MarshalIndent(Response.Result, "", " ")
if err != nil { if err != nil {
log.Fatal(err) log.Print(err)
return
} }
err = os.WriteFile("classes.json", data, 0644) err = os.WriteFile("classes.json", data, 0o644)
if err != nil { if err != nil {
log.Fatal(err) log.Print(err)
return
} }
log.Println("Updated Classes") // log.Println("Updated Classes")//dont need log anymore
} }

View file

@ -31,60 +31,63 @@ type Room struct {
} }
func Rooms(cookies []*http.Cookie) { func Rooms(cookies []*http.Cookie) {
//log.Println("Abrufen der Stunden") // log.Println("Abrufen der Stunden")
g := getRooms{"2023-05-06 15:44:22.215292", "getRooms", map[string]interface{}{}, "2.0"} g := getRooms{"2023-05-06 15:44:22.215292", "getRooms", map[string]interface{}{}, "2.0"}
roomsJson, err := json.Marshal(g) roomsJson, err := json.Marshal(g)
if err != nil { if err != nil {
log.Fatalf("Error marshaling login data: %v", err) log.Printf("Error marshaling login data: %v", err)
return return
} }
rooms := bytes.NewReader(roomsJson) rooms := bytes.NewReader(roomsJson)
prompt, err := http.NewRequest("POST", Url, rooms) prompt, err := http.NewRequest("POST", Url, rooms)
if err != nil { if err != nil {
log.Fatalf("Error creatingrequest: %v", err) log.Printf("Error creatingrequest: %v", err)
return return
} }
//log.Println("prompt without extra header or cookie ", prompt) // log.Println("prompt without extra header or cookie ", prompt)
//log.Println("Cookie: ", cookies) // log.Println("Cookie: ", cookies)
prompt.Header.Set("Content-Type", "application/json") prompt.Header.Set("Content-Type", "application/json")
prompt.Header.Set("User-Agent", "Webuntis Test") prompt.Header.Set("User-Agent", "Webuntis Test")
for _, cookie := range cookies { for _, cookie := range cookies {
//if cookie.Name == "JSESSIONID" { // if cookie.Name == "JSESSIONID" {
prompt.AddCookie(cookie) prompt.AddCookie(cookie)
// log.Printf("Added JSESSIONID cookie: %s=%s", cookie.Name, cookie.Value) // log.Printf("Added JSESSIONID cookie: %s=%s", cookie.Name, cookie.Value)
//} //}
} }
//log.Println("Request JSON:", string(roomsJson)) // log.Println("Request JSON:", string(roomsJson))
out, err := http.DefaultClient.Do(prompt) out, err := http.DefaultClient.Do(prompt)
if err != nil { if err != nil {
log.Printf("Error during request: %v", err) log.Printf("Error during request: %v", err)
return return
} }
defer out.Body.Close() defer out.Body.Close()
//log.Println(out.Status) // log.Println(out.Status)
response, err := io.ReadAll(out.Body) response, err := io.ReadAll(out.Body)
if err != nil { if err != nil {
log.Printf("Error reading response body: %v", err) log.Printf("Error reading response body: %v", err)
return return
} }
//responseString := string(response) // responseString := string(response)
//log.Println("Repsonse ", responseString) // log.Println("Repsonse ", responseString)
var Response RoomsResponse var Response RoomsResponse
err = json.Unmarshal(response, &Response) err = json.Unmarshal(response, &Response)
if err != nil { if err != nil {
log.Fatalf("Error unmarshaling response: %v", err) log.Printf("Error unmarshaling response: %v", err)
return
} }
data, err := json.MarshalIndent(Response.Result, "", " ") data, err := json.MarshalIndent(Response.Result, "", " ")
if err != nil { if err != nil {
log.Fatal(err) log.Print(err)
return
} }
err = os.WriteFile("rooms.json", data, 0644) err = os.WriteFile("rooms.json", data, 0o644)
if err != nil { if err != nil {
log.Fatal(err) log.Print(err)
return
} }
log.Println("Updated Rooms") // log.Println("Updated Rooms")//dont need log anymore
} }

View file

@ -32,55 +32,58 @@ func Subjects(cookies []*http.Cookie) {
g := getSubjects{"2023-05-06 15:44:22.215292", "getSubjects", map[string]interface{}{}, "2.0"} g := getSubjects{"2023-05-06 15:44:22.215292", "getSubjects", map[string]interface{}{}, "2.0"}
SubjectsJson, err := json.Marshal(g) SubjectsJson, err := json.Marshal(g)
if err != nil { if err != nil {
log.Fatalf("Error marshaling login data: %v", err) log.Printf("Error marshaling login data: %v", err)
return return
} }
subjects := bytes.NewReader(SubjectsJson) subjects := bytes.NewReader(SubjectsJson)
prompt, err := http.NewRequest("POST", Url, subjects) prompt, err := http.NewRequest("POST", Url, subjects)
if err != nil { if err != nil {
log.Fatalf("Error creatingrequest: %v", err) log.Printf("Error creatingrequest: %v", err)
return return
} }
//log.Println("prompt without extra header or cookie ", prompt) // log.Println("prompt without extra header or cookie ", prompt)
//log.Println("Cookie: ", cookies) // log.Println("Cookie: ", cookies)
prompt.Header.Set("Content-Type", "application/json") prompt.Header.Set("Content-Type", "application/json")
prompt.Header.Set("User-Agent", "Webuntis Test") prompt.Header.Set("User-Agent", "Webuntis Test")
for _, cookie := range cookies { for _, cookie := range cookies {
//if cookie.Name == "JSESSIONID" { // if cookie.Name == "JSESSIONID" {
prompt.AddCookie(cookie) prompt.AddCookie(cookie)
//log.Printf("Added JSESSIONID cookie: %s=%s", cookie.Name, cookie.Value) //log.Printf("Added JSESSIONID cookie: %s=%s", cookie.Name, cookie.Value)
//} //}
} }
//log.Println("Request JSON:", string(SubjectsJson)) // log.Println("Request JSON:", string(SubjectsJson))
out, err := http.DefaultClient.Do(prompt) out, err := http.DefaultClient.Do(prompt)
if err != nil { if err != nil {
log.Printf("Error during request: %v", err) log.Printf("Error during request: %v", err)
return return
} }
defer out.Body.Close() defer out.Body.Close()
//log.Println(out.Status) // log.Println(out.Status)
response, err := io.ReadAll(out.Body) response, err := io.ReadAll(out.Body)
if err != nil { if err != nil {
log.Printf("Error reading response body: %v", err) log.Printf("Error reading response body: %v", err)
return return
} }
//responseString := string(response) // responseString := string(response)
//log.Println("Repsonse ", responseString) // log.Println("Repsonse ", responseString)
var Response SubjectsResponse var Response SubjectsResponse
err = json.Unmarshal(response, &Response) err = json.Unmarshal(response, &Response)
if err != nil { if err != nil {
log.Fatalf("Error unmarshaling response: %v", err) log.Printf("Error unmarshaling response: %v", err)
return
} }
data, err := json.MarshalIndent(Response.Result, "", " ") data, err := json.MarshalIndent(Response.Result, "", " ")
if err != nil { if err != nil {
log.Fatal(err) log.Print(err)
return
} }
err = os.WriteFile("subjects.json", data, 0644) err = os.WriteFile("subjects.json", data, 0o644)
if err != nil { if err != nil {
log.Fatal(err) log.Print(err)
return
} }
log.Println("Updated Subjects") // log.Println("Updated Subjects")//dont need log anymore
} }

View file

@ -32,55 +32,58 @@ func Teachers(cookies []*http.Cookie) {
g := getTeachers{"2023-05-06 15:44:22.215292", "getTeachers", map[string]interface{}{}, "2.0"} g := getTeachers{"2023-05-06 15:44:22.215292", "getTeachers", map[string]interface{}{}, "2.0"}
TeachersJson, err := json.Marshal(g) TeachersJson, err := json.Marshal(g)
if err != nil { if err != nil {
log.Fatalf("Error marshaling login data: %v", err) log.Printf("Error marshaling login data: %v", err)
return return
} }
teachers := bytes.NewReader(TeachersJson) teachers := bytes.NewReader(TeachersJson)
prompt, err := http.NewRequest("POST", Url, teachers) prompt, err := http.NewRequest("POST", Url, teachers)
if err != nil { if err != nil {
log.Fatalf("Error creatingrequest: %v", err) log.Printf("Error creatingrequest: %v", err)
return return
} }
//log.Println("prompt without extra header or cookie ", prompt) // log.Println("prompt without extra header or cookie ", prompt)
//log.Println("Cookie: ", cookies) // log.Println("Cookie: ", cookies)
prompt.Header.Set("Content-Type", "application/json") prompt.Header.Set("Content-Type", "application/json")
prompt.Header.Set("User-Agent", "Webuntis Test") prompt.Header.Set("User-Agent", "Webuntis Test")
for _, cookie := range cookies { for _, cookie := range cookies {
//if cookie.Name == "JSESSIONID" { // if cookie.Name == "JSESSIONID" {
prompt.AddCookie(cookie) prompt.AddCookie(cookie)
//log.Printf("Added JSESSIONID cookie: %s=%s", cookie.Name, cookie.Value) //log.Printf("Added JSESSIONID cookie: %s=%s", cookie.Name, cookie.Value)
//} //}
} }
//log.Println("Request JSON:", string(TeachersJson)) // log.Println("Request JSON:", string(TeachersJson))
out, err := http.DefaultClient.Do(prompt) out, err := http.DefaultClient.Do(prompt)
if err != nil { if err != nil {
log.Printf("Error during request: %v", err) log.Printf("Error during request: %v", err)
return return
} }
defer out.Body.Close() defer out.Body.Close()
//log.Println(out.Status) // log.Println(out.Status)
response, err := io.ReadAll(out.Body) response, err := io.ReadAll(out.Body)
if err != nil { if err != nil {
log.Printf("Error reading response body: %v", err) log.Printf("Error reading response body: %v", err)
return return
} }
//responseString := string(response) // responseString := string(response)
//log.Println("Repsonse ", responseString) // log.Println("Repsonse ", responseString)
var Response TeachersResponse var Response TeachersResponse
err = json.Unmarshal(response, &Response) err = json.Unmarshal(response, &Response)
if err != nil { if err != nil {
log.Fatalf("Error unmarshaling response: %v", err) log.Printf("Error unmarshaling response: %v", err)
return
} }
data, err := json.MarshalIndent(Response.Result, "", " ") data, err := json.MarshalIndent(Response.Result, "", " ")
if err != nil { if err != nil {
log.Fatal(err) log.Print(err)
return
} }
err = os.WriteFile("teachers.json", data, 0644) err = os.WriteFile("teachers.json", data, 0o644)
if err != nil { if err != nil {
log.Fatal(err) log.Print(err)
return
} }
log.Println("Updated Teachers") // log.Println("Updated Teachers")//dont need log anymore
} }

View file

@ -8,7 +8,6 @@ import (
"log" "log"
"net/http" "net/http"
"os" "os"
"time"
) )
type TimetableResponse struct { type TimetableResponse struct {
@ -100,7 +99,7 @@ func Timetable(cookies []*http.Cookie, userID string) {
return return
} }
today := time.Now().Format("20060102") today := GetTime().Format("20060102")
g := getTimetable{"2023-05-06 15:44:22.215292", "getTimetable", params{today, today, loginResult.PersonID, loginResult.PersonType}, "2.0"} g := getTimetable{"2023-05-06 15:44:22.215292", "getTimetable", params{today, today, loginResult.PersonID, loginResult.PersonType}, "2.0"}
timetablesJson, err := json.Marshal(g) timetablesJson, err := json.Marshal(g)
if err != nil { if err != nil {
@ -148,12 +147,12 @@ func Timetable(cookies []*http.Cookie, userID string) {
if userID != "" { if userID != "" {
timetableFile = "timetable_" + userID + ".json" timetableFile = "timetable_" + userID + ".json"
} }
if err := os.WriteFile(timetableFile, data, 0644); err != nil { if err := os.WriteFile(timetableFile, data, 0o644); err != nil {
log.Printf("Error writing timetable file: %v", err) log.Printf("Error writing timetable file: %v", err)
return return
} }
log.Printf("Updated timetable for user %s", userID) // log.Printf("Updated timetable for user %s", userID) // dont need log anymore
setTimetable(userID) setTimetable(userID)
} }
@ -172,6 +171,7 @@ func LoadIDMap(path string) (map[int]string, error) {
} }
return m, nil return m, nil
} }
func LoadTimetable(path string) ([]TimetableEntry, error) { func LoadTimetable(path string) ([]TimetableEntry, error) {
data, err := os.ReadFile(path) data, err := os.ReadFile(path)
if err != nil { if err != nil {
@ -183,11 +183,13 @@ func LoadTimetable(path string) ([]TimetableEntry, error) {
} }
return entries, nil return entries, nil
} }
func formatTime(t int) string { func formatTime(t int) string {
h := t / 100 h := t / 100
m := t % 100 m := t % 100
return fmt.Sprintf("%02d:%02d", h, m) return fmt.Sprintf("%02d:%02d", h, m)
} }
func formatDate(date int) string { func formatDate(date int) string {
s := fmt.Sprintf("%08d", date) // ensures leading zeros s := fmt.Sprintf("%08d", date) // ensures leading zeros
year := s[:4] year := s[:4]
@ -195,6 +197,7 @@ func formatDate(date int) string {
day := s[6:8] day := s[6:8]
return fmt.Sprintf("%s-%s-%s", day, month, year) return fmt.Sprintf("%s-%s-%s", day, month, year)
} }
func setTimetable(userID string) { func setTimetable(userID string) {
subjects, _ := LoadIDMap("subjects.json") subjects, _ := LoadIDMap("subjects.json")
rooms, _ := LoadIDMap("rooms.json") rooms, _ := LoadIDMap("rooms.json")
@ -242,9 +245,9 @@ func setTimetable(userID string) {
if userID != "" { if userID != "" {
timetableFilledFile = "timetableFilled_" + userID + ".json" timetableFilledFile = "timetableFilled_" + userID + ".json"
} }
if err := os.WriteFile(timetableFilledFile, data, 0644); err != nil { if err := os.WriteFile(timetableFilledFile, data, 0o644); err != nil {
log.Printf("Error writing timetableFilled file: %v", err) log.Printf("Error writing timetableFilled file: %v", err)
return return
} }
log.Printf("Filled timetable for user %s", userID) // log.Printf("Filled timetable for user %s", userID)//log not needed
} }

View file

@ -7,6 +7,7 @@ import (
"log" "log"
"net/http" "net/http"
"os" "os"
"time"
"github.com/joho/godotenv" "github.com/joho/godotenv"
) )
@ -32,8 +33,6 @@ type LoginResponse struct {
var Url = os.Getenv("URL") var Url = os.Getenv("URL")
// var Password = os.Getenv("UNTIS_PASSWORD")
// var USERS = os.Getenv("UNTIS_USER")
func Main(user, password, userID string) { func Main(user, password, userID string) {
godotenv.Load("../.env") godotenv.Load("../.env")
cookies, err := Auth(user, password, userID) cookies, err := Auth(user, password, userID)
@ -46,26 +45,46 @@ func Main(user, password, userID string) {
Subjects(cookies) Subjects(cookies)
Timetable(cookies, userID) Timetable(cookies, userID)
Teachers(cookies) Teachers(cookies)
log.Printf("updated everything for user: %s ", user)
}
func Update(user, password, userID string) {
godotenv.Load("../.env")
cookies, err := Auth(user, password, userID)
if err != nil {
log.Printf("Authentication failed for user %s: %v", user, err)
return
}
Timetable(cookies, userID)
log.Printf("Updated info for user: %s ", user)
} }
func Auth(user, password, userID string) ([]*http.Cookie, error) { func Auth(user, password, userID string) ([]*http.Cookie, error) {
l := Login{"2023-05-06 15:44:22.215292", "authenticate", Params{user, password, "WebUntis Test"}, "2.0"} loginJSON, _ := json.Marshal(Login{
loginJSON, err := json.Marshal(l) "2023-05-06 15:44:22.215292", "authenticate",
if err != nil { Params{user, password, "WebUntis Test"},
return nil, err "2.0",
} })
login := bytes.NewReader(loginJSON)
if Url == "" { if Url == "" {
Url = os.Getenv("URL") Url = os.Getenv("URL")
} }
LoginOut, err := http.Post(Url, "application/json", login)
var LoginOut *http.Response
var err error
for attempt := 1; attempt <= 3; attempt++ {
LoginOut, err = http.Post(Url, "application/json", bytes.NewReader(loginJSON))
if err == nil {
break
}
log.Printf("Auth attempt %d/3 failed for %s: %v", attempt, user, err)
time.Sleep(time.Duration(attempt*2) * time.Second)
}
if err != nil { if err != nil {
return nil, err return nil, err
} }
defer LoginOut.Body.Close() defer LoginOut.Body.Close()
cookies := LoginOut.Cookies() cookies := LoginOut.Cookies()
log.Printf("Login successful for user: %s", user) // log.Printf("Login successful for user: %s", user)//log not needed
response, err := io.ReadAll(LoginOut.Body) response, err := io.ReadAll(LoginOut.Body)
if err != nil { if err != nil {

29
Untis/timeutil.go Normal file
View file

@ -0,0 +1,29 @@
package Untis
import (
"log"
"os"
"time"
"github.com/joho/godotenv"
)
var Location *time.Location
func init() {
godotenv.Load("../.env")
timezone := os.Getenv("LOCATION_ENV")
if timezone == "" {
timezone = "UTC"
}
loc, err := time.LoadLocation(timezone)
if err != nil {
log.Printf("Failed to load timezone, set as UTC")
loc = time.UTC
}
Location = loc
}
func GetTime() time.Time {
return time.Now().In(Location)
}

View file

@ -4,4 +4,4 @@ UNTIS_USER=[Default user username]
DISCORD_BOT_TOKEN=[Paste Bot token] DISCORD_BOT_TOKEN=[Paste Bot token]
ENC_KEY=[Generate enc key and paste] ENC_KEY=[Generate enc key and paste]
URL=[Untis url, create from tutorial in readme] URL=[Untis url, create from tutorial in readme]
LOCATION_ENV=Europe/Berlin [change to your timezone, needs to be usable by go's time package via time.LoadLocation()] LOCATION_ENV=Europe/Berlin [change to your timezone, needs to be usable by go's time package via time.LoadLocation(LOCATION_ENV)]

2
go.mod
View file

@ -1,6 +1,6 @@
module untislogger module untislogger
go 1.25.2 go 1.27.0
require ( require (
github.com/bwmarrin/discordgo v0.29.0 github.com/bwmarrin/discordgo v0.29.0

65
main.go
View file

@ -4,7 +4,7 @@ import (
"bytes" "bytes"
"encoding/json" "encoding/json"
"fmt" "fmt"
"io/ioutil" "io"
"log" "log"
"net/http" "net/http"
"os" "os"
@ -93,7 +93,7 @@ func init() {
} }
discordWebhookURL = os.Getenv("DISCORD_WEBHOOK_URL") discordWebhookURL = os.Getenv("DISCORD_WEBHOOK_URL")
log.Println("Initializing application...") log.Println("Initializing application...")
log.Printf("DISCORD_WEBHOOK_URL: %q", discordWebhookURL) // log.Printf("DISCORD_WEBHOOK_URL: %q", discordWebhookURL) //Debug info, not needed at the moment
// Check if Discord webhook is configured // Check if Discord webhook is configured
if discordWebhookURL != "" { if discordWebhookURL != "" {
@ -101,37 +101,15 @@ func init() {
} else { } else {
log.Println("No Discord webhook provided, Discord notifications will be disabled") log.Println("No Discord webhook provided, Discord notifications will be disabled")
} }
locEnv := os.Getenv("LOCATION_ENV")
var locErr error
location, locErr = time.LoadLocation(locEnv)
if locErr != nil {
log.Fatalf("Failed to load timezone: %v", locErr)
}
log.Printf("Timezone set to: %s", location)
}
func getTime() time.Time {
return time.Now().In(location)
} }
func main() { func main() {
godotenv.Load(".env") initUpdate()
// Untis.Main() //starting API calls function| happens in schedule func
// Run()
// Starts logging the timetable for each new Lesson and logs changes
go BotStart.Start() go BotStart.Start()
scheduleTimetableUpdate() scheduleTimetableUpdate()
sigChan := make(chan os.Signal, 1) sigChan := make(chan os.Signal, 1)
signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM) signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM)
log.Println("Program is running. Press Ctrl+C to stop.")
// Start logging
// Run()
// Block until we receive a signal
<-sigChan <-sigChan
log.Println("Shutting down...") log.Println("Shutting down...")
} }
@ -147,6 +125,12 @@ func isScheduledTime(now time.Time) bool {
return false return false
} }
func initUpdate() {
defaultUser := os.Getenv("UNTIS_USER")
defaultPassword := os.Getenv("UNTIS_PASSWORD")
Untis.Main(defaultUser, defaultPassword, "default")
}
func scheduleTimetableUpdate() { func scheduleTimetableUpdate() {
prevData := make(map[string][]byte) prevData := make(map[string][]byte)
@ -157,7 +141,6 @@ func scheduleTimetableUpdate() {
if err != nil { if err != nil {
log.Printf("Error loading accounts: %v", err) log.Printf("Error loading accounts: %v", err)
} }
// Add the default user from .env // Add the default user from .env
defaultUser := os.Getenv("UNTIS_USER") defaultUser := os.Getenv("UNTIS_USER")
defaultPassword := os.Getenv("UNTIS_PASSWORD") defaultPassword := os.Getenv("UNTIS_PASSWORD")
@ -171,8 +154,8 @@ func scheduleTimetableUpdate() {
// Process each user // Process each user
for _, acc := range accounts { for _, acc := range accounts {
// Fetch the latest timetable // Fetch the latest timetable and only timetable
Untis.Main(acc.Username, acc.DecryptedPassword, acc.UserID) Untis.Update(acc.Username, acc.DecryptedPassword, acc.UserID)
// Check for changes // Check for changes
timetableFile := fmt.Sprintf("timetableFilled_%s.json", acc.UserID) timetableFile := fmt.Sprintf("timetableFilled_%s.json", acc.UserID)
@ -208,7 +191,15 @@ func scheduleTimetableUpdate() {
prevTimeslotMap := make(map[string]NamedTimetableEntry) prevTimeslotMap := make(map[string]NamedTimetableEntry)
// Get current date to filter out new day changes // Get current date to filter out new day changes
today := time.Now().Format("02-01-2006") today := Untis.GetTime().Format("02-01-2006")
// Get current time to filter any changes to Timetable before 3am so the new day changes stop
//
now := Untis.GetTime()
// If before 1am stop and update userdata
if now.Hour() < 1 {
prevData[acc.UserID] = data
continue
}
for _, e := range currentEntries { for _, e := range currentEntries {
key := lessonKey(e) key := lessonKey(e)
@ -307,13 +298,10 @@ func scheduleTimetableUpdate() {
sendUpdateDiscordWebhookWithDetails(changes) sendUpdateDiscordWebhookWithDetails(changes)
} }
} }
} else {
// First run — no previous data, so don't notify
log.Printf("First timetable fetch for user %s", acc.Username)
} }
// Always update prevData // Always update prevData
prevData[acc.UserID] = data prevData[acc.UserID] = data
time.Sleep(3 * time.Second)
} }
} }
@ -330,7 +318,7 @@ func scheduleTimetableUpdate() {
// Ticker for scheduled lesson notifications // Ticker for scheduled lesson notifications
startMinuteTicker(func() { startMinuteTicker(func() {
now := getTime() now := Untis.GetTime()
if isScheduledTime(now) { if isScheduledTime(now) {
log.Println("Scheduled time reached, running notifications...") log.Println("Scheduled time reached, running notifications...")
accounts, _ := BotStart.LoadAndDecryptAccounts() accounts, _ := BotStart.LoadAndDecryptAccounts()
@ -342,10 +330,11 @@ func scheduleTimetableUpdate() {
log.Println("Finished running notifications.") log.Println("Finished running notifications.")
} }
}) })
log.Println("Updated all users")
} }
func startMinuteTicker(f func()) { func startMinuteTicker(f func()) {
now := getTime() now := Untis.GetTime()
next := now.Truncate(time.Minute).Add(time.Minute) next := now.Truncate(time.Minute).Add(time.Minute)
time.Sleep(time.Until(next)) time.Sleep(time.Until(next))
ticker := time.NewTicker(1 * time.Minute) ticker := time.NewTicker(1 * time.Minute)
@ -374,7 +363,7 @@ func Run(userID string) {
roomByStartTime, _ := MapTimeToRoom(timetableFile) roomByStartTime, _ := MapTimeToRoom(timetableFile)
subjectByStartTime, _ := MapTimeToSubject(timetableFile) subjectByStartTime, _ := MapTimeToSubject(timetableFile)
now := getTime().Format("15:04") now := Untis.GetTime().Format("15:04")
nextTime, room, foundRoom := NextRoomForTime(roomByStartTime, now) nextTime, room, foundRoom := NextRoomForTime(roomByStartTime, now)
if !foundRoom { if !foundRoom {
@ -623,7 +612,7 @@ func sendDiscordWebhook(subject string, room string, nextTime string, Status str
if resp.StatusCode >= 200 && resp.StatusCode < 300 { if resp.StatusCode >= 200 && resp.StatusCode < 300 {
log.Println("Discord webhook notification sent successfully") log.Println("Discord webhook notification sent successfully")
} else { } else {
body, _ := ioutil.ReadAll(resp.Body) body, _ := io.ReadAll(resp.Body)
log.Printf("Discord webhook failed with status %d: %s", resp.StatusCode, string(body)) log.Printf("Discord webhook failed with status %d: %s", resp.StatusCode, string(body))
} }
} }
@ -654,7 +643,7 @@ func sendUpdateDiscordWebhookWithDetails(changes []string) {
if resp.StatusCode >= 200 && resp.StatusCode < 300 { if resp.StatusCode >= 200 && resp.StatusCode < 300 {
log.Println("Detailed Discord webhook sent successfully") log.Println("Detailed Discord webhook sent successfully")
} else { } else {
body, _ := ioutil.ReadAll(resp.Body) body, _ := io.ReadAll(resp.Body)
log.Printf("Discord webhook failed with status %d: %s", resp.StatusCode, string(body)) log.Printf("Discord webhook failed with status %d: %s", resp.StatusCode, string(body))
} }
} }