KEMBAR78
Chatbot Example | PDF | Computer Programming | Software
0% found this document useful (0 votes)
21 views4 pages

Chatbot Example

Uploaded by

arayan56213
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views4 pages

Chatbot Example

Uploaded by

arayan56213
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 4

🔧 What We'll Build

A Telegram chatbot that:

 Runs on Python
 Listens to user messages on Telegram
 Sends the messages to OpenAI’s GPT API
 Replies with a GPT-generated response

✅ Prerequisites
1. Python 3.7+
2. Install Python packages:

pip install python-telegram-bot openai

3. Get:
o A Telegram Bot Token from BotFather
o An OpenAI API Key from https://platform.openai.com

🧠 Step-by-Step Tutorial
Step 1: Import Libraries
from telegram import Update
from telegram.ext import ApplicationBuilder, ContextTypes, CommandHandler,
MessageHandler, filters
import openai
import os

Step 2: Set Your API Keys


openai.api_key = "YOUR_OPENAI_API_KEY"
TELEGRAM_TOKEN = "YOUR_TELEGRAM_BOT_TOKEN"

💡 For security, you should ideally load these from environment variables using
os.getenv("KEY_NAME").

Step 3: Create the GPT Chat Function


async def chat_with_gpt(message: str) -> str:
try:
response = openai.ChatCompletion.create(
model="gpt-4",
messages=[{"role": "user", "content": message}],
)
return response['choices'][0]['message']['content'].strip()
except Exception as e:
return f"Error: {str(e)}"

Step 4: Define Telegram Handlers


async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
await update.message.reply_text("Hi! I'm your AI chatbot. Just type
anything to chat!")

async def handle_message(update: Update, context: ContextTypes.DEFAULT_TYPE):


user_message = update.message.text
reply = await chat_with_gpt(user_message)
await update.message.reply_text(reply)

Step 5: Run the Bot


def main():
app = ApplicationBuilder().token(TELEGRAM_TOKEN).build()

app.add_handler(CommandHandler("start", start))
app.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND,
handle_message))

print("Bot is running...")
app.run_polling()

if __name__ == "__main__":
main()

✅ Summary
Feature Description
Platform Telegram
Intelligence OpenAI GPT (any model: GPT-3.5/4)
Framework python-telegram-bot
Language Python
Mode Polling (easy to deploy anywhere)

🧠 What is ChatterBot?
ChatterBot is a Python library that uses machine learning to generate responses based on past
conversations. It can be trained using preloaded datasets or your own data.

✅ Prerequisites
1. Install ChatterBot and dependencies:
bash
CopyEdit
pip install chatterbot==1.0.5
pip install chatterbot_corpus

⚠️chatterbot development has slowed down, so we use version 1.0.5 which is stable with
Python 3.7–3.9.

🧪 Step-by-Step Example: ChatterBot in Action


Step 1: Basic Bot Setup
from chatterbot import ChatBot
from chatterbot.trainers import ChatterBotCorpusTrainer

# Create chatbot instance


chatbot = ChatBot('SimpleBot')

# Create and train the bot using English corpus


trainer = ChatterBotCorpusTrainer(chatbot)
trainer.train("chatterbot.corpus.english")

Step 2: Interactive Chat Loop


print("SimpleBot is ready to chat! Type 'exit' to stop.")
while True:
user_input = input("You: ")
if user_input.lower() == 'exit':
break
response = chatbot.get_response(user_input)
print("Bot:", response)

🧠 Sample Output
txt
You: Hello
Bot: Hi there!

You: What is your name?


Bot: My name is SimpleBot.

You: exit

🔁 How to Improve It
 Custom training:

from chatterbot.trainers import ListTrainer


trainer = ListTrainer(chatbot)
trainer.train([
"Hi there!",
"Hello!",
"How are you?",
"I'm good, thank you.",
])

 Multi-language support: train with "chatterbot.corpus.french" or other languages.


 Save/load conversations: ChatterBot uses a SQLite database (db.sqlite3 by default).

⚠️Limitations
 Doesn't use modern NLP (like transformers or GPT).
 Basic conversation only — it doesn’t understand context or intent deeply.

✅ Summary
Feature Description
Library chatterbot
Intelligence Learns from corpus or user input
Training Prebuilt or custom conversations
Good for Learning, demos, offline use

You might also like