coollsd commited on
Commit
29254f8
·
verified ·
1 Parent(s): cdf8327

Update sportbet.py

Browse files
Files changed (1) hide show
  1. sportbet.py +75 -150
sportbet.py CHANGED
@@ -9,20 +9,6 @@ user_bets = {}
9
 
10
  API_KEY = "jE7yBJVRNAwdDesMgTzTXUUSx1It41Fq"
11
 
12
- def get_current_nfl_week():
13
- """
14
- Calculate the current NFL week based on the start date.
15
- Adjust the start_date as per the actual NFL season start.
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:
23
- week_number = 1
24
- return week_number
25
-
26
  async def fetch_nhl_scores():
27
  today = datetime.now().strftime('%Y%m%d')
28
  url = f"https://api.foxsports.com/bifrost/v1/nhl/scoreboard/segment/{today}?apikey={API_KEY}"
@@ -30,11 +16,16 @@ 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(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()
 
 
 
 
 
38
 
39
  class SportSelect(discord.ui.Select):
40
  def __init__(self):
@@ -54,41 +45,34 @@ class SportSelect(discord.ui.Select):
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.")
58
  return
59
  view = GameSelect(upcoming_games, "NHL")
60
- await interaction.followup.send("Select a game to bet on:", view=view)
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.")
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)
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
 
@@ -102,31 +86,23 @@ class GameOptionSelect(discord.ui.Select):
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.")
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)
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
 
@@ -159,7 +135,7 @@ class BetModal(discord.ui.Modal, title="Place Your Bet"):
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}**.")
163
 
164
  user = await interaction.client.fetch_user(self.user_id)
165
  embed = discord.Embed(title="Bet Placed", color=0x787878)
@@ -183,17 +159,12 @@ class BetModal(discord.ui.Modal, title="Place Your Bet"):
183
 
184
  asyncio.create_task(self.monitor_game(interaction, bet_amount))
185
  except ValueError as e:
186
- await interaction.response.send_message(str(e))
187
 
188
  async def monitor_game(self, interaction, bet_amount):
189
- if self.league == "NHL":
190
- game_start = datetime.fromisoformat(self.game_data['eventTime'].replace('Z', '+00:00'))
191
- event_id = self.game_data['id']
192
- fetch_scores = fetch_nhl_scores
193
- elif self.league == "NFL":
194
- game_start = datetime.fromisoformat(self.game_data['eventTime'].replace('Z', '+00:00'))
195
- event_id = self.game_data['id']
196
- fetch_scores = lambda: fetch_nfl_scores(get_current_nfl_week())
197
 
198
  sleep_duration = (game_start - datetime.now(timezone.utc)).total_seconds()
199
  if sleep_duration > 0:
@@ -202,80 +173,45 @@ class BetModal(discord.ui.Modal, title="Place Your Bet"):
202
  user = await interaction.client.fetch_user(self.user_id)
203
  await user.send(f"Your team **{self.team}** has started playing!")
204
 
205
- previous_scores = {}
206
- if self.league == "NHL":
207
- previous_scores = {
208
- self.game_data['lowerTeam']['name']: self.game_data.get('lowerTeam', {}).get('score', 0),
209
- self.game_data['upperTeam']['name']: self.game_data.get('upperTeam', {}).get('score', 0)
210
- }
211
- elif self.league == "NFL":
212
- previous_scores = {
213
- self.game_data['lowerTeam']['name']: self.game_data.get('lowerTeam', {}).get('score', 0),
214
- self.game_data['upperTeam']['name']: self.game_data.get('upperTeam', {}).get('score', 0)
215
- }
216
 
217
  while True:
218
  scores = await fetch_scores()
219
- if self.league == "NHL":
220
- sections = scores.get('sectionList', [])
221
- game = None
222
- for section in sections:
223
- for evt in section.get('events', []):
224
- if evt['id'] == event_id:
225
- game = evt
226
- break
227
- if game:
228
- break
229
- if not game:
230
- await asyncio.sleep(60)
231
- continue
232
- event_status = game.get('eventStatus', 2)
233
- current_scores = {
234
- game['lowerTeam']['name']: game.get('lowerTeam', {}).get('score', 0),
235
- game['upperTeam']['name']: game.get('upperTeam', {}).get('score', 0)
236
- }
237
- is_final = event_status == 3
238
- elif self.league == "NFL":
239
- sections = scores.get('sectionList', [])
240
- game = None
241
- for section in sections:
242
- for evt in section.get('events', []):
243
- if evt['id'] == event_id:
244
- game = evt
245
- break
246
- if game:
247
  break
248
- if not game:
249
- await asyncio.sleep(60)
250
- continue
251
- event_status = game.get('eventStatus', 2)
252
- current_scores = {
253
- game['lowerTeam']['name']: game['lowerTeam'].get('score', 0),
254
- game['upperTeam']['name']: game['upperTeam'].get('score', 0)
255
- }
256
- is_final = event_status == 3
 
 
 
257
 
258
  # Check for score updates
259
  for team, score in current_scores.items():
260
  if score > previous_scores.get(team, 0):
261
- team_name = self.team
262
- if self.league == "NHL":
263
- team_name = self.game_data['lowerTeam']['longName'] if team == self.game_data['lowerTeam']['name'] else self.game_data['upperTeam']['longName']
264
- message = f"**{team_name}** SCORED! Current score: {current_scores[self.game_data['lowerTeam']['name']]} - {current_scores[self.game_data['upperTeam']['name']]}"
265
- elif self.league == "NFL":
266
- team_name = self.game_data['lowerTeam']['longName'] if team == self.game_data['lowerTeam']['name'] else self.game_data['upperTeam']['longName']
267
- message = f"**{team_name}** SCORED! Current score: {current_scores[self.game_data['lowerTeam']['name']]} - {current_scores[self.game_data['upperTeam']['name']]}"
268
  await user.send(message)
269
 
270
  previous_scores = current_scores.copy()
271
 
272
  if is_final:
273
- if self.league == "NHL":
274
- 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']
275
- elif self.league == "NFL":
276
- away_score = current_scores.get(self.game_data['lowerTeam']['name'], 0)
277
- home_score = current_scores.get(self.game_data['upperTeam']['name'], 0)
278
- winner = self.game_data['lowerTeam']['name'] if away_score > home_score else self.game_data['upperTeam']['name']
279
 
280
  if winner == self.team:
281
  winnings = bet_amount * 2
@@ -302,7 +238,7 @@ class SportBetView(discord.ui.View):
302
  async def show_current_bets(interaction: discord.Interaction):
303
  user_id = interaction.user.id
304
  if user_id not in user_bets or not user_bets[user_id]:
305
- await interaction.response.send_message("You have no active bets.")
306
  return
307
 
308
  embed = discord.Embed(title="Your Current Bets", color=0x787878)
@@ -311,16 +247,10 @@ async def show_current_bets(interaction: discord.Interaction):
311
  team = bet['team']
312
  amount = bet['amount']
313
  game = bet['game_data']
314
- if league == "NHL":
315
- game_description = f"{game['lowerTeam']['longName']} vs {game['upperTeam']['longName']}"
316
- start_time = game['eventTime']
317
- score = f"{game['lowerTeam'].get('score', 'N/A')} - {game['upperTeam'].get('score', 'N/A')}"
318
- 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>"
319
- elif league == "NFL":
320
- game_description = f"{game['lowerTeam']['longName']} vs {game['upperTeam']['longName']}"
321
- start_time = game['eventTime']
322
- score = f"{game['lowerTeam'].get('score', 'N/A')} - {game['upperTeam'].get('score', 'N/A')}"
323
- 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>"
324
 
325
  embed.add_field(
326
  name=f"Bet {i}: {league}",
@@ -348,33 +278,28 @@ async def show_current_bets(interaction: discord.Interaction):
348
 
349
  async def cancel_callback(interaction_cancel: discord.Interaction):
350
  if interaction_cancel.user.id != user_id:
351
- await interaction_cancel.response.send_message("You cannot cancel other users' bets.")
352
  return
353
 
354
  bet_index = int(cancel_select.values[0])
355
  cancelled_bet = user_bets[user_id][bet_index]
356
- league = cancelled_bet['league']
357
- game = cancelled_bet['game_data']
358
- if league == "NHL":
359
- start_time = datetime.fromisoformat(game['eventTime'].replace('Z', '+00:00'))
360
- elif league == "NFL":
361
- start_time = datetime.fromisoformat(game['eventTime'].replace('Z', '+00:00'))
362
 
363
  if datetime.now(timezone.utc) >= start_time:
364
- await interaction_cancel.response.send_message("You cannot cancel your bet as the game has already started.")
365
  return
366
 
367
  user_cash[user_id] += cancelled_bet['amount']
368
  user_bets[user_id].pop(bet_index)
369
- await interaction_cancel.response.send_message(f"Bet cancelled. **${cancelled_bet['amount']}** has been refunded.")
370
  if not user_bets[user_id]:
371
  del user_bets[user_id]
372
 
373
  cancel_select.callback = cancel_callback
374
 
375
- await interaction.response.send_message(embed=embed, view=view)
376
 
377
  @app_commands.command(name="sportbet", description="Bet on sports games")
378
  async def sportbet(interaction: discord.Interaction):
379
  view = SportBetView()
380
- await interaction.response.send_message("Select a sport to bet on:", view=view)
 
9
 
10
  API_KEY = "jE7yBJVRNAwdDesMgTzTXUUSx1It41Fq"
11
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12
  async def fetch_nhl_scores():
13
  today = datetime.now().strftime('%Y%m%d')
14
  url = f"https://api.foxsports.com/bifrost/v1/nhl/scoreboard/segment/{today}?apikey={API_KEY}"
 
16
  async with session.get(url) as response:
17
  return await response.json()
18
 
19
+ async def fetch_nfl_scores():
20
+ current_year = datetime.now().year
21
+ for week in range(1, 18): # NFL regular season has 17 weeks
22
+ url = f"https://api.foxsports.com/bifrost/v1/nfl/scoreboard/segment/{current_year}-{week}-1?apikey={API_KEY}"
23
+ async with aiohttp.ClientSession() as session:
24
+ async with session.get(url) as response:
25
+ data = await response.json()
26
+ if data['sectionList'][0]['events'][0]['eventStatus'] == 2:
27
+ return data
28
+ return None # If no current week is found
29
 
30
  class SportSelect(discord.ui.Select):
31
  def __init__(self):
 
45
  events = scores.get('sectionList', [])[0].get('events', [])
46
  upcoming_games = [game for game in events if game.get('eventStatus') == 2]
47
  if not upcoming_games:
48
+ await interaction.followup.send("No NHL games available for betting today.", ephemeral=False)
49
  return
50
  view = GameSelect(upcoming_games, "NHL")
51
+ await interaction.followup.send("Select a game to bet on:", view=view, ephemeral=False)
52
  elif selected_sport == "NFL":
53
+ scores = await fetch_nfl_scores()
54
+ if not scores:
55
+ await interaction.followup.send("No NFL games available for betting this week.", ephemeral=False)
56
+ return
57
  events = scores.get('sectionList', [])[0].get('events', [])
58
  upcoming_games = [game for game in events if game.get('eventStatus') == 2]
59
  if not upcoming_games:
60
+ await interaction.followup.send("No NFL games available for betting this week.", ephemeral=False)
61
  return
62
  view = GameSelect(upcoming_games, "NFL")
63
+ await interaction.followup.send("Select a game to bet on:", view=view, ephemeral=False)
64
 
65
  class GameSelect(discord.ui.View):
66
  def __init__(self, games, league):
67
  super().__init__()
68
  self.league = league
69
+ options = [
70
+ discord.SelectOption(
71
+ label=f"{game['lowerTeam']['longName']} vs {game['upperTeam']['longName']}",
72
+ value=game['id'],
73
+ description=f"Start time: <t:{int(datetime.fromisoformat(game['eventTime'].replace('Z', '+00:00')).timestamp())}:F>"
74
+ ) for game in games
75
+ ]
 
 
 
 
 
 
 
 
 
76
  self.games = {game['id']: game for game in games}
77
  self.add_item(GameOptionSelect(options, self.league, self.games))
78
 
 
86
  selected_game_id = self.values[0]
87
  game_data = self.games.get(selected_game_id)
88
  if not game_data:
89
+ await interaction.response.send_message("Selected game data not found.", ephemeral=False)
90
  return
91
  await interaction.response.edit_message(content="Select a team to bet on:", view=None)
92
  await asyncio.sleep(1) # Brief pause for better UX
93
  view = TeamSelect(game_data, self.league)
94
+ await interaction.followup.send("Select a team to bet on:", view=view, ephemeral=False)
95
 
96
  class TeamSelect(discord.ui.View):
97
  def __init__(self, game, league):
98
  super().__init__()
99
  self.league = league
100
+ away_team = game['lowerTeam']
101
+ home_team = game['upperTeam']
102
+ options = [
103
+ discord.SelectOption(label=away_team['longName'], value=away_team['name']),
104
+ discord.SelectOption(label=home_team['longName'], value=home_team['name'])
105
+ ]
 
 
 
 
 
 
 
 
106
  self.game = game
107
  self.add_item(TeamOptionSelect(options, league, game))
108
 
 
135
  raise ValueError("Insufficient balance. Please check your balance and try again.")
136
 
137
  user_cash[self.user_id] -= bet_amount
138
+ await interaction.response.send_message(f"Bet placed on **{self.team}** for **${bet_amount}**.", ephemeral=False)
139
 
140
  user = await interaction.client.fetch_user(self.user_id)
141
  embed = discord.Embed(title="Bet Placed", color=0x787878)
 
159
 
160
  asyncio.create_task(self.monitor_game(interaction, bet_amount))
161
  except ValueError as e:
162
+ await interaction.response.send_message(str(e), ephemeral=False)
163
 
164
  async def monitor_game(self, interaction, bet_amount):
165
+ game_start = datetime.fromisoformat(self.game_data['eventTime'].replace('Z', '+00:00'))
166
+ event_id = self.game_data['id']
167
+ fetch_scores = fetch_nhl_scores if self.league == "NHL" else fetch_nfl_scores
 
 
 
 
 
168
 
169
  sleep_duration = (game_start - datetime.now(timezone.utc)).total_seconds()
170
  if sleep_duration > 0:
 
173
  user = await interaction.client.fetch_user(self.user_id)
174
  await user.send(f"Your team **{self.team}** has started playing!")
175
 
176
+ previous_scores = {
177
+ self.game_data['lowerTeam']['name']: self.game_data.get('lowerTeam', {}).get('score', 0),
178
+ self.game_data['upperTeam']['name']: self.game_data.get('upperTeam', {}).get('score', 0)
179
+ }
 
 
 
 
 
 
 
180
 
181
  while True:
182
  scores = await fetch_scores()
183
+ game = None
184
+ for section in scores.get('sectionList', []):
185
+ for evt in section.get('events', []):
186
+ if evt['id'] == event_id:
187
+ game = evt
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
188
  break
189
+ if game:
190
+ break
191
+ if not game:
192
+ await asyncio.sleep(60)
193
+ continue
194
+
195
+ event_status = game.get('eventStatus', 2)
196
+ current_scores = {
197
+ game['lowerTeam']['name']: game['lowerTeam'].get('score', 0),
198
+ game['upperTeam']['name']: game['upperTeam'].get('score', 0)
199
+ }
200
+ is_final = event_status == 3
201
 
202
  # Check for score updates
203
  for team, score in current_scores.items():
204
  if score > previous_scores.get(team, 0):
205
+ team_name = self.game_data['lowerTeam']['longName'] if team == self.game_data['lowerTeam']['name'] else self.game_data['upperTeam']['longName']
206
+ message = f"**{team_name}** SCORED! Current score: {current_scores[self.game_data['lowerTeam']['name']]} - {current_scores[self.game_data['upperTeam']['name']]}"
 
 
 
 
 
207
  await user.send(message)
208
 
209
  previous_scores = current_scores.copy()
210
 
211
  if is_final:
212
+ away_score = current_scores.get(self.game_data['lowerTeam']['name'], 0)
213
+ home_score = current_scores.get(self.game_data['upperTeam']['name'], 0)
214
+ winner = self.game_data['lowerTeam']['name'] if away_score > home_score else self.game_data['upperTeam']['name']
 
 
 
215
 
216
  if winner == self.team:
217
  winnings = bet_amount * 2
 
238
  async def show_current_bets(interaction: discord.Interaction):
239
  user_id = interaction.user.id
240
  if user_id not in user_bets or not user_bets[user_id]:
241
+ await interaction.response.send_message("You have no active bets.", ephemeral=False)
242
  return
243
 
244
  embed = discord.Embed(title="Your Current Bets", color=0x787878)
 
247
  team = bet['team']
248
  amount = bet['amount']
249
  game = bet['game_data']
250
+ game_description = f"{game['lowerTeam']['longName']} vs {game['upperTeam']['longName']}"
251
+ start_time = game['eventTime']
252
+ score = f"{game['lowerTeam'].get('score', 'N/A')} - {game['upperTeam'].get('score', 'N/A')}"
253
+ 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>"
 
 
 
 
 
 
254
 
255
  embed.add_field(
256
  name=f"Bet {i}: {league}",
 
278
 
279
  async def cancel_callback(interaction_cancel: discord.Interaction):
280
  if interaction_cancel.user.id != user_id:
281
+ await interaction_cancel.response.send_message("You cannot cancel other users' bets.", ephemeral=False)
282
  return
283
 
284
  bet_index = int(cancel_select.values[0])
285
  cancelled_bet = user_bets[user_id][bet_index]
286
+ start_time = datetime.fromisoformat(cancelled_bet['game_data']['eventTime'].replace('Z', '+00:00'))
 
 
 
 
 
287
 
288
  if datetime.now(timezone.utc) >= start_time:
289
+ await interaction_cancel.response.send_message("You cannot cancel your bet as the game has already started.", ephemeral=False)
290
  return
291
 
292
  user_cash[user_id] += cancelled_bet['amount']
293
  user_bets[user_id].pop(bet_index)
294
+ await interaction_cancel.response.send_message(f"Bet cancelled. **${cancelled_bet['amount']}** has been refunded.", ephemeral=False)
295
  if not user_bets[user_id]:
296
  del user_bets[user_id]
297
 
298
  cancel_select.callback = cancel_callback
299
 
300
+ await interaction.response.send_message(embed=embed, view=view, ephemeral=False)
301
 
302
  @app_commands.command(name="sportbet", description="Bet on sports games")
303
  async def sportbet(interaction: discord.Interaction):
304
  view = SportBetView()
305
+ await interaction.response.send_message("Select a sport to bet on:", view=view, ephemeral=False)