Here's your content rewritten in Markdown format:
Self-hosted Telegram Bot for Tracking Baby Sleep and Awake Time
A small Python-based Telegram bot to help parents track when their baby goes to sleep and wakes up. It uses SQLite for data storage and is based on the SZ_BabySWTime app.
🎥 Video Manual
✨ Features
- Add sleep time
- Add awake time
- View baby’s awaken times in a table format
- View baby’s sleep times in a table format
📋 Commands
/start- Start the bot/help- List all commands/adds- Add sleep time (enterbackto exit adds menu)/addw- Add awake time (enterbackto exit addw menu)/shows- Show calculated sleep time in table/showa- Show calculated awake time in table/delall- Erase entire database/dels- Delete last sleep record/dela- Delete last wake-up record
🧱 Dependencies
- PrettyTable
pip install prettytable - pyTelegramBotAPI
pip install pyTelegramBotAPI
🛠 Setup & Running
- Place
main.py,time_calc_f.pyandconfig.txtin the same directory. - On first run, the script will create a
Database.dband aconfig.txtfile if not present. - Edit
config.txtto add your bot token:
TOKEN = your_token_here
4. Re-run main.py to start the bot.
📁 Files Overview
config.txt
TOKEN = your token
main.py
# SZ_BabySWTime_bot_1.0
# App that writes time to DB and calculate how much baby
# sleep or awake
# Usage
# help - open list with commands
# adds - saves time when baby go to sleep (enter "back" to exit from adds menu)
# addw - saves time when baby waked up (enter "back" to exit from addw menu)
# shows - show table with calculated sleep time
# showa - show table with calculated awake time
# delall - full erase of database
# dels - delete last sleep record
# dela - delete last wake up record
# Program depends of PrettyTable module and pyTelegramBotApi
# that can be installed by "pip install prettytable"
# and "pip install pyTelegramBotAPI"
import telebot
import os
import sqlite3
# time_calc_f.py functions that calculate sleep and awake time
import time_calc_f
from prettytable import PrettyTable
from datetime import date
from sys import exit
print("Bot starting...")
print("Checking database... ")
# Checking if DB file exist
if os.path.isfile('Database.db'):
print("Exist")
else:
print("Not Exist")
print("Creating database...")
con = sqlite3.connect('Database.db')
cur = con.cursor()
# Create table
cur.execute('''CREATE TABLE add_sleep (id INTEGER PRIMARY KEY, date text, hour text, minute text)''')
cur.execute('''CREATE TABLE add_wakeup (id INTEGER PRIMARY KEY, date text, hour text, minute text)''')
cur.execute('''CREATE TABLE sleep_time (id INTEGER PRIMARY KEY, date text, time text)''')
cur.execute('''CREATE TABLE wakeup_time (id INTEGER PRIMARY KEY, date text, time text)''')
# Checking if config file exists
print("Checking config file... ")
if os.path.isfile('config.txt'):
print("Exist")
else:
# Creating file if not exist
with open('config.txt', 'w') as f:
f.write('TOKEN = token example')
exit()
print("Bot started")
# Parsing TOKEN from config file
with open('config.txt') as f:
lines = f.readlines()
for line in lines:
if "TOKEN" in line:
ext_token = line.split(" = ")[1]
rep=["\n"]
for r in rep:
ext_token=ext_token.replace(r,"")
# BOT Token
bot = telebot.TeleBot(ext_token)
# BOT Start Message
@bot.message_handler(commands=['start'])
def send_welcome(message):
bot.reply_to(message, """
Hi, this is Telegram bot which calculate baby sleep time. For more information use command /help""")
# BOT Help Message
help_message = """
SZ_BabySWTime_console_1.0\n\n
Commands:\n
/help - open list with commands\n
/adds - saves time when baby go to sleep (enter \"back\" to exit from adds menu)\n
/addw - saves time when baby waked up (enter \"back\" to exit from addw menu)\n
/shows - show table with calculated sleep time\n
/showa - show table with calculated awake time\n
/delall - full erase of database\n
/dels - delete last sleep record\n
/dela - delete last wake up record\n
"""
@bot.message_handler(commands=['help'])
def send_welcome(message): bot.send_message(message.chat.id, help_message.format(message.chat.id, bot.get_me()), parse_mode='html')
# BOT Add Sleep Command
@bot.message_handler(commands=['adds'])
def adds_f(message):
bot.send_message(message.chat.id, "Enter time when go to sleep (time format XX:XX):")
bot.register_next_step_handler(message, add_sleep_time_f)
# Checking for correct symbols entered
def add_sleep_time_f(message):
if len(message.text) == 5:
if message.text[0:2].isnumeric() and message.text[2] == ":" and message.text[3:5].isnumeric():
if (int(message.text[0:2]) >=0 and int(message.text[0:2]) <=24) and (int(message.text[3:5]) >=0 and int(message.text[3:5]) <=59):
sleep_hour = message.text[0:2]
sleep_minute = message.text[3:5]
# Write time to add_sleep table
## Checking if clean table add_sleep in DB
con = sqlite3.connect('Database.db')
cur = con.cursor()
cur.execute("SELECT id FROM add_sleep ORDER BY id DESC LIMIT 1")
if cur.fetchone() is None:
cur.execute("""INSERT INTO add_sleep (date, hour, minute )
VALUES (?, ?, ?)""", (date.today(), sleep_hour, sleep_minute))
con.commit()
con.close()
bot.send_message(message.chat.id, "Sleep time saved")
## Check if table add_wakeup has record
else:
cur.execute("SELECT id FROM add_sleep ORDER BY id DESC LIMIT 1")
sleep_exist_id = int(cur.fetchone()[0])
cur.execute("""SELECT id FROM add_wakeup ORDER BY id DESC LIMIT 1""")
wakeup_exist_id = int(cur.fetchone()[0])
if sleep_exist_id == wakeup_exist_id:
cur.execute("""INSERT INTO add_sleep (date, hour, minute )
VALUES (?, ?, ?)""", (date.today(), sleep_hour, sleep_minute))
con.commit()
con.close()
get_data_from_add_wakeup()
bot.send_message(message.chat.id, "Sleep time saved")
else:
bot.send_message(message.chat.id, "Please enter wake up time")
else:
bot.send_message(message.chat.id, "Value not correct")
adds_f(message)
else:
bot.send_message(message.chat.id, "Value not correct")
adds_f(message)
elif message.text == "back":
pass
else:
bot.send_message(message.chat.id, "Value not correct")
adds_f(message)
# BOT Add Wake Up Command
@bot.message_handler(commands=['addw'])
def addw_f(message):
bot.send_message(message.chat.id, "Enter time when waked up (time format XX:XX):")
bot.register_next_step_handler(message, add_wakeup_time_f)
# Checking for correct symbols entered
def add_wakeup_time_f(message):
if len(message.text) == 5:
if message.text[0:2].isnumeric() and message.text[2] == ":" and message.text[3:5].isnumeric():
if (int(message.text[0:2]) >=0 and int(message.text[0:2]) <=24) and (int(message.text[3:5]) >=0 and int(message.text[3:5]) <=59):
wake_hour = message.text[0:2]
wake_minute = message.text[3:5]
# Write time to add_sleep table
## Check if table add_sleep is clean
con = sqlite3.connect('Database.db')
cur = con.cursor()
cur.execute("SELECT id FROM add_sleep ORDER BY id DESC LIMIT 1")
if cur.fetchone() is None:
bot.send_message(message.chat.id, "Please enter sleep time")
#print("Please enter sleep time")
# Check if table add_wakeup has record
else:
cur.execute("SELECT id FROM add_sleep ORDER BY id DESC LIMIT 1")
sleep_exist_id = cur.fetchone()
if sleep_exist_id is not None:
sleep_exist_id = (int(sleep_exist_id[0]))
cur.execute("""SELECT id FROM add_wakeup ORDER BY id DESC LIMIT 1""")
wakeup_exist_id = cur.fetchone()
if wakeup_exist_id is not None:
wakeup_exist_id = (int(wakeup_exist_id[0]))
else:
wakeup_exist_id = 0
if sleep_exist_id > wakeup_exist_id:
cur.execute("""INSERT INTO add_wakeup (date, hour, minute )
VALUES (?, ?, ?)""", (date.today(), wake_hour, wake_minute))
con.commit()
con.close()
get_data_from_add_sleep()
bot.send_message(message.chat.id, "Wake up time saved")
else:
bot.send_message(message.chat.id, "No sleep record found")
else:
bot.send_message(message.chat.id, "Value not correct")
addw_f(message)
else:
bot.send_message(message.chat.id, "Value not correct")
addw_f(message)
elif message.text == "back":
pass
else:
bot.send_message(message.chat.id, "Value not correct")
addw_f(message)
# BOT Show Sleep Command
@bot.message_handler(commands=['shows'])
def shows_f(message):
my_table = PrettyTable()
con = sqlite3.connect('Database.db')
cur = con.cursor()
cur.execute("SELECT * FROM sleep_time")
rows = cur.fetchone()
if rows is not None:
cur.execute("SELECT * FROM sleep_time")
rows = cur.fetchall()
for row in rows:
my_table.add_row(row)
my_table.border = False
my_table.field_names = ["No", "Date", "Sleep time"]
bot.send_message(message.chat.id, f'{my_table}'.format(message.chat.id, bot.get_me()), parse_mode='html')
else:
bot.send_message(message.chat.id, "Empty Database")
# BOT Show Awake Command
@bot.message_handler(commands=['showa'])
def send_welcome(message):
my_table = PrettyTable()
con = sqlite3.connect('Database.db')
cur = con.cursor()
cur.execute("SELECT * FROM wakeup_time")
rows = cur.fetchone()
if rows is not None:
cur.execute("SELECT * FROM wakeup_time")
rows = cur.fetchall()
for row in rows:
my_table.add_row(row)
my_table.border = False
my_table.field_names = ["No", "Date", "Awake time"]
bot.send_message(message.chat.id, f'{my_table}'.format(message.chat.id, bot.get_me()), parse_mode='html')
else:
bot.send_message(message.chat.id, "Empty Database")
# BOT Drop DB Command
@bot.message_handler(commands=['delall'])
def send_welcome(message):
con = sqlite3.connect('Database.db')
cur = con.cursor()
cur.execute("DELETE FROM sleep_time;",)
cur.execute("DELETE FROM wakeup_time;",)
cur.execute("DELETE FROM add_sleep;",)
cur.execute("DELETE FROM add_wakeup;",)
con.commit()
con.close()
bot.send_message(message.chat.id, "Database erased".format(message.chat.id, bot.get_me()), parse_mode='html')
# BOT Delete Last Sleep Record from DB Command
@bot.message_handler(commands=['dels'])
def send_welcome(message):
con = sqlite3.connect('Database.db')
cur = con.cursor()
cur.execute("DELETE FROM add_sleep WHERE id = (SELECT MAX(id) FROM add_sleep)")
cur.execute("DELETE FROM wakeup_time WHERE id = (SELECT MAX(id) FROM wakeup_time)")
con.commit()
con.close()
bot.send_message(message.chat.id, "Last sleep record deleted".format(message.chat.id, bot.get_me()), parse_mode='html')
# BOT Delete Last Awake Record from DB Command
@bot.message_handler(commands=['dela'])
def send_welcome(message):
con = sqlite3.connect('Database.db')
cur = con.cursor()
cur.execute("DELETE FROM add_wakeup WHERE id = (SELECT MAX(id) FROM add_wakeup)")
cur.execute("DELETE FROM sleep_time WHERE id = (SELECT MAX(id) FROM sleep_time)")
con.commit()
con.close()
bot.send_message(message.chat.id, "Last wake up record deleted".format(message.chat.id, bot.get_me()), parse_mode='html')
# Function to write calculated time to sleep
def write_data_to_sleep(sleep_time):
con = sqlite3.connect('Database.db')
cur = con.cursor()
cur.execute("""SELECT date FROM add_sleep ORDER BY id DESC LIMIT 1""")
date_created = cur.fetchone()[0]
cur.execute("""INSERT INTO sleep_time (date, time)
VALUES (?, ?)""", (date_created, sleep_time))
con.commit()
con.close()
# Function to write calculated time to wakeup
def write_data_to_wakeup(wakeup_time):
con = sqlite3.connect('Database.db')
cur = con.cursor()
cur.execute("""SELECT date FROM add_wakeup ORDER BY id DESC LIMIT 1""")
date_created = cur.fetchone()[0]
cur.execute("""INSERT INTO wakeup_time (date, time)
VALUES (?, ?)""", (date_created, wakeup_time))
con.commit()
con.close()
# Function to operate with times in add tables
def get_data_from_add_sleep():
con = sqlite3.connect('Database.db')
cur = con.cursor()
cur.execute("""SELECT hour FROM add_sleep ORDER BY id DESC LIMIT 1""")
sleep_last_h = int(cur.fetchone()[0])
cur.execute("""SELECT minute FROM add_sleep ORDER BY id DESC LIMIT 1""")
sleep_last_m = int(cur.fetchone()[0])
cur.execute("""SELECT hour FROM add_wakeup ORDER BY id DESC LIMIT 1""")
wakeup_last_h = int(cur.fetchone()[0])
cur.execute("""SELECT minute FROM add_wakeup ORDER BY id DESC LIMIT 1""")
wakeup_last_m = int(cur.fetchone()[0])
sleep_time = time_calc_f.sleep_f(wakeup_last_h, wakeup_last_m, sleep_last_h, sleep_last_m)
write_data_to_sleep(sleep_time)
# Function to operate with times in add tables
def get_data_from_add_wakeup():
con = sqlite3.connect('Database.db')
cur = con.cursor()
cur.execute("""SELECT hour FROM add_sleep ORDER BY id DESC LIMIT 1""")
sleep_last_h = int(cur.fetchone()[0])
cur.execute("""SELECT minute FROM add_sleep ORDER BY id DESC LIMIT 1""")
sleep_last_m = int(cur.fetchone()[0])
cur.execute("""SELECT hour FROM add_wakeup ORDER BY id DESC LIMIT 1""")
wakeup_last_h = int(cur.fetchone()[0])
cur.execute("""SELECT minute FROM add_wakeup ORDER BY id DESC LIMIT 1""")
wakeup_last_m = int(cur.fetchone()[0])
awake_time = time_calc_f.wakeup_f(wakeup_last_h, wakeup_last_m, sleep_last_h, sleep_last_m)
write_data_to_wakeup(awake_time)
bot.polling()
time_calc_f.py
time_calc_f.py
# Just for test uncomment to enter manualy time to calculate
#wakeup_h = input("wakeup_h: ")
#wakeup_m = input("wakeup_m: ")
#sleep_h = input("sleep_h: ")
#sleep_m = input("sleep_m: ")
#wakeup_h = int(wakeup_h)
#wakeup_m = int(wakeup_m)
#sleep_h = int(sleep_h)
#sleep_m = int(sleep_m)
# Function calculates how much time pass from sleep to wakeup
def sleep_f(wakeup_h, wakeup_m, sleep_h, sleep_m):
if wakeup_h < sleep_h:
time_in_min =(1440 - abs(((wakeup_h *60)+wakeup_m) - ((sleep_h*60)+sleep_m)))
else:
time_in_min = abs(((wakeup_h *60)+wakeup_m) - ((sleep_h*60)+sleep_m))
time_h = int(time_in_min/60)
time_m = time_in_min - (time_h * 60)
sleep_time = str(time_h) + ":" + str(time_m)
return(sleep_time)
# Function calculates how much time pass from wake up to sleep
def wakeup_f(wakeup_h, wakeup_m, sleep_h, sleep_m):
if wakeup_h > sleep_h:
time_in_min =1440 - abs(((sleep_h * 60) + sleep_m)-((wakeup_h * 60) + wakeup_m))
else:
time_in_min = abs(((sleep_h * 60) + sleep_m)-((wakeup_h * 60) + wakeup_m))
time_h = int(time_in_min/60)
time_m = time_in_min - (time_h * 60)
wakeup_time = str(time_h) + ":" + str(time_m)
return(wakeup_time)
🖥 Screenshots
