How to make a Telegram bot run 24/7 without your laptop
A bot has to be running all the time, so your laptop is the wrong place for it. Here we build a small prayer-times bot for Kuala Terengganu, test it properly, and leave it running on an awx computer, where it keeps answering after you close the lid.
A Telegram bot is a small program that has to be running all the time. If it runs on your laptop, it stops when you close the lid. In this walk-through we put one on an awx computer instead, so it keeps answering while your laptop is off.
The bot sends prayer times for Kuala Terengganu. It has three commands:
/startsays what it does./todaysends today's times./nextsends the next prayer and how long until it.
The times come from JAKIM's e-Solat. The bot is one Python file of 172 lines, with one library (requests). No bot framework, so you can read every line.
What you need
- An
awxcomputer. Small is enough: the running bot used about 30 MB of memory. - The Telegram app, signed in.
- About 30 minutes.
Step 1. Make the bot in Telegram
Every Telegram bot is made by another bot, called BotFather.
- In Telegram, search for @BotFather (it has a blue tick) and open it.
- Send
/newbot. - Give it a name people will see, for example Awi Waktu Solat.
- Give it a username. It must end in
bot, for exampleawi_waktusolat_bot.
BotFather replies with a token, a long line like 123456789:AA.... The token is the bot's password. Anyone who has it can control your bot. Do not paste it into a chat, a screenshot, an AI prompt or a GitHub repository.
Step 2. Put the token in a file on the computer
Open your computer's Terminal tab and run:
mkdir -p ~/bot
cd ~/bot
touch .env
chmod 600 .env
nano .env
Type one line, with your own token after the =:
TELEGRAM_TOKEN=123456789:AA...
Press Ctrl+O, Enter, then Ctrl+X to save and leave nano.
chmod 600 means only the computer's own user can read the file. Check it:
ls -l ~/bot/.env
You should see -rw------- at the start of the line. The token lives only in this file. It is not in the code, so you can share the code safely.
Step 3. Where the prayer times come from
JAKIM publishes the official times on e-Solat, by zone. Kuala Terengganu is zone TRG01. Try it in the terminal:
curl -s 'https://www.e-solat.gov.my/index.php?r=esolatApi/TakwimSolat&period=today&zone=TRG01'
We got this back (369 bytes, in about 0.12 s, from the computer):
{"prayerTime":[{"hijri":"1448-06-21","date":"01-Dis-2026","day":"Tuesday","imsak":"05:38:00","fajr":"05:48:00","syuruk":"07:01:00","dhuha":"07:26:00","dhuhr":"12:59:00","asr":"16:20:00","maghrib":"18:53:00","isha":"20:07:00"}],"status":"OK!","serverTime":"2026-12-01 23:29:28","periodType":"today","lang":"ms_my","zone":"TRG01","bearing":"291° 23′ 2″"}
Two things to notice:
- The date is in Malay:
01-Dis-2026. Our code needs a small table of Malay month names (Mac, Mei, Ogos, Okt, Dis). syurukis sunrise. It is useful to show, but it is not a prayer, so/nextmust skip it.
The bot asks for period=week instead of today. That gives 8 days at once, starting today. One reason is fewer calls. The other is /next late at night: after Isyak, the next prayer is tomorrow's Subuh, so the bot needs tomorrow's times too.
Step 4. A Python environment for the bot
Still in ~/bot:
python3 -m venv .venv
echo 'requests==2.32.3' > requirements.txt
.venv/bin/pip install -r requirements.txt
This took 5.4 seconds on our computer and the .venv folder is 19 MB. A venv keeps the bot's libraries apart from the rest of the computer, so other projects cannot break it.
Step 5. The code
Save this as ~/bot/bot.py (for example with nano bot.py, or upload it from the Files tab).
"""A small Telegram bot: prayer times for Kuala Terengganu.
Commands:
/start what the bot does
/today today's prayer times
/next the next prayer and how long until it
Times come from JAKIM's e-Solat (zone TRG01, Kuala Terengganu).
The bot talks to Telegram with plain HTTPS long polling (no framework).
"""
import os
import time
from datetime import date, datetime, timedelta
from pathlib import Path
from zoneinfo import ZoneInfo
import requests
ZONE = "TRG01" # Kuala Terengganu in JAKIM's zone list
TZ = ZoneInfo("Asia/Kuala_Lumpur")
ESOLAT_URL = "https://www.e-solat.gov.my/index.php"
API_BASE = os.environ.get("TELEGRAM_API_BASE", "https://api.telegram.org")
ENV_FILE = Path(__file__).with_name(".env") # ~/bot/.env, next to this file
# (key in the e-Solat reply, name we show). Syuruk is sunrise, not a prayer.
TIMES = [
("fajr", "Subuh"),
("syuruk", "Syuruk"),
("dhuhr", "Zohor"),
("asr", "Asar"),
("maghrib", "Maghrib"),
("isha", "Isyak"),
]
PRAYERS = [t for t in TIMES if t[0] != "syuruk"]
# e-Solat writes dates in Malay, like "01-Dis-2026".
MONTHS = {"Jan": 1, "Feb": 2, "Mac": 3, "Apr": 4, "Mei": 5, "Jun": 6,
"Jul": 7, "Ogos": 8, "Sep": 9, "Okt": 10, "Nov": 11, "Dis": 12}
def log(msg):
print(datetime.now(TZ).strftime("%Y-%m-%d %H:%M:%S"), msg, flush=True)
# ---------- prayer times ----------
def parse_esolat(data):
"""Turn an e-Solat reply into {date: {"fajr": datetime, ...}}."""
days = {}
for row in data["prayerTime"]:
d, m, y = row["date"].split("-")
day = date(int(y), MONTHS[m], int(d))
days[day] = {}
for key, _ in TIMES:
hh, mm, _ss = row[key].split(":")
days[day][key] = datetime(day.year, day.month, day.day,
int(hh), int(mm), tzinfo=TZ)
return days
_cache = {} # date -> times, filled once a day
def times_for(day):
"""Times for one day. Fetches a week at a time, so /next works after Isyak."""
if day not in _cache:
log(f"fetching e-Solat week for {ZONE}")
r = requests.get(ESOLAT_URL, timeout=20, params={
"r": "esolatApi/TakwimSolat", "period": "week", "zone": ZONE})
r.raise_for_status()
_cache.clear()
_cache.update(parse_esolat(r.json()))
return _cache[day]
def next_prayer(now, today, tomorrow):
"""Return (name, time) of the first prayer after `now`."""
for key, name in PRAYERS:
if today[key] > now:
return name, today[key]
return "Subuh", tomorrow["fajr"]
def until(delta):
"""timedelta -> '2 h 15 min'."""
minutes = int(delta.total_seconds() // 60)
h, m = divmod(minutes, 60)
return f"{h} h {m} min" if h else f"{m} min"
def today_text(now):
t = times_for(now.date())
lines = [f"Prayer times, Kuala Terengganu, {now:%a %d %b %Y}"]
for key, name in TIMES:
lines.append(f"{name}: {t[key]:%H:%M}")
return "\n".join(lines)
def next_text(now):
name, at = next_prayer(now, times_for(now.date()),
times_for(now.date() + timedelta(days=1)))
return f"Next: {name} at {at:%H:%M}, in {until(at - now)}."
START_TEXT = ("Assalamualaikum! I send prayer times for Kuala Terengganu "
"(JAKIM e-Solat, zone TRG01).\n"
"/today - today's times\n"
"/next - the next prayer and how long until it")
def reply_for(text, now):
cmd = text.split()[0].split("@")[0].lower() if text.strip() else ""
if cmd == "/today":
return today_text(now)
if cmd == "/next":
return next_text(now)
return START_TEXT # /start, and anything else
# ---------- Telegram ----------
def read_token():
"""TELEGRAM_TOKEN from the environment, or from ~/bot/.env."""
token = os.environ.get("TELEGRAM_TOKEN", "").strip()
if token:
return token
try:
for line in ENV_FILE.read_text().splitlines():
if line.startswith("TELEGRAM_TOKEN="):
return line.split("=", 1)[1].strip().strip('"\'')
except FileNotFoundError:
pass
return ""
def call(token, method, **params):
r = requests.post(f"{API_BASE}/bot{token}/{method}", json=params, timeout=40)
r.raise_for_status()
return r.json()["result"]
def main():
token = read_token()
while not token:
log("waiting for TELEGRAM_TOKEN in ~/bot/.env")
time.sleep(30)
token = read_token()
log("bot started, long polling Telegram")
offset = 0
while True:
try:
updates = call(token, "getUpdates", offset=offset, timeout=30)
for u in updates:
offset = u["update_id"] + 1
msg = u.get("message")
if not msg or "text" not in msg:
continue
try:
text = reply_for(msg["text"], datetime.now(TZ))
except requests.RequestException:
text = "Sorry, I could not reach e-Solat just now. Try again soon."
call(token, "sendMessage", chat_id=msg["chat"]["id"], text=text)
log(f"chat {msg['chat']['id']}: {msg['text']!r} -> replied")
except Exception as e: # network blip, Telegram or e-Solat down
log("error: " + str(e).replace(token, "***"))
time.sleep(5)
if __name__ == "__main__":
main()
How it works, from the bottom up:
main()reads the token. If there is none yet, it printswaiting for TELEGRAM_TOKEN in ~/bot/.envand checks again every 30 seconds. It does not exit. This matters later: a service that exits at once would be restarted again and again.- Long polling.
getUpdateswithtimeout=30asks Telegram: "anything new? I will wait up to 30 seconds." When a message comes, Telegram answers at once. The bot replies withsendMessage, then asks again.offsettells Telegram which messages we have already handled. This needs no public address, no web server and no open port. The bot only makes outgoing HTTPS calls. - The cache.
times_for()fetches the week from e-Solat once and keeps it in_cache. It fetches again only when it needs a day it does not have. next_prayer()walks through today's prayers and returns the first one later than now. If none is left, it is tomorrow's Subuh.- Time zone. Every time is made in
Asia/Kuala_Lumpur, so the answers are right whatever time zone the computer itself uses. (Our computer's clock is in UTC.) - Errors. If Telegram or e-Solat cannot be reached, the bot logs the error, waits 5 seconds and carries on. A user who asks while e-Solat is down gets a short "try again soon". The log hides the token, because some errors print the address, and the address contains the token.
print(..., flush=True)sends each log line out at once, so you can read it in the service log.
Step 6. Test it before it goes live
Test the time logic
sample-week.json is a saved e-Solat reply (the one from step 3, with period=week). The tests use it, so they need no network and always give the same answer. Save this as ~/bot/test_bot.py:
"""Tests for the time logic, using a saved e-Solat reply (no network)."""
import json
import unittest
from datetime import date, datetime, timedelta
import bot
with open("sample-week.json") as f:
DAYS = bot.parse_esolat(json.load(f))
TODAY = DAYS[date(2026, 12, 1)]
TOMORROW = DAYS[date(2026, 12, 2)]
def at(h, m, day=1):
return datetime(2026, 12, day, h, m, tzinfo=bot.TZ)
class TimeLogic(unittest.TestCase):
def test_parse_malay_date(self):
self.assertEqual(len(DAYS), 8)
self.assertEqual(TODAY["fajr"], at(5, 48))
self.assertEqual(TODAY["isha"], at(20, 7))
def test_next_in_the_morning(self):
self.assertEqual(bot.next_prayer(at(4, 0), TODAY, TOMORROW), ("Subuh", at(5, 48)))
def test_syuruk_is_not_a_prayer(self):
# After Subuh the next prayer is Zohor, not Syuruk.
self.assertEqual(bot.next_prayer(at(6, 30), TODAY, TOMORROW)[0], "Zohor")
def test_exactly_at_prayer_time_gives_the_next_one(self):
self.assertEqual(bot.next_prayer(at(16, 20), TODAY, TOMORROW)[0], "Maghrib")
def test_after_isyak_is_tomorrow_subuh(self):
name, when = bot.next_prayer(at(23, 30), TODAY, TOMORROW)
self.assertEqual(name, "Subuh")
self.assertEqual(when.date(), date(2026, 12, 2))
def test_until(self):
self.assertEqual(bot.until(timedelta(hours=2, minutes=15)), "2 h 15 min")
self.assertEqual(bot.until(timedelta(minutes=9, seconds=59)), "9 min")
def test_replies(self):
bot._cache.update(DAYS) # no network in tests
self.assertIn("Zohor: 12:59", bot.reply_for("/today", at(10, 0)))
self.assertEqual(bot.reply_for("/next@AnyBot", at(10, 0)),
"Next: Zohor at 12:59, in 2 h 59 min.")
self.assertEqual(bot.reply_for("hello", at(10, 0)), bot.START_TEXT)
if __name__ == "__main__":
unittest.main()
Run it:
cd ~/bot
curl -s 'https://www.e-solat.gov.my/index.php?r=esolatApi/TakwimSolat&period=week&zone=TRG01' > sample-week.json
.venv/bin/python -m unittest test_bot -v
Our run (the dates in the test match the day we saved the sample, 1 December 2026; change them to your own day):
test_after_isyak_is_tomorrow_subuh ... ok
test_exactly_at_prayer_time_gives_the_next_one ... ok
test_next_in_the_morning ... ok
test_parse_malay_date ... ok
test_replies ... ok
test_syuruk_is_not_a_prayer ... ok
test_until ... ok
----------------------------------------------------------------------
Ran 7 tests in 0.000s
OK
The tests cover the places where a bot like this usually goes wrong: the moment a prayer starts, sunrise, and the hours after Isyak.
Try the whole bot without Telegram
You can test the bot from start to end without a token and without touching Telegram. The bot reads TELEGRAM_API_BASE, which is normally https://api.telegram.org. We pointed it at a tiny fake Telegram server, 36 lines of Python on the same computer. The fake server hands the bot three messages (/start, /today, /next) and prints whatever the bot sends back.
The fake server is fake_telegram.py (download it next to bot.py). Start it in the background, then the bot:
python3 fake_telegram.py 8765 &
TELEGRAM_TOKEN=123:FAKE TELEGRAM_API_BASE=http://127.0.0.1:8765 .venv/bin/python bot.py
The bot's log, at 23:31 Malaysia time:
2026-12-01 23:31:23 bot started, long polling Telegram
2026-12-01 23:31:23 chat 42: '/start' -> replied
2026-12-01 23:31:23 fetching e-Solat week for TRG01
2026-12-01 23:31:23 chat 42: '/today' -> replied
2026-12-01 23:31:23 chat 42: '/next' -> replied
What the bot sent, as the fake server saw it:
Assalamualaikum! I send prayer times for Kuala Terengganu (JAKIM e-Solat, zone TRG01).
/today - today's times
/next - the next prayer and how long until it
Prayer times, Kuala Terengganu, Tue 01 Dec 2026
Subuh: 05:48
Syuruk: 07:01
Zohor: 12:59
Asar: 16:20
Maghrib: 18:53
Isyak: 20:07
Next: Subuh at 05:49, in 6 h 17 min.
At 23:31 Isyak had passed, so /next gave tomorrow's Subuh, 05:49 (a minute later than today's). The e-Solat data was live; only Telegram was fake.
Check the "no token yet" case
We also started the bot with an empty .env, waited, and then wrote a (fake) token into the file while it ran:
2026-12-01 23:33:23 waiting for TELEGRAM_TOKEN in ~/bot/.env
2026-12-01 23:33:53 waiting for TELEGRAM_TOKEN in ~/bot/.env
2026-12-01 23:34:23 bot started, long polling Telegram
It waited quietly, then picked up the token within 30 seconds, with no restart.
Now with the real Telegram
Run it by hand once with your real token (it is read from .env):
.venv/bin/python bot.py
Open your bot in Telegram, press Start, and send /today and /next.
Our real bot answered on a phone at 09:44 the next morning (the screenshot at the top of this post), and the log showed:
2026-12-02 09:42:49 bot started, long polling Telegram
2026-12-02 09:44:13 chat 1234567: '/start' -> replied
2026-12-02 09:44:33 fetching e-Solat week for TRG01
2026-12-02 09:44:33 chat 1234567: '/today' -> replied
(We changed the chat number; it identifies the person.)
Press Ctrl+C to stop it. Next we let awx run it for you.
Step 7. Run it as a service
A program you start in the terminal stops when the terminal closes, or when the computer goes to sleep and starts again. An awx service is a command that awx keeps running for you: if it stops, awx starts it again after about 3 seconds, and it comes back by itself whenever the computer starts.
Open your computer, then the Links tab, and find Services. Fill in:
- Name:
prayer-bot - Command:
/home/agent/bot/.venv/bin/python /home/agent/bot/bot.py - Port: leave it empty. The bot only makes outgoing calls, so there is nothing to open.
- Tick Keep this computer awake.
Press Add service. The row shows running and an always on chip.
The command uses full paths, so it works whichever folder awx starts it from. Do not run the bot by hand at the same time as the service: two copies asking Telegram for the same messages get in each other's way.
Press Log next to the service to see what the bot is doing. These are the same lines it printed in the terminal.
Step 8. Keep it on 24/7, and what sleep means
An awx computer goes to sleep after 30 minutes without activity. Activity means a terminal command, an agent run, the screen being open, or a visit to one of the computer's links. A Telegram bot has none of these: Telegram does not visit your computer, your bot calls Telegram. So without help, the computer would fall asleep half an hour after you leave, and the bot would go quiet.
When the computer sleeps: the bot stops. Files stay, including .env, the venv and the code. Messages people send in the meantime wait at Telegram (Telegram keeps them for up to 24 hours). When the computer starts again, the service starts by itself, and the bot answers the waiting messages.
Keep this computer awake prevents that. Ticking it on the service sets the computer to stay on:
- On the Free plan, the computer runs on credit. A Small computer is RM0.03 an hour, about RM22 for a month of 24 hours a day. The computer sleeps when your credit runs out.
- On the paid plan (RM15 a month), running is free and one computer can stay on with no time limit.
You can see and change this later under the computer's Settings, Power. More in why a computer sleeps, and how to keep it running.
Ideas to take it further
- Another zone: change
ZONE. JAKIM lists every zone, for example SGR01 for Gombak, Petaling and Shah Alam. - A daily message: send everyone who pressed Start the day's times after Subuh. You would need to save their chat ids in a file.
- Malay replies: the names are already in Malay; translate the rest.
Files from this post
bot.py(172 lines),test_bot.py(53 lines),requirements.txt(requests==2.32.3)- Download: bot.py, test_bot.py, requirements.txt, fake_telegram.py
Keep reading
- Run a script every morning without your laptop
- How to run Jupyter notebooks on awx, from any browser
- Why a computer sleeps and how to keep it running
Getting started
Sign in with your Google account, give your name and confirm your email. New accounts are approved by hand, and you start on the Free plan. See Pricing for what the paid plan includes.
Awi, signing off.