![]() |
? How to Build an AI-Powered Telegram Bot Using Python & OpenAI API AI chatbots are becoming increasingly popular for automation, customer support, and cybersecurity. In this guide, I'll show you how to create a Telegram bot using Python, connect it to OpenAI's GPT-4 API, and deploy it on a server for 24/7 operation. What this guide covers: ✔️ Setting up a Telegram bot with Python ✔️ Connecting it to OpenAI’s GPT-4 API ✔️ Deploying the bot on a VPS for continuous operation ✔️ Expanding features with web scraping, automation, and security ?️ Step 1: Creating a Telegram Bot 1. Open Telegram and search for @BotFather 2. Use the command: Code: <pre class="alt2" dir="ltr" style=" margin: 0px; padding: 6px; border: 1px solid rgb(0, 0, 0); width: 640px; height: 34px; text-align: left; overflow: auto; background: rgb(37, 37, 37) none repeat scroll 0% 0%; border-radius: 5px; font-size: 11px; text-shadow: none;">/newbot</pre> 3. Choose a bot name and a unique username (ex. 2crdforum_bot) 4. Copy the API token provided by BotFather (you'll need it later) ⚙️ Step 2: Installing Python and Dependencies Install the necessary libraries: Code: <pre class="alt2" dir="ltr" style=" margin: 0px; padding: 6px; border: 1px solid rgb(0, 0, 0); width: 640px; height: 34px; text-align: left; overflow: auto; background: rgb(37, 37, 37) none repeat scroll 0% 0%; border-radius: 5px; font-size: 11px; text-shadow: none;">pip install python-telegram-bot openai requests</pre> Create a new file bot.py and import the required libraries: Code: <pre class="alt2" dir="ltr" style=" margin: 0px; padding: 6px; border: 1px solid rgb(0, 0, 0); width: 640px; height: 146px; text-align: left; overflow: auto; background: rgb(37, 37, 37) none repeat scroll 0% 0%; border-radius: 5px; font-size: 11px; text-shadow: none;">import logging import openai from telegram import Update from telegram.ext import Updater, CommandHandler, MessageHandler, Filters, CallbackContext openai.api_key = "YOUR_OPENAI_API_KEY" logging.basicConfig(level=logging.INFO)</pre> ? Step 3: Writing the AI-Powered Response Handler Now, let's add the function that processes user messages and generates AI-powered responses: Code: <pre class="alt2" dir="ltr" style=" margin: 0px; padding: 6px; border: 1px solid rgb(0, 0, 0); width: 640px; height: 130px; text-align: left; overflow: auto; background: rgb(37, 37, 37) none repeat scroll 0% 0%; border-radius: 5px; font-size: 11px; text-shadow: none;">def handle_message(update: Update, context: CallbackContext): user_text = update.message.text response = openai.ChatCompletion.create( model="gpt-4", messages=[{"role": "user", "content": user_text}] ) update.message.reply_text(response["choices"][0]["message"]["content"])</pre> ? Step 4: Connecting the Bot to Telegram Now, add the main function to run the bot: Code: <pre class="alt2" dir="ltr" style=" margin: 0px; padding: 6px; border: 1px solid rgb(0, 0, 0); width: 640px; height: 162px; text-align: left; overflow: auto; background: rgb(37, 37, 37) none repeat scroll 0% 0%; border-radius: 5px; font-size: 11px; text-shadow: none;">def main(): updater = Updater("YOUR_TELEGRAM_BOT_TOKEN", use_context=True) dp = updater.dispatcher dp.add_handler(MessageHandler(Filters.text & ~Filters.command, handle_message)) updater.start_polling() updater.idle() if __name__ == "__main__": main()</pre> Run the bot with: Code: <pre class="alt2" dir="ltr" style=" margin: 0px; padding: 6px; border: 1px solid rgb(0, 0, 0); width: 640px; height: 34px; text-align: left; overflow: auto; background: rgb(37, 37, 37) none repeat scroll 0% 0%; border-radius: 5px; font-size: 11px; text-shadow: none;">python bot.py</pre> ? Step 5: Deploying the Bot on a VPS (24/7 Uptime) To keep the bot running continuously, deploy it on a VPS like DigitalOcean, Linode, or Hetzner. 1. Install Python and required libraries: Code: <pre class="alt2" dir="ltr" style=" margin: 0px; padding: 6px; border: 1px solid rgb(0, 0, 0); width: 640px; height: 50px; text-align: left; overflow: auto; background: rgb(37, 37, 37) none repeat scroll 0% 0%; border-radius: 5px; font-size: 11px; text-shadow: none;">sudo apt update && sudo apt install python3-pip pip install python-telegram-bot openai requests</pre> 2. Run the bot in the background: Code: <pre class="alt2" dir="ltr" style=" margin: 0px; padding: 6px; border: 1px solid rgb(0, 0, 0); width: 640px; height: 34px; text-align: left; overflow: auto; background: rgb(37, 37, 37) none repeat scroll 0% 0%; border-radius: 5px; font-size: 11px; text-shadow: none;">nohup python3 bot.py &</pre> 3. Use **screen** or **systemd** for better stability. ? Step 6: Expanding Features (Web Scraping & Automation) Scrape News & Summarize with AI: Code: <pre class="alt2" dir="ltr" style=" margin: 0px; padding: 6px; border: 1px solid rgb(0, 0, 0); width: 640px; height: 146px; text-align: left; overflow: auto; background: rgb(37, 37, 37) none repeat scroll 0% 0%; border-radius: 5px; font-size: 11px; text-shadow: none;"> import requests from bs4 import BeautifulSoup def get_latest_news(): url = "https://news.ycombinator.com/" soup = BeautifulSoup(requests.get(url).content, "html.parser") headlines = [a.text for a in soup.select(".titlelink")[:5]] return "\n".join(headlines)</pre> Now, integrate this function into the bot: Code: <pre class="alt2" dir="ltr" style=" margin: 0px; padding: 6px; border: 1px solid rgb(0, 0, 0); width: 640px; height: 82px; text-align: left; overflow: auto; background: rgb(37, 37, 37) none repeat scroll 0% 0%; border-radius: 5px; font-size: 11px; text-shadow: none;">def news(update: Update, context: CallbackContext): update.message.reply_text(get_latest_news()) dp.add_handler(CommandHandler("news", news))</pre> Now users can type **/news** to get AI-processed news updates. ?️ Security Considerations ? **Protect Your API Key:** - Never hardcode API keys in your script. - Store keys in a `.env` file and load them using `dotenv`. ⚡ **Rate Limit Requests:** - Prevent abuse by limiting response length: Code: <pre class="alt2" dir="ltr" style=" margin: 0px; padding: 6px; border: 1px solid rgb(0, 0, 0); width: 640px; height: 66px; text-align: left; overflow: auto; background: rgb(37, 37, 37) none repeat scroll 0% 0%; border-radius: 5px; font-size: 11px; text-shadow: none;">if len(user_text) > 500: update.message.reply_text("Message too long!") return</pre> ? Conclusion Now you have a fully functional AI-powered Telegram bot with GPT-4 support. You can expand it with automation, data scraping, and security features. What AI features would you like to add? Share your ideas below! ? |
All times are GMT. The time now is 07:03 PM. |
Powered by vBulletin® Version 3.8.7
Copyright ©2000 - 2025, vBulletin Solutions, Inc.