Spaces:
Building
Building
import discord | |
from discord import app_commands | |
import aiohttp | |
import asyncio | |
from datetime import datetime, timezone, timedelta | |
from cash import user_cash # Ensure you have a 'cash.py' module managing user_cash as a dictionary | |
user_bets = {} | |
API_KEY = "jE7yBJVRNAwdDesMgTzTXUUSx1It41Fq" | |
def get_current_nfl_week(): | |
""" | |
Calculate the current NFL week based on the start date. | |
Adjust the start_date as per the actual NFL season start. | |
""" | |
# Example start date for NFL Week 1 | |
start_date = datetime(2024, 9, 6) # Adjust this date to the actual start of the NFL season | |
today = datetime.now() | |
delta_days = (today.date() - start_date.date()).days | |
week_number = (delta_days // 7) + 1 | |
if week_number < 1: | |
week_number = 1 | |
return week_number | |
async def fetch_nhl_scores(): | |
today = datetime.now().strftime('%Y%m%d') | |
url = f"https://api.foxsports.com/bifrost/v1/nhl/scoreboard/segment/{today}?apikey={API_KEY}" | |
async with aiohttp.ClientSession() as session: | |
async with session.get(url) as response: | |
return await response.json() | |
async def fetch_nfl_scores(): | |
current_week = get_current_nfl_week() | |
url = f"https://api.foxsports.com/bifrost/v1/nfl/scoreboard/segment/2024-{current_week}-1?apikey={API_KEY}" | |
async with aiohttp.ClientSession() as session: | |
async with session.get(url) as response: | |
return await response.json() | |
class SportSelect(discord.ui.Select): | |
def __init__(self): | |
options = [ | |
discord.SelectOption(label="NHL", description="Bet on NHL games"), | |
discord.SelectOption(label="NFL", description="Bet on NFL games") | |
] | |
super().__init__(placeholder="Select a sport to bet on", min_values=1, max_values=1, options=options) | |
class GameSelect(discord.ui.Select): | |
def __init__(self, games, league): | |
options = [ | |
discord.SelectOption( | |
label=f"{game['lowerTeam']['longName']} vs {game['upperTeam']['longName']}" if league == "NHL" else f"{game['teams']['away']['teamName']} vs {game['teams']['home']['teamName']}", | |
value=f"{game['lowerTeam']['name']}_{game['upperTeam']['name']}" if league == "NHL" else f"{game['teams']['away']['abbreviation']}_{game['teams']['home']['abbreviation']}", | |
description=f"Start time: <t:{int(datetime.fromisoformat(game['eventTime'].replace('Z', '+00:00')).timestamp())}:R>" | |
) for game in games | |
] | |
super().__init__(placeholder="Select a game", min_values=1, max_values=1, options=options) | |
self.league = league | |
self.games = games | |
async def callback(self, interaction: discord.Interaction): | |
selected_value = self.values[0] | |
if self.league == "NHL": | |
selected_game = next(game for game in self.games if f"{game['lowerTeam']['name']}_{game['upperTeam']['name']}" == selected_value) | |
await interaction.response.edit_message(content="Select a team to bet on:", view=TeamSelect(selected_game, self.league)) | |
elif self.league == "NFL": | |
selected_game = next(game for game in self.games if f"{game['teams']['away']['abbreviation']}_{game['teams']['home']['abbreviation']}" == selected_value) | |
await interaction.response.edit_message(content="Select a team to bet on:", view=TeamSelect(selected_game, self.league)) | |
class TeamSelect(discord.ui.View): | |
def __init__(self, game, league): | |
super().__init__() | |
self.league = league | |
if league == "NHL": | |
away_team = game['lowerTeam'] | |
home_team = game['upperTeam'] | |
elif league == "NFL": | |
away_team = game['teams']['away'] | |
home_team = game['teams']['home'] | |
self.add_item(TeamOptionSelect(away_team, home_team, league)) | |
class TeamOptionSelect(discord.ui.Select): | |
def __init__(self, away_team, home_team, league): | |
options = [ | |
discord.SelectOption(label=away_team['longName'] if league == "NHL" else away_team['teamName'], value=away_team['name'] if league == "NHL" else away_team['abbreviation']), | |
discord.SelectOption(label=home_team['longName'] if league == "NHL" else home_team['teamName'], value=home_team['name'] if league == "NHL" else home_team['abbreviation']) | |
] | |
super().__init__(placeholder="Select a team to bet on", min_values=1, max_values=1, options=options) | |
self.league = league | |
self.game = None | |
async def callback(self, interaction: discord.Interaction): | |
selected_team = self.values[0] | |
view = self.view # Access the parent view | |
if self.league == "NHL": | |
selected_game = next(game for game in view.games if f"{game['lowerTeam']['name']}_{game['upperTeam']['name']}" == view.children[0].values[0]) | |
elif self.league == "NFL": | |
selected_game = next(game for game in view.games if f"{game['teams']['away']['abbreviation']}_{game['teams']['home']['abbreviation']}" == view.children[0].values[0]) | |
await interaction.response.send_modal(BetModal(selected_team, interaction.user.id, selected_game, self.league)) | |
class BetModal(discord.ui.Modal, title="Place Your Bet"): | |
bet_amount = discord.ui.TextInput(label="Bet Amount", placeholder="Enter bet amount", required=True) | |
def __init__(self, team, user_id, game_data, league): | |
super().__init__() | |
self.team = team | |
self.user_id = user_id | |
self.game_data = game_data | |
self.league = league | |
async def on_submit(self, interaction: discord.Interaction): | |
try: | |
bet_amount = int(self.bet_amount.value) | |
if bet_amount <= 0: | |
raise ValueError("Bet amount must be greater than 0.") | |
if bet_amount > user_cash.get(self.user_id, 0): | |
raise ValueError("Insufficient balance. Please check your balance and try again.") | |
user_cash[self.user_id] -= bet_amount | |
await interaction.response.send_message(f"Bet placed on {self.team} for ${bet_amount}.", ephemeral=True) | |
user = await interaction.client.fetch_user(self.user_id) | |
embed = discord.Embed(title="Bet Placed", color=0x00ff00) | |
embed.add_field(name="League", value=self.league, inline=False) | |
embed.add_field(name="Team", value=self.team, inline=False) | |
embed.add_field(name="Amount", value=f"${bet_amount}", inline=False) | |
if self.league == "NHL": | |
game_description = f"{self.game_data['lowerTeam']['longName']} vs {self.game_data['upperTeam']['longName']}" | |
start_time = self.game_data['eventTime'] | |
elif self.league == "NFL": | |
game_description = f"{self.game_data['teams']['away']['teamName']} vs {self.game_data['teams']['home']['teamName']}" | |
start_time = self.game_data['startTime'] | |
embed.add_field(name="Game", value=game_description, inline=False) | |
embed.add_field(name="Start Time", value=f"<t:{int(datetime.fromisoformat(start_time.replace('Z', '+00:00')).timestamp())}:F>", inline=False) | |
await user.send(embed=embed) | |
if self.user_id not in user_bets: | |
user_bets[self.user_id] = [] | |
user_bets[self.user_id].append({ | |
"league": self.league, | |
"team": self.team, | |
"amount": bet_amount, | |
"game_data": self.game_data | |
}) | |
asyncio.create_task(self.monitor_game(interaction, bet_amount)) | |
except ValueError as e: | |
await interaction.response.send_message(str(e), ephemeral=True) | |
async def monitor_game(self, interaction, bet_amount): | |
if self.league == "NHL": | |
game_start = datetime.fromisoformat(self.game_data['eventTime'].replace('Z', '+00:00')) | |
elif self.league == "NFL": | |
game_start = datetime.fromisoformat(self.game_data['startTime'].replace('Z', '+00:00')) | |
sleep_duration = (game_start - datetime.now(timezone.utc)).total_seconds() | |
if sleep_duration > 0: | |
await asyncio.sleep(sleep_duration) | |
user = await interaction.client.fetch_user(self.user_id) | |
await user.send(f"Your team {self.team} has started playing!") | |
previous_scores = {} | |
if self.league == "NHL": | |
previous_scores = {self.game_data['lowerTeam']['name']: 0, self.game_data['upperTeam']['name']: 0} | |
elif self.league == "NFL": | |
previous_scores = {self.game_data['teams']['away']['abbreviation']: 0, self.game_data['teams']['home']['abbreviation']: 0} | |
while True: | |
if self.league == "NHL": | |
scores = await fetch_nhl_scores() | |
events = scores.get('sectionList', [])[0].get('events', []) | |
game = next((g for g in events if g['lowerTeam']['name'] == self.game_data['lowerTeam']['name'] and | |
g['upperTeam']['name'] == self.game_data['upperTeam']['name']), None) | |
elif self.league == "NFL": | |
scores = await fetch_nfl_scores() | |
events = scores.get('sectionList', [])[0].get('events', []) | |
game = next((g for g in events if g['teams']['away']['abbreviation'] == self.game_data['teams']['away']['abbreviation'] and | |
g['teams']['home']['abbreviation'] == self.game_data['teams']['home']['abbreviation']), None) | |
if game is None: | |
await asyncio.sleep(60) | |
continue | |
if self.league == "NHL": | |
event_status = game.get('eventStatus', 2) # Default to 2 if not present | |
current_scores = { | |
game['lowerTeam']['name']: game.get('score', 0), | |
game['upperTeam']['name']: game.get('score', 0) | |
} | |
is_final = event_status == 3 | |
elif self.league == "NFL": | |
event_status = game.get('status', {}).get('state', 'PREVIEW') | |
current_scores = game.get('scores', {}) | |
is_final = event_status == 'FINAL' | |
for team, score in current_scores.items(): | |
if score > previous_scores.get(team, 0): | |
if self.league == "NHL": | |
team_name = self.game_data['lowerTeam']['longName'] if team == self.game_data['lowerTeam']['name'] else self.game_data['upperTeam']['longName'] | |
message = f"{team_name} SCORED! Current score: {current_scores[self.game_data['lowerTeam']['name']]} - {current_scores[self.game_data['upperTeam']['name']]}" | |
elif self.league == "NFL": | |
team_name = self.game_data['teams']['away']['teamName'] if team == self.game_data['teams']['away']['abbreviation'] else self.game_data['teams']['home']['teamName'] | |
opponent = self.game_data['teams']['home']['teamName'] if team == self.game_data['teams']['away']['abbreviation'] else self.game_data['teams']['away']['teamName'] | |
message = f"{team_name} scored! Current score: {current_scores.get(self.game_data['teams']['away']['abbreviation'],0)} - {current_scores.get(self.game_data['teams']['home']['abbreviation'],0)}" | |
await user.send(message) | |
previous_scores = current_scores.copy() | |
if is_final: | |
if self.league == "NHL": | |
winner = self.game_data['lowerTeam']['name'] if current_scores[self.game_data['lowerTeam']['name']] > current_scores[self.game_data['upperTeam']['name']] else self.game_data['upperTeam']['name'] | |
elif self.league == "NFL": | |
away_score = current_scores.get(self.game_data['teams']['away']['abbreviation'], 0) | |
home_score = current_scores.get(self.game_data['teams']['home']['abbreviation'], 0) | |
winner = self.game_data['teams']['away']['abbreviation'] if away_score > home_score else self.game_data['teams']['home']['abbreviation'] | |
if winner == self.team: | |
winnings = bet_amount * 2 | |
user_cash[self.user_id] += winnings | |
await user.send(f"Congratulations! Your team won. You won ${winnings}!") | |
else: | |
await user.send(f"Sorry, your team lost. Better luck next time!") | |
user_bets[self.user_id] = [bet for bet in user_bets[self.user_id] if bet['game_data'] != self.game_data] | |
break | |
await asyncio.sleep(60) # Check every minute | |
class SportBetView(discord.ui.View): | |
def __init__(self): | |
super().__init__() | |
self.add_item(SportSelect()) | |
async def view_bets(self, interaction: discord.Interaction, button: discord.ui.Button): | |
await show_current_bets(interaction) | |
async def show_game_selection(interaction: discord.Interaction): | |
view = SportBetView() | |
await interaction.response.send_message("Select a sport to bet on:", view=view, ephemeral=True) | |
class SportSelectView(discord.ui.View): | |
def __init__(self): | |
super().__init__() | |
self.add_item(SportSelect()) | |
class SportSelect(discord.ui.Select): | |
def __init__(self): | |
options = [ | |
discord.SelectOption(label="NHL", description="Bet on NHL games"), | |
discord.SelectOption(label="NFL", description="Bet on NFL games") | |
] | |
super().__init__(placeholder="Select a sport to bet on", min_values=1, max_values=1, options=options) | |
async def callback(self, interaction: discord.Interaction): | |
selected_sport = self.values[0] | |
if selected_sport == "NHL": | |
scores = await fetch_nhl_scores() | |
events = scores.get('sectionList', [])[0].get('events', []) | |
upcoming_games = [game for game in events if game['eventStatus'] == 2] | |
elif selected_sport == "NFL": | |
scores = await fetch_nfl_scores() | |
events = scores.get('sectionList', [])[0].get('events', []) | |
upcoming_games = [game for game in events if game['status']['state'] == 'PREVIEW'] | |
if not upcoming_games: | |
await interaction.response.edit_message(content="No games available for betting.", view=None) | |
return | |
view = discord.ui.View() | |
game_select = GameSelect(upcoming_games, selected_sport) | |
view.add_item(game_select) | |
await interaction.response.edit_message(content="Select a game to bet on:", view=view) | |
async def show_current_bets(interaction: discord.Interaction): | |
user_id = interaction.user.id | |
if user_id not in user_bets or not user_bets[user_id]: | |
await interaction.response.send_message("You have no active bets.", ephemeral=True) | |
return | |
embed = discord.Embed(title="Your Current Bets", color=0xFF5733) | |
for i, bet in enumerate(user_bets[user_id], 1): | |
league = bet['league'] | |
team = bet['team'] | |
amount = bet['amount'] | |
if league == "NHL": | |
game = bet['game_data'] | |
game_description = f"{game['lowerTeam']['longName']} vs {game['upperTeam']['longName']}" | |
start_time = game['eventTime'] | |
score = f"{game.get('lowerTeam', {}).get('score', 'N/A')} - {game.get('upperTeam', {}).get('score', 'N/A')}" if game.get('score') else "N/A" | |
status = "Final" if game.get('score') else f"Starts <t:{int(datetime.fromisoformat(start_time.replace('Z', '+00:00')).timestamp())}:R>" | |
elif league == "NFL": | |
game = bet['game_data'] | |
game_description = f"{game['teams']['away']['teamName']} vs {game['teams']['home']['teamName']}" | |
start_time = game['startTime'] | |
score = f"{game['scores'].get(game['teams']['away']['abbreviation'], 'N/A')} - {game['scores'].get(game['teams']['home']['abbreviation'], 'N/A')}" if 'scores' in game else "N/A" | |
status = "Final" if game['status']['state'] == 'FINAL' else f"Starts <t:{int(datetime.fromisoformat(start_time.replace('Z', '+00:00')).timestamp())}:R>" | |
embed.add_field( | |
name=f"Bet {i}: {league}", | |
value=( | |
f"**Team:** {team}\n" | |
f"**Amount:** ${amount}\n" | |
f"**Game:** {game_description}\n" | |
f"**Status:** {status}\n" | |
f"**Current Score:** {score}\n" | |
f"**Start Time:** <t:{int(datetime.fromisoformat(start_time.replace('Z', '+00:00')).timestamp())}:F>" | |
), | |
inline=False | |
) | |
view = discord.ui.View() | |
cancel_select = discord.ui.Select( | |
placeholder="Select a bet to cancel", | |
min_values=1, | |
max_values=1, | |
options=[ | |
discord.SelectOption(label=f"Bet {i}", value=str(i-1)) for i in range(1, len(user_bets[user_id]) + 1) | |
] | |
) | |
view.add_item(cancel_select) | |
async def cancel_callback(interaction: discord.Interaction): | |
if interaction.user.id != user_id: | |
await interaction.response.send_message("You cannot cancel other users' bets.", ephemeral=True) | |
return | |
bet_index = int(cancel_select.values[0]) | |
cancelled_bet = user_bets[user_id][bet_index] | |
league = cancelled_bet['league'] | |
game = cancelled_bet['game_data'] | |
if league == "NHL": | |
start_time = datetime.fromisoformat(game['eventTime'].replace('Z', '+00:00')) | |
elif league == "NFL": | |
start_time = datetime.fromisoformat(game['startTime'].replace('Z', '+00:00')) | |
if datetime.now(timezone.utc) >= start_time: | |
await interaction.response.send_message("You cannot cancel your bet as the game has already started.", ephemeral=True) | |
return | |
user_cash[interaction.user.id] += cancelled_bet['amount'] | |
user_bets[user_id].pop(bet_index) | |
await interaction.response.send_message(f"Bet cancelled. ${cancelled_bet['amount']} has been refunded.", ephemeral=True) | |
if not user_bets[user_id]: | |
del user_bets[user_id] | |
cancel_select.callback = cancel_callback | |
await interaction.response.send_message(embed=embed, view=view, ephemeral=True) | |
async def sportbet(interaction: discord.Interaction): | |
await show_game_selection(interaction) |