Creating a complex Python Telegram bot involves several components: handling messages, commands, and possibly integrating with third-party APIs. Here's a starter example using the python-telegram-bot library, which is popular for building Telegram bots in Python.
Before you get started, make sure you have this library installed. You can install it via pip:
pip install python-telegram-bot
Here's a sample code structure for a more complex bot, capable of handling commands, messages, and accessing an external API (e.g., fetching data from a public API):
import logging
from telegram import Update, ForceReply
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters, CallbackContext
import requests
# Enable logging
logging.basicConfig(
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=logging.INFO
)
logger = logging.getLogger(__name__)
# Define a command handler. Usually takes the two arguments update and context.
def start(update: Update, context: CallbackContext) -> None:
user = update.effective_user
update.message.reply_markdown_v2(
fr'Hi {user.mention_markdown_v2()}\!',
reply_markup=ForceReply(selective=True),
)
def help_command(update: Update, context: CallbackContext) -> None:
update.message.reply_text('Help! Ask me anything or use /start to begin the conversation.')
def echo(update: Update, context: CallbackContext) -> None:
update.message.reply_text(update.message.text)
def get_external_data() -> str:
"""Fetch some data from a public API - for example, a joke API."""
try:
response = requests.get("https://api.chucknorris.io/jokes/random")
if response.status_code == 200:
json_data = response.json()
return json_data.get('value', 'Could not fetch a joke at this time.')
else:
return 'Failed to retrieve data.'
except requests.RequestException as e:
logger.error(f"Request failed: {e}")
return 'Error accessing external API.'
def joke(update: Update, context: CallbackContext) -> None:
"""Respond with a joke fetched from an external API."""
joke = get_external_data()
update.message.reply_text(joke)
def main() -> None:
# Replace 'YOUR_TOKEN' with your actual bot token
updater = Updater("YOUR_TOKEN", use_context=True)
dispatcher = updater.dispatcher
# Register handlers
dispatcher.add_handler(CommandHandler("start", start))
dispatcher.add_handler(CommandHandler("help", help_command))
dispatcher.add_handler(CommandHandler("joke", joke))
dispatcher.add_handler(MessageHandler(Filters.text & ~Filters.command, echo))
# Start the Bot
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
Explanation
-
Command Handlers: These are functions that handle Telegram commands prefixed with / such as /start, /help, and /joke.
-
Message Handlers: These handle non-command messages sent to the bot. Here it echoes the user's message back to them.
-
External API Access: The get_external_data function fetches a random joke from an external API. This could be replaced or extended with other API calls to make the bot more complex and useful.
-
Logging: This script uses Python's built-in logging module for logging information and errors.
Getting Your Bot Token
To create a bot and get your token, you need to use Telegram's BotFather. Here's a quick guide:
- Open Telegram and search for the BotFather.
- Start a chat with the BotFather and use the
/newbot command to create a new bot.
- Follow the instructions to name your bot and get the token.
Running the Bot
Replace 'YOUR_TOKEN' with the bot token you received from BotFather and run the script. The bot will be active and ready to interact.