Jul 14, 2024
TOKEN: Final = 'your-token-here'
BOT_USERNAME: Final = '@your_bot_username'
pip install python-telegram-bot
python from telegram import Update from telegram.ext import Application, CommandHandler, MessageHandler, Filters, ContextTypes from typing import Final
async def start_command(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
await update.message.reply_text('Hello, thanks for chatting with me. I am a banana.')
Define a handler function for processing text:
def handle_response(text: str) -> str:
text = text.lower()
if 'hello' in text:
return 'Hey there!'
elif 'how are you' in text:
return 'I am good!'
elif 'i love python' in text:
return 'Remember to subscribe!'
else:
return 'I do not understand what you wrote.'
Define the message handler:
async def handle_message(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
message_type = update.message.chat.type
text = update.message.text.lower()
if message_type == 'group' and BOT_USERNAME in text:
text = text.replace(BOT_USERNAME, '').strip()
response = handle_response(text)
else:
response = handle_response(text)
await update.message.reply_text(response)
async def error(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
print(f'Update {update} caused error {context.error}')
if __name__ == '__main__':
app = Application.builder().token(TOKEN).build()
app.add_handler(CommandHandler('start', start_command))
app.add_handler(CommandHandler('help', help_command))
app.add_handler(CommandHandler('custom', custom_command))
app.add_handler(MessageHandler(Filters.text & (~Filters.command), handle_message))
app.add_error_handler(error)
print('Starting bot...')
app.run_polling(poll_interval=3)
start - Starts the bot
help - Provides help for the bot
custom - This is a custom command
Enjoy coding your Telegram bot! 🚀
Note: The project is updated for 2023 as APIs change frequently; regular updates might be needed.
Keywords: Telegram, Bot, Python, API, Async Programming, Chatbot, 2023
For More: Follow and subscribe for more Python and programming-related content! 😉
Resources:
Author's Note: Thanks for watching! See you in the next video.
Create interactive Telegram bots with Python! 🤖✨