Skip to content

Commit d8b2e98

Browse files
authored
Merge pull request #708 from faizalanwar/main
feat: Add AI Chatbot, Password Generator, Snake Game, and File Organizer
2 parents 2d7f79a + 9731dd2 commit d8b2e98

File tree

8 files changed

+2033
-0
lines changed

8 files changed

+2033
-0
lines changed

AI_Chatbot/README.md

Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
# AI Chatbot - Intelligent Conversational Assistant
2+
3+
A powerful and interactive AI chatbot built with Python that can engage in meaningful conversations and provide various helpful services.
4+
5+
## Features
6+
7+
- 🤖 **Intelligent Conversations**: Natural language processing for engaging dialogue
8+
- 🌤️ **Weather Information**: Get current weather for any city
9+
- 🧮 **Mathematical Calculations**: Safe evaluation of mathematical expressions
10+
- 😄 **Entertainment**: Tell jokes and stories
11+
- 💻 **Programming Help**: Get tips and advice for coding
12+
-**Time & Date**: Current time and date information
13+
- 💾 **Conversation History**: Save and recall previous conversations
14+
- 🎯 **Context Awareness**: Remembers user name and conversation flow
15+
16+
## Installation
17+
18+
```bash
19+
# Clone the repository
20+
git clone <repository-url>
21+
cd AI_Chatbot
22+
23+
# Install required dependencies
24+
pip install requests datetime random json re math
25+
```
26+
27+
## Usage
28+
29+
```bash
30+
python chatbot.py
31+
```
32+
33+
## Example Conversations
34+
35+
```
36+
You: Hello!
37+
AI Assistant: Nice to meet you, John! Hello! I'm your AI assistant. How can I help you today?
38+
39+
You: What's the weather in Jakarta?
40+
AI Assistant: The weather in Jakarta is: Sunny, 32°C
41+
42+
You: Calculate 15 * 8 + 32
43+
AI Assistant: The result is: 152
44+
45+
You: Tell me a joke
46+
AI Assistant: Why don't scientists trust atoms? Because they make up everything!
47+
48+
You: What time is it?
49+
AI Assistant: Current time: 14:30:25, Date: 2024-01-15
50+
```
51+
52+
## Commands
53+
54+
- **Greetings**: "hello", "hi", "hey", "good morning"
55+
- **Weather**: "weather in [city]", "what's the weather"
56+
- **Math**: "calculate [expression]", "what is 5 + 3"
57+
- **Jokes**: "tell me a joke", "make me laugh"
58+
- **Stories**: "tell me a story", "narrative"
59+
- **Programming**: "programming help", "coding tips"
60+
- **Time**: "what time is it", "current date"
61+
- **Exit**: "quit", "exit", "bye"
62+
63+
## Technical Details
64+
65+
- **Language**: Python 3
66+
- **Architecture**: Object-oriented design with modular components
67+
- **Safety**: Secure mathematical expression evaluation
68+
- **Extensibility**: Easy to add new features and responses
69+
- **Error Handling**: Robust error handling and graceful degradation
70+
71+
## Contributing
72+
73+
Feel free to contribute by:
74+
- Adding new conversation topics
75+
- Improving natural language processing
76+
- Adding new features
77+
- Fixing bugs
78+
- Improving documentation
79+
80+
## License
81+
82+
This project is open source and available under the MIT License.

AI_Chatbot/chatbot.py

Lines changed: 232 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,232 @@
1+
#!/usr/bin/env python3
2+
"""
3+
AI Chatbot - Intelligent Conversational Assistant
4+
=================================================
5+
6+
A simple yet powerful AI chatbot that can:
7+
- Answer questions intelligently
8+
- Provide weather information
9+
- Calculate mathematical expressions
10+
- Tell jokes and stories
11+
- Help with programming concepts
12+
- Remember conversation context
13+
14+
Author: AI Assistant
15+
Language: Python 3
16+
Dependencies: requests, datetime, random, json
17+
"""
18+
19+
import json
20+
import random
21+
import datetime
22+
import requests
23+
import re
24+
import math
25+
26+
class AIChatbot:
27+
def __init__(self):
28+
self.name = "AI Assistant"
29+
self.conversation_history = []
30+
self.user_name = ""
31+
32+
# Knowledge base
33+
self.responses = {
34+
"greeting": [
35+
"Hello! I'm your AI assistant. How can I help you today?",
36+
"Hi there! What would you like to know?",
37+
"Greetings! I'm here to assist you with anything you need.",
38+
"Hello! Ready to chat and help you out!"
39+
],
40+
"farewell": [
41+
"Goodbye! It was nice talking to you!",
42+
"See you later! Feel free to come back anytime.",
43+
"Take care! Have a great day!",
44+
"Farewell! Remember, I'm always here to help."
45+
],
46+
"jokes": [
47+
"Why don't scientists trust atoms? Because they make up everything!",
48+
"Why did the scarecrow win an award? He was outstanding in his field!",
49+
"What do you call a fake noodle? An impasta!",
50+
"Why don't eggs tell jokes? They'd crack each other up!",
51+
"What do you call a bear with no teeth? A gummy bear!"
52+
],
53+
"programming_tips": [
54+
"Always write clean, readable code with meaningful variable names.",
55+
"Comment your code - your future self will thank you!",
56+
"Test your code thoroughly before deploying.",
57+
"Use version control (Git) for all your projects.",
58+
"Learn one programming language deeply before moving to others."
59+
]
60+
}
61+
62+
def get_weather(self, city="Jakarta"):
63+
"""Get weather information for a city"""
64+
try:
65+
# Using a free weather API (OpenWeatherMap)
66+
api_key = "demo_key" # Replace with actual API key
67+
url = f"http://api.openweathermap.org/data/2.5/weather?q={city}&appid={api_key}&units=metric"
68+
69+
# For demo purposes, return mock data
70+
mock_weather = {
71+
"Jakarta": "Sunny, 32°C",
72+
"Bandung": "Cloudy, 28°C",
73+
"Surabaya": "Rainy, 26°C",
74+
"Yogyakarta": "Partly cloudy, 30°C"
75+
}
76+
77+
return f"The weather in {city} is: {mock_weather.get(city, 'Weather data not available')}"
78+
except:
79+
return "Sorry, I couldn't fetch weather data right now."
80+
81+
def calculate_math(self, expression):
82+
"""Safely evaluate mathematical expressions"""
83+
try:
84+
# Remove dangerous functions and only allow safe math operations
85+
safe_dict = {
86+
"__builtins__": {},
87+
"abs": abs, "round": round, "min": min, "max": max,
88+
"sum": sum, "pow": pow, "sqrt": math.sqrt,
89+
"sin": math.sin, "cos": math.cos, "tan": math.tan,
90+
"log": math.log, "pi": math.pi, "e": math.e
91+
}
92+
93+
# Clean the expression
94+
expression = re.sub(r'[^0-9+\-*/().\s]', '', expression)
95+
result = eval(expression, safe_dict)
96+
return f"The result is: {result}"
97+
except:
98+
return "Sorry, I couldn't calculate that. Please check your math expression."
99+
100+
def tell_story(self):
101+
"""Tell a random short story"""
102+
stories = [
103+
"Once upon a time, there was a little robot who dreamed of becoming a painter. Every day, it would collect colorful data and create beautiful digital art. The robot's art became so popular that it inspired humans to see the world in new ways.",
104+
"In a distant galaxy, there lived a wise alien who could speak every programming language in the universe. One day, it met a curious human programmer, and together they created the most efficient algorithm ever known.",
105+
"There was a magical computer that could solve any problem, but it had one condition: you had to ask the right question. Many tried, but only those who understood the problem deeply could unlock its power."
106+
]
107+
return random.choice(stories)
108+
109+
def process_message(self, user_input):
110+
"""Process user input and generate appropriate response"""
111+
user_input = user_input.lower().strip()
112+
113+
# Store conversation
114+
self.conversation_history.append(f"User: {user_input}")
115+
116+
# Greeting detection
117+
if any(word in user_input for word in ["hello", "hi", "hey", "good morning", "good afternoon"]):
118+
if not self.user_name:
119+
self.user_name = input("What's your name? ")
120+
return f"Nice to meet you, {self.user_name}! " + random.choice(self.responses["greeting"])
121+
return random.choice(self.responses["greeting"])
122+
123+
# Farewell detection
124+
if any(word in user_input for word in ["bye", "goodbye", "see you", "farewell"]):
125+
return random.choice(self.responses["farewell"])
126+
127+
# Weather request
128+
if "weather" in user_input:
129+
city = "Jakarta" # Default city
130+
words = user_input.split()
131+
for i, word in enumerate(words):
132+
if word == "in" and i + 1 < len(words):
133+
city = words[i + 1].capitalize()
134+
return self.get_weather(city)
135+
136+
# Math calculation
137+
if any(op in user_input for op in ["+", "-", "*", "/", "calculate", "math", "="]):
138+
# Extract mathematical expression
139+
math_pattern = r'[\d+\-*/().\s]+'
140+
match = re.search(math_pattern, user_input)
141+
if match:
142+
expression = match.group().strip()
143+
return self.calculate_math(expression)
144+
145+
# Joke request
146+
if any(word in user_input for word in ["joke", "funny", "laugh"]):
147+
return random.choice(self.responses["jokes"])
148+
149+
# Story request
150+
if any(word in user_input for word in ["story", "tell me", "narrative"]):
151+
return self.tell_story()
152+
153+
# Programming help
154+
if any(word in user_input for word in ["programming", "code", "coding", "developer", "programmer"]):
155+
return random.choice(self.responses["programming_tips"])
156+
157+
# Time and date
158+
if any(word in user_input for word in ["time", "date", "what time", "what date"]):
159+
now = datetime.datetime.now()
160+
return f"Current time: {now.strftime('%H:%M:%S')}, Date: {now.strftime('%Y-%m-%d')}"
161+
162+
# Default responses
163+
default_responses = [
164+
"That's interesting! Can you tell me more about that?",
165+
"I'm not sure I understand. Could you rephrase that?",
166+
"That's a great question! Let me think about it...",
167+
"I'm learning new things every day. What else would you like to know?",
168+
"Fascinating! I'd love to hear more about your thoughts on this."
169+
]
170+
171+
return random.choice(default_responses)
172+
173+
def chat(self):
174+
"""Main chat loop"""
175+
print(f"🤖 {self.name} is online!")
176+
print("=" * 50)
177+
print("Type 'quit' or 'exit' to end the conversation")
178+
print("Try asking about weather, math, jokes, stories, or programming!")
179+
print("=" * 50)
180+
181+
while True:
182+
try:
183+
user_input = input("\nYou: ").strip()
184+
185+
if user_input.lower() in ['quit', 'exit', 'bye']:
186+
print(f"\n{self.name}: {random.choice(self.responses['farewell'])}")
187+
break
188+
189+
if not user_input:
190+
continue
191+
192+
response = self.process_message(user_input)
193+
print(f"\n{self.name}: {response}")
194+
195+
# Store bot response
196+
self.conversation_history.append(f"Bot: {response}")
197+
198+
except KeyboardInterrupt:
199+
print(f"\n\n{self.name}: Goodbye! Thanks for chatting!")
200+
break
201+
except Exception as e:
202+
print(f"\n{self.name}: Oops! Something went wrong: {e}")
203+
204+
def save_conversation(self, filename="conversation_history.json"):
205+
"""Save conversation history to file"""
206+
try:
207+
with open(filename, 'w') as f:
208+
json.dump(self.conversation_history, f, indent=2)
209+
print(f"Conversation saved to {filename}")
210+
except Exception as e:
211+
print(f"Could not save conversation: {e}")
212+
213+
def main():
214+
"""Main function to run the chatbot"""
215+
print("🚀 Starting AI Chatbot...")
216+
217+
# Create and run chatbot
218+
bot = AIChatbot()
219+
bot.chat()
220+
221+
# Ask if user wants to save conversation
222+
try:
223+
save = input("\nWould you like to save this conversation? (y/n): ").lower()
224+
if save == 'y':
225+
bot.save_conversation()
226+
except:
227+
pass
228+
229+
print("\n👋 Thanks for using AI Chatbot!")
230+
231+
if __name__ == "__main__":
232+
main()

0 commit comments

Comments
 (0)