1. Termux Setup Install Termux: Get it from F-Droid for the latest version and best compatibility. Update Packages: pkg update && pkg upgrade Install Python: pkg install python Install Git (optional, but recommended): pkg install git Allow Storage Access: termux-setup-storage This allows your bot to read/write files to your device's storage. 2. Telegram Bot Token & BotFather Open Telegram: Search for @BotFather . Create New Bot: Send /newbot to BotFather. Follow Prompts: Give your bot a name and a unique username. Get Bot Token: BotFather will give you an HTTP API token (e.g., 123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11 ). Keep this token secret! 3. Python Telegram Bot Library 3.1. Installation In Termux, install the library: pip install python-telegram-bot --pre ( --pre is often needed for the latest stable version with async features) 3.2. Basic Bot Structure ( bot.py ) from telegram import Update from telegram.ext import Application, CommandHandler, MessageHandler, filters, ContextTypes # Replace with your actual bot token TOKEN = "YOUR_TELEGRAM_BOT_TOKEN" async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None: """Sends a greeting message when the /start command is issued.""" await update.message.reply_text('Hello! I am your bot. How can I help you today?') async def echo(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None: """Echoes the user's message.""" await update.message.reply_text(update.message.text) async def help_command(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None: """Sends a help message when the /help command is issued.""" await update.message.reply_text('You can use /start to greet me or just send me a message to echo it.') def main() -> None: """Start the bot.""" # Create the Application and pass your bot's token. application = Application.builder().token(TOKEN).build() # Register command handlers application.add_handler(CommandHandler("start", start)) application.add_handler(CommandHandler("help", help_command)) # Register a message handler for all text messages (except commands) 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() Remember to replace "YOUR_TELEGRAM_BOT_TOKEN" with your actual token from BotFather. Save this code as bot.py in your Termux home directory or a specific folder. 4. Integrating AI (e.g., OpenAI API) 4.1. Get an API Key Sign up on OpenAI (or another AI provider like Google Gemini, Hugging Face). Obtain your API key. Keep it secret! 4.2. Install OpenAI Library In Termux: pip install openai 4.3. Modify Bot for AI Response import openai import os # For environment variables from telegram import Update from telegram.ext import Application, CommandHandler, MessageHandler, filters, ContextTypes # --- Configuration --- TOKEN = os.environ.get("TELEGRAM_BOT_TOKEN", "YOUR_TELEGRAM_BOT_TOKEN") # Use env var or hardcode OPENAI_API_KEY = os.environ.get("OPENAI_API_KEY", "YOUR_OPENAI_API_KEY") # Use env var or hardcode openai.api_key = OPENAI_API_KEY if not TOKEN or not OPENAI_API_KEY: print("WARNING: TELEGRAM_BOT_TOKEN or OPENAI_API_KEY not set. Bot may not function.") # --- Bot Functions --- async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None: await update.message.reply_text('Hello! I am an AI bot. Ask me anything!') async def ai_response(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None: """Gets a response from OpenAI based on the user's message.""" user_message = update.message.text try: # Use a simple chat completion model (e.g., gpt-3.5-turbo) response = openai.chat.completions.create( model="gpt-3.5-turbo", messages=[ {"role": "system", "content": "You are a helpful AI assistant."}, {"role": "user", "content": user_message}, ], max_tokens=150 ) ai_text = response.choices[0].message.content await update.message.reply_text(ai_text) except openai.APIError as e: await update.message.reply_text(f"OpenAI API Error: {e}") except Exception as e: await update.message.reply_text(f"An unexpected error occurred: {e}") # --- Main Bot Logic --- def main() -> None: application = Application.builder().token(TOKEN).build() application.add_handler(CommandHandler("start", start)) # Change the MessageHandler to use the ai_response function application.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, ai_response)) application.run_polling(allowed_updates=Update.ALL_TYPES) if __name__ == "__main__": main() Security Note: It's best practice to store sensitive keys (like API tokens) in environment variables rather than directly in your code. To set environment variables in Termux: export TELEGRAM_BOT_TOKEN="YOUR_TELEGRAM_BOT_TOKEN" export OPENAI_API_KEY="YOUR_OPENAI_API_KEY" python bot.py For persistent environment variables, add them to ~/.bashrc or ~/.zshrc . 5. Running Your Bot Navigate to the directory where you saved bot.py (e.g., cd ~/ ). Run the bot: python bot.py The bot will start polling for updates. You can now interact with it on Telegram. To stop the bot, press Ctrl+C in the Termux terminal. 6. Keeping Your Bot Online (Optional) tmux / screen : Use these tools to keep your bot running in the background even if you close Termux. pkg install tmux # or screen tmux new -s bot_session python bot.py # Press Ctrl+B then D to detach (Ctrl+A then D for screen) # To reattach: tmux attach -t bot_session Foreground Service (Advanced): For more robust background operation, you might explore Termux:API and Android foreground services, but this is more complex. 7. Troubleshooting & Tips Check Token/Key: Double-check that your Telegram bot token and AI API key are correct. Network Connection: Ensure Termux has internet access. Error Messages: Read terminal output carefully for Python tracebacks or API errors. Dependencies: Make sure all required Python libraries are installed ( pip install ... ). Resource Limits: AI APIs often have rate limits or usage costs. Monitor your usage. Context Management: For more complex AI interactions, you'll need to manage conversation history (context) to allow the AI to remember previous turns. This involves storing messages (e.g., in a list) and sending them with each new query to the AI API.