coollsd commited on
Commit
4d35aef
·
verified ·
1 Parent(s): dd980b2

Update sportbet.py

Browse files
Files changed (1) hide show
  1. sportbet.py +127 -146
sportbet.py CHANGED
@@ -18,17 +18,14 @@ async def fetch_nhl_scores():
18
 
19
  async def fetch_nfl_scores():
20
  current_year = datetime.now().year
21
- all_games = []
22
  for week in range(1, 18): # NFL regular season has 17 weeks
23
  url = f"https://api.foxsports.com/bifrost/v1/nfl/scoreboard/segment/{current_year}-{week}-1?apikey={API_KEY}"
24
  async with aiohttp.ClientSession() as session:
25
  async with session.get(url) as response:
26
  data = await response.json()
27
- for section in data.get('sectionList', []):
28
- for event in section.get('events', []):
29
- if event['eventStatus'] == 2: # Change this condition based on your needs
30
- all_games.append(event)
31
- return all_games if all_games else None
32
 
33
  class SportSelect(discord.ui.Select):
34
  def __init__(self):
@@ -57,7 +54,8 @@ class SportSelect(discord.ui.Select):
57
  if not scores:
58
  await interaction.followup.send("No NFL games available for betting this week.", ephemeral=False)
59
  return
60
- upcoming_games = [game for game in scores if game.get('eventStatus') == 2]
 
61
  if not upcoming_games:
62
  await interaction.followup.send("No NFL games available for betting this week.", ephemeral=False)
63
  return
@@ -159,154 +157,137 @@ class BetModal(discord.ui.Modal, title="Place Your Bet"):
159
  "game_data": self.game_data
160
  })
161
 
162
- asyncio.create_task(self.monitor_game(interaction, bet_amount))
 
163
  except ValueError as e:
164
  await interaction.response.send_message(str(e), ephemeral=False)
165
 
166
- async def monitor_game(self, interaction: discord.Interaction, bet_amount: int):
167
- game_start = datetime.fromisoformat(self.game_data['eventTime'].replace('Z', '+00:00'))
168
- event_id = self.game_data['id']
169
 
170
- fetch_scores_func_map = {
171
- "NHL": fetch_nhl_scores,
172
- "NFL": fetch_nfl_scores,
173
- # Add other leagues here as needed.
174
- }
175
 
176
- fetch_scores_func_map["NFL"]()
177
-
178
- sleep_duration =(game_start - datetime.now(timezone.utc)).total_seconds()
179
- if sleep_duration > 0:
180
- await asyncio.sleep(sleep_duration)
181
-
182
- user = await interaction.client.fetch_user(self.user_id)
183
- await user.send(f"Your team **{self.team}** has started playing!")
184
-
185
- previous_scores={
186
- self.game_data['lowerTeam']['name']:self.game_data.get('lowerTeam', {}).get('score', 0),
187
- self.game_data['upperTeam']['name']:self.game_data.get('upperTeam', {}).get('score', 0),
188
- }
189
-
190
- while True:
191
- scores=await fetch_scores_func_map[self.league]()
192
- game=None
193
-
194
- for section in scores.get('sectionList', []):
195
- for evt in section.get('events', []):
196
- if evt['id'] == event_id:
197
- game=evt
198
- break
199
-
200
- if game:
201
- break
202
-
203
- if not game:
204
- await asyncio.sleep(60)
205
- continue
206
-
207
- event_status=game.get('eventStatus', 2)
208
- current_scores={
209
- game['lowerTeam']['name']:game['lowerTeam'].get('score', 0),
210
- game['upperTeam']['name']:game['upperTeam'].get('score', 0),
211
- }
212
- is_final=event_status ==3
213
-
214
- # Check for score updates
215
- for team ,score in current_scores.items():
216
- if score > previous_scores.get(team ,0):
217
- team_name=self.game_data['lowerTeam']['longName'] if team ==self.game_data['lowerTeam']['name'] else self.game_data['upperTeam']['longName']
218
- message=f"**{team_name}** SCORED! Current score: {current_scores[self.game_data['lowerTeam']['name']]} - {current_scores[self.game_data['upperTeam']['name']]}"
219
- await user.send(message)
220
-
221
- previous_scores=current_scores.copy()
222
-
223
- if is_final:
224
- away_score=current_scores.get(self.game_data['lowerTeam']['name'],0)
225
- home_score=current_scores.get(self.game_data['upperTeam']['name'],0)
226
- winner=self.game_data['lowerTeam']['name'] if away_score > home_score else self.game_data['upperTeam']['name']
227
-
228
- if winner ==self.team:
229
- winnings=bet_amount *2
230
- user_cash[self.user_id] +=winnings
231
- await user.send(f"🎉 **Congratulations!** Your team **{self.team}** won! You won **${winnings}**!")
232
- else :
233
- await user.send(f"😞 **Sorry!** Your team **{self.team}** lost. Better luck next time!")
234
-
235
- # Remove the completed bet
236
- 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)]
237
- break
238
-
239
- await asyncio.sleep(60) # Check every minute
240
 
241
  class SportBetView(discord.ui.View):
242
  def __init__(self):
243
- super().__init__()
244
- self.add_item(SportSelect())
245
-
246
- @discord.ui.button(label ="View Bets", style=discord.ButtonStyle.secondary )
247
- async def view_bets (interaction :discord.Interaction ,button :discord.ui.Button ):
248
- await show_current_bets(interaction )
249
-
250
- async def show_current_bets (interaction :discord.Interaction ):
251
- user_id=interaction.user.id
252
- if user_id not in user_bets or not user_bets[user_id]:
253
- await interaction.response.send_message("You have no active bets.", ephemeral=False )
254
- return
255
-
256
- embed=discord.Embed(title ="Your Current Bets", color=0x787878 )
257
- for i ,bet in enumerate(user_bets[user_id],1 ):
258
- league=bet ['league']
259
- team=bet ['team']
260
- amount=bet ['amount']
261
- game=bet ['game_data']
262
- game_description=f"{game ['lowerTeam']['longName']} vs {game ['upperTeam']['longName']}"
263
- start_time=game ['eventTime']
264
- score=f"{game ['lowerTeam'].get('score','N/A')} - {game ['upperTeam'].get('score','N/A')}"
265
- 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>"
266
-
267
- embed.add_field(
268
- name=f"Bet {i}: {league}",
269
- value=(f"**Team:** {team}\n"
270
- f"**Amount:** ${amount}\n"
271
- f"**Game:** {game_description}\n"
272
- f"**Status:** {status}\n"
273
- f"**Current Score:** {score}\n"
274
- f"**Start Time:** <t:{int(datetime.fromisoformat(start_time.replace ('Z','+00:00')).timestamp())}:F>"),
275
- inline=False
276
- )
277
-
278
- view=discord.ui.View()
279
- cancel_select=discord.ui.Select(
280
- placeholder ="Select a bet to cancel",
281
- min_values=1 ,
282
- max_values=1 ,
283
- options=[
284
- discord.SelectOption(label=f"Bet {i}", value=str(i-1))for i in range(1 ,len(user_bets[user_id])+1 )
285
- ]
286
- )
287
- view.add_item(cancel_select )
288
-
289
- async def cancel_callback (interaction_cancel :discord.Interaction ):
290
  if interaction_cancel.user.id !=user_id :
291
- await interaction_cancel.response.send_message("You cannot cancel other users' bets.", ephemeral=False )
292
- return
293
 
294
  bet_index=int(cancel_select.values[0])
295
  cancelled_bet=user_bets[user_id][bet_index]
296
- start_time=datetime.fromisoformat(cancelled_bet ['game_data']['eventTime'].replace ('Z','+00:00'))
297
-
298
- if datetime.now(timezone.utc) >=start_time :
299
- await interaction_cancel.response.send_message("You cannot cancel your bet as the game has already started.", ephemeral=False )
300
- return
301
-
302
- user_cash[user_id] +=cancelled_bet ['amount']
303
- user_bets[user_id].pop(bet_index )
304
- await interaction_cancel.response.send_message(f"Bet cancelled. **${cancelled_bet ['amount']}** has been refunded.", ephemeral=False )
305
-
306
-
307
-
308
-
309
- @app_commands.command(name ="sportbet", description ="Bet on sports games")
310
- async def sportbet (interaction :discord.Interaction ):
311
- view=SportBetView()
312
- await interaction.response.send_message("Select a sport to bet on:", view=view ,ephemeral=False )
 
 
 
 
 
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):
 
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
 
157
  "game_data": self.game_data
158
  })
159
 
160
+ asyncio.create_task(self.monitor_game(interaction))
161
+
162
  except ValueError as e:
163
  await interaction.response.send_message(str(e), ephemeral=False)
164
 
165
+ async def monitor_game(self, interaction):
 
 
166
 
167
+ # Fetch initial scores and set up monitoring loop
 
 
 
 
168
 
169
+ previous_scores = {
170
+ self.game_data['lowerTeam']['name']: None,
171
+ self.game_data['upperTeam']['name']: None,
172
+ }
173
+
174
+ while True:
175
+ scores_response = await fetch_nhl_scores() if self.league == "NHL" else fetch_nfl_scores()
176
+ event_list_key='events' if 'events' in scores_response.get('sectionList', [{}])[0] else 'games'
177
+ current_game=None
178
+
179
+ for section in scores_response.get('sectionList', []):
180
+ for event in section.get(event_list_key , []):
181
+ if event['id'] == self.game_data['id']:
182
+ current_game=event
183
+ break
184
+
185
+ if not current_game:
186
+ await asyncio.sleep(60)
187
+ continue
188
+
189
+ current_scores={
190
+ current_game['lowerTeam']['name']: current_game['lowerTeam'].get('score'),
191
+ current_game['upperTeam']['name']: current_game['upperTeam'].get('score'),
192
+ }
193
+
194
+ score_changed=False
195
+
196
+ for team_name,current_score in current_scores.items():
197
+ previous_score=previous_scores[team_name]
198
+
199
+ if previous_score is None or current_score!=previous_score:
200
+ score_changed=True
201
+
202
+ previous_scores=current_scores.copy()
203
+
204
+ if score_changed:
205
+ away_score=current_scores[self.game_data['lowerTeam']['name']] or 'N/A'
206
+ home_score=current_scores[self.game_data['upperTeam']['name']] or 'N/A'
207
+ message=f"Current score update: {away_score} - {home_score}"
208
+ user=await interaction.client.fetch_user(self.user_id)
209
+ await user.send(message)
210
+
211
+ event_status=current_game.get('eventStatus')
212
+
213
+ if event_status==3:
214
+ break
215
+
216
+ await asyncio.sleep(60)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
217
 
218
  class SportBetView(discord.ui.View):
219
  def __init__(self):
220
+ super().__init__()
221
+ self.add_item(SportSelect())
222
+
223
+ @discord.ui.button(label="View Bets", style=discord.ButtonStyle.secondary)
224
+ async def view_bets(self ,interaction:discord.Interaction ,button :discord.ui.Button ):
225
+ await show_current_bets(interaction)
226
+
227
+ async def show_current_bets(interaction:discord.Interaction ):
228
+ user_id=interaction.user.id
229
+
230
+ if user_id not in user_bets or not user_bets[user_id]:
231
+ await interaction.response.send_message("You have no active bets." ,ephemeral=False )
232
+ return
233
+
234
+ embed=discord.Embed(title ="Your Current Bets" ,color=0x787878 )
235
+
236
+ for i ,bet in enumerate(user_bets[user_id] ,1 ):
237
+ league=bet ['league']
238
+ team=bet ['team']
239
+ amount=bet ['amount']
240
+ game=bet ['game_data']
241
+ away_score='N/A' if 'score' not in game ['lowerTeam'] else str(game ['lowerTeam']['score'])
242
+ home_score='N/A' if 'score' not in game ['upperTeam'] else str(game ['upperTeam']['score'])
243
+ status='Final' if 'score' in game ['upperTeam'] else f"Starts <t:{int(datetime.fromisoformat(game ['eventTime'].replace('Z','+00:00')).timestamp())}:R>"
244
+
245
+ embed.add_field(
246
+ name=f"Bet {i}: {league}" ,
247
+ value=(f"**Team:** {team}\n"
248
+ f"**Amount:** ${amount}\n"
249
+ f"**Game:** {game ['lowerTeam']['longName']} vs {game ['upperTeam']['longName']}\n"
250
+ f"**Status:** {status}\n"
251
+ f"**Current Score:** {away_score} - {home_score}\n"
252
+ f"**Start Time:** <t:{int(datetime.fromisoformat(game ['eventTime'].replace('Z','+00:00')).timestamp())}:F>"),
253
+ inline=False )
254
+
255
+ view=discord.ui.View()
256
+ cancel_select=discord.ui.Select(
257
+ placeholder ="Select a bet to cancel",
258
+ min_values=1 ,
259
+ max_values=1 ,
260
+ options=[
261
+ discord.SelectOption(label=f"Bet {i}" ,value=str(i-1)) for i in range(1 ,len(user_bets[user_id])+1 )
262
+ ]
263
+ )
264
+ view.add_item(cancel_select)
265
+
266
+ async def cancel_callback(interaction_cancel :discord.Interaction ):
267
  if interaction_cancel.user.id !=user_id :
268
+ await interaction_cancel.response.send_message("You cannot cancel other users' bets." ,ephemeral=False )
269
+ return
270
 
271
  bet_index=int(cancel_select.values[0])
272
  cancelled_bet=user_bets[user_id][bet_index]
273
+ start_time=datetime.fromisoformat(cancelled_bet ['game_data']['eventTime'].replace('Z','+00:00'))
274
+
275
+ if datetime.now(timezone.utc)>=start_time :
276
+ await interaction_cancel.response.send_message("You cannot cancel your bet as the game has already started." ,ephemeral=False )
277
+ return
278
+
279
+ user_cash[user_id]+=cancelled_bet ['amount']
280
+ user_bets[user_id].pop(bet_index)
281
+ await interaction_cancel.response.send_message(f"Bet cancelled. **${cancelled_bet ['amount']}** has been refunded." ,ephemeral=False )
282
+
283
+ if not user_bets[user_id]:
284
+ del user_bets[user_id]
285
+
286
+ cancel_select.callback=cancel_callback
287
+
288
+ await interaction.response.send_message(embed=embed ,view=view ,ephemeral=False )
289
+
290
+ @app_commands.command(name ="sportbet" ,description ="Bet on sports games")
291
+ async def sportbet(interaction :discord.Interaction ):
292
+ view=SportBetView()
293
+ await interaction.response.send_message("Select a sport to bet on:" ,view=view ,ephemeral=False )