Posted by Kosal
Creating a Telegram bot with Python involves a few steps. You'll need to create a bot using the Telegram BotFather, get an API token, set up a Python environment, install necessary libraries, and write the bot code. Below is a step-by-step guide to help you create a Telegram bot using Python:
/newbot
command to create a new bot.You'll need the python-telegram-bot
library to interact with the Telegram Bot API. You can install it using pip:
pip install python-telegram-bot
Create a Python script (e.g., bot.py
) in your project directory and write the code to create and run your bot.
Here's a simple example to get you started:
import requests
from telegram import InlineQueryResultArticle, InputTextMessageContent
from telegram.ext import Application, CommandHandler, InlineQueryHandler
import logging
# Enable logging
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=logging.INFO)
logger = logging.getLogger(__name__)
# Define a function to handle the /start command
async def start(update, context):
await update.message.reply_text("Hello! I'm your Telegram Bot. Type /help for available commands.")
# Define a function to handle the /help command
async def help_command(update, context):
await update.message.reply_text("Available commands:\n"
"/start - Start the bot\n"
"/help - Display available commands\n"
"/cat - Get a random cat picture")
# Define a function to handle the /cat command
async def cat(update, context):
response = requests.get("https://api.thecatapi.com/v1/images/search")
data = response.json()
cat_url = data[0]['url']
print(cat_url)
await update.message.reply_photo(cat_url)
# Define a function to handle text messages
async def echo(update, context):
await update.message.reply_text(update.message.text)
# Define a function to handle inline queries
def inline_query(update, context):
query = update.inline_query.query
results = [
InlineQueryResultArticle(
id=str(uuid4()),
title="Echo",
input_message_content=InputTextMessageContent(query)
)
]
update.inline_query.answer(results)
def main():
# Replace 'YOUR_API_TOKEN' with your actual API token
api_key = 'YOUR_API_TOKEN'
application = Application.builder().token(api_key).build()
# Register command handlers
application.add_handler(CommandHandler("start", start))
application.add_handler(CommandHandler("help", help_command))
application.add_handler(CommandHandler("cat", cat))
# Register an inline query handler
application.add_handler(InlineQueryHandler(inline_query))
# Start the Bot
application.run_polling(1.0)
# Run the bot until you press Ctrl-C
application.idle()
if __name__ == '__main__':
main()
Replace 'YOUR_API_TOKEN'
with the API token provided by BotFather.
Execute your Python script from the terminal or command prompt:
python bot.py
Go to your Telegram app, search for your bot by its username, and start a chat. Send the /start
command to initiate the conversation with your bot.
Congratulations! You've successfully created a Telegram bot with Python. You can expand its functionality by adding more command handlers and implementing various features using the Telegram Bot API.