Building a sports betting Discord bot with Claude API integration transforms your community into a real-time betting intelligence hub. Your members get instant line movement explanations, odds analysis, and edge identification without leaving Discord.
This isn't another generic chatbot tutorial. We're building a production-ready system that combines Anthropic's Claude-3.5-Sonnet with live MoneyLine API data to deliver actionable betting insights directly to your Discord server.
Architecture Overview
Our Discord bot leverages three core components:
- Discord.py 2.4.0 for server integration and slash commands
- Claude-3.5-Sonnet via Anthropic SDK for intelligent analysis
- MoneyLine API for real-time odds and edge data
The bot monitors specific betting channels, responds to user queries about line movements, and proactively alerts members when significant edges appear. Unlike basic odds display bots, this system explains why lines moved and what it means for your betting strategy.
Core Functionality
The bot handles four primary use cases:
- Line Movement Analysis: User asks "Why did Lakers spread move from -3 to -5?"
- Edge Identification: Automated alerts when EV exceeds user-defined thresholds
- Matchup Breakdowns: Pre-game analysis combining odds data with contextual reasoning
- Portfolio Tracking: Monitor active bets and calculate real-time CLV
Setting Up the Discord Bot Framework
First, establish the Discord bot foundation with proper error handling and rate limiting:
import discord
from discord.ext import commands, tasks
import anthropic
import aiohttp
import asyncio
from datetime import datetime, timedelta
import json
from typing import Optional, Dict, List
# Bot configuration
DISCORD_TOKEN = "your_discord_bot_token"
ANTHROPIC_API_KEY = "your_anthropic_api_key"
MONEYLINE_API_KEY = "your_moneyline_api_key"
# Initialize clients
anthropic_client = anthropic.Anthropic(api_key=ANTHROPIC_API_KEY)
bot = commands.Bot(command_prefix='!', intents=discord.Intents.all())
class BettingBot:
def __init__(self):
self.session = None
self.active_edges = {}
self.user_thresholds = {}
async def setup_session(self):
"""Initialize aiohttp session for API calls"""
self.session = aiohttp.ClientSession(
headers={
'Authorization': f'Bearer {MONEYLINE_API_KEY}',
'Content-Type': 'application/json'
}
)
async def fetch_odds_data(self, sport: str = "NBA", limit: int = 50) -> Dict:
"""Fetch live odds from MoneyLine API"""
url = f"https://mlapi.bet/v1/odds?sport={sport}&limit={limit}"
async with self.session.get(url) as response:
if response.status == 200:
return await response.json()
else:
raise Exception(f"API call failed: {response.status}")
async def fetch_edge_data(self, sport: str = "NBA") -> List[Dict]:
"""Get current edges from MoneyLine API"""
url = f"https://mlapi.bet/v1/edge?sport={sport}&min_ev=3.0"
async with self.session.get(url) as response:
if response.status == 200:
data = await response.json()
return data.get('edges', [])
return []
betting_bot = BettingBot()
@bot.event
async def on_ready():
print(f'{bot.user} has connected to Discord!')
await betting_bot.setup_session()
edge_monitor.start()
Claude Integration for Line Movement Analysis
The core intelligence comes from Claude's ability to analyze betting data contextually. Our prompt engineering focuses on actionable insights rather than generic explanations:
class LineMovementAnalyzer:
def __init__(self, anthropic_client):
self.client = anthropic_client
async def analyze_line_movement(self, odds_data: Dict, movement_context: str) -> str:
"""Use Claude to analyze why a line moved"""
prompt = f"""
You are a sharp sports betting analyst explaining line movements to experienced bettors.
Current odds data:
{json.dumps(odds_data, indent=2)}
Movement context: {movement_context}
Analyze this line movement and provide:
1. Most likely reason for the movement (injury, weather, steam, sharp action)
2. Whether this creates betting value on either side
3. Recommended action (bet, wait, avoid) with reasoning
4. Risk factors to consider
Be specific and actionable. Avoid generic gambling disclaimers. These bettors understand risk.
Format response in Discord-friendly markdown with clear sections.
"""
message = self.client.messages.create(
model="claude-3-5-sonnet-20241022",
max_tokens=1000,
messages=[
{"role": "user", "content": prompt}
]
)
return message.content[0].text
analyzer = LineMovementAnalyzer(anthropic_client)
@bot.slash_command(description="Analyze recent line movement for a game")
async def line_movement(
ctx,
team: str,
sport: str = "NBA"
):
"""Slash command for line movement analysis"""
await ctx.defer()
try:
# Fetch current and historical odds
odds_data = await betting_bot.fetch_odds_data(sport)
# Filter for requested team
team_games = [
game for game in odds_data.get('games', [])
if team.lower() in game.get('teams', {}).get('away', '').lower()
or team.lower() in game.get('teams', {}).get('home', '').lower()
]
if not team_games:
await ctx.followup.send(f"No games found for {team} in {sport}")
return
game = team_games[0] # Most recent game
# Create movement context
movement_context = f"User asking about {team} line movement in {sport}"
# Get Claude analysis
analysis = await analyzer.analyze_line_movement(game, movement_context)
# Format for Discord
embed = discord.Embed(
title=f"๐ Line Movement Analysis: {team}",
description=analysis[:2000], # Discord embed limit
color=0x00ff00 if "bet" in analysis.lower() else 0xffff00
)
await ctx.followup.send(embed=embed)
except Exception as e:
await ctx.followup.send(f"Error analyzing line movement: {str(e)}")
Automated Edge Detection and Alerts
The bot's most valuable feature is proactive edge identification. It continuously monitors the MoneyLine API /v1/edge endpoint and alerts users when opportunities match their criteria:
@tasks.loop(minutes=5)
async def edge_monitor():
"""Monitor for new edges and alert users"""
if not betting_bot.session:
return
try:
# Fetch edges for major sports
sports = ["NBA", "NFL", "MLB", "NHL"]
all_edges = []
for sport in sports:
edges = await betting_bot.fetch_edge_data(sport)
all_edges.extend(edges)
# Process each edge
for edge in all_edges:
edge_id = f"{edge['game_id']}_{edge['market']}"
# Skip if already alerted
if edge_id in betting_bot.active_edges:
continue
# Check if edge meets user thresholds
ev_percentage = edge.get('ev_percentage', 0)
if ev_percentage >= 10.0: # 10% EV threshold
await alert_high_ev_edge(edge)
betting_bot.active_edges[edge_id] = edge
except Exception as e:
print(f"Edge monitoring error: {e}")
async def alert_high_ev_edge(edge: Dict):
"""Send Discord alert for high EV edges"""
channel = bot.get_channel(YOUR_ALERTS_CHANNEL_ID)
if not channel:
return
# Get Claude analysis of the edge
edge_analysis = await analyzer.analyze_edge_opportunity(edge)
embed = discord.Embed(
title=f"๐จ High EV Alert: {edge['ev_percentage']:.1f}%",
description=f"**{edge['teams']['away']} @ {edge['teams']['home']}**\n{edge['market']}",
color=0xff0000
)
embed.add_field(
name="Opportunity Details",
value=f"**Book:** {edge['sportsbook']}\n**Line:** {edge['odds']}\n**True Odds:** {edge['true_odds']}\n**EV:** {edge['ev_percentage']:.2f}%",
inline=False
)
embed.add_field(
name="Analysis",
value=edge_analysis[:1000],
inline=False
)
await channel.send(embed=embed)
User Experience and Command Interface
The bot provides an intuitive slash command interface that feels natural to Discord users:
Primary Commands
/line_movement [team] [sport]- Analyze recent line movements/edges [sport] [min_ev]- Show current high-value edges/matchup [team1] [team2]- Pre-game analysis with betting angles/track [bet_id]- Add bet to portfolio tracking/portfolio- View active bets and CLV calculations
Interactive Features
Users can react to edge alerts with emoji to:
- ๐ Save edge for later review
- ๐ Request deeper statistical analysis
- ๐ซ Mute similar alerts for 24 hours
- โก Get live odds updates via DM
The bot remembers user preferences and customizes alerts accordingly. Power users can set sport-specific EV thresholds and receive DM notifications for premium opportunities.
Advanced Prompt Engineering for Betting Analysis
Effective betting bot prompts require domain expertise and context awareness. Generic AI responses don't cut it when money is on the line:
ANALYSIS_PROMPTS = {
"line_movement": """
You are a professional sports betting analyst with 15+ years of market experience.
Analyze this line movement data:
{data}
Context: {context}
Provide analysis in this exact format:
**Movement Summary:**
[2-3 sentences on what moved and by how much]
**Most Likely Catalyst:**
[Primary reason: injury, weather, sharp money, public sentiment, etc.]
**Betting Recommendation:**
[Specific action with reasoning - be definitive]
**Risk Assessment:**
[Key factors that could make this wrong]
**Confidence Level:** [High/Medium/Low]
No gambling disclaimers. Be direct and actionable.
""",
"edge_analysis": """
You are evaluating a positive EV betting opportunity for sharp bettors.
Edge data:
{edge_data}
Market context:
{market_context}
Assess:
1. Edge reliability (model confidence, sample size, recency)
2. Market efficiency concerns (why is this line available?)
3. Optimal bet sizing considerations
4. Potential line shopping opportunities
Rate this edge: SMASH/BET/LEAN/PASS with reasoning.
"""
}
The key is treating Claude as a betting advisor, not a generic chatbot. Specific output formats and professional context produce actionable insights that users actually trust with their bankroll.
Integration with MoneyLine API Features
The bot leverages multiple MoneyLine API endpoints for comprehensive betting intelligence:
- /v1/edge - Core positive EV opportunities with built-in market analysis
- /v1/odds - Real-time line data across 50+ sportsbooks
- /v1/events - Game schedules and metadata for context
- /v1/players/trending - Player prop edges and injury impact analysis
This multi-endpoint approach provides the contextual depth Claude needs for meaningful analysis. The MoneyLine API handles the complex data aggregation while your bot focuses on user experience and intelligent interpretation.
Deployment and Production Considerations
Production Discord bots require robust error handling and rate limit management:
Rate Limiting Strategy
- Discord: 50 requests per second with proper bucketing
- Anthropic Claude: 5 requests per second on paid tier
- MoneyLine API: 100 requests per minute on free tier, unlimited on paid
Error Recovery
Implement exponential backoff for API failures and graceful degradation when services are unavailable. Cache frequently requested data to reduce API load during peak usage.
Scalability Planning
Start with a single Discord server deployment, then expand to multi-server architecture as your user base grows. Consider sharding for servers with 10,000+ members.
FAQ
What's the cost to run a Discord betting bot with Claude API?
Monthly costs typically range from $50-200 depending on usage. Discord hosting is free, Claude API costs $0.003 per 1k input tokens, and MoneyLine API offers 1,000 free credits monthly. A busy server with 500 members might generate 50,000 Claude tokens daily ($4.50/day).
How accurate are Claude's line movement explanations?
Claude excels at synthesizing available information but can't access real-time injury reports or insider information. Accuracy improves significantly when you provide rich context data from MoneyLine API. Expect 70-80% accuracy on obvious movements (major injuries, weather) but verify major betting decisions independently.
Can I customize the bot for specific sports or betting strategies?
Absolutely. The prompt system is fully customizable for different sports, bet types, and risk preferences. You can create specialized analyzers for NBA player props, NFL totals, or European soccer markets. The MoneyLine API supports all major sports with consistent data structures.
How do I prevent the bot from being banned by Discord?
Follow Discord's rate limits strictly, use proper error handling, and avoid spammy behavior. Don't send more than one edge alert per channel per minute, implement user-controlled notification preferences, and respect server admin settings. Register slash commands properly and use embeds for rich content formatting.
What happens if MoneyLine API or Claude goes down?
Implement graceful degradation with cached responses and status monitoring. Store recent odds data locally for basic functionality during API outages. Consider having backup data sources for critical features, though MoneyLine API has 99.9% uptime in practice. Your bot should degrade to basic Discord functionality rather than crash completely.