help@rskworld.in +91 93305 39277
RSK World
  • Home
  • Development
    • Web Development
    • Mobile Apps
    • Software
    • Games
    • Project
  • Technologies
    • Data Science
    • AI Development
    • Cloud Development
    • Blockchain
    • Cyber Security
    • Dev Tools
    • Testing Tools
  • Blog
  • About
  • Contact

Theme Settings

Color Scheme
Display Options
Font Size
100%
Back to Project
RSK World
weather-chatbot
/
tests
RSK World
weather-chatbot
Weather Chatbot - Python + Flask + OpenWeatherMap + OpenAI + Weather Forecast + Weather Alerts + Natural Language Processing
tests
  • __init__.py110 B
  • conftest.py1.3 KB
  • test_app.py3.3 KB
  • test_utils.py1.8 KB
  • test_weather_api.py1.6 KB
run.pyREADME.mdapp.cpython-313.pycsample_002.jsonsentiment_analyzer.cpython-313.pyctest_utils.py
run.py
Raw Download
Find: Go to:
#!/usr/bin/env python3
"""
Weather Chatbot Runner
======================

Author: RSK World (https://rskworld.in)
Founded by: Molla Samser
Designer & Tester: Rima Khatun
Contact: +91 93305 39277, hello@rskworld.in, support@rskworld.in
Location: Nutanhat, Mongolkote, Purba Burdwan, West Bengal, India, 713147
Year: 2026

Description: Entry point for the Weather Chatbot application
"""

import os
import sys
from app import app

def main():
    """Main entry point for the Weather Chatbot application"""
    
    # Print startup banner
    print("=" * 60)
    print("๐ŸŒค๏ธ  Weather Chatbot - RSK World")
    print("=" * 60)
    print("Author: RSK World (https://rskworld.in)")
    print("Founded by: Molla Samser")
    print("Designer & Tester: Rima Khatun")
    print("Contact: +91 93305 39277")
    print("Email: hello@rskworld.in, support@rskworld.in")
    print("Location: Nutanhat, Mongolkote, Purba Burdwan, West Bengal, India")
    print("Year: 2026")
    print("=" * 60)
    print("Features:")
    print("โ€ข Real-time weather data")
    print("โ€ข Weather forecasts")
    print("โ€ข Weather alerts")
    print("โ€ข Natural language processing")
    print("โ€ข Web interface")
    print("=" * 60)
    
    # Check environment variables
    openweather_key = os.getenv('OPENWEATHER_API_KEY')
    openai_key = os.getenv('OPENAI_API_KEY')
    
    if not openweather_key:
        print("โš ๏ธ  Warning: OPENWEATHER_API_KEY not found in environment variables")
        print("   Get your free API key from: https://openweathermap.org/api")
        print("   Set it in your .env file or environment variables")
    else:
        print("โœ… OpenWeatherMap API key configured")
    
    if not openai_key:
        print("โš ๏ธ  Warning: OPENAI_API_KEY not found (optional)")
        print("   Chatbot will work with keyword matching")
        print("   For enhanced NLP, get API key from: https://platform.openai.com/api-keys")
    else:
        print("โœ… OpenAI API key configured")
    
    print("=" * 60)
    
    # Get configuration
    host = os.getenv('HOST', '0.0.0.0')
    port = int(os.getenv('PORT', 5000))
    debug = os.getenv('FLASK_DEBUG', 'True').lower() == 'true'
    
    print(f"๐Ÿš€ Starting Weather Chatbot on http://{host}:{port}")
    print("๐Ÿ“ฑ Web Interface: http://localhost:5000")
    print("๐Ÿ”— API Endpoints:")
    print("   โ€ข GET  /health - Health check")
    print("   โ€ข POST /chat   - Chat interface")
    print("   โ€ข GET  /weather/<city> - Current weather")
    print("   โ€ข GET  /forecast/<city> - Weather forecast")
    print("   โ€ข GET  /alerts/<city> - Weather alerts")
    print("=" * 60)
    print("Press Ctrl+C to stop the server")
    print("=" * 60)
    
    try:
        # Start the Flask application
        app.run(host=host, port=port, debug=debug)
    except KeyboardInterrupt:
        print("\n๐Ÿ‘‹ Weather Chatbot stopped by user")
        print("ยฉ 2026 RSK World. All rights reserved.")
        sys.exit(0)
    except Exception as e:
        print(f"โŒ Error starting server: {e}")
        sys.exit(1)

if __name__ == '__main__':
    main()
93 linesโ€ข3.1 KB
python
README.md
Raw Download

README.md

# Weather Chatbot ๐ŸŒค๏ธ

**Author:** RSK World (https://rskworld.in)
**Founded by:** Molla Samser
**Designer & Tester:** Rima Khatun
**Contact:** +91 93305 39277, hello@rskworld.in, support@rskworld.in
**Location:** Nutanhat, Mongolkote, Purba Burdwan, West Bengal, India, 713147
**Year:** 2026

A sophisticated weather chatbot providing real-time weather forecasts, alerts, and comprehensive weather information using natural language processing.

## ๐ŸŒŸ Features

- **Real-time Weather Data**: Get current weather conditions for any city worldwide
- **Weather Forecasts**: 5-day weather forecasts with detailed information
- **Weather Alerts**: Real-time weather alerts and warnings for specific locations
- **Natural Language Processing**: Chat interface powered by OpenAI API for intelligent conversations
- **Location-based Services**: Automatic location detection and weather data
- **Web Interface**: Beautiful, responsive web interface
- **API Endpoints**: RESTful API for integration with other services
- **Multiple Query Types**: Support for current weather, forecasts, and alerts
- **Fallback Support**: Works without OpenAI API using keyword matching

## ๐Ÿ› ๏ธ Technologies Used

- **Python 3.8+**: Core programming language
- **Flask**: Web framework for the application
- **OpenWeatherMap API**: Weather data provider
- **OpenAI API**: Natural language processing (optional)
- **HTML/CSS/JavaScript**: Frontend interface
- **Bootstrap**: UI framework for responsive design
- **Requests**: HTTP library for API calls

## ๐Ÿ“‹ Prerequisites

- Python 3.8 or higher
- OpenWeatherMap API key (free at https://openweathermap.org/api)
- OpenAI API key (optional, for enhanced NLP)
- Git for cloning the repository

## ๐Ÿš€ Quick Start

### 1. Clone the Repository

```bash
git clone https://github.com/rskworld/weather-chatbot.git
cd weather-chatbot
```

### 2. Create Virtual Environment

```bash
python -m venv venv

# Windows
venv\Scripts\activate

# macOS/Linux
source venv/bin/activate
```

### 3. Install Dependencies

```bash
pip install -r requirements.txt
```

### 4. Configure Environment Variables

```bash
# Copy the example environment file
cp .env.example .env

# Edit .env file with your API keys
# OPENWEATHER_API_KEY=your_openweathermap_api_key_here
# OPENAI_API_KEY=your_openai_api_key_here
```

### 5. Run the Application

```bash
python app.py
```

The application will be available at `http://localhost:5000`

## ๐Ÿ”ง Configuration

### Required Environment Variables

- `OPENWEATHER_API_KEY`: Your OpenWeatherMap API key (required)
- `OPENAI_API_KEY`: Your OpenAI API key (optional, for enhanced NLP)

### Optional Configuration

- `SECRET_KEY`: Flask secret key for sessions
- `HOST`: Server host (default: 0.0.0.0)
- `PORT`: Server port (default: 5000)
- `WEATHER_UNITS`: Temperature units (metric/imperial/kelvin)
- `DEFAULT_CITY`: Default city for weather queries

## ๐Ÿ“ก API Endpoints

### Chat Interface
- `POST /chat` - Send chat message and get weather response

### Weather Data
- `GET /weather/<city>` - Get current weather for a city
- `GET /forecast/<city>` - Get 5-day forecast for a city
- `GET /alerts/<city>` - Get weather alerts for a city

### System
- `GET /health` - Health check endpoint
- `GET /` - Main web interface

## ๐Ÿ’ฌ Usage Examples

### Basic Weather Queries
- "What's the weather in London?"
- "How's the weather in New York today?"
- "Tell me about the weather in Tokyo"

### Forecast Queries
- "What's the forecast for Paris tomorrow?"
- "Will it rain in Mumbai this week?"
- "Weather forecast for Delhi next 5 days"

### Alert Queries
- "Any weather alerts for Sydney?"
- "Are there warnings for Beijing?"
- "Weather alerts in Dubai"

## ๐ŸŽฏ Supported Features

### Weather Information
- Temperature (current, feels like)
- Humidity and pressure
- Wind speed and direction
- Weather description and conditions
- Visibility
- Sunrise and sunset times

### Forecast Data
- Hourly forecasts (3-hour intervals)
- Daily weather summaries
- Temperature trends
- Precipitation predictions
- Weather condition changes

### Weather Alerts
- Severe weather warnings
- Temperature alerts
- Storm warnings
- Precipitation alerts
- Custom alert thresholds

## ๐ŸŒ Supported Cities

The chatbot supports weather queries for cities worldwide, including:
- Major international cities (London, New York, Paris, Tokyo)
- Indian cities (Delhi, Mumbai, Kolkata, Chennai, Bangalore)
- Regional cities and towns
- Custom location support

## ๐Ÿ”’ Security Features

- Environment variable configuration
- Secure session handling
- Input validation and sanitization
- Rate limiting protection
- CORS configuration
- Error handling and logging

## ๐Ÿ“Š Logging and Monitoring

- Comprehensive logging system
- Error tracking and reporting
- Performance monitoring
- API usage statistics
- Health check endpoints

## ๐Ÿงช Testing

```bash
# Run unit tests
python -m pytest tests/

# Run with coverage
python -m pytest --cov=app tests/

# Run specific test file
python -m pytest tests/test_weather_api.py
```

## ๐Ÿ“ Project Structure

```
weather-chatbot/
โ”œโ”€โ”€ app.py # Main Flask application
โ”œโ”€โ”€ config.py # Configuration settings
โ”œโ”€โ”€ requirements.txt # Python dependencies
โ”œโ”€โ”€ .env.example # Environment variables template
โ”œโ”€โ”€ README.md # Project documentation
โ”œโ”€โ”€ static/ # Static files (CSS, JS, images)
โ”œโ”€โ”€ templates/ # HTML templates
โ”œโ”€โ”€ utils/ # Utility functions
โ”œโ”€โ”€ tests/ # Test files
โ””โ”€โ”€ logs/ # Application logs
```

## ๐Ÿš€ Deployment

### Docker Deployment

```bash
# Build Docker image
docker build -t weather-chatbot .

# Run container
docker run -p 5000:5000 --env-file .env weather-chatbot
```

### Heroku Deployment

```bash
# Install Heroku CLI
heroku create your-app-name

# Set environment variables
heroku config:set OPENWEATHER_API_KEY=your_key
heroku config:set OPENAI_API_KEY=your_key

# Deploy
git push heroku main
```

## ๐Ÿค Contributing

1. Fork the repository
2. Create a feature branch (`git checkout -b feature/amazing-feature`)
3. Commit your changes (`git commit -m 'Add amazing feature'`)
4. Push to the branch (`git push origin feature/amazing-feature`)
5. Open a Pull Request

## ๐Ÿ“ License

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.

## ๐Ÿ“ž Support

For support and inquiries:

- **Email:** hello@rskworld.in, support@rskworld.in
- **Phone:** +91 93305 39277
- **Website:** https://rskworld.in
- **Location:** Nutanhat, Mongolkote, Purba Burdwan, West Bengal, India, 713147

## ๐Ÿ™ Acknowledgments

- OpenWeatherMap for providing weather data API
- OpenAI for natural language processing capabilities
- Flask framework for web development
- Bootstrap for responsive UI components

---

**ยฉ 2026 RSK World. All rights reserved.**
*Content used for educational purposes only. View Disclaimer: https://rskworld.in/disclaimer.php*
app.cpython-313.pyc

This file cannot be displayed in the browser.

Download File
tests/test_utils.py
Raw Download
Find: Go to:
#!/usr/bin/env python3
"""
Utility Functions Tests
=======================

Author: RSK World (https://rskworld.in)
Year: 2026

Description: Unit tests for utility functions
"""

import pytest
import sys
import os

sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))

from utils.weather_utils import (
    format_temperature,
    format_wind_speed,
    get_weather_emoji,
    validate_city_name,
    extract_city_from_query
)

def test_format_temperature():
    """Test temperature formatting."""
    assert format_temperature(20, 'metric') == '20ยฐC'
    assert format_temperature(20, 'imperial') == '68ยฐF'
    assert format_temperature(20, 'kelvin') == '293K'

def test_format_wind_speed():
    """Test wind speed formatting."""
    assert 'm/s' in format_wind_speed(10, 'metric')
    assert 'mph' in format_wind_speed(10, 'imperial')

def test_get_weather_emoji():
    """Test weather emoji selection."""
    assert get_weather_emoji('clear sky') == 'โ˜€๏ธ'
    assert get_weather_emoji('cloudy') == 'โ˜๏ธ'
    assert get_weather_emoji('rain') == '๐ŸŒง๏ธ'
    assert get_weather_emoji('snow') == 'โ„๏ธ'

def test_validate_city_name():
    """Test city name validation."""
    assert validate_city_name('London') == True
    assert validate_city_name('New York') == True
    assert validate_city_name('') == False
    assert validate_city_name('A') == False
    assert validate_city_name('123') == False

def test_extract_city_from_query():
    """Test city extraction from queries."""
    assert extract_city_from_query('weather in London') == 'London'
    assert extract_city_from_query('What is the weather in New York?') == 'New York'
    assert extract_city_from_query('forecast for Paris') == 'Paris'
57 linesโ€ข1.8 KB
python
๐Ÿš€ Support RSK World

Subscribe to our YouTube channel for latest tutorials & updates!



Click subscribe & support our work โค๏ธ

About RSK World

Founded by Molla Samser, with Designer & Tester Rima Khatun, RSK World is your one-stop destination for free programming resources, source code, and development tools.

Founder: Molla Samser
Designer & Tester: Rima Khatun

Development

  • Game Development
  • Web Development
  • Mobile Development
  • AI Development
  • Development Tools

Legal

  • Terms & Conditions
  • Privacy Policy
  • Disclaimer

Contact Info

Nutanhat, Mongolkote
Purba Burdwan, West Bengal
India, 713147

+91 93305 39277

hello@rskworld.in
support@rskworld.in

© 2026 RSK World. All rights reserved.

Content used for educational purposes only. View Disclaimer