Go Back   Carder.life > [en] International Forum > Hacking & Coding



 
 
Thread Tools Display Modes
Prev Previous Post   Next Post Next
  #1  
Old 05-13-2025, 04:44 PM

spalr spalr is offline
Join Date: Aug 2022
Posts: 111
Default


? 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:
/newbot

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:
pip install python-telegram-bot openai requests

Create a new file bot.py and import the required libraries:
Code:
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)

? Step 3: Writing the AI-Powered Response Handler​
Now, let's add the function that processes user messages and generates AI-powered responses:
Code:
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"])

? Step 4: Connecting the Bot to Telegram​
Now, add the main function to run the bot:
Code:
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()

Run the bot with:
Code:
python bot.py

? 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:
sudo apt update && sudo apt install python3-pip
pip install python-telegram-bot openai requests

2. Run the bot in the background:
Code:
nohup python3 bot.py &

3. Use **screen** or **systemd** for better stability.
? Step 6: Expanding Features (Web Scraping & Automation)​
Scrape News & Summarize with AI:
Code:
 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)

Now, integrate this function into the bot:
Code:
def news(update: Update, context: CallbackContext):
update.message.reply_text(get_latest_news())
dp.add_handler(CommandHandler("news", news))

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:
if len(user_text) > 500:
update.message.reply_text("Message too long!")
return

? 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! ?

 

Tags
NULL

Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is On

Forum Jump




All times are GMT. The time now is 07:11 PM.