coollsd commited on
Commit
87c1a2c
·
verified ·
1 Parent(s): 94166cb

Update sportbet.py

Browse files
Files changed (1) hide show
  1. sportbet.py +159 -127
sportbet.py CHANGED
@@ -16,7 +16,7 @@ def get_current_nfl_week():
16
  """
17
  # Example start date for NFL Week 1
18
  start_date = datetime(2024, 9, 6) # Adjust this date to the actual start of the NFL season
19
- today = datetime.now()
20
  delta_days = (today.date() - start_date.date()).days
21
  week_number = (delta_days // 7) + 1
22
  if week_number < 1:
@@ -30,9 +30,8 @@ async def fetch_nhl_scores():
30
  async with session.get(url) as response:
31
  return await response.json()
32
 
33
- async def fetch_nfl_scores():
34
- current_week = get_current_nfl_week()
35
- url = f"https://api.foxsports.com/bifrost/v1/nfl/scoreboard/segment/2024-{current_week}-1?apikey={API_KEY}"
36
  async with aiohttp.ClientSession() as session:
37
  async with session.get(url) as response:
38
  return await response.json()
@@ -45,58 +44,101 @@ class SportSelect(discord.ui.Select):
45
  ]
46
  super().__init__(placeholder="Select a sport to bet on", min_values=1, max_values=1, options=options)
47
 
48
- class GameSelect(discord.ui.Select):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49
  def __init__(self, games, league):
50
- options = [
51
- discord.SelectOption(
52
- label=f"{game['lowerTeam']['longName']} vs {game['upperTeam']['longName']}" if league == "NHL" else f"{game['teams']['away']['teamName']} vs {game['teams']['home']['teamName']}",
53
- value=f"{game['lowerTeam']['name']}_{game['upperTeam']['name']}" if league == "NHL" else f"{game['teams']['away']['abbreviation']}_{game['teams']['home']['abbreviation']}",
54
- description=f"Start time: <t:{int(datetime.fromisoformat(game['eventTime'].replace('Z', '+00:00')).timestamp())}:R>"
55
- ) for game in games
56
- ]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
57
  super().__init__(placeholder="Select a game", min_values=1, max_values=1, options=options)
58
  self.league = league
59
  self.games = games
60
 
61
  async def callback(self, interaction: discord.Interaction):
62
- selected_value = self.values[0]
63
- if self.league == "NHL":
64
- selected_game = next(game for game in self.games if f"{game['lowerTeam']['name']}_{game['upperTeam']['name']}" == selected_value)
65
- await interaction.response.edit_message(content="Select a team to bet on:", view=TeamSelect(selected_game, self.league))
66
- elif self.league == "NFL":
67
- selected_game = next(game for game in self.games if f"{game['teams']['away']['abbreviation']}_{game['teams']['home']['abbreviation']}" == selected_value)
68
- await interaction.response.edit_message(content="Select a team to bet on:", view=TeamSelect(selected_game, self.league))
 
 
69
 
70
  class TeamSelect(discord.ui.View):
71
  def __init__(self, game, league):
72
  super().__init__()
73
  self.league = league
74
- if league == "NHL":
75
  away_team = game['lowerTeam']
76
  home_team = game['upperTeam']
77
- elif league == "NFL":
78
- away_team = game['teams']['away']
79
- home_team = game['teams']['home']
80
- self.add_item(TeamOptionSelect(away_team, home_team, league))
 
 
 
 
 
 
 
 
 
81
 
82
  class TeamOptionSelect(discord.ui.Select):
83
- def __init__(self, away_team, home_team, league):
84
- options = [
85
- discord.SelectOption(label=away_team['longName'] if league == "NHL" else away_team['teamName'], value=away_team['name'] if league == "NHL" else away_team['abbreviation']),
86
- discord.SelectOption(label=home_team['longName'] if league == "NHL" else home_team['teamName'], value=home_team['name'] if league == "NHL" else home_team['abbreviation'])
87
- ]
88
  super().__init__(placeholder="Select a team to bet on", min_values=1, max_values=1, options=options)
89
  self.league = league
90
- self.game = None
91
 
92
  async def callback(self, interaction: discord.Interaction):
93
  selected_team = self.values[0]
94
- view = self.view # Access the parent view
95
- if self.league == "NHL":
96
- selected_game = next(game for game in view.games if f"{game['lowerTeam']['name']}_{game['upperTeam']['name']}" == view.children[0].values[0])
97
- elif self.league == "NFL":
98
- selected_game = next(game for game in view.games if f"{game['teams']['away']['abbreviation']}_{game['teams']['home']['abbreviation']}" == view.children[0].values[0])
99
- await interaction.response.send_modal(BetModal(selected_team, interaction.user.id, selected_game, self.league))
100
 
101
  class BetModal(discord.ui.Modal, title="Place Your Bet"):
102
  bet_amount = discord.ui.TextInput(label="Bet Amount", placeholder="Enter bet amount", required=True)
@@ -117,7 +159,7 @@ class BetModal(discord.ui.Modal, title="Place Your Bet"):
117
  raise ValueError("Insufficient balance. Please check your balance and try again.")
118
 
119
  user_cash[self.user_id] -= bet_amount
120
- await interaction.response.send_message(f"Bet placed on {self.team} for ${bet_amount}.", ephemeral=True)
121
 
122
  user = await interaction.client.fetch_user(self.user_id)
123
  embed = discord.Embed(title="Bet Placed", color=0x00ff00)
@@ -128,8 +170,8 @@ class BetModal(discord.ui.Modal, title="Place Your Bet"):
128
  game_description = f"{self.game_data['lowerTeam']['longName']} vs {self.game_data['upperTeam']['longName']}"
129
  start_time = self.game_data['eventTime']
130
  elif self.league == "NFL":
131
- game_description = f"{self.game_data['teams']['away']['teamName']} vs {self.game_data['teams']['home']['teamName']}"
132
- start_time = self.game_data['startTime']
133
  embed.add_field(name="Game", value=game_description, inline=False)
134
  embed.add_field(name="Start Time", value=f"<t:{int(datetime.fromisoformat(start_time.replace('Z', '+00:00')).timestamp())}:F>", inline=False)
135
  await user.send(embed=embed)
@@ -150,58 +192,83 @@ class BetModal(discord.ui.Modal, title="Place Your Bet"):
150
  async def monitor_game(self, interaction, bet_amount):
151
  if self.league == "NHL":
152
  game_start = datetime.fromisoformat(self.game_data['eventTime'].replace('Z', '+00:00'))
 
 
153
  elif self.league == "NFL":
154
- game_start = datetime.fromisoformat(self.game_data['startTime'].replace('Z', '+00:00'))
 
 
 
155
  sleep_duration = (game_start - datetime.now(timezone.utc)).total_seconds()
156
  if sleep_duration > 0:
157
  await asyncio.sleep(sleep_duration)
158
 
159
  user = await interaction.client.fetch_user(self.user_id)
160
- await user.send(f"Your team {self.team} has started playing!")
161
 
162
  previous_scores = {}
163
  if self.league == "NHL":
164
- previous_scores = {self.game_data['lowerTeam']['name']: 0, self.game_data['upperTeam']['name']: 0}
 
 
 
165
  elif self.league == "NFL":
166
- previous_scores = {self.game_data['teams']['away']['abbreviation']: 0, self.game_data['teams']['home']['abbreviation']: 0}
 
 
 
167
 
168
  while True:
 
169
  if self.league == "NHL":
170
- scores = await fetch_nhl_scores()
171
- events = scores.get('sectionList', [])[0].get('events', [])
172
- game = next((g for g in events if g['lowerTeam']['name'] == self.game_data['lowerTeam']['name'] and
173
- g['upperTeam']['name'] == self.game_data['upperTeam']['name']), None)
174
- elif self.league == "NFL":
175
- scores = await fetch_nfl_scores()
176
- events = scores.get('sectionList', [])[0].get('events', [])
177
- game = next((g for g in events if g['teams']['away']['abbreviation'] == self.game_data['teams']['away']['abbreviation'] and
178
- g['teams']['home']['abbreviation'] == self.game_data['teams']['home']['abbreviation']), None)
179
-
180
- if game is None:
181
- await asyncio.sleep(60)
182
- continue
183
-
184
- if self.league == "NHL":
185
- event_status = game.get('eventStatus', 2) # Default to 2 if not present
186
  current_scores = {
187
- game['lowerTeam']['name']: game.get('score', 0),
188
- game['upperTeam']['name']: game.get('score', 0)
189
  }
190
  is_final = event_status == 3
191
  elif self.league == "NFL":
192
- event_status = game.get('status', {}).get('state', 'PREVIEW')
193
- current_scores = game.get('scores', {})
194
- is_final = event_status == 'FINAL'
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
195
 
 
196
  for team, score in current_scores.items():
197
  if score > previous_scores.get(team, 0):
 
198
  if self.league == "NHL":
199
  team_name = self.game_data['lowerTeam']['longName'] if team == self.game_data['lowerTeam']['name'] else self.game_data['upperTeam']['longName']
200
- message = f"{team_name} SCORED! Current score: {current_scores[self.game_data['lowerTeam']['name']]} - {current_scores[self.game_data['upperTeam']['name']]}"
201
  elif self.league == "NFL":
202
- team_name = self.game_data['teams']['away']['teamName'] if team == self.game_data['teams']['away']['abbreviation'] else self.game_data['teams']['home']['teamName']
203
- opponent = self.game_data['teams']['home']['teamName'] if team == self.game_data['teams']['away']['abbreviation'] else self.game_data['teams']['away']['teamName']
204
- 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)}"
205
  await user.send(message)
206
 
207
  previous_scores = current_scores.copy()
@@ -210,18 +277,19 @@ class BetModal(discord.ui.Modal, title="Place Your Bet"):
210
  if self.league == "NHL":
211
  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']
212
  elif self.league == "NFL":
213
- away_score = current_scores.get(self.game_data['teams']['away']['abbreviation'], 0)
214
- home_score = current_scores.get(self.game_data['teams']['home']['abbreviation'], 0)
215
- winner = self.game_data['teams']['away']['abbreviation'] if away_score > home_score else self.game_data['teams']['home']['abbreviation']
216
 
217
  if winner == self.team:
218
  winnings = bet_amount * 2
219
  user_cash[self.user_id] += winnings
220
- await user.send(f"Congratulations! Your team won. You won ${winnings}!")
221
  else:
222
- await user.send(f"Sorry, your team lost. Better luck next time!")
223
 
224
- user_bets[self.user_id] = [bet for bet in user_bets[self.user_id] if bet['game_data'] != self.game_data]
 
225
  break
226
 
227
  await asyncio.sleep(60) # Check every minute
@@ -235,43 +303,6 @@ class SportBetView(discord.ui.View):
235
  async def view_bets(self, interaction: discord.Interaction, button: discord.ui.Button):
236
  await show_current_bets(interaction)
237
 
238
- async def show_game_selection(interaction: discord.Interaction):
239
- view = SportBetView()
240
- await interaction.response.send_message("Select a sport to bet on:", view=view, ephemeral=True)
241
-
242
- class SportSelectView(discord.ui.View):
243
- def __init__(self):
244
- super().__init__()
245
- self.add_item(SportSelect())
246
-
247
- class SportSelect(discord.ui.Select):
248
- def __init__(self):
249
- options = [
250
- discord.SelectOption(label="NHL", description="Bet on NHL games"),
251
- discord.SelectOption(label="NFL", description="Bet on NFL games")
252
- ]
253
- super().__init__(placeholder="Select a sport to bet on", min_values=1, max_values=1, options=options)
254
-
255
- async def callback(self, interaction: discord.Interaction):
256
- selected_sport = self.values[0]
257
- if selected_sport == "NHL":
258
- scores = await fetch_nhl_scores()
259
- events = scores.get('sectionList', [])[0].get('events', [])
260
- upcoming_games = [game for game in events if game['eventStatus'] == 2]
261
- elif selected_sport == "NFL":
262
- scores = await fetch_nfl_scores()
263
- events = scores.get('sectionList', [])[0].get('events', [])
264
- upcoming_games = [game for game in events if game['status']['state'] == 'PREVIEW']
265
-
266
- if not upcoming_games:
267
- await interaction.response.edit_message(content="No games available for betting.", view=None)
268
- return
269
-
270
- view = discord.ui.View()
271
- game_select = GameSelect(upcoming_games, selected_sport)
272
- view.add_item(game_select)
273
- await interaction.response.edit_message(content="Select a game to bet on:", view=view)
274
-
275
  async def show_current_bets(interaction: discord.Interaction):
276
  user_id = interaction.user.id
277
  if user_id not in user_bets or not user_bets[user_id]:
@@ -283,18 +314,17 @@ async def show_current_bets(interaction: discord.Interaction):
283
  league = bet['league']
284
  team = bet['team']
285
  amount = bet['amount']
 
286
  if league == "NHL":
287
- game = bet['game_data']
288
  game_description = f"{game['lowerTeam']['longName']} vs {game['upperTeam']['longName']}"
289
  start_time = game['eventTime']
290
- score = f"{game.get('lowerTeam', {}).get('score', 'N/A')} - {game.get('upperTeam', {}).get('score', 'N/A')}" if game.get('score') else "N/A"
291
- status = "Final" if game.get('score') else f"Starts <t:{int(datetime.fromisoformat(start_time.replace('Z', '+00:00')).timestamp())}:R>"
292
  elif league == "NFL":
293
- game = bet['game_data']
294
- game_description = f"{game['teams']['away']['teamName']} vs {game['teams']['home']['teamName']}"
295
- start_time = game['startTime']
296
- 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"
297
- status = "Final" if game['status']['state'] == 'FINAL' else f"Starts <t:{int(datetime.fromisoformat(start_time.replace('Z', '+00:00')).timestamp())}:R>"
298
 
299
  embed.add_field(
300
  name=f"Bet {i}: {league}",
@@ -320,9 +350,9 @@ async def show_current_bets(interaction: discord.Interaction):
320
  )
321
  view.add_item(cancel_select)
322
 
323
- async def cancel_callback(interaction: discord.Interaction):
324
- if interaction.user.id != user_id:
325
- await interaction.response.send_message("You cannot cancel other users' bets.", ephemeral=True)
326
  return
327
 
328
  bet_index = int(cancel_select.values[0])
@@ -332,21 +362,23 @@ async def show_current_bets(interaction: discord.Interaction):
332
  if league == "NHL":
333
  start_time = datetime.fromisoformat(game['eventTime'].replace('Z', '+00:00'))
334
  elif league == "NFL":
335
- start_time = datetime.fromisoformat(game['startTime'].replace('Z', '+00:00'))
336
 
337
  if datetime.now(timezone.utc) >= start_time:
338
- await interaction.response.send_message("You cannot cancel your bet as the game has already started.", ephemeral=True)
339
  return
340
 
341
- user_cash[interaction.user.id] += cancelled_bet['amount']
342
  user_bets[user_id].pop(bet_index)
343
- await interaction.response.send_message(f"Bet cancelled. ${cancelled_bet['amount']} has been refunded.", ephemeral=True)
344
  if not user_bets[user_id]:
345
  del user_bets[user_id]
346
 
347
  cancel_select.callback = cancel_callback
 
348
  await interaction.response.send_message(embed=embed, view=view, ephemeral=True)
349
 
350
  @app_commands.command(name="sportbet", description="Bet on sports games")
351
  async def sportbet(interaction: discord.Interaction):
352
- await show_game_selection(interaction)
 
 
16
  """
17
  # Example start date for NFL Week 1
18
  start_date = datetime(2024, 9, 6) # Adjust this date to the actual start of the NFL season
19
+ today = datetime.now(timezone.utc)
20
  delta_days = (today.date() - start_date.date()).days
21
  week_number = (delta_days // 7) + 1
22
  if week_number < 1:
 
30
  async with session.get(url) as response:
31
  return await response.json()
32
 
33
+ async def fetch_nfl_scores(week_number):
34
+ url = f"https://api.foxsports.com/bifrost/v1/nfl/scoreboard/segment/2024-{week_number}-1?apikey={API_KEY}"
 
35
  async with aiohttp.ClientSession() as session:
36
  async with session.get(url) as response:
37
  return await response.json()
 
44
  ]
45
  super().__init__(placeholder="Select a sport to bet on", min_values=1, max_values=1, options=options)
46
 
47
+ async def callback(self, interaction: discord.Interaction):
48
+ selected_sport = self.values[0]
49
+ await interaction.response.edit_message(content=f"Selected Sport: {selected_sport}. Fetching games...", view=None)
50
+ await asyncio.sleep(1) # Brief pause for better UX
51
+
52
+ if selected_sport == "NHL":
53
+ scores = await fetch_nhl_scores()
54
+ events = scores.get('sectionList', [])[0].get('events', [])
55
+ upcoming_games = [game for game in events if game.get('eventStatus') == 2]
56
+ if not upcoming_games:
57
+ await interaction.followup.send("No NHL games available for betting today.", ephemeral=True)
58
+ return
59
+ view = GameSelect(upcoming_games, "NHL")
60
+ await interaction.followup.send("Select a game to bet on:", view=view, ephemeral=True)
61
+ elif selected_sport == "NFL":
62
+ current_week = get_current_nfl_week()
63
+ scores = await fetch_nfl_scores(current_week)
64
+ events = scores.get('sectionList', [])[0].get('events', [])
65
+ upcoming_games = [game for game in events if game.get('eventStatus') == 2]
66
+ if not upcoming_games:
67
+ await interaction.followup.send("No NFL games available for betting this week.", ephemeral=True)
68
+ return
69
+ view = GameSelect(upcoming_games, "NFL")
70
+ await interaction.followup.send(f"Select a game to bet on for Week {current_week}:", view=view, ephemeral=True)
71
+
72
+ class GameSelect(discord.ui.View):
73
  def __init__(self, games, league):
74
+ super().__init__()
75
+ self.league = league
76
+ if self.league == "NHL":
77
+ options = [
78
+ discord.SelectOption(
79
+ label=f"{game['lowerTeam']['longName']} vs {game['upperTeam']['longName']}",
80
+ value=game['id'],
81
+ description=f"Start time: <t:{int(datetime.fromisoformat(game['eventTime'].replace('Z', '+00:00')).timestamp())}:F>"
82
+ ) for game in games
83
+ ]
84
+ elif self.league == "NFL":
85
+ options = [
86
+ discord.SelectOption(
87
+ label=f"{game['lowerTeam']['longName']} vs {game['upperTeam']['longName']}",
88
+ value=game['id'],
89
+ description=f"Start time: <t:{int(datetime.fromisoformat(game['eventTime'].replace('Z', '+00:00')).timestamp())}:F>"
90
+ ) for game in games
91
+ ]
92
+ self.games = {game['id']: game for game in games}
93
+ self.add_item(GameOptionSelect(options, self.league, self.games))
94
+
95
+ class GameOptionSelect(discord.ui.Select):
96
+ def __init__(self, options, league, games):
97
  super().__init__(placeholder="Select a game", min_values=1, max_values=1, options=options)
98
  self.league = league
99
  self.games = games
100
 
101
  async def callback(self, interaction: discord.Interaction):
102
+ selected_game_id = self.values[0]
103
+ game_data = self.games.get(selected_game_id)
104
+ if not game_data:
105
+ await interaction.response.send_message("Selected game data not found.", ephemeral=True)
106
+ return
107
+ await interaction.response.edit_message(content="Select a team to bet on:", view=None)
108
+ await asyncio.sleep(1) # Brief pause for better UX
109
+ view = TeamSelect(game_data, self.league)
110
+ await interaction.followup.send("Select a team to bet on:", view=view, ephemeral=True)
111
 
112
  class TeamSelect(discord.ui.View):
113
  def __init__(self, game, league):
114
  super().__init__()
115
  self.league = league
116
+ if self.league == "NHL":
117
  away_team = game['lowerTeam']
118
  home_team = game['upperTeam']
119
+ options = [
120
+ discord.SelectOption(label=away_team['longName'], value=away_team['name']),
121
+ discord.SelectOption(label=home_team['longName'], value=home_team['name'])
122
+ ]
123
+ elif self.league == "NFL":
124
+ away_team = game['lowerTeam']
125
+ home_team = game['upperTeam']
126
+ options = [
127
+ discord.SelectOption(label=away_team['longName'], value=away_team['name']),
128
+ discord.SelectOption(label=home_team['longName'], value=home_team['name'])
129
+ ]
130
+ self.game = game
131
+ self.add_item(TeamOptionSelect(options, league, game))
132
 
133
  class TeamOptionSelect(discord.ui.Select):
134
+ def __init__(self, options, league, game):
 
 
 
 
135
  super().__init__(placeholder="Select a team to bet on", min_values=1, max_values=1, options=options)
136
  self.league = league
137
+ self.game = game
138
 
139
  async def callback(self, interaction: discord.Interaction):
140
  selected_team = self.values[0]
141
+ await interaction.response.send_modal(BetModal(selected_team, interaction.user.id, self.game, self.league))
 
 
 
 
 
142
 
143
  class BetModal(discord.ui.Modal, title="Place Your Bet"):
144
  bet_amount = discord.ui.TextInput(label="Bet Amount", placeholder="Enter bet amount", required=True)
 
159
  raise ValueError("Insufficient balance. Please check your balance and try again.")
160
 
161
  user_cash[self.user_id] -= bet_amount
162
+ await interaction.response.send_message(f"Bet placed on **{self.team}** for **${bet_amount}**.", ephemeral=True)
163
 
164
  user = await interaction.client.fetch_user(self.user_id)
165
  embed = discord.Embed(title="Bet Placed", color=0x00ff00)
 
170
  game_description = f"{self.game_data['lowerTeam']['longName']} vs {self.game_data['upperTeam']['longName']}"
171
  start_time = self.game_data['eventTime']
172
  elif self.league == "NFL":
173
+ game_description = f"{self.game_data['lowerTeam']['longName']} vs {self.game_data['upperTeam']['longName']}"
174
+ start_time = self.game_data['eventTime']
175
  embed.add_field(name="Game", value=game_description, inline=False)
176
  embed.add_field(name="Start Time", value=f"<t:{int(datetime.fromisoformat(start_time.replace('Z', '+00:00')).timestamp())}:F>", inline=False)
177
  await user.send(embed=embed)
 
192
  async def monitor_game(self, interaction, bet_amount):
193
  if self.league == "NHL":
194
  game_start = datetime.fromisoformat(self.game_data['eventTime'].replace('Z', '+00:00'))
195
+ event_id = self.game_data['id']
196
+ fetch_scores = fetch_nhl_scores
197
  elif self.league == "NFL":
198
+ game_start = datetime.fromisoformat(self.game_data['eventTime'].replace('Z', '+00:00'))
199
+ event_id = self.game_data['id']
200
+ fetch_scores = lambda: fetch_nfl_scores(get_current_nfl_week())
201
+
202
  sleep_duration = (game_start - datetime.now(timezone.utc)).total_seconds()
203
  if sleep_duration > 0:
204
  await asyncio.sleep(sleep_duration)
205
 
206
  user = await interaction.client.fetch_user(self.user_id)
207
+ await user.send(f"Your team **{self.team}** has started playing!")
208
 
209
  previous_scores = {}
210
  if self.league == "NHL":
211
+ previous_scores = {
212
+ self.game_data['lowerTeam']['name']: self.game_data.get('lowerTeam', {}).get('score', 0),
213
+ self.game_data['upperTeam']['name']: self.game_data.get('upperTeam', {}).get('score', 0)
214
+ }
215
  elif self.league == "NFL":
216
+ previous_scores = {
217
+ self.game_data['lowerTeam']['name']: self.game_data.get('lowerTeam', {}).get('score', 0),
218
+ self.game_data['upperTeam']['name']: self.game_data.get('upperTeam', {}).get('score', 0)
219
+ }
220
 
221
  while True:
222
+ scores = await fetch_scores()
223
  if self.league == "NHL":
224
+ sections = scores.get('sectionList', [])
225
+ game = None
226
+ for section in sections:
227
+ for evt in section.get('events', []):
228
+ if evt['id'] == event_id:
229
+ game = evt
230
+ break
231
+ if game:
232
+ break
233
+ if not game:
234
+ await asyncio.sleep(60)
235
+ continue
236
+ event_status = game.get('eventStatus', 2)
 
 
 
237
  current_scores = {
238
+ game['lowerTeam']['name']: game.get('lowerTeam', {}).get('score', 0),
239
+ game['upperTeam']['name']: game.get('upperTeam', {}).get('score', 0)
240
  }
241
  is_final = event_status == 3
242
  elif self.league == "NFL":
243
+ sections = scores.get('sectionList', [])
244
+ game = None
245
+ for section in sections:
246
+ for evt in section.get('events', []):
247
+ if evt['id'] == event_id:
248
+ game = evt
249
+ break
250
+ if game:
251
+ break
252
+ if not game:
253
+ await asyncio.sleep(60)
254
+ continue
255
+ event_status = game.get('eventStatus', 2)
256
+ current_scores = {
257
+ game['lowerTeam']['name']: game['lowerTeam'].get('score', 0),
258
+ game['upperTeam']['name']: game['upperTeam'].get('score', 0)
259
+ }
260
+ is_final = event_status == 3
261
 
262
+ # Check for score updates
263
  for team, score in current_scores.items():
264
  if score > previous_scores.get(team, 0):
265
+ team_name = self.team
266
  if self.league == "NHL":
267
  team_name = self.game_data['lowerTeam']['longName'] if team == self.game_data['lowerTeam']['name'] else self.game_data['upperTeam']['longName']
268
+ message = f"**{team_name}** SCORED! Current score: {current_scores[self.game_data['lowerTeam']['name']]} - {current_scores[self.game_data['upperTeam']['name']]}"
269
  elif self.league == "NFL":
270
+ team_name = self.game_data['lowerTeam']['longName'] if team == self.game_data['lowerTeam']['name'] else self.game_data['upperTeam']['longName']
271
+ message = f"**{team_name}** SCORED! Current score: {current_scores[self.game_data['lowerTeam']['name']]} - {current_scores[self.game_data['upperTeam']['name']]}"
 
272
  await user.send(message)
273
 
274
  previous_scores = current_scores.copy()
 
277
  if self.league == "NHL":
278
  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']
279
  elif self.league == "NFL":
280
+ away_score = current_scores.get(self.game_data['lowerTeam']['name'], 0)
281
+ home_score = current_scores.get(self.game_data['upperTeam']['name'], 0)
282
+ winner = self.game_data['lowerTeam']['name'] if away_score > home_score else self.game_data['upperTeam']['name']
283
 
284
  if winner == self.team:
285
  winnings = bet_amount * 2
286
  user_cash[self.user_id] += winnings
287
+ await user.send(f"🎉 **Congratulations!** Your team **{self.team}** won! You won **${winnings}**!")
288
  else:
289
+ await user.send(f"😞 **Sorry!** Your team **{self.team}** lost. Better luck next time!")
290
 
291
+ # Remove the completed bet
292
+ user_bets[self.user_id] = [bet for bet in user_bets[self.user_id] if not (bet['league'] == self.league and bet['team'] == self.team and bet['game_data']['id'] == event_id)]
293
  break
294
 
295
  await asyncio.sleep(60) # Check every minute
 
303
  async def view_bets(self, interaction: discord.Interaction, button: discord.ui.Button):
304
  await show_current_bets(interaction)
305
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
306
  async def show_current_bets(interaction: discord.Interaction):
307
  user_id = interaction.user.id
308
  if user_id not in user_bets or not user_bets[user_id]:
 
314
  league = bet['league']
315
  team = bet['team']
316
  amount = bet['amount']
317
+ game = bet['game_data']
318
  if league == "NHL":
 
319
  game_description = f"{game['lowerTeam']['longName']} vs {game['upperTeam']['longName']}"
320
  start_time = game['eventTime']
321
+ score = f"{game['lowerTeam'].get('score', 'N/A')} - {game['upperTeam'].get('score', 'N/A')}"
322
+ status = "Final" if game.get('upperTeam', {}).get('score') is not None else f"Starts <t:{int(datetime.fromisoformat(start_time.replace('Z', '+00:00')).timestamp())}:R>"
323
  elif league == "NFL":
324
+ game_description = f"{game['lowerTeam']['longName']} vs {game['upperTeam']['longName']}"
325
+ start_time = game['eventTime']
326
+ score = f"{game['lowerTeam'].get('score', 'N/A')} - {game['upperTeam'].get('score', 'N/A')}"
327
+ status = "Final" if game.get('upperTeam', {}).get('score') is not None else f"Starts <t:{int(datetime.fromisoformat(start_time.replace('Z', '+00:00')).timestamp())}:R>"
 
328
 
329
  embed.add_field(
330
  name=f"Bet {i}: {league}",
 
350
  )
351
  view.add_item(cancel_select)
352
 
353
+ async def cancel_callback(interaction_cancel: discord.Interaction):
354
+ if interaction_cancel.user.id != user_id:
355
+ await interaction_cancel.response.send_message("You cannot cancel other users' bets.", ephemeral=True)
356
  return
357
 
358
  bet_index = int(cancel_select.values[0])
 
362
  if league == "NHL":
363
  start_time = datetime.fromisoformat(game['eventTime'].replace('Z', '+00:00'))
364
  elif league == "NFL":
365
+ start_time = datetime.fromisoformat(game['eventTime'].replace('Z', '+00:00'))
366
 
367
  if datetime.now(timezone.utc) >= start_time:
368
+ await interaction_cancel.response.send_message("You cannot cancel your bet as the game has already started.", ephemeral=True)
369
  return
370
 
371
+ user_cash[user_id] += cancelled_bet['amount']
372
  user_bets[user_id].pop(bet_index)
373
+ await interaction_cancel.response.send_message(f"Bet cancelled. **${cancelled_bet['amount']}** has been refunded.", ephemeral=True)
374
  if not user_bets[user_id]:
375
  del user_bets[user_id]
376
 
377
  cancel_select.callback = cancel_callback
378
+
379
  await interaction.response.send_message(embed=embed, view=view, ephemeral=True)
380
 
381
  @app_commands.command(name="sportbet", description="Bet on sports games")
382
  async def sportbet(interaction: discord.Interaction):
383
+ view = SportBetView()
384
+ await interaction.response.send_message("?", view=view, ephemeral=True)