Posted December 28, 2024Dec 28 Objective Build a simple chatbot in a programming language of your choice. The bot should respond contextually to user inputs and include a unique personality or theme. Requirements Personality/Theme: Define the chatbot’s personality or theme (e.g., a sarcastic movie critic, a helpful librarian, or a medieval knight offering advice). Context Awareness: The chatbot should remember at least two pieces of information shared by the user and reference them later in the conversation. Responses: Include at least 10 unique responses based on keywords, context, or a combination of both. Error Handling: Gracefully handle invalid or unclear user inputs. Stretch Goals (optional but encouraged): Implement randomness to make some responses dynamic. Add a command like !exit or !reset to exit or reset the chatbot’s memory. Code Quality: Write clear, modular code with meaningful comments for each section. Example Interaction User: Hi there! Bot: Greetings, traveler! What brings you here? User: I want to learn coding. Bot: Coding, you say? A fine skill for any aspiring hero. What language? User: Python. Bot: Python! Ah, the serpent's tongue. Powerful and versatile. Remember, "import" is your sword and "print" your shield. Submission Instructions Share your code and a short description of your chatbot's theme/personality. Include examples of sample interactions. If you need assistance where to start, post your questions. CodeName: Jessica 💻 Linux Enthusiast | 🌍 Adventurer | 🦄 Unicorn 🌐 My Site | 📢 Join the Forum
Wednesday at 01:25 PM2 days Author Here is my example of a python chatbot that connects to Weather and OpenAI. (You will need your own API keys) import random import openai import requests # Set your OpenAI API key openai.api_key = "YOUR_OPENAI_API_KEY" # Define the chatbot's personality and theme class MedievalKnightChatbot: def __init__(self): self.memory = {} self.responses = { "greeting": ["Greetings, traveler! What brings you here?", "Ah, a new face! State your purpose, noble one."], "coding": ["Coding, you say? A fine skill for any aspiring hero.", "The path of coding is arduous, but rewarding. What language dost thou seek?"], "python": ["Python! Ah, the serpent's tongue. Powerful and versatile.", "Python is a worthy choice. It slithers through challenges gracefully."], "help": ["I am here to guide thee. Ask, and thou shalt receive wisdom.", "Troubled, are we? Fear not, for I hold answers aplenty."], } def get_response(self, user_input): # Keyword-based responses user_input_lower = user_input.lower() if "hello" in user_input_lower or "hi" in user_input_lower: return random.choice(self.responses["greeting"]) elif "coding" in user_input_lower: self.memory["interest"] = "coding" return random.choice(self.responses["coding"]) elif "python" in user_input_lower: self.memory["language"] = "Python" return random.choice(self.responses["python"]) elif "weather" in user_input_lower: return self.get_weather_response(user_input) elif "help" in user_input_lower: return random.choice(self.responses["help"]) elif "exit" in user_input_lower: return "Farewell, noble traveler. May your journey be prosperous!" else: return self.get_openai_response(user_input) def get_weather_response(self, user_input): # Extract location from user input (basic extraction for demonstration purposes) words = user_input.split() location = words[-1] if len(words) > 1 else "Camelot" try: api_url = f"http://api.weatherapi.com/v1/current.json?key=YOUR_API_KEY&q={location}" response = requests.get(api_url) if response.status_code == 200: data = response.json() condition = data['current']['condition']['text'] temp_c = data['current']['temp_c'] return f"The weather in {location} is {condition} with a temperature of {temp_c}°C." else: return "I couldn't fetch the weather. Try again later." except Exception as e: return "Alas, an error occurred whilst fetching the weather." def get_openai_response(self, prompt): try: response = openai.Completion.create( engine="text-davinci-003", prompt=f"You are a medieval knight chatbot. Respond to this: {prompt}", max_tokens=150 ) return response.choices[0].text.strip() except Exception as e: return "Alas, I encountered an error whilst consulting the archives of knowledge." def remember_user_info(self): if "interest" in self.memory and "language" in self.memory: return f"I recall thou art interested in {self.memory['interest']} with a focus on {self.memory['language']}. A noble pursuit!" return "Share with me more, so I may remember thy quest." # Main interaction loop def main(): chatbot = MedievalKnightChatbot() print("Medieval Knight Chatbot: Hail, traveler! I am at your service.") while True: user_input = input("You: ") if user_input.lower() in ["exit", "quit"]: print("Medieval Knight Chatbot: Farewell, noble traveler. May your journey be prosperous!") break response = chatbot.get_response(user_input) print(f"Medieval Knight Chatbot: {response}") # Periodically offer a memory-based response if random.random() < 0.3: print(f"Medieval Knight Chatbot: {chatbot.remember_user_info()}") if __name__ == "__main__": main() CodeName: Jessica 💻 Linux Enthusiast | 🌍 Adventurer | 🦄 Unicorn 🌐 My Site | 📢 Join the Forum
Please sign in to comment
You will be able to leave a comment after signing in
Sign In Now