Hey there, fellow developer! Ready to dive into the world of Telegram bots? You're in for a treat. The Telegram Bot API is a powerful tool that lets you create some seriously cool stuff. In this guide, we'll walk through the process of building a Telegram bot using Python. Buckle up!
Before we jump in, make sure you've got:
python-telegram-bot
library installed (pip install python-telegram-bot
)First things first, let's create our bot:
/newbot
command.Keep that token safe – it's the key to your bot's kingdom!
Alright, let's get coding! Here's the skeleton of our bot:
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters def start(update, context): context.bot.send_message(chat_id=update.effective_chat.id, text="I'm a bot, please talk to me!") def main(): updater = Updater("YOUR_TOKEN_HERE", use_context=True) dp = updater.dispatcher dp.add_handler(CommandHandler("start", start)) updater.start_polling() updater.idle() if __name__ == '__main__': main()
Now, let's make our bot do something useful:
def echo(update, context): context.bot.send_message(chat_id=update.effective_chat.id, text=update.message.text) dp.add_handler(MessageHandler(Filters.text & ~Filters.command, echo))
This will make your bot echo back any message it receives. Pretty neat, huh?
Let's kick it up a notch with some fancy features:
from telegram import InlineKeyboardButton, InlineKeyboardMarkup def button(update, context): query = update.callback_query query.answer() query.edit_message_text(text=f"Selected option: {query.data}") keyboard = [ [InlineKeyboardButton("Option 1", callback_data='1'), InlineKeyboardButton("Option 2", callback_data='2')] ] reply_markup = InlineKeyboardMarkup(keyboard) update.message.reply_text('Please choose:', reply_markup=reply_markup)
def send_photo(update, context): context.bot.send_photo(chat_id=update.effective_chat.id, photo=open('image.jpg', 'rb'))
Polling is easier for development, but webhooks are more efficient for production. To use a webhook:
updater.start_webhook(listen="0.0.0.0", port=int(PORT), url_path=TOKEN) updater.bot.setWebhook('https://yourherokuapp.com/' + TOKEN)
Always be prepared for the unexpected:
import logging logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO) def error(update, context): logger.warning('Update "%s" caused error "%s"', update, context.error) dp.add_error_handler(error)
Heroku is a great option for hosting your bot. Just create a Procfile
:
web: python bot.py
And you're good to go!
And there you have it! You're now equipped to create your own Telegram bot. Remember, the key to mastering this is practice and experimentation. Don't be afraid to try new things and push the boundaries of what your bot can do.
Happy coding, and may your bot bring joy to Telegram users everywhere!
Here's a complete working example that puts it all together:
import logging from telegram.ext import Updater, CommandHandler, MessageHandler, Filters, CallbackQueryHandler from telegram import InlineKeyboardButton, InlineKeyboardMarkup # Enable logging logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO) logger = logging.getLogger(__name__) # Define a few command handlers def start(update, context): context.bot.send_message(chat_id=update.effective_chat.id, text="I'm a bot, please talk to me!") def help(update, context): update.message.reply_text('Help!') def echo(update, context): update.message.reply_text(update.message.text) def button(update, context): query = update.callback_query query.answer() query.edit_message_text(text=f"Selected option: {query.data}") def keyboard(update, context): keyboard = [[InlineKeyboardButton("Option 1", callback_data='1'), InlineKeyboardButton("Option 2", callback_data='2')]] reply_markup = InlineKeyboardMarkup(keyboard) update.message.reply_text('Please choose:', reply_markup=reply_markup) def error(update, context): logger.warning('Update "%s" caused error "%s"', update, context.error) def main(): # Create the Updater and pass it your bot's token updater = Updater("YOUR_TOKEN_HERE", use_context=True) # Get the dispatcher to register handlers dp = updater.dispatcher # on different commands - answer in Telegram dp.add_handler(CommandHandler("start", start)) dp.add_handler(CommandHandler("help", help)) dp.add_handler(CommandHandler("keyboard", keyboard)) # on noncommand i.e message - echo the message on Telegram dp.add_handler(MessageHandler(Filters.text, echo)) # on button press dp.add_handler(CallbackQueryHandler(button)) # log all errors dp.add_error_handler(error) # Start the Bot updater.start_polling() # Run the bot until you press Ctrl-C or the process receives SIGINT, # SIGTERM or SIGABRT. This should be used most of the time, since # start_polling() is non-blocking and will stop the bot gracefully. updater.idle() if __name__ == '__main__': main()
Now go forth and create something awesome!