Skip to content

Commit 07c3643

Browse files
authored
Merge branch 'main' into main
2 parents d0ccb36 + 6e6e77b commit 07c3643

20 files changed

+924
-33
lines changed

.github/workflows/pr-validation.yml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ jobs:
3030
run: |
3131
# Simple check for common broken link patterns
3232
echo "Checking for potential broken links..."
33-
if grep -r "http://localhost\|http://127.0.0.1" docs/; then
33+
if grep -r "http://localhost\|http://127.0.0.1" docs/ --exclude-dir=showcase; then
3434
echo "❌ Found localhost links that should be removed"
3535
exit 1
3636
fi
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
.env.example
2+
DISCORD_TOKEN="YOUR_DISCORD_BOT_TOKEN_HERE"
3+
PERPLEXITY_API_KEY="YOUR_PPLX_API_KEY_HERE"
Lines changed: 104 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,104 @@
1+
---
2+
title: Perplexity Discord Bot
3+
description: A runnable discord.py bot that adds a /ask_perplexity command to your server, using the Sonar API for web-connected answers.
4+
sidebar_position: 4
5+
keywords: [discord, bot, discord.py, python, chatbot, perplexity, sonar api, command, slash command]
6+
---
7+
8+
# Perplexity Discord Bot
9+
10+
A runnable `discord.py` application that adds a `/ask_perplexity` slash command to your Discord server, using Perplexity's Sonar API for real-time, web-connected answers.
11+
12+
## 🌟 Features
13+
14+
- **Direct Sonar API Integration**: Uses Perplexity's API for real-time, web-connected answers.
15+
- **Slash Command Ready**: Implements a modern `/ask_perplexity` command that's easy to use.
16+
- **Secure Configuration**: Uses environment variables (`.env`) for both Discord and Perplexity keys, keeping them safe.
17+
- **Administrator Permissions**: Locked to server administrators by default for easy control over API usage.
18+
- **Formatted Embeds**: Delivers answers in a clean, professional Discord embed.
19+
- **Self-Contained Example**: Minimal, single-file code designed to be easy to run and understand.
20+
21+
## 📋 Prerequisites
22+
23+
- **Python 3.8+**
24+
- **A Perplexity API Key**
25+
- **A Discord Bot Token**
26+
27+
## 🚀 Installation & Setup
28+
29+
1. **Clone the Repository:** Fork and clone the `api-cookbook` repository to your local machine.
30+
31+
2. **Navigate to this Example:**
32+
```bash
33+
cd docs/examples/discord-py-bot/
34+
```
35+
3. **Install Dependencies:**
36+
```bash
37+
pip install -r requirements.txt
38+
```
39+
4. **Get Your Secret Keys:**
40+
- **Perplexity API Key:** Get your key from the [Perplexity AI Account Settings](https://www.perplexity.ai/settings/api).
41+
- **Discord Bot Token:**
42+
1. Go to the [Discord Developer Portal](https://discord.com/developers/applications).
43+
2. Click **"New Application"** and give it a name.
44+
3. Go to the **"Bot"** tab and click **"Reset Token"** (or "Add Bot" first if needed).
45+
4. Copy the token. This is your bot's password – keep it safe!
46+
47+
5. **Set Up Your Environment File:**
48+
- Rename the `.env.example` file to `.env`.
49+
- Open the `.env` file and add your secret keys:
50+
```
51+
DISCORD_TOKEN="YOUR_DISCORD_BOT_TOKEN_HERE"
52+
PERPLEXITY_API_KEY="YOUR_PPLX_API_KEY_HERE"
53+
```
54+
55+
## 🔧 Usage
56+
57+
### 1. Invite Your Bot to a Server
58+
59+
- In the Discord Developer Portal, go to "OAuth2" -> "URL Generator".
60+
- Select the `bot` and `applications.commands` scopes.
61+
- Under "Bot Permissions," select **Administrator**.
62+
- Copy the generated URL, paste it into your browser, and invite the bot to your server.
63+
64+
### 2. Run the Bot Script
65+
66+
Simply execute the `bot.py` script from your terminal:
67+
```bash
68+
python bot.py
69+
This will connect the bot to Discord and sync the /ask_perplexity command.
70+
3. Use the Command in Discord
71+
In any channel in your server, an administrator can type:
72+
code
73+
Code
74+
/ask_perplexity prompt:What is the latest news in the world of generative AI?
75+
📄 Output Example
76+
The bot will defer the interaction and then respond with a formatted embed containing the answer:
77+
code
78+
Code
79+
HatchMate [APP]
80+
🌐 Perplexity's Response
81+
82+
The latest news in generative AI includes advancements in large language models... (and so on).
83+
84+
Your Prompt```
85+
What is the latest news in the world of generative AI?
86+
Requested by YourUsername
87+
code
88+
Code
89+
## 🛠️ Extending the Bot
90+
91+
- **Role-Based Access**: Modify the permission checks to allow specific roles, not just administrators.
92+
- **Model Selection**: Add an option to the slash command to choose between different models like `sonar-pro` or `sonar-small-online`.
93+
- **Conversation History**: Implement a database (like SQLite or Redis) to store recent messages and send them with new prompts for conversational context.
94+
95+
## ⚠️ Limitations
96+
97+
- The permission system is basic (administrator-only) to keep the example simple and database-free.
98+
- The command is single-turn and does not remember conversation history.
99+
- API rate limits may apply based on your Perplexity account status.
100+
101+
## 🙏 Acknowledgements
102+
103+
- This project uses the [Perplexity AI API](https://docs.perplexity.ai/).
104+
- Built with the [discord.py](https://discordpy.readthedocs.io/en/stable/) library.

docs/examples/discord-py-bot/bot.py

Lines changed: 119 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,119 @@
1+
# This code is a simplified example of a Discord bot that integrates with the Perplexity AI API. This is a complete, minimal bot script that someone can run directly. Notice I have simplified the permission logic to only check for administrators to remove the need for an external database, making the example much more focused on the Perplexity API.
2+
3+
# bot.py
4+
import os
5+
import discord
6+
from discord.ext import commands
7+
from discord import app_commands
8+
import openai
9+
from dotenv import load_dotenv
10+
11+
# --- Step 1: Load Environment Variables ---
12+
# This ensures your secret keys are kept safe in a .env file.
13+
load_dotenv()
14+
DISCORD_TOKEN = os.getenv("DISCORD_TOKEN")
15+
PERPLEXITY_API_KEY = os.getenv("PERPLEXITY_API_KEY")
16+
17+
# --- Step 2: Bot Setup ---
18+
# We define the bot's intents, which tell Discord what events our bot needs to receive.
19+
intents = discord.Intents.default()
20+
bot = commands.Bot(command_prefix="!", intents=intents)
21+
22+
# --- Step 3: Create a Command Cog ---
23+
# Cogs are how modern discord.py bots organize commands, listeners, and state.
24+
class AIChatCog(commands.Cog):
25+
def __init__(self, bot: commands.Bot):
26+
self.bot = bot
27+
28+
# Initialize the Perplexity AI Client using the key from our .env file.
29+
# The `base_url` is the crucial part that directs the OpenAI library to Perplexity's API.
30+
if PERPLEXITY_API_KEY:
31+
self.perplexity_client = openai.OpenAI(
32+
api_key=PERPLEXITY_API_KEY,
33+
base_url="https://api.perplexity.ai"
34+
)
35+
print("Perplexity AI Client Initialized.")
36+
else:
37+
self.perplexity_client = None
38+
print("CRITICAL: PERPLEXITY_API_KEY not found in .env file.")
39+
40+
# Define the slash command.
41+
# The `has_permissions` check restricts this command to server administrators.
42+
@app_commands.command(name="ask_perplexity", description="Ask a question to Perplexity AI (with web access).")
43+
@app_commands.describe(prompt="The question you want to ask.")
44+
@app_commands.checks.has_permissions(administrator=True)
45+
async def ask_perplexity(self, interaction: discord.Interaction, prompt: str):
46+
if not self.perplexity_client:
47+
return await interaction.response.send_message(
48+
"The Perplexity AI service is not configured on this bot.",
49+
ephemeral=True
50+
)
51+
52+
# Defer the response to give the API time to process without a timeout.
53+
await interaction.response.defer(thinking=True)
54+
55+
try:
56+
# Create the list of messages for the API call, following the standard format.
57+
messages = [{"role": "user", "content": prompt}]
58+
59+
# Call the Perplexity API with the desired model.
60+
response = self.perplexity_client.chat.completions.create(
61+
model="sonar-pro",
62+
messages=messages
63+
)
64+
65+
answer = response.choices[0].message.content
66+
67+
# Create and send a nicely formatted Discord embed for the response.
68+
embed = discord.Embed(
69+
title="🌐 Perplexity's Response",
70+
description=answer,
71+
color=discord.Color.from_rgb(0, 255, 0) # Perplexity Green
72+
)
73+
embed.set_footer(text=f"Requested by {interaction.user.display_name}")
74+
75+
# Truncate the original prompt if it's too long to fit in an embed field.
76+
truncated_prompt = (prompt[:1020] + '...') if len(prompt) > 1024 else prompt
77+
embed.add_field(name="Your Prompt", value=f"```{truncated_prompt}```", inline=False)
78+
79+
await interaction.followup.send(embed=embed)
80+
81+
except Exception as e:
82+
# Inform the user if an error occurs.
83+
error_message = f"An error occurred with the Perplexity API: {e}"
84+
print(error_message)
85+
await interaction.followup.send(error_message, ephemeral=True)
86+
87+
# A local error handler specifically for this command's permission check.
88+
@ask_perplexity.error
89+
async def on_ask_perplexity_error(self, interaction: discord.Interaction, error: app_commands.AppCommandError):
90+
if isinstance(error, app_commands.MissingPermissions):
91+
await interaction.response.send_message("You must be an administrator to use this command.", ephemeral=True)
92+
else:
93+
# For other errors, print them to the console.
94+
print(f"An unhandled error occurred: {error}")
95+
# Potentially send a generic error message back to the user as well.
96+
if not interaction.response.is_done():
97+
await interaction.response.send_message("An unexpected error occurred.", ephemeral=True)
98+
99+
100+
# --- Step 4: Main Bot Events and Startup Logic ---
101+
@bot.event
102+
async def on_ready():
103+
print(f'Logged in as {bot.user}!')
104+
try:
105+
# Add the cog to the bot so its commands are registered.
106+
await bot.add_cog(AIChatCog(bot))
107+
108+
# Sync the slash commands to Discord. This makes them appear for users.
109+
synced = await bot.tree.sync()
110+
print(f"Synced {len(synced)} command(s).")
111+
except Exception as e:
112+
print(f"Error during setup: {e}")
113+
114+
# This is the entry point for running the bot.
115+
if __name__ == "__main__":
116+
if not DISCORD_TOKEN or not PERPLEXITY_API_KEY:
117+
print("CRITICAL: DISCORD_TOKEN and/or PERPLEXITY_API_KEY not found in .env file. Bot cannot start.")
118+
else:
119+
bot.run(DISCORD_TOKEN)
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
# requirements.txt
2+
discord.py
3+
openai
4+
python-dotenv

docs/showcase/4point-Hoops.mdx

Lines changed: 94 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,94 @@
1+
---
2+
title: 4Point Hoops | AI Basketball Analytics Platform
3+
description: Advanced NBA analytics platform that combines live Basketball-Reference data with Perplexity Sonar to deliver deep-dive player stats, cross-season comparisons and expert-grade AI explanations
4+
sidebar_position: 14
5+
keywords: [4point hoops, nba, basketball, analytics, ai, perplexity, sonar, sports-data, comparisons]
6+
---
7+
8+
![4Point Hoops Dashboard](https://d112y698adiu2z.cloudfront.net/photos/production/software_photos/003/442/047/datas/original.png)
9+
10+
**4Point Hoops** is an advanced NBA analytics platform that turns raw basketball statistics into actionable, narrative-driven insights. By scraping Basketball-Reference in real time and routing context-rich prompts to Perplexity's Sonar Pro model, it helps fans, analysts, and fantasy players understand the "why" and "what's next" – not just the numbers.
11+
12+
<iframe
13+
className="w-full aspect-video rounded-xl"
14+
src="https://www.youtube.com/embed/lThCWq0ij7k"
15+
title="YouTube video player"
16+
frameBorder="0"
17+
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
18+
allowFullScreen
19+
></iframe>
20+
21+
## Features
22+
23+
* **Player Analytics** with season & playoff splits, shot-type breakdowns, and performance radar for any NBA player
24+
* **Cross-Era Comparisons** enabling side-by-side stat comparisons (e.g., Michael Jordan '97 vs. Stephen Curry '22)
25+
* **Team Dashboards** with standings, playoff-probability Sankey flows, and auto-refreshing KPI tiles
26+
* **AI Explain & Similar Players** providing one-click Sonar explanations of stat lines and AI-picked comparable athletes
27+
* **Basketball AI Chat** allowing users to ask an expert LLM about NBA history, rosters, or projections
28+
* **Credit-Based SaaS System** with Firebase Auth, Google login, credit wallets, and admin tooling
29+
30+
## Prerequisites
31+
32+
* Node.js 16+ and npm
33+
* Python 3.8+ and pip
34+
* Firebase project setup
35+
* Perplexity API key (Sonar Pro)
36+
* Basketball-Reference access
37+
38+
## Installation
39+
40+
```bash
41+
# Clone the frontend repository
42+
git clone https://github.com/rapha18th/hoop-ai-frontend-44.git
43+
cd hoop-ai-frontend-44
44+
npm install
45+
46+
# Clone the backend repository
47+
git clone https://github.com/rapha18th/4Point-Hoops-Server.git
48+
cd 4Point-Hoops-Server
49+
pip install -r requirements.txt
50+
```
51+
52+
## Configuration
53+
54+
Create `.env` file in the backend directory:
55+
```ini
56+
PERPLEXITY_API_KEY=your_sonar_pro_api_key
57+
FIREBASE_PROJECT_ID=your_firebase_project_id
58+
FIREBASE_PRIVATE_KEY=your_firebase_private_key
59+
FIREBASE_CLIENT_EMAIL=your_firebase_client_email
60+
```
61+
62+
## Usage
63+
64+
1. **Start Backend**:
65+
```bash
66+
cd 4Point-Hoops-Server
67+
python app.py
68+
```
69+
70+
2. **Start Frontend**:
71+
```bash
72+
cd hoop-ai-frontend-44
73+
npm run dev
74+
```
75+
76+
3. **Access Application**: Open the frontend URL and explore NBA analytics with AI-powered insights
77+
78+
4. **Use AI Features**: Click "AI Explain" on any player or stat to get intelligent analysis powered by Perplexity Sonar
79+
80+
## Code Explanation
81+
82+
* **Frontend**: React with shadcn/ui components and Recharts for data visualization
83+
* **Backend**: Python Flask API serving Basketball-Reference data and managing Perplexity API calls
84+
* **Data Pipeline**: BRScraper for real-time data collection with Firebase caching
85+
* **AI Integration**: Perplexity Sonar Pro for intelligent basketball analysis and explanations
86+
* **Authentication**: Firebase Auth with Google login and credit-based access control
87+
* **Deployment**: Frontend on Netlify, backend on Hugging Face Spaces with Docker
88+
89+
## Links
90+
91+
- [Frontend Repository](https://github.com/rapha18th/hoop-ai-frontend-44)
92+
- [Backend Repository](https://github.com/rapha18th/4Point-Hoops-Server)
93+
- [Live Demo](https://4pointhoops.netlify.app/)
94+
- [Devpost Submission](https://devpost.com/software/4point-hoops)

0 commit comments

Comments
 (0)