from flask import Flask, request, jsonify
import requests
from bs4 import BeautifulSoup
import re
app = Flask(__name__)
# Function to fetch news headlines using a public API (e.g., NewsAPI)
def fetch_news(query=None):
api_key = "AIzaSyDaGmWKa4JsXZ-HjGw7ISLn_3namBGewQe" # Replace with your
NewsAPI key
url = f"https://newsapi.org/v2/top-headlines?
country=us&apiKey={AIzaSyDaGmWKa4JsXZ-HjGw7ISLn_3namBGewQe}"
if query:
url = f"https://newsapi.org/v2/everything?
q={query}&apiKey={AIzaSyDaGmWKa4JsXZ-HjGw7ISLn_3namBGewQe}"
try:
response = requests.get(url)
response.raise_for_status()
articles = response.json().get("articles", [])
if not articles:
return "No news found."
return "\n".join([f"{i+1}. {article['title']} ({article['source']
['name']})" for i, article in enumerate(articles[:3])])
except requests.RequestException as e:
return f"Error fetching news: {str(e)}"
# Function to scrape a website (example: Wikipedia)
def scrape_website(query):
search_url = f"https://en.wikipedia.org/wiki/{query.replace(' ', '_')}"
try:
response = requests.get(search_url)
response.raise_for_status()
soup = BeautifulSoup(response.text, 'html.parser')
paragraphs = soup.find_all('p')
for p in paragraphs:
text = p.get_text().strip()
if len(text) > 100: # Return first substantial paragraph
return re.sub(r'\[\d+\]', '', text)[:500] + "..."
return "No relevant information found on Wikipedia."
except requests.RequestException as e:
return f"Error scraping website: {str(e)}"
# Simple chatbot logic
def process_query(query):
query = query.lower().strip()
if "news" in query:
topic = query.replace("news", "").strip() or None
return fetch_news(topic)
elif "info" in query or "about" in query:
topic = query.replace("info", "").replace("about", "").strip()
if topic:
return scrape_website(topic)
return "Please specify a topic to search for."
else:
return "I can help with news or info on a topic. Try 'news about AI' or
'info about Python'."
# Flask route for chatbot
@app.route('/chat', methods=['POST'])
def chat():
data = request.get_json()
user_query = data.get('query', '')
if not user_query:
return jsonify({"response": "Please provide a query."})
response = process_query(user_query)
return jsonify({"response": response})
# Home route
@app.route('/')
def home():
return "AI Bot is running! Send POST requests to /chat with JSON {'query':
'your query'}."
if __name__ == '__main__':
app.run(debug=True)
@echo off
ECHO Starting AI Bot...
:: Check if Python is installed
python --version >nul 2>&1
IF %ERRORLEVEL% NEQ 0 (
ECHO Python is not installed. Please install Python and try again.
pause
exit /b 1
)
:: Optional: Activate virtual environment (uncomment and update path if using a
virtual environment)
:: CALL .\venv\Scripts\activate
:: Run the Python script
ECHO Running ai_bot.py...
python ai_bot.py
:: Pause to keep the window open (optional, remove if not needed)
pause
CALL .\venv\Scripts\activate
@echo off
ECHO Starting Advanced AI Bot...
:: Check if Python is installed
python --version >nul 2>&1
IF %ERRORLEVEL% NEQ 0 (
ECHO Python is not installed. Please install Python 3.8+ and try again.
pause
exit /b 1
)
:: Check for required Python packages
ECHO Checking for required Python packages...
python -c "import flask, requests, bs4, transformers" >nul 2>&1
IF %ERRORLEVEL% NEQ 0 (
ECHO Installing required packages...
pip install flask requests beautifulsoup4 transformers torch
IF %ERRORLEVEL% NEQ 0 (
ECHO Failed to install packages. Please check your internet connection or
pip configuration.
pause
exit /b 1
)
)
:: Optional: Activate virtual environment (uncomment and update path if using a
virtual environment)
:: CALL .\venv\Scripts\activate
:: Run the Python script
ECHO Starting advanced_ai_bot.py...
python advanced_ai_bot.py
:: Pause to keep the window open (optional, remove if not needed)
pause
@echo off
ECHO Advanced AI Bot (Limited - No Python)
:: Check if curl is installed
curl --version >nul 2>&1
IF %ERRORLEVEL% NEQ 0 (
ECHO curl is not installed. Please install curl and try again.
pause
exit /b 1
)
:: Set NewsAPI key (replace with your own)
SET API_KEY=AIzaSyDaGmWKa4JsXZ-HjGw7ISLn_3namBGewQe
:menu
cls
ECHO Welcome to the AI Bot!
ECHO Type a topic to get news (e.g., "AI", "politics") or "exit" to quit.
SET /P QUERY="Enter query: "
IF /I "%QUERY%"=="exit" (
ECHO Goodbye!
pause
exit /b 0
)
:: Remove spaces and replace with URL-encoded equivalent
SET "QUERY=%QUERY: =+%"
:: Fetch news using curl and save to temp file
ECHO Fetching news for "%QUERY%"...
curl -s "https://newsapi.org/v2/everything?q=%QUERY%&apiKey=%API_KEY%" -o news.json
:: Check if curl request was successful
IF %ERRORLEVEL% NEQ 0 (
ECHO Error fetching news. Check your internet or API key.
pause
goto menu
)
:: Basic parsing of JSON response (limited to extracting titles)
findstr "title" news.json > temp.txt
IF %ERRORLEVEL% NEQ 0 (
ECHO No news found for "%QUERY%".
del news.json
pause
goto menu
)
:: Display up to 3 news titles
ECHO.
ECHO Top news for "%QUERY%":
SET COUNT=0
FOR /F "tokens=2 delims=:" %%a IN (temp.txt) DO (
SET /A COUNT+=1
ECHO !COUNT!. %%a
IF !COUNT! GEQ 3 GOTO :break
)
:break
:: Clean up
del news.json temp.txt
ECHO.
ECHO Press any key to continue...
pause >nul
goto menu