Build a Telegram bot for random quotes and facts
Learning how to set up a Telegram bot that generates random quotes or facts can be a weekend project, even if you have never written code. The bot lives inside Telegram, replies to simple commands, and can send a fresh line whenever someone asks. It suits a book club, classroom, workplace channel, or community group that wants an occasional lift without filling conversations with more links.
Start with one purpose and one audience. A daily quote bot can post at 8am; an on-demand /quote command can answer instantly; a /fact option can mix in useful tidbits. A button labelled “Give me something” may be easier than a long menu for people joining on mobile. Before opening Telegram’s BotFather, decide which messages should be random, who may use the bot, and whether it will operate in one approved group or accept direct messages everywhere.
The basic design is straightforward: BotFather creates the bot and supplies an access token, a small script selects content, and Telegram carries the messages. You can run everything on a laptop while testing, then move it to a server so it stays online. Python is a good choice because it is readable and widely supported, although the same architecture works with JavaScript, Go, or a no-code automation service.
Choose the bot’s purpose and message style
Write down the experience before writing code. A useful first release might answer /quote, /fact, and /random, then provide two inline buttons under /start. Keep each reply to one idea, include attribution when it is known, and avoid sending the same item twice in a row. That simple behaviour is easier to maintain than a large personality system and gives users a predictable way to share results with friends.
Think about tone as well. Some groups want formal quotations for meetings; others welcome plain Australian English, with expressions such as “no worries” or “arvo” appearing in original material rather than forced into every response. If the audience includes people in Sydney, Melbourne, Brisbane, or Perth, remember that many will interact on a phone and that some mobile plans include capped data, so short replies are kinder to both screen space and data allowances.
Decide how the bot will behave in public and private chats. It may work in one moderated Telegram channel for an Australian community group, or accept direct messages from anyone. A narrow role is safer: it can use an allowlist of chat IDs, ignore unknown commands, and avoid collecting names or locations it does not need. A short explainer linked from the bot profile is also sensible; a project overview can provide that context when the bot supports a broader community initiative.
Build a clean quote and fact library
Keep the content library separate from the bot logic. Two UTF-8 JSON files—one for quotations and one for facts—are enough for a small project, and they make corrections or additions easy without rewriting code. A quote record should include:
- The quotation text, kept short enough for one Telegram message.
- The speaker, writer, or work to credit, using “Unknown” only when genuinely uncertain.
- A source URL and a permission or licence note where relevant.
- Tags such as courage, nature, science, or Australia.
Keep facts in a similarly consistent format. A fact needs clear wording and a traceable source, especially when it touches health, law, finance, or Indigenous culture:
- The statement in one or two plain-English sentences.
- A topic tag so you can filter the pool later.
- A reliable source, publication date, and date checked.
- A caveat or region label, such as “Australia only”, when needed.
Begin with a modest library—perhaps thirty quotes and thirty facts—then test whether the selection feels varied. Load each file once at startup and use Python’s random.choice to pick an item. If you want categories, let /quote nature choose only from tagged records, but avoid creating dozens of nearly empty lists. Check every quotation for accurate attribution and copyright status before publishing, and ask permission rather than treating a social-media caption as permission.
Create the bot and its core commands
Create the bot in Telegram by opening BotFather and choosing /newbot. Give it a distinctive name, a username ending in “bot”, and a simple description; BotFather returns a token that acts like a password. Store that token in an environment variable named TELEGRAM_BOT_TOKEN rather than pasting it into source code. If the token is ever exposed, revoke it through BotFather and issue a new one.
Create a virtual environment, install python-telegram-bot, and register one command handler for each action. A compact starting point looks like this:
import os
import random
from telegram.ext import Application, CommandHandler
QUOTES = [
{"text": "Add a verified quotation here.", "author": "Writer or source"}
]
FACTS = [
{"text": "Add a verified fact here.", "source": "Reliable source"}
]
async def quote(update, context):
item = random.choice(QUOTES)
await update.message.reply_text(
f"{item['text']}\n— {item['author']}"
)
async def fact(update, context):
item = random.choice(FACTS)
await update.message.reply_text(
f"{item['text']}\nSource: {item['source']}"
)
application = (
Application.builder()
.token(os.environ["TELEGRAM_BOT_TOKEN"])
.build()
)
application.add_handler(CommandHandler("quote", quote))
application.add_handler(CommandHandler("fact", fact))
application.run_polling()
The script deliberately keeps output as plain text, which prevents accidental formatting errors when quotations contain asterisks or angle brackets. Add a /random handler that chooses from the combined pool, and a /start handler that explains the available commands. Inline buttons can call the same functions through a callback query handler, so a button and typed command do not need separate content rules. Test each handler in a private chat before adding the bot to a group.
Add hosting, controls, and local usability
During testing, polling is convenient: the script asks Telegram for updates while it runs. For a permanent service, place it on a small virtual private server or a managed application host, keep it running with a process supervisor or container, and store configuration outside the repository. Run only one polling worker unless you have designed a queue or webhook system. A provider with a Sydney region may reduce network distance for many Australian users, although Telegram routes messages globally; benchmark rather than assuming the nearest region label guarantees the fastest response.
Treat access, privacy, and moderation as product features. Keep the bot token secret, log errors without message contents, and explain whether the bot is public. BotFather can register commands in the menu, while group administrators can restrict where it is added. For a broader view of the platform’s role in expression and moderation, this Telegram free speech context is useful background. If the bot reaches public groups, provide a reporting route and remove abusive or misleading material promptly.
Schedule any recurring posts with Australian time zones in mind rather than assuming every reader shares one clock. Python’s zoneinfo supports identifiers such as Australia/Sydney, Australia/Adelaide, and Australia/Perth, including daylight-saving changes. If the bot is later monetised, price in AUD and check Australian GST and consumer rules rather than copying an overseas template. The same local awareness applies to accessibility: clear commands, readable line lengths, and alternative text for any images.
Test, launch, and build a daily habit
Test like a new group member. Run /quote, /fact, /random, and /start from both a private chat and a test group; try an empty data file, a missing author, a long quotation, and several simultaneous requests. Restart the server to confirm that startup works from a clean process, then check that logs contain no token. Invite a few readers and watch for confusing responses before opening access.
Launch with a short explanation of what the bot offers, when it posts, and how to report a problem. In BotFather, use /setcommands to label /quote, /fact, and /random so users can discover them without typing. Pin a sample message in the group and avoid automated posting during late-night hours; a daily item at a civilised morning time is usually more useful than constant interruptions. If you expand into short clips, this quick video messages guide explains the Telegram format before you add a media feature.
Open Telegram now, create a private test group, and add the bot with the token you have stored securely. Run each command, confirm the replies look right on an Australian mobile connection, and give the bot to two or three trusted testers before you promote it. Once those checks pass, share the channel with your community and set a simple weekly routine for reviewing sources, correcting errors, and adding fresh material.