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 | |
user_bets = {} | |
API_KEY = "jE7yBJVRNAwdDesMgTzTXUUSx1It41Fq" | |
async def fetch_nfl_scores(): | |
current_year = datetime.now().year | |
for week in range(1, 18): | |
url = f"https://api.foxsports.com/bifrost/v1/nfl/scoreboard/segment/{current_year}-{week}-1?apikey={API_KEY}" | |
async with aiohttp.ClientSession() as session: | |
async with session.get(url) as response: | |
data = await response.json() | |
if data['sectionList'][0]['events'][0]['eventStatus'] == 2: | |
return data | |
return None | |
class NFLBetView(discord.ui.View): | |
def __init__(self, games): | |
super().__init__() | |
self.add_item(GameSelect(games)) | |
class GameSelect(discord.ui.Select): | |
def __init__(self, games): | |
options = [ | |
discord.SelectOption( | |
label=f"{game['upperTeam']['longName']} vs {game['lowerTeam']['longName']}", | |
value=game['id'], | |
description=f"Start time: <t:{int(datetime.fromisoformat(game['eventTime'].replace('Z', '+00:00')).timestamp())}:F>" | |
) for game in games | |
] | |
super().__init__(placeholder="Select a game to bet on", min_values=1, max_values=1, options=options) | |
self.games = {game['id']: game for game in games} | |
async def callback(self, interaction: discord.Interaction): | |
selected_game_id = self.values[0] | |
game_data = self.games.get(selected_game_id) | |
if not game_data: | |
await interaction.response.send_message("Selected game data not found.", ephemeral=True) | |
return | |
await interaction.response.edit_message(content="Select a team to bet on:", view=TeamSelect(game_data)) | |
class TeamSelect(discord.ui.View): | |
def __init__(self, game): | |
super().__init__() | |
away_team = game['upperTeam'] | |
home_team = game['lowerTeam'] | |
options = [ | |
discord.SelectOption(label=away_team['longName'], value=away_team['name']), | |
discord.SelectOption(label=home_team['longName'], value=home_team['name']) | |
] | |
self.add_item(TeamOptionSelect(options, game)) | |
class TeamOptionSelect(discord.ui.Select): | |
def __init__(self, options, game): | |
super().__init__(placeholder="Select a team to bet on", min_values=1, max_values=1, options=options) | |
self.game = game | |
async def callback(self, interaction: discord.Interaction): | |
selected_team = self.values[0] | |
await interaction.response.send_modal(BetModal(selected_team, interaction.user.id, self.game)) | |
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): | |
super().__init__() | |
self.team = team | |
self.user_id = user_id | |
self.game_data = game_data | |
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=0x787878) | |
embed.add_field(name="League", value="NFL", inline=False) | |
embed.add_field(name="Team", value=self.team, inline=False) | |
embed.add_field(name="Amount", value=f"${bet_amount}", inline=False) | |
game_description = f"{self.game_data['upperTeam']['longName']} vs {self.game_data['lowerTeam']['longName']}" | |
start_time = self.game_data['eventTime'] | |
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": "NFL", | |
"team": self.team, | |
"amount": bet_amount, | |
"game_data": self.game_data | |
}) | |
asyncio.create_task(self.monitor_game(interaction)) | |
except ValueError as e: | |
await interaction.response.send_message(str(e), ephemeral=True) | |
async def monitor_game(self, interaction): | |
previous_scores = { | |
self.game_data['upperTeam']['name']: None, | |
self.game_data['lowerTeam']['name']: None, | |
} | |
while True: | |
scores_response = await fetch_nfl_scores() | |
if not scores_response: | |
await asyncio.sleep(60) | |
continue | |
current_game = None | |
for section in scores_response.get('sectionList', []): | |
for event in section.get('events', []): | |
if event['id'] == self.game_data['id']: | |
current_game = event | |
break | |
if current_game: | |
break | |
if not current_game: | |
await asyncio.sleep(60) | |
continue | |
current_scores = { | |
current_game['upperTeam']['name']: current_game['upperTeam'].get('score'), | |
current_game['lowerTeam']['name']: current_game['lowerTeam'].get('score'), | |
} | |
score_changed = False | |
for team_name, current_score in current_scores.items(): | |
previous_score = previous_scores[team_name] | |
if previous_score is None or current_score != previous_score: | |
score_changed = True | |
previous_scores = current_scores.copy() | |
if score_changed: | |
away_score = current_scores[self.game_data['upperTeam']['name']] or 'N/A' | |
home_score = current_scores[self.game_data['lowerTeam']['name']] or 'N/A' | |
message = f"Current score update: {away_score} - {home_score}" | |
user = await interaction.client.fetch_user(self.user_id) | |
await user.send(message) | |
event_status = current_game.get('eventStatus') | |
if event_status == 3: | |
winner = self.game_data['upperTeam']['name'] if current_scores[self.game_data['upperTeam']['name']] > current_scores[self.game_data['lowerTeam']['name']] else self.game_data['lowerTeam']['name'] | |
bet_result = "won" if winner == self.team else "lost" | |
final_message = f"Game over! Final score: {away_score} - {home_score}. You {bet_result} your bet on {self.team}." | |
user = await interaction.client.fetch_user(self.user_id) | |
await user.send(final_message) | |
break | |
await asyncio.sleep(60) | |
async def nflbet(interaction: discord.Interaction): | |
scores = await fetch_nfl_scores() | |
if not scores: | |
await interaction.response.send_message("No NFL games available for betting this week.", ephemeral=True) | |
return | |
events = scores.get('sectionList', [])[0].get('events', []) | |
upcoming_games = [game for game in events if game.get('eventStatus') == 2] | |
if not upcoming_games: | |
await interaction.response.send_message("No NFL games available for betting this week.", ephemeral=True) | |
return | |
view = NFLBetView(upcoming_games) | |
await interaction.response.send_message("Select a game to bet on:", view=view, ephemeral=True) | |
async def viewbets(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=0x787878) | |
for i, bet in enumerate(user_bets[user_id], 1): | |
league = bet['league'] | |
team = bet['team'] | |
amount = bet['amount'] | |
game = bet['game_data'] | |
away_score = 'N/A' if 'score' not in game['upperTeam'] else str(game['upperTeam']['score']) | |
home_score = 'N/A' if 'score' not in game['lowerTeam'] else str(game['lowerTeam']['score']) | |
start_time = datetime.fromisoformat(game['eventTime'].replace('Z', '+00:00')) | |
current_time = datetime.now(timezone.utc) | |
if current_time < start_time: | |
status = f"Starts <t:{int(start_time.timestamp())}:R>" | |
elif 'score' in game['lowerTeam']: | |
status = 'Final' | |
winner = game['upperTeam']['name'] if game['upperTeam']['score'] > game['lowerTeam']['score'] else game['lowerTeam']['name'] | |
bet_result = "Won" if winner == team else "Lost" | |
else: | |
status = "In Progress" | |
bet_result = "Pending" | |
embed.add_field( | |
name=f"Bet {i}: {league}", | |
value=(f"**Team:** {team}\n" | |
f"**Amount:** ${amount}\n" | |
f"**Game:** {game['upperTeam']['longName']} vs {game['lowerTeam']['longName']}\n" | |
f"**Status:** {status}\n" | |
f"**Current Score:** {away_score} - {home_score}\n" | |
f"**Start Time:** <t:{int(start_time.timestamp())}:F>\n" | |
f"**Bet Result:** {bet_result}"), | |
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_cancel: discord.Interaction): | |
if interaction_cancel.user.id != user_id: | |
await interaction_cancel.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] | |
start_time = datetime.fromisoformat(cancelled_bet['game_data']['eventTime'].replace('Z', '+00:00')) | |
if datetime.now(timezone.utc) >= start_time: | |
await interaction_cancel.response.send_message("You cannot cancel your bet as the game has already started.", ephemeral=True) | |
return | |
user_cash[user_id] += cancelled_bet['amount'] | |
user_bets[user_id].pop(bet_index) | |
await interaction_cancel.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 nflbet(interaction: discord.Interaction): | |
scores = await fetch_nfl_scores() | |
if not scores: | |
await interaction.response.send_message("No NFL games available for betting this week.", ephemeral=True) | |
return | |
events = scores.get('sectionList', [])[0].get('events', []) | |
upcoming_games = [game for game in events if game.get('eventStatus') == 2] | |
if not upcoming_games: | |
await interaction.response.send_message("No NFL games available for betting this week.", ephemeral=True) | |
return | |
view = NFLBetView(upcoming_games) | |
await interaction.response.send_message("Select a game to bet on:", view=view, ephemeral=True) | |
async def viewbets(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=0x787878) | |
for i, bet in enumerate(user_bets[user_id], 1): | |
league = bet['league'] | |
team = bet['team'] | |
amount = bet['amount'] | |
game = bet['game_data'] | |
away_score = 'N/A' if 'score' not in game['upperTeam'] else str(game['upperTeam']['score']) | |
home_score = 'N/A' if 'score' not in game['lowerTeam'] else str(game['lowerTeam']['score']) | |
start_time = datetime.fromisoformat(game['eventTime'].replace('Z', '+00:00')) | |
current_time = datetime.now(timezone.utc) | |
if current_time < start_time: | |
status = f"Starts <t:{int(start_time.timestamp())}:R>" | |
elif 'score' in game['lowerTeam']: | |
status = 'Final' | |
winner = game['upperTeam']['name'] if game['upperTeam']['score'] > game['lowerTeam']['score'] else game['lowerTeam']['name'] | |
bet_result = "Won" if winner == team else "Lost" | |
else: | |
status = "In Progress" | |
bet_result = "Pending" | |
embed.add_field( | |
name=f"Bet {i}: {league}", | |
value=(f"**Team:** {team}\n" | |
f"**Amount:** ${amount}\n" | |
f"**Game:** {game['upperTeam']['longName']} vs {game['lowerTeam']['longName']}\n" | |
f"**Status:** {status}\n" | |
f"**Current Score:** {away_score} - {home_score}\n" | |
f"**Start Time:** <t:{int(start_time.timestamp())}:F>\n" | |
f"**Bet Result:** {bet_result}"), | |
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_cancel: discord.Interaction): | |
if interaction_cancel.user.id != user_id: | |
await interaction_cancel.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] | |
start_time = datetime.fromisoformat(cancelled_bet['game_data']['eventTime'].replace('Z', '+00:00')) | |
if datetime.now(timezone.utc) >= start_time: | |
await interaction_cancel.response.send_message("You cannot cancel your bet as the game has already started.", ephemeral=True) | |
return | |
user_cash[user_id] += cancelled_bet['amount'] | |
user_bets[user_id].pop(bet_index) | |
await interaction_cancel.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) |