Build Telegram Bot with Python
What is a Telegram bot?
Bots are simple Telegram accounts operated by software — not people — and they often have AI features. They can do anything — teach, play, search, broadcast, remind, connect, integrate with other services, or even pass commands to the Internet of Things. You can read more on the Telegrams website.
Creating Telegram Bot
To start with you must have a Telegram account to create a bot. If you do, you can search for BotFather in the Telegram app (do look for the bluetick after the name) and follow the steps:
- Start a conversation with BotFather by clicking Start button. You will see a command list immediately.
- To create a new telegram bot, you have to type /newbot command and follow the instructions. Be careful, your bot’s username has to end with a bot. For example, Pizzabot or Pizza_bot.
- I chose PYTHON3DemoBot, which is pretty straightforward.
Once everything is working properly, you’ll see the bot’s token or API access key, which we’ll need to develop the bot.
Let’s Code a Telegram Bot
Let’s install the libraries we need before we build our bot.
pip install python-telegram-bot
Create a Python file named echo_bot.py and copy and paste the below script
import logging
from telegram import ForceReply, Update
from telegram.ext import Application, CommandHandler, ContextTypes, MessageHandler, filters
# Enable logging
logging.basicConfig(
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.INFO
)
# set higher logging level for httpx to avoid all GET and POST requests being logged
logging.getLogger("httpx").setLevel(logging.WARNING)
logger = logging.getLogger(__name__)
# Define a few command handlers. These usually take the two arguments update and
# context.
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
"""Send a message when the command /start is issued."""
user = update.effective_user
await update.message.reply_html(
rf"Hi {user.mention_html()}!",
reply_markup=ForceReply(selective=True),
)
async def help_command(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
"""Send a message when the command /help is issued."""
await update.message.reply_text("Help!")
async def echo(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
"""Echo the user message."""
await update.message.reply_text(update.message.text)
def main() -> None:
"""Start the bot."""
# Create the Application and pass it your bot's token.
application = Application.builder().token("TOKEN").build()
# on different commands - answer in Telegram
application.add_handler(CommandHandler("start", start))
application.add_handler(CommandHandler("help", help_command))
# on non command i.e message - echo the message on Telegram
application.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, echo))
# Run the bot until the user presses Ctrl-C
application.run_polling(allowed_updates=Update.ALL_TYPES)
if __name__ == "__main__":
main()
Replace TOKEN with the token we have generated through bot father.
Save and run execute the script.
Now, go to the bot we have created start messaging, and have fun.
Conclusion
We have successfully coded our first telegram bot.
You can find more scripts here.
Thank you for reading, please comment, like share.