Skip to content

Commit 36b8d85

Browse files
committed
examples
1 parent 01a9a5b commit 36b8d85

File tree

4 files changed

+818
-668
lines changed

4 files changed

+818
-668
lines changed

daily-knowledge-bot.py

Lines changed: 127 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,127 @@
1+
#!/usr/bin/env python3
2+
"""
3+
Daily Knowledge Bot
4+
5+
This script uses the Perplexity API to fetch an interesting fact about a rotating
6+
topic each day. It can be scheduled to run daily using cron or Task Scheduler.
7+
8+
Usage:
9+
python daily_knowledge_bot.py
10+
11+
Requirements:
12+
- requests
13+
"""
14+
15+
import requests
16+
import json
17+
import os
18+
from datetime import datetime
19+
20+
# Store your API key securely (consider using environment variables in production)
21+
# API_KEY = os.environ.get("PERPLEXITY_API_KEY")
22+
API_KEY = "API_KEY" # Replace with your actual API key
23+
24+
25+
def get_daily_fact(topic):
26+
"""
27+
Fetches an interesting fact about the given topic using Perplexity API.
28+
29+
Args:
30+
topic (str): The topic to get a fact about
31+
32+
Returns:
33+
str: An interesting fact about the topic
34+
"""
35+
url = "https://api.perplexity.ai/chat/completions"
36+
37+
headers = {
38+
"Authorization": f"Bearer {API_KEY}",
39+
"Content-Type": "application/json"
40+
}
41+
42+
data = {
43+
"model": "sonar",
44+
"messages": [
45+
{
46+
"role": "system",
47+
"content": "You are a helpful assistant that provides interesting, accurate, and concise facts. Respond with only one fascinating fact, kept under 100 words."
48+
},
49+
{
50+
"role": "user",
51+
"content": f"Tell me an interesting fact about {topic} that most people don't know."
52+
}
53+
],
54+
"max_tokens": 150,
55+
"temperature": 0.7
56+
}
57+
58+
try:
59+
response = requests.post(url, headers=headers, json=data)
60+
response.raise_for_status() # Raise an exception for 4XX/5XX responses
61+
62+
result = response.json()
63+
return result["choices"][0]["message"]["content"]
64+
except requests.exceptions.RequestException as e:
65+
return f"Error making API request: {str(e)}"
66+
except (KeyError, IndexError) as e:
67+
return f"Error parsing API response: {str(e)}"
68+
except Exception as e:
69+
return f"Unexpected error: {str(e)}"
70+
71+
72+
def save_fact_to_file(topic, fact):
73+
"""
74+
Saves the fact to a text file with timestamp.
75+
76+
Args:
77+
topic (str): The topic of the fact
78+
fact (str): The fact content
79+
"""
80+
timestamp = datetime.now().strftime("%Y-%m-%d")
81+
filename = f"daily_fact_{timestamp}.txt"
82+
83+
with open(filename, "w") as f:
84+
f.write(f"DAILY FACT - {timestamp}\n")
85+
f.write(f"Topic: {topic}\n\n")
86+
f.write(fact)
87+
88+
print(f"Fact saved to {filename}")
89+
90+
91+
def main():
92+
"""Main function that runs the daily knowledge bot."""
93+
# List of topics to rotate through
94+
# You could expand this to read from a configuration file
95+
topics = [
96+
"astronomy",
97+
"history",
98+
"biology",
99+
"technology",
100+
"psychology",
101+
"ocean life",
102+
"ancient civilizations",
103+
"quantum physics",
104+
"art history",
105+
"culinary science"
106+
]
107+
108+
# Use the current day of month to select a topic (rotates through the list)
109+
day = datetime.now().day
110+
topic_index = (day % len(topics)) - 1
111+
today_topic = topics[topic_index]
112+
113+
print(f"Getting today's fact about: {today_topic}")
114+
115+
# Get and display the fact
116+
fact = get_daily_fact(today_topic)
117+
print(f"\nToday's {today_topic} fact: {fact}")
118+
119+
# Save the fact to a file
120+
save_fact_to_file(today_topic, fact)
121+
122+
# In a real application, you might send this via email, SMS, etc.
123+
# Example: send_email("Daily Interesting Fact", fact, "[email protected]")
124+
125+
126+
if __name__ == "__main__":
127+
main()

daily_fact_2025-02-26.txt

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
DAILY FACT - 2025-02-26
2+
Topic: ocean life
3+
4+
An interesting and lesser-known fact about ocean life is that **deep-sea hydrothermal vents** support ecosystems that don't rely on sunlight. Instead, these ecosystems use chemosynthesis to convert chemicals from the Earth's crust into energy, allowing unique creatures like tube worms and giant clams to thrive in extreme conditions[1][3]. This unique adaptation allows life to flourish in places where sunlight cannot reach.

0 commit comments

Comments
 (0)