Spaces:
Building
Building
Update sportbet.py
Browse files- sportbet.py +32 -29
sportbet.py
CHANGED
@@ -8,17 +8,20 @@ from cash import user_cash
|
|
8 |
user_bets = {}
|
9 |
|
10 |
async def fetch_nhl_scores():
|
|
|
|
|
|
|
11 |
async with aiohttp.ClientSession() as session:
|
12 |
-
async with session.get(
|
13 |
return await response.json()
|
14 |
|
15 |
class GameSelect(discord.ui.Select):
|
16 |
def __init__(self, games):
|
17 |
options = [
|
18 |
discord.SelectOption(
|
19 |
-
label=f"{game['
|
20 |
-
value=f"{game['
|
21 |
-
description=f"Start time: <t:{int(datetime.fromisoformat(game['
|
22 |
) for game in games
|
23 |
]
|
24 |
super().__init__(placeholder="Select a game", options=options)
|
@@ -26,8 +29,8 @@ class GameSelect(discord.ui.Select):
|
|
26 |
class TeamSelect(discord.ui.Select):
|
27 |
def __init__(self, away_team, home_team):
|
28 |
options = [
|
29 |
-
discord.SelectOption(label=away_team['
|
30 |
-
discord.SelectOption(label=home_team['
|
31 |
]
|
32 |
super().__init__(placeholder="Select a team to bet on", options=options)
|
33 |
|
@@ -55,8 +58,8 @@ class BetModal(discord.ui.Modal, title="Place Your Bet"):
|
|
55 |
embed = discord.Embed(title="Bet Placed", color=0x787878)
|
56 |
embed.add_field(name="Team", value=self.team, inline=False)
|
57 |
embed.add_field(name="Amount", value=f"${bet_amount}", inline=False)
|
58 |
-
embed.add_field(name="Game", value=f"{self.game_data['
|
59 |
-
embed.add_field(name="Start Time", value=f"<t:{int(datetime.fromisoformat(self.game_data['
|
60 |
await user.send(embed=embed)
|
61 |
|
62 |
if self.user_id not in user_bets:
|
@@ -72,34 +75,34 @@ class BetModal(discord.ui.Modal, title="Place Your Bet"):
|
|
72 |
await interaction.response.send_message(str(e), ephemeral=True)
|
73 |
|
74 |
async def monitor_game(self, interaction, bet_amount):
|
75 |
-
game_start = datetime.fromisoformat(self.game_data['
|
76 |
await asyncio.sleep((game_start - datetime.now(timezone.utc)).total_seconds())
|
77 |
|
78 |
user = await interaction.client.fetch_user(self.user_id)
|
79 |
await user.send(f"Your team {self.team} has started playing!")
|
80 |
|
81 |
-
previous_scores = {self.game_data['
|
82 |
|
83 |
while True:
|
84 |
scores = await fetch_nhl_scores()
|
85 |
-
game = next((g for g in scores['
|
86 |
-
g['
|
87 |
|
88 |
-
if game is None or game['
|
89 |
await asyncio.sleep(60)
|
90 |
continue
|
91 |
|
92 |
-
current_scores =
|
93 |
|
94 |
-
for team in [self.game_data['
|
95 |
if current_scores[team] > previous_scores[team]:
|
96 |
-
team_name =
|
97 |
-
await user.send(f"{team_name} SCORED! Current score: {current_scores[self.game_data['
|
98 |
|
99 |
previous_scores = current_scores.copy()
|
100 |
|
101 |
-
if game['
|
102 |
-
winner = self.game_data['
|
103 |
if winner == self.team:
|
104 |
winnings = bet_amount * 2
|
105 |
user_cash[self.user_id] += winnings
|
@@ -126,7 +129,7 @@ class SportBetView(discord.ui.View):
|
|
126 |
|
127 |
async def show_game_selection(interaction: discord.Interaction):
|
128 |
scores = await fetch_nhl_scores()
|
129 |
-
upcoming_games = [game for game in scores['
|
130 |
|
131 |
if not upcoming_games:
|
132 |
await interaction.response.send_message("No games available for betting.")
|
@@ -139,10 +142,10 @@ async def show_game_selection(interaction: discord.Interaction):
|
|
139 |
await interaction.response.send_message("Select a game to bet on:", view=view)
|
140 |
|
141 |
async def game_callback(interaction: discord.Interaction):
|
142 |
-
selected_game = next(game for game in upcoming_games if f"{game['
|
143 |
|
144 |
team_view = discord.ui.View()
|
145 |
-
team_select = TeamSelect(selected_game['
|
146 |
team_view.add_item(team_select)
|
147 |
|
148 |
await interaction.response.edit_message(content="Select a team to bet on:", view=team_view)
|
@@ -165,23 +168,23 @@ async def show_current_bets(interaction: discord.Interaction):
|
|
165 |
scores = await fetch_nhl_scores()
|
166 |
|
167 |
for i, bet in enumerate(user_bets[user_id]):
|
168 |
-
game = next((g for g in scores['
|
169 |
-
g['
|
170 |
|
171 |
-
start_time = datetime.fromisoformat(bet['game_data']['
|
172 |
current_time = datetime.now(timezone.utc)
|
173 |
|
174 |
if current_time < start_time:
|
175 |
status = f"Starts <t:{int(start_time.timestamp())}:R>"
|
176 |
score = "N/A"
|
177 |
else:
|
178 |
-
status = game['
|
179 |
-
score = f"{game
|
180 |
|
181 |
embed.add_field(name=f"Bet {i+1}", value=(
|
182 |
f"Team: {bet['team']}\n"
|
183 |
f"Amount: ${bet['amount']}\n"
|
184 |
-
f"Game: {bet['game_data']['
|
185 |
f"Status: {status}\n"
|
186 |
f"Current Score: {score}\n"
|
187 |
f"Start Time: <t:{int(start_time.timestamp())}:F>"
|
@@ -202,7 +205,7 @@ async def show_current_bets(interaction: discord.Interaction):
|
|
202 |
cancelled_bet = user_bets[user_id][bet_index]
|
203 |
game = cancelled_bet['game_data']
|
204 |
current_time = datetime.now(timezone.utc)
|
205 |
-
game_start = datetime.fromisoformat(game['
|
206 |
|
207 |
if current_time >= game_start:
|
208 |
await interaction.response.send_message("You cannot cancel your bet as the game has already started.", ephemeral=True)
|
|
|
8 |
user_bets = {}
|
9 |
|
10 |
async def fetch_nhl_scores():
|
11 |
+
today = datetime.now().strftime('%Y%m%d')
|
12 |
+
api_key = "jE7yBJVRNAwdDesMgTzTXUUSx1It41Fq"
|
13 |
+
url = f"https://api.foxsports.com/bifrost/v1/nhl/scoreboard/segment/{today}?apikey={api_key}"
|
14 |
async with aiohttp.ClientSession() as session:
|
15 |
+
async with session.get(url) as response:
|
16 |
return await response.json()
|
17 |
|
18 |
class GameSelect(discord.ui.Select):
|
19 |
def __init__(self, games):
|
20 |
options = [
|
21 |
discord.SelectOption(
|
22 |
+
label=f"{game['lowerTeam']['longName']} vs {game['upperTeam']['longName']}",
|
23 |
+
value=f"{game['lowerTeam']['name']}_{game['upperTeam']['name']}",
|
24 |
+
description=f"Start time: <t:{int(datetime.fromisoformat(game['eventTime'].replace('Z', '+00:00')).timestamp())}:R>"
|
25 |
) for game in games
|
26 |
]
|
27 |
super().__init__(placeholder="Select a game", options=options)
|
|
|
29 |
class TeamSelect(discord.ui.Select):
|
30 |
def __init__(self, away_team, home_team):
|
31 |
options = [
|
32 |
+
discord.SelectOption(label=away_team['longName'], value=away_team['name']),
|
33 |
+
discord.SelectOption(label=home_team['longName'], value=home_team['name'])
|
34 |
]
|
35 |
super().__init__(placeholder="Select a team to bet on", options=options)
|
36 |
|
|
|
58 |
embed = discord.Embed(title="Bet Placed", color=0x787878)
|
59 |
embed.add_field(name="Team", value=self.team, inline=False)
|
60 |
embed.add_field(name="Amount", value=f"${bet_amount}", inline=False)
|
61 |
+
embed.add_field(name="Game", value=f"{self.game_data['lowerTeam']['longName']} vs {self.game_data['upperTeam']['longName']}", inline=False)
|
62 |
+
embed.add_field(name="Start Time", value=f"<t:{int(datetime.fromisoformat(self.game_data['eventTime'].replace('Z', '+00:00')).timestamp())}:F>", inline=False)
|
63 |
await user.send(embed=embed)
|
64 |
|
65 |
if self.user_id not in user_bets:
|
|
|
75 |
await interaction.response.send_message(str(e), ephemeral=True)
|
76 |
|
77 |
async def monitor_game(self, interaction, bet_amount):
|
78 |
+
game_start = datetime.fromisoformat(self.game_data['eventTime'].replace('Z', '+00:00'))
|
79 |
await asyncio.sleep((game_start - datetime.now(timezone.utc)).total_seconds())
|
80 |
|
81 |
user = await interaction.client.fetch_user(self.user_id)
|
82 |
await user.send(f"Your team {self.team} has started playing!")
|
83 |
|
84 |
+
previous_scores = {self.game_data['lowerTeam']['name']: 0, self.game_data['upperTeam']['name']: 0}
|
85 |
|
86 |
while True:
|
87 |
scores = await fetch_nhl_scores()
|
88 |
+
game = next((g for g in scores['sectionList'][0]['events'] if g['lowerTeam']['name'] == self.game_data['lowerTeam']['name'] and
|
89 |
+
g['upperTeam']['name'] == self.game_data['upperTeam']['name']), None)
|
90 |
|
91 |
+
if game is None or game['eventStatus'] == 'PREVIEW':
|
92 |
await asyncio.sleep(60)
|
93 |
continue
|
94 |
|
95 |
+
current_scores = {g['lowerTeam']['name']: g.get('score', 0), g['upperTeam']['name']: g.get('score', 0)}
|
96 |
|
97 |
+
for team in [self.game_data['lowerTeam']['name'], self.game_data['upperTeam']['name']]:
|
98 |
if current_scores[team] > previous_scores[team]:
|
99 |
+
team_name = self.game_data['lowerTeam']['longName'] if team == self.game_data['lowerTeam']['name'] else self.game_data['upperTeam']['longName']
|
100 |
+
await user.send(f"{team_name} SCORED! Current score: {current_scores[self.game_data['lowerTeam']['name']]} - {current_scores[self.game_data['upperTeam']['name']]}")
|
101 |
|
102 |
previous_scores = current_scores.copy()
|
103 |
|
104 |
+
if game['eventStatus'] == 'FINAL':
|
105 |
+
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']
|
106 |
if winner == self.team:
|
107 |
winnings = bet_amount * 2
|
108 |
user_cash[self.user_id] += winnings
|
|
|
129 |
|
130 |
async def show_game_selection(interaction: discord.Interaction):
|
131 |
scores = await fetch_nhl_scores()
|
132 |
+
upcoming_games = [game for game in scores['sectionList'][0]['events'] if game['eventStatus'] == 'PREVIEW']
|
133 |
|
134 |
if not upcoming_games:
|
135 |
await interaction.response.send_message("No games available for betting.")
|
|
|
142 |
await interaction.response.send_message("Select a game to bet on:", view=view)
|
143 |
|
144 |
async def game_callback(interaction: discord.Interaction):
|
145 |
+
selected_game = next(game for game in upcoming_games if f"{game['lowerTeam']['name']}_{game['upperTeam']['name']}" == game_select.values[0])
|
146 |
|
147 |
team_view = discord.ui.View()
|
148 |
+
team_select = TeamSelect(selected_game['lowerTeam'], selected_game['upperTeam'])
|
149 |
team_view.add_item(team_select)
|
150 |
|
151 |
await interaction.response.edit_message(content="Select a team to bet on:", view=team_view)
|
|
|
168 |
scores = await fetch_nhl_scores()
|
169 |
|
170 |
for i, bet in enumerate(user_bets[user_id]):
|
171 |
+
game = next((g for g in scores['sectionList'][0]['events'] if g['lowerTeam']['name'] == bet['game_data']['lowerTeam']['name'] and
|
172 |
+
g['upperTeam']['name'] == bet['game_data']['upperTeam']['name']), None)
|
173 |
|
174 |
+
start_time = datetime.fromisoformat(bet['game_data']['eventTime'].replace('Z', '+00:00'))
|
175 |
current_time = datetime.now(timezone.utc)
|
176 |
|
177 |
if current_time < start_time:
|
178 |
status = f"Starts <t:{int(start_time.timestamp())}:R>"
|
179 |
score = "N/A"
|
180 |
else:
|
181 |
+
status = game['eventStatus'] if game else "Unknown"
|
182 |
+
score = f"{game.get('lowerTeam', {}).get('score', 'Unknown')} - {game.get('upperTeam', {}).get('score', 'Unknown')}" if game else "Unknown"
|
183 |
|
184 |
embed.add_field(name=f"Bet {i+1}", value=(
|
185 |
f"Team: {bet['team']}\n"
|
186 |
f"Amount: ${bet['amount']}\n"
|
187 |
+
f"Game: {bet['game_data']['lowerTeam']['longName']} vs {bet['game_data']['upperTeam']['longName']}\n"
|
188 |
f"Status: {status}\n"
|
189 |
f"Current Score: {score}\n"
|
190 |
f"Start Time: <t:{int(start_time.timestamp())}:F>"
|
|
|
205 |
cancelled_bet = user_bets[user_id][bet_index]
|
206 |
game = cancelled_bet['game_data']
|
207 |
current_time = datetime.now(timezone.utc)
|
208 |
+
game_start = datetime.fromisoformat(game['eventTime'].replace('Z', '+00:00'))
|
209 |
|
210 |
if current_time >= game_start:
|
211 |
await interaction.response.send_message("You cannot cancel your bet as the game has already started.", ephemeral=True)
|