Compare commits

..

1 commit
main ... v0.9.1

Author SHA1 Message Date
Jannover5000r
2b6ef61266
Merge pull request #3 from Jannover5000r/feat/implement-timetable-fetching
feat: Implement timetable fetching in checkTimetableChangesForUser
2025-10-20 02:19:08 +00:00
15 changed files with 214 additions and 504 deletions

View file

@ -1,7 +0,0 @@
DISCORD_WEBHOOK_URL=[Paste Webhook]
UNTIS_PASSWORD=[Default user passwd]
UNTIS_USER=[Default user username]
DISCORD_BOT_TOKEN=[Paste Bot token]
ENC_KEY=[Generate enc key and paste]
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()]

5
.gitignore vendored
View file

@ -6,10 +6,7 @@ teachers.json
login.json
timetable*.json
timetableFilled*.json
accounts/
accounts.json
login_*.json
AGENTS.md
untislogger
untislogger*
CHANGES_SUMMARY.md

View file

@ -12,13 +12,12 @@ import (
"io"
"os"
"os/signal"
"path/filepath"
"sync"
"syscall"
"untislogger/Untis"
"time"
"github.com/joho/godotenv"
"untislogger/Untis"
"github.com/bwmarrin/discordgo"
)
@ -39,13 +38,11 @@ type UserState struct {
var (
userStates = make(map[string]*UserState) // userID -> state
stateMutex sync.Mutex // protect userStates
accountsFile = "accounts/accounts.json"
accountsFile = "accounts.json"
)
var encryptionKey []byte
var WebHook = true
func init() {
godotenv.Load(".env")
keyStr := os.Getenv("ENC_KEY")
@ -108,12 +105,6 @@ func decrypt(encrypted string) (string, error) {
func saveAccount(userID, username, password string) error {
var accounts []Account
// Ensure the accounts directory exists
accountsDir := filepath.Dir(accountsFile)
if err := os.MkdirAll(accountsDir, 0o755); err != nil {
return fmt.Errorf("failed to create accounts directory: %v", err)
}
// Load existing accounts if file exists
if data, err := os.ReadFile(accountsFile); err == nil && len(data) > 0 {
_ = json.Unmarshal(data, &accounts)
@ -144,7 +135,7 @@ func saveAccount(userID, username, password string) error {
if err != nil {
return err
}
if err := os.WriteFile(accountsFile, newData, 0o644); err != nil {
if err := os.WriteFile(accountsFile, newData, 0644); err != nil {
return err
}
@ -152,10 +143,10 @@ func saveAccount(userID, username, password string) error {
timetableFile := getTimetableFile(userID)
timetableFilledFile := getTimetableFilledFile(userID)
if _, err := os.Stat(timetableFile); os.IsNotExist(err) {
os.WriteFile(timetableFile, []byte("[]"), 0o644)
os.WriteFile(timetableFile, []byte("[]"), 0644)
}
if _, err := os.Stat(timetableFilledFile); os.IsNotExist(err) {
os.WriteFile(timetableFilledFile, []byte("[]"), 0o644)
os.WriteFile(timetableFilledFile, []byte("[]"), 0644)
}
return nil
@ -205,8 +196,7 @@ func checkTimetableChangesForUser(user Account, decPwd string, s *discordgo.Sess
// Compare and notify if changed
if !bytes.Equal(newData, prevData) {
// The main.go now handles detailed change notifications
// This function is kept for compatibility but no longer sends generic messages
sendLessonNotification(s, user.UserID, user.Username, "Your timetable has changed!")
}
}
@ -224,6 +214,7 @@ func checkAllUsersTimetables(s *discordgo.Session) {
accounts := loadAllAccounts()
for _, user := range accounts {
decPwd, _ := decrypt(user.Password)
// You can use decPwd to fetch the timetable for this user
checkTimetableChangesForUser(user, decPwd, s)
}
}
@ -251,6 +242,14 @@ func Start() {
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.")
// Wait for CTRL+C or other term signal to exit.
sc := make(chan os.Signal, 1)
@ -356,7 +355,7 @@ func deleteAccount(userID string) error {
if err != nil {
return err
}
if err := os.WriteFile(accountsFile, newData, 0o644); err != nil {
if err := os.WriteFile(accountsFile, newData, 0644); err != nil {
return err
}
@ -372,18 +371,9 @@ func messageCreate(s *discordgo.Session, m *discordgo.MessageCreate) {
if m.Author.ID == s.State.User.ID {
return
}
if m.GuildID != "" && m.Content == "!WebHook" {
_ = s.ChannelMessageDelete(m.ChannelID, m.ID)
WebHook = !WebHook
if WebHook {
s.ChannelMessageSend(m.ChannelID, "Sending Webhook set to True")
} else {
s.ChannelMessageSend(m.ChannelID, "Sending Webhook set to False")
}
return
}
// Handle "!addaccount" only in guilds (not in DMs)
if m.Content == "!addaccount" {
if m.GuildID != "" && m.Content == "!addaccount" {
// Delete the command for privacy
_ = s.ChannelMessageDelete(m.ChannelID, m.ID)
// Create DM channel
@ -400,12 +390,6 @@ func messageCreate(s *discordgo.Session, m *discordgo.MessageCreate) {
return
}
if m.Content == "!update" {
_ = s.ChannelMessageDelete(m.ChannelID, m.ID)
checkAllUsersTimetables(DiscordSession)
s.ChannelMessageSend(m.ChannelID, "Updated all Timetables manually")
}
// Handle "!deleteaccount" and "!removeaccount" commands
if m.GuildID != "" && (m.Content == "!deleteaccount" || m.Content == "!removeaccount") {
// Delete the command message for privacy

View file

@ -1,31 +1,25 @@
# Discord bot for logging Untis timetable to a Discord Webhook and Multiple accounts which can be added using !addaccount in a server whit the Bot
## create .env with Credentials
## create .env with Credentials:
- UNTIS_PASSWORD
- UNTIS_USER
- DISCORD_WEBHOOK_URL
- DISCORD_BOT_TOKEN
- ENC_KEY (generated via head -c 32 /dev/urandom | base64)
- 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>"
# This is a project for me, issues will be resolved as i find the motivation to do so, improvements may follow in the future
### 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.
# Installation
# This is a discord application intended for self hosting. You will need to add an application in the [disord developer website](https://discord.com/developers/applications) for this bot mainly with the read messages and write messages privelege as well as send privat messages for the account handling. If you give it administrator permissions you dont have to worry further but this could present you with a security risk if my github account gets compromised and a malicious update to the script gets pushed which you than use since the bot got access to your whole server
# This is a discord application intended for self hosting. You will need to add an application in the [disord developer website](https://discord.com/developers/applications) for this bot mainly with the read messages and write messages privelege as well as send privat messages for the account handling. If you give it administrator permissions you dont have to worry further but this could present you with a security risk if my github account gets compromised and a malicious update to the script gets pushed which you than use since the bot got access to your whole server.
# I also recommend to use a tool like [coolify](https://coolify.io/) to host the bot. Make sure to add the Env's and add the **accounts/** folder to persistent storage
# I also recommend to use a tool like [coolify](https://coolify.io/) to host the bot. Make sure to add the Env's and add **accounts.json** to persistant storage
### This bot is self hosted and will run correctly when doing "go run . " in the root folder of the project. **Before usage add the .env file with the Credentials as mentioned above.** When you run the Program for the first time, all important files will be created automatically and the bot is ready to go. The user added via the fields UNTIS_USER and UNTIS_PASSWORD in the .env will be the one where the Webhook is sourced from and the other users will be send a DM after adding their account with the command. Add the Discord Webhook via the DISCORD_WEBHOOK_URL point in the .env and will send the messages for the timetable in there
### For multi user support: using the command **!addaccount** in the discord server the bot is used in, it will than dm you with the sign up process prompting you to enter your untis Username and password (no email neededd just untis username). The username is stored as plain text and the password is hashed on the device hosting the bot, so currently it is **not secure** since the host will have access to the hashed password and the hash used! Deleting an account is done by using **!removeaccount** which will delete the account and the password, created with your discord account
### This bot is self hosted and will run correctly when doing "go run . " in the root folder of the project. **Before usage add the .env file with the Credentials as mentioned above.** When you run the Program for the first time, all important files will be created automatically and the bot is ready to go. The user added via the fields UNTIS_USER and UNTIS_PASSWORD in the .env will be the one where the Webhook is sourced from and the other users will be send a DM after adding their account with the command. Add the Discord Webhook via the DISCORD_WEBHOOK_URL point in the .env and will send the messages for the timetable in there.
## For your timezone setup an ENV called "LOCATION_ENV" with your timezone as explained in the example env file. In case your school is using a different timing for the Lessons than mine, you can change the times where you will be notified with the next room and Lesson for the day in **Line 71 in the main.go** file. The bot may not send you a message if there is no lesson after the specified time so that you can leave empty lessons as is for the days
### For multi user support: using the command **!addaccount** in the discord server the bot is used in, it will than dm you with the sign up process prompting you to enter your untis Username and password (no email neededd just untis username). The username is stored as plain text and the password is hashed on the device hosting the bot, so currently it is **not secure** since the host will have access to the hashed password and the hash used! Deleting an account is done by using **!removeaccount** which will delete the account and the password, created with your discord account.
# I am neither a representative of Untis, Untis Baden-Württemberg GmbH nor a Developer in their team. This project is based on their API and my code and is not affiliated with them
## In case your school is using a different timing for the Lessons than mine, you can change the times where you will be notified with the next room and Lesson for the day in **Line 71 in the main.go** file. The bot may not send you a message if there is no lesson after the specified time so that you can leave empty lessons as is for the days.
# I am neither a representative of Untis, Untis Baden-Württemberg GmbH nor a Developer in their team. This project is based on their API and my code and is not affiliated with them.

View file

@ -32,14 +32,14 @@ func Classes(cookies []*http.Cookie) {
g := getClasses{"2023-05-06 15:44:22.215292", "getKlassen", map[string]interface{}{}, "2.0"}
ClassesJson, err := json.Marshal(g)
if err != nil {
log.Printf("Error marshaling login data: %v", err)
log.Fatalf("Error marshaling login data: %v", err)
return
}
classes := bytes.NewReader(ClassesJson)
prompt, err := http.NewRequest("POST", Url, classes)
if err != nil {
log.Printf("Error creatingrequest: %v", err)
log.Fatalf("Error creatingrequest: %v", err)
return
}
//log.Println("prompt without extra header or cookie ", prompt)
@ -72,17 +72,15 @@ func Classes(cookies []*http.Cookie) {
var Response ClassesResponse
err = json.Unmarshal(response, &Response)
if err != nil {
log.Printf("Error unmarshaling response: %v", err)
log.Fatalf("Error unmarshaling response: %v", err)
}
data, err := json.MarshalIndent(Response.Result, "", " ")
if err != nil {
log.Print(err)
return
log.Fatal(err)
}
err = os.WriteFile("classes.json", data, 0o644)
err = os.WriteFile("classes.json", data, 0644)
if err != nil {
log.Print(err)
return
log.Fatal(err)
}
// log.Println("Updated Classes")//dont need log anymore
log.Println("Updated Classes")
}

View file

@ -35,14 +35,14 @@ func Rooms(cookies []*http.Cookie) {
g := getRooms{"2023-05-06 15:44:22.215292", "getRooms", map[string]interface{}{}, "2.0"}
roomsJson, err := json.Marshal(g)
if err != nil {
log.Printf("Error marshaling login data: %v", err)
log.Fatalf("Error marshaling login data: %v", err)
return
}
rooms := bytes.NewReader(roomsJson)
prompt, err := http.NewRequest("POST", Url, rooms)
if err != nil {
log.Printf("Error creatingrequest: %v", err)
log.Fatalf("Error creatingrequest: %v", err)
return
}
//log.Println("prompt without extra header or cookie ", prompt)
@ -75,19 +75,16 @@ func Rooms(cookies []*http.Cookie) {
var Response RoomsResponse
err = json.Unmarshal(response, &Response)
if err != nil {
log.Printf("Error unmarshaling response: %v", err)
return
log.Fatalf("Error unmarshaling response: %v", err)
}
data, err := json.MarshalIndent(Response.Result, "", " ")
if err != nil {
log.Print(err)
return
log.Fatal(err)
}
err = os.WriteFile("rooms.json", data, 0o644)
err = os.WriteFile("rooms.json", data, 0644)
if err != nil {
log.Print(err)
return
log.Fatal(err)
}
// log.Println("Updated Rooms")//dont need log anymore
log.Println("Updated Rooms")
}

View file

@ -32,14 +32,14 @@ func Subjects(cookies []*http.Cookie) {
g := getSubjects{"2023-05-06 15:44:22.215292", "getSubjects", map[string]interface{}{}, "2.0"}
SubjectsJson, err := json.Marshal(g)
if err != nil {
log.Printf("Error marshaling login data: %v", err)
log.Fatalf("Error marshaling login data: %v", err)
return
}
subjects := bytes.NewReader(SubjectsJson)
prompt, err := http.NewRequest("POST", Url, subjects)
if err != nil {
log.Printf("Error creatingrequest: %v", err)
log.Fatalf("Error creatingrequest: %v", err)
return
}
//log.Println("prompt without extra header or cookie ", prompt)
@ -72,18 +72,15 @@ func Subjects(cookies []*http.Cookie) {
var Response SubjectsResponse
err = json.Unmarshal(response, &Response)
if err != nil {
log.Printf("Error unmarshaling response: %v", err)
return
log.Fatalf("Error unmarshaling response: %v", err)
}
data, err := json.MarshalIndent(Response.Result, "", " ")
if err != nil {
log.Print(err)
return
log.Fatal(err)
}
err = os.WriteFile("subjects.json", data, 0o644)
err = os.WriteFile("subjects.json", data, 0644)
if err != nil {
log.Print(err)
return
log.Fatal(err)
}
// log.Println("Updated Subjects")//dont need log anymore
log.Println("Updated Subjects")
}

View file

@ -32,14 +32,14 @@ func Teachers(cookies []*http.Cookie) {
g := getTeachers{"2023-05-06 15:44:22.215292", "getTeachers", map[string]interface{}{}, "2.0"}
TeachersJson, err := json.Marshal(g)
if err != nil {
log.Printf("Error marshaling login data: %v", err)
log.Fatalf("Error marshaling login data: %v", err)
return
}
teachers := bytes.NewReader(TeachersJson)
prompt, err := http.NewRequest("POST", Url, teachers)
if err != nil {
log.Printf("Error creatingrequest: %v", err)
log.Fatalf("Error creatingrequest: %v", err)
return
}
//log.Println("prompt without extra header or cookie ", prompt)
@ -72,18 +72,15 @@ func Teachers(cookies []*http.Cookie) {
var Response TeachersResponse
err = json.Unmarshal(response, &Response)
if err != nil {
log.Printf("Error unmarshaling response: %v", err)
return
log.Fatalf("Error unmarshaling response: %v", err)
}
data, err := json.MarshalIndent(Response.Result, "", " ")
if err != nil {
log.Print(err)
return
log.Fatal(err)
}
err = os.WriteFile("teachers.json", data, 0o644)
err = os.WriteFile("teachers.json", data, 0644)
if err != nil {
log.Print(err)
return
log.Fatal(err)
}
// log.Println("Updated Teachers")//dont need log anymore
log.Println("Updated Teachers")
}

View file

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

View file

@ -7,7 +7,6 @@ import (
"log"
"net/http"
"os"
"time"
"github.com/joho/godotenv"
)
@ -31,7 +30,10 @@ type LoginResponse struct {
Result Loginresult `json:"result"`
}
var Url = os.Getenv("URL")
var Url = "https://thalia.webuntis.com/WebUntis/jsonrpc.do?school=Mons_Tabor"
//var Password = os.Getenv("UNTIS_PASSWORD")
//var USERS = os.Getenv("UNTIS_USER")
func Main(user, password, userID string) {
godotenv.Load("../.env")
@ -45,46 +47,24 @@ func Main(user, password, userID string) {
Subjects(cookies)
Timetable(cookies, userID)
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) {
loginJSON, _ := json.Marshal(Login{
"2023-05-06 15:44:22.215292", "authenticate",
Params{user, password, "WebUntis Test"},
"2.0",
})
if Url == "" {
Url = os.Getenv("URL")
l := Login{"2023-05-06 15:44:22.215292", "authenticate", Params{user, password, "WebUntis Test"}, "2.0"}
loginJSON, err := json.Marshal(l)
if err != nil {
return nil, err
}
login := bytes.NewReader(loginJSON)
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)
}
LoginOut, err := http.Post(Url, "application/json", login)
if err != nil {
return nil, err
}
defer LoginOut.Body.Close()
cookies := LoginOut.Cookies()
// log.Printf("Login successful for user: %s", user)//log not needed
log.Printf("Login successful for user: %s", user)
response, err := io.ReadAll(LoginOut.Body)
if err != nil {
@ -105,7 +85,7 @@ func Auth(user, password, userID string) ([]*http.Cookie, error) {
if userID != "" {
loginFile = "login_" + userID + ".json"
}
if err := os.WriteFile(loginFile, data, 0o644); err != nil {
if err := os.WriteFile(loginFile, data, 0644); err != nil {
return nil, err
}

View file

@ -1,29 +0,0 @@
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

@ -1,7 +0,0 @@
DISCORD_WEBHOOK_URL=[Paste Webhook]
UNTIS_PASSWORD=[Default user passwd]
UNTIS_USER=[Default user username]
DISCORD_BOT_TOKEN=[Paste Bot token]
ENC_KEY=[Generate enc key and paste]
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)]

2
go.mod
View file

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

346
main.go
View file

@ -4,17 +4,14 @@ import (
"bytes"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
"os"
"os/signal"
"sort"
"strings"
"syscall"
"time"
_ "time/tzdata"
Untis "untislogger/Untis"
BotStart "untislogger/Botrun"
@ -35,55 +32,6 @@ type NamedTimetableEntry struct {
ActivityType string `json:"activityType"`
}
var location *time.Location
// lessonKey creates a stable key for a lesson (date + time + subject)
func lessonKey(e NamedTimetableEntry) string {
subject := "unknown"
if len(e.Su) > 0 {
subject = e.Su[0]
}
// Include date for multi-day accuracy (e.g., Monday vs Tuesday)
return e.Date + "|" + e.StartTime + "|" + subject
}
// getSubject returns the first subject or "Free period"
func getSubject(e NamedTimetableEntry) string {
if len(e.Su) == 0 {
return "Free period"
}
return e.Su[0]
}
// formatRoom returns a readable room string
func formatRoom(rooms []string) string {
if len(rooms) == 0 {
return "no room"
}
return strings.Join(rooms, ", ")
}
// formatStatus returns a human-readable status
func formatStatus(code string) string {
if code == "" {
return "regular"
}
return code
}
// slicesEqual checks if two string slices are equal (order-sensitive)
func slicesEqual(a, b []string) bool {
if len(a) != len(b) {
return false
}
for i := range a {
if a[i] != b[i] {
return false
}
}
return true
}
// init and main//
func init() {
godotenv.Load(".env")
@ -93,7 +41,7 @@ func init() {
}
discordWebhookURL = os.Getenv("DISCORD_WEBHOOK_URL")
log.Println("Initializing application...")
// log.Printf("DISCORD_WEBHOOK_URL: %q", discordWebhookURL) //Debug info, not needed at the moment
log.Printf("DISCORD_WEBHOOK_URL: %q", discordWebhookURL)
// Check if Discord webhook is configured
if discordWebhookURL != "" {
@ -104,18 +52,25 @@ func init() {
}
func main() {
initUpdate()
godotenv.Load(".env")
//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()
scheduleTimetableUpdate()
sigChan := make(chan os.Signal, 1)
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
log.Println("Shutting down...")
}
func isScheduledTime(now time.Time) bool {
scheduled := []string{"07:45", "08:35", "09:35", "10:25", "11:25", "12:15", "13:40", "14:25", "15:20", "16:00"}
scheduled := []string{"07:45", "08:35", "09:35", "10:25", "11:25", "12:15", "13:45", "14:25"}
current := now.Format("15:04")
for _, t := range scheduled {
if t == current {
@ -124,13 +79,6 @@ func isScheduledTime(now time.Time) bool {
}
return false
}
func initUpdate() {
defaultUser := os.Getenv("UNTIS_USER")
defaultPassword := os.Getenv("UNTIS_PASSWORD")
Untis.Main(defaultUser, defaultPassword, "default")
}
func scheduleTimetableUpdate() {
prevData := make(map[string][]byte)
@ -141,6 +89,7 @@ func scheduleTimetableUpdate() {
if err != nil {
log.Printf("Error loading accounts: %v", err)
}
// Add the default user from .env
defaultUser := os.Getenv("UNTIS_USER")
defaultPassword := os.Getenv("UNTIS_PASSWORD")
@ -154,154 +103,25 @@ func scheduleTimetableUpdate() {
// Process each user
for _, acc := range accounts {
// Fetch the latest timetable and only timetable
Untis.Update(acc.Username, acc.DecryptedPassword, acc.UserID)
// Fetch the latest timetable
Untis.Main(acc.Username, acc.DecryptedPassword, acc.UserID)
// Check for changes
timetableFile := fmt.Sprintf("timetableFilled_%s.json", acc.UserID)
if acc.UserID == "default" {
timetableFile = "timetableFilled_default.json"
timetableFile = "timetableFilled.json"
}
data, err := os.ReadFile(timetableFile)
if err != nil {
log.Printf("Error reading timetable for user %s: %v", acc.Username, err)
continue
}
// Parse current and previous timetable data
var currentEntries, prevEntries []NamedTimetableEntry
if err := json.Unmarshal(data, &currentEntries); err != nil {
log.Printf("Failed to parse new timetable for user %s: %v", acc.Username, err)
prevData[acc.UserID] = data // still update to avoid repeated errors
continue
if prev, ok := prevData[acc.UserID]; ok && !bytes.Equal(data, prev) {
log.Printf("Timetable has changed for user %s.", acc.Username)
BotStart.SendDM(acc.UserID, "Your timetable has changed!")
}
if prev, ok := prevData[acc.UserID]; ok {
if err := json.Unmarshal(prev, &prevEntries); err != nil {
log.Printf("Failed to parse previous timetable for user %s: %v", acc.Username, err)
prevData[acc.UserID] = data
continue
}
// Build maps keyed by a stable lesson identifier
currMap := make(map[string]NamedTimetableEntry)
prevMap := make(map[string]NamedTimetableEntry)
// Also build timeslot-based maps for better exchange detection
currTimeslotMap := make(map[string]NamedTimetableEntry)
prevTimeslotMap := make(map[string]NamedTimetableEntry)
// Get current date to filter out new day changes
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 {
key := lessonKey(e)
currMap[key] = e
}
for _, e := range prevEntries {
key := lessonKey(e)
prevMap[key] = e
}
var changes []string
// Check for modified or new lessons
for key, curr := range currMap {
// Skip lessons that are not for today to avoid new day spam
if curr.Date != today {
continue
}
if prev, exists := prevMap[key]; exists {
// Existing lesson — check for changes
subject := getSubject(curr)
// Room change?
if !slicesEqual(prev.Ro, curr.Ro) {
oldRoom := formatRoom(prev.Ro)
newRoom := formatRoom(curr.Ro)
changes = append(changes, fmt.Sprintf("Room changed for %s: %s → %s", subject, oldRoom, newRoom))
}
for _, e := range currentEntries {
key := lessonKey(e)
currMap[key] = e
// Create timeslot key (date + startTime + endTime)
timeslotKey := e.Date + "|" + e.StartTime + "|" + e.EndTime
currTimeslotMap[timeslotKey] = e
}
for _, e := range prevEntries {
key := lessonKey(e)
prevMap[key] = e
// Create timeslot key (date + startTime + endTime)
timeslotKey := e.Date + "|" + e.StartTime + "|" + e.EndTime
prevTimeslotMap[timeslotKey] = e
}
// Code/status change?
if prev.Code != curr.Code {
oldStatus := formatStatus(prev.Code)
newStatus := formatStatus(curr.Code)
changes = append(changes, fmt.Sprintf("Status changed for %s: %s → %s", subject, oldStatus, newStatus))
}
} else {
// New lesson - but check if it's actually an exchange in the same timeslot
timeslotKey := curr.Date + "|" + curr.StartTime + "|" + curr.EndTime
if prevInTimeslot, exists := prevTimeslotMap[timeslotKey]; exists {
// This is an exchange: old lesson was removed, new one added in same timeslot
oldSubject := getSubject(prevInTimeslot)
newSubject := getSubject(curr)
room := formatRoom(curr.Ro)
changes = append(changes, fmt.Sprintf("Lesson exchanged: %s → %s in %s", oldSubject, newSubject, room))
} else {
// Truly new lesson
subject := getSubject(curr)
room := formatRoom(curr.Ro)
changes = append(changes, fmt.Sprintf("New lesson: %s in %s", subject, room))
}
}
}
// Check for removed lessons
for key, prev := range prevMap {
// Skip lessons that were not for today
if prev.Date != today {
continue
}
if _, exists := currMap[key]; !exists {
subject := getSubject(prev)
// Check if this removal is part of an exchange (already handled above)
timeslotKey := prev.Date + "|" + prev.StartTime + "|" + prev.EndTime
if _, newExists := currTimeslotMap[timeslotKey]; !newExists {
// Only report as removed if no new lesson took its place
changes = append(changes, fmt.Sprintf("Lesson removed: %s", subject))
}
}
}
// Send notification if changes detected
if len(changes) > 0 {
log.Printf("Timetable changed for user %s: %d changes", acc.Username, len(changes))
message := "Your timetable has changed!\n\n" + strings.Join(changes, "\n")
BotStart.SendDM(acc.UserID, message)
// Optional: send to Discord webhook if configured and user is "default"
if acc.UserID == "default" && discordWebhookURL != "" {
sendUpdateDiscordWebhookWithDetails(changes)
}
}
}
// Always update prevData
prevData[acc.UserID] = data
time.Sleep(3 * time.Second)
}
}
@ -309,7 +129,7 @@ func scheduleTimetableUpdate() {
updateAllUsers()
// Ticker for periodic updates
hourTicker := time.NewTicker(30 * time.Minute)
hourTicker := time.NewTicker(1 * time.Minute) // For testing, 1 minute. Change to 1 * time.Hour for production.
go func() {
for range hourTicker.C {
updateAllUsers()
@ -318,7 +138,7 @@ func scheduleTimetableUpdate() {
// Ticker for scheduled lesson notifications
startMinuteTicker(func() {
now := Untis.GetTime()
now := time.Now()
if isScheduledTime(now) {
log.Println("Scheduled time reached, running notifications...")
accounts, _ := BotStart.LoadAndDecryptAccounts()
@ -330,11 +150,10 @@ func scheduleTimetableUpdate() {
log.Println("Finished running notifications.")
}
})
log.Println("Updated all users")
}
func startMinuteTicker(f func()) {
now := Untis.GetTime()
now := time.Now()
next := now.Truncate(time.Minute).Add(time.Minute)
time.Sleep(time.Until(next))
ticker := time.NewTicker(1 * time.Minute)
@ -347,7 +166,7 @@ func startMinuteTicker(f func()) {
}
func Run(userID string) {
timetableFile := "timetableFilled_default.json"
timetableFile := "timetableFilled.json"
if userID != "default" {
timetableFile = fmt.Sprintf("timetableFilled_%s.json", userID)
}
@ -363,8 +182,7 @@ func Run(userID string) {
roomByStartTime, _ := MapTimeToRoom(timetableFile)
subjectByStartTime, _ := MapTimeToSubject(timetableFile)
now := Untis.GetTime().Format("15:04")
now := time.Now().Format("15:04")
nextTime, room, foundRoom := NextRoomForTime(roomByStartTime, now)
if !foundRoom {
return // No upcoming lessons
@ -378,22 +196,19 @@ func Run(userID string) {
status, _ := NextCodeForTime(codeByStartTime, now)
var message string
if status == "cancelled" {
message = fmt.Sprintf("Next lesson: **%s** at **%s**. is **%s**", subject, nextTime, status)
} else if status != "" && status != "cancelled" {
if status != "" {
message = fmt.Sprintf("Next lesson: **%s** in room **%s** at **%s**. Status: **%s**", subject, room, nextTime, status)
} else {
message = fmt.Sprintf("Next lesson: **%s** in room **%s** at **%s**.", subject, room, nextTime)
}
if userID == "default" {
if BotStart.WebHook {
log.Println("WebHook status ", BotStart.WebHook)
// The default user still sends to the webhook
sendDiscordWebhook(subject, room, nextTime, status)
}
}
} else {
BotStart.SendDM(userID, message)
}
}
/*
*/
@ -403,10 +218,6 @@ func NextRoomForTime(roomByStartTime map[string]string, current string) (string,
if err != nil {
return "", "", false
}
// Calculate 30 minutes from now
thirtyMinutesLater := now.Add(30 * time.Minute)
var times []time.Time
timeToStr := make(map[time.Time]string)
for t := range roomByStartTime {
@ -414,32 +225,23 @@ func NextRoomForTime(roomByStartTime map[string]string, current string) (string,
if err != nil {
continue
}
// Only include times within the next 30 minutes
if parsed.After(now) && parsed.Before(thirtyMinutesLater) {
times = append(times, parsed)
timeToStr[parsed] = t
}
sort.Slice(times, func(i, j int) bool { return times[i].Before(times[j]) })
for _, t := range times {
if t.After(now) {
return timeToStr[t], roomByStartTime[timeToStr[t]], true
}
}
if len(times) == 0 {
return "", "", false
}
sort.Slice(times, func(i, j int) bool { return times[i].Before(times[j]) })
// Return the first (earliest) room within the 30-minute window
return timeToStr[times[0]], roomByStartTime[timeToStr[times[0]]], true
}
func NextSubjectForTime(subjectByStartTime map[string]string, current string) (string, bool) {
layout := "15:04"
now, err := time.Parse(layout, current)
if err != nil {
return "", false
}
// Calculate 30 minutes from now
thirtyMinutesLater := now.Add(30 * time.Minute)
var times []time.Time
timeToStr := make(map[time.Time]string)
for t := range subjectByStartTime {
@ -447,32 +249,24 @@ func NextSubjectForTime(subjectByStartTime map[string]string, current string) (s
if err != nil {
continue
}
// Only include times within the next 30 minutes
if parsed.After(now) && parsed.Before(thirtyMinutesLater) {
times = append(times, parsed)
timeToStr[parsed] = t
}
sort.Slice(times, func(i, j int) bool { return times[i].Before(times[j]) })
for _, t := range times {
if t.After(now) {
return subjectByStartTime[timeToStr[t]], true
}
}
if len(times) == 0 {
return "", false
}
sort.Slice(times, func(i, j int) bool { return times[i].Before(times[j]) })
// Return the first (earliest) subject within the 30-minute window
return subjectByStartTime[timeToStr[times[0]]], true
}
func NextCodeForTime(codeByStartTime map[string]string, current string) (string, bool) {
layout := "15:04"
now, err := time.Parse(layout, current)
if err != nil {
return "", false
}
// Calculate 30 minutes from now
thirtyMinutesLater := now.Add(30 * time.Minute)
var times []time.Time
timeToStr := make(map[time.Time]string)
for t := range codeByStartTime {
@ -480,22 +274,18 @@ func NextCodeForTime(codeByStartTime map[string]string, current string) (string,
if err != nil {
continue
}
// Only include times within the next 30 minutes
if parsed.After(now) && parsed.Before(thirtyMinutesLater) {
times = append(times, parsed)
timeToStr[parsed] = t
}
}
if len(times) == 0 {
return "", false
}
sort.Slice(times, func(i, j int) bool { return times[i].Before(times[j]) })
// Return the first (earliest) code within the 30-minute window
return codeByStartTime[timeToStr[times[0]]], true
for _, t := range times {
if t.After(now) {
return codeByStartTime[timeToStr[t]], true
}
}
return "", false
}
func MapTimeToRoom(path string) (map[string]string, error) {
data, err := os.ReadFile(path)
if err != nil {
@ -514,7 +304,6 @@ func MapTimeToRoom(path string) (map[string]string, error) {
}
return roomByStartTime, nil
}
func MapTimeToCode(path string) (map[string]string, error) {
data, err := os.ReadFile(path)
if err != nil {
@ -528,12 +317,13 @@ func MapTimeToCode(path string) (map[string]string, error) {
codeByStartTime := make(map[string]string)
for _, entry := range table {
if len(entry.Code) > 0 {
if _, exists := codeByStartTime[entry.StartTime]; !exists {
codeByStartTime[entry.StartTime] = entry.Code
}
}
}
return codeByStartTime, nil
}
func MapTimeToSubject(path string) (map[string]string, error) {
data, err := os.ReadFile(path)
if err != nil {
@ -612,17 +402,40 @@ func sendDiscordWebhook(subject string, room string, nextTime string, Status str
if resp.StatusCode >= 200 && resp.StatusCode < 300 {
log.Println("Discord webhook notification sent successfully")
} else {
body, _ := io.ReadAll(resp.Body)
body, _ := ioutil.ReadAll(resp.Body)
log.Printf("Discord webhook failed with status %d: %s", resp.StatusCode, string(body))
}
}
func sendUpdateDiscordWebhookWithDetails(changes []string) {
if BotStart.WebHook {
log.Println("Sending detailed Discord webhook notification...")
message := "**Timetable Update**\n\n" + strings.Join(changes, "\n")
func sendUpdateDiscordWebhook() {
log.Println("Sending Discord webhook notification...")
// Create a rich embed message
message := "A lesson on your timetable has changed"
/*embed := Embed{
Title: "Next Lesson ",
Description: "The next lesson is starting soon: ",
Color: 3066993, // Green color
Timestamp: time.Now().Format(time.RFC3339),
Fields: []Field{
{
Name: "New Lesson",
// Value: fmt.Sprintf("`%s`", ip),
Value: fmt.Sprintf("Room: %s", room),
Inline: true,
},
{
Name: "Start-Time",
Value: fmt.Sprintf("Start time: %s", nextTime),
Inline: true,
},
{
Name: "Status",
Value: fmt.Sprintf("Status: %s", Status),
Inline: true,
},
},
}
*/
payload := DiscordWebhookPayload{
Content: message,
}
@ -641,10 +454,9 @@ func sendUpdateDiscordWebhookWithDetails(changes []string) {
defer resp.Body.Close()
if resp.StatusCode >= 200 && resp.StatusCode < 300 {
log.Println("Detailed Discord webhook sent successfully")
log.Println("Discord webhook notification sent successfully")
} else {
body, _ := io.ReadAll(resp.Body)
body, _ := ioutil.ReadAll(resp.Body)
log.Printf("Discord webhook failed with status %d: %s", resp.StatusCode, string(body))
}
}
}

BIN
untislogger Executable file

Binary file not shown.