package main import ( "database/sql" "encoding/json" "fmt" "log" "os" "strconv" "strings" "time" _ "github.com/mattn/go-sqlite3" ) func main() { // Open the database db, err := sql.Open("sqlite3", "../../ldr_readings.db") if err != nil { log.Fatal(err) } defer db.Close() // Create the table if it doesn't exist createTable := ` CREATE TABLE IF NOT EXISTS ldr_readings ( id INTEGER PRIMARY KEY AUTOINCREMENT, value INTEGER NOT NULL, timestamp DATETIME DEFAULT CURRENT_TIMESTAMP );` _, err = db.Exec(createTable) if err != nil { log.Fatal(err) } // Read the Telegram export file data, err := os.ReadFile("../../../tg_export.json") if err != nil { log.Fatal(err) } // Parse the JSON into a map var export map[string]interface{} if err := json.Unmarshal(data, &export); err != nil { log.Printf("Error unmarshaling JSON: %v", err) log.Printf("First 100 bytes of data: %s", string(data[:100])) log.Fatal(err) } // Get the messages array messages, ok := export["messages"].([]interface{}) if !ok { log.Fatal("Could not find messages array in export") } // Prepare the insert statement stmt, err := db.Prepare("INSERT INTO ldr_readings (value, timestamp) VALUES (?, ?)") if err != nil { log.Fatal(err) } defer stmt.Close() // Process each message count := 0 for _, msgInterface := range messages { msg, ok := msgInterface.(map[string]interface{}) if !ok { continue } // Get the text field text, ok := msg["text"].(string) if !ok { continue } // Only process messages containing LDR values if !strings.HasPrefix(text, "Current LDR value: ") { continue } // Extract the LDR value valueStr := strings.TrimPrefix(text, "Current LDR value: ") value, err := strconv.Atoi(valueStr) if err != nil { log.Printf("Error parsing LDR value from message: %s", text) continue } // Get the date field date, ok := msg["date"].(string) if !ok { continue } // Parse the timestamp timestamp, err := time.Parse("2006-01-02T15:04:05", date) if err != nil { log.Printf("Error parsing timestamp from message: %s", date) continue } // Insert into database _, err = stmt.Exec(value, timestamp) if err != nil { log.Printf("Error inserting record: %v", err) continue } count++ if count%100 == 0 { fmt.Printf("Imported %d readings...\n", count) } } fmt.Printf("Successfully imported %d LDR readings\n", count) }