coollsd commited on
Commit
ec17a11
1 Parent(s): 9f69a55

Update sportbet.py

Browse files
Files changed (1) hide show
  1. sportbet.py +40 -60
sportbet.py CHANGED
@@ -1,5 +1,4 @@
1
  import discord
2
- from discord.ext import commands
3
  from discord import app_commands
4
  import aiohttp
5
  import asyncio
@@ -8,7 +7,7 @@ from cash import user_cash # Ensure you have a 'cash.py' module managing user_c
8
 
9
  user_bets = {}
10
 
11
- API_KEY = "jE7yBJVRNAwdDesMgTzTXUUSx1It41Fq" # Replace with your actual API key
12
 
13
  async def fetch_nhl_scores():
14
  today = datetime.now().strftime('%Y%m%d')
@@ -19,29 +18,13 @@ async def fetch_nhl_scores():
19
 
20
  async def fetch_nfl_scores():
21
  current_year = datetime.now().year
22
- # Start by fetching data to get quickNav
23
- url = f"https://api.foxsports.com/bifrost/v1/nfl/scoreboard/segment/{current_year}-1-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
- quick_nav = data.get('quickNav', [])
28
- current_week_id = None
29
- for week_info in quick_nav:
30
- if week_info.get('selected'):
31
- current_week_id = week_info['id'] # e.g., '2024-7-1'
32
- break
33
- if current_week_id:
34
- # Fetch data for the current week
35
- url_current_week = f"https://api.foxsports.com/bifrost/v1/nfl/scoreboard/segment/{current_week_id}?apikey={API_KEY}"
36
- async with session.get(url_current_week) as response_current_week:
37
- data_current_week = await response_current_week.json()
38
- return data_current_week
39
- return None # If no current week is found
40
-
41
- intents = discord.Intents.default()
42
- intents.message_content = True # Required for receiving message content
43
-
44
- bot = commands.Bot(command_prefix='!', intents=intents)
45
 
46
  class SportSelect(discord.ui.Select):
47
  def __init__(self):
@@ -70,10 +53,8 @@ class SportSelect(discord.ui.Select):
70
  if not scores:
71
  await interaction.followup.send("No NFL games available for betting this week.", ephemeral=False)
72
  return
73
- events = []
74
- for section in scores.get('sectionList', []):
75
- events.extend(section.get('events', []))
76
- upcoming_games = [game for game in events if game.get('eventStatus') == 2]
77
  if not upcoming_games:
78
  await interaction.followup.send("No NFL games available for betting this week.", ephemeral=False)
79
  return
@@ -220,21 +201,16 @@ class BetModal(discord.ui.Modal, title="Place Your Bet"):
220
  # Check for score updates
221
  for team, score in current_scores.items():
222
  if score > previous_scores.get(team, 0):
223
- team_name = game['lowerTeam']['longName'] if team == game['lowerTeam']['name'] else game['upperTeam']['longName']
224
- message = f"**{team_name}** SCORED! Current score: {current_scores[game['lowerTeam']['name']]} - {current_scores[game['upperTeam']['name']]}"
225
  await user.send(message)
226
 
227
  previous_scores = current_scores.copy()
228
 
229
  if is_final:
230
- away_score = current_scores.get(game['lowerTeam']['name'], 0)
231
- home_score = current_scores.get(game['upperTeam']['name'], 0)
232
- if away_score > home_score:
233
- winner = game['lowerTeam']['name']
234
- elif home_score > away_score:
235
- winner = game['upperTeam']['name']
236
- else:
237
- winner = None # It's a tie
238
 
239
  if winner == self.team:
240
  winnings = bet_amount * 2
@@ -273,7 +249,7 @@ async def show_current_bets(interaction: discord.Interaction):
273
  game_description = f"{game['lowerTeam']['longName']} vs {game['upperTeam']['longName']}"
274
  start_time = game['eventTime']
275
  score = f"{game['lowerTeam'].get('score', 'N/A')} - {game['upperTeam'].get('score', 'N/A')}"
276
- status = "Final" if game.get('eventStatus') == 3 else f"Starts <t:{int(datetime.fromisoformat(start_time.replace('Z', '+00:00')).timestamp())}:R>"
277
 
278
  embed.add_field(
279
  name=f"Bet {i}: {league}",
@@ -289,36 +265,40 @@ async def show_current_bets(interaction: discord.Interaction):
289
  )
290
 
291
  view = discord.ui.View()
292
-
293
- cancel_options = [
294
- discord.SelectOption(
295
- label=f"Bet {i}",
296
- value=str(i-1),
297
- description=f"{bet['league']} - {bet['team']} vs {bet['game_data']['lowerTeam']['longName']} vs {bet['game_data']['upperTeam']['longName']}"
298
- )
299
- for i, bet in enumerate(user_bets[user_id], 1)
300
- ]
301
-
302
  cancel_select = discord.ui.Select(
303
  placeholder="Select a bet to cancel",
304
  min_values=1,
305
  max_values=1,
306
- options=cancel_options
 
 
307
  )
 
 
 
 
 
 
308
 
309
- async def cancel_callback(interaction: discord.Interaction):
310
- index = int(cancel_select.values[0])
311
- bet = user_bets[user_id][index]
312
- refund_amount = bet['amount']
313
- user_cash[user_id] += refund_amount
314
- del user_bets[user_id][index]
315
- await interaction.response.send_message(f"Bet on **{bet['team']}** has been canceled. **${refund_amount}** has been refunded to your account.", ephemeral=False)
 
 
 
 
 
 
316
 
317
  cancel_select.callback = cancel_callback
318
- view.add_item(cancel_select)
319
 
320
  await interaction.response.send_message(embed=embed, view=view, ephemeral=False)
321
 
322
- @bot.tree.command(name="sportbet")
323
- async def bet(interaction: discord.Interaction):
324
- await interaction.response.send_message("Choose a sport to bet on:", view=SportBetView(), ephemeral=False)
 
 
1
  import discord
 
2
  from discord import app_commands
3
  import aiohttp
4
  import asyncio
 
7
 
8
  user_bets = {}
9
 
10
+ API_KEY = "jE7yBJVRNAwdDesMgTzTXUUSx1It41Fq"
11
 
12
  async def fetch_nhl_scores():
13
  today = datetime.now().strftime('%Y%m%d')
 
18
 
19
  async def fetch_nfl_scores():
20
  current_year = datetime.now().year
21
+ current_week = (datetime.now().isocalendar()[1] - 36) % 18 # Approximate NFL week
22
+ if current_week == 0:
23
+ current_week = 18
24
+ url = f"https://api.foxsports.com/bifrost/v1/nfl/scoreboard/segment/{current_year}-{current_week}-1?apikey={API_KEY}"
25
  async with aiohttp.ClientSession() as session:
26
  async with session.get(url) as response:
27
+ return await response.json()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28
 
29
  class SportSelect(discord.ui.Select):
30
  def __init__(self):
 
53
  if not scores:
54
  await interaction.followup.send("No NFL games available for betting this week.", ephemeral=False)
55
  return
56
+ events = scores.get('sectionList', [])[0].get('events', [])
57
+ upcoming_games = [game for game in events if 'score' not in game.get('upperTeam', {}) and 'score' not in game.get('lowerTeam', {})]
 
 
58
  if not upcoming_games:
59
  await interaction.followup.send("No NFL games available for betting this week.", ephemeral=False)
60
  return
 
201
  # Check for score updates
202
  for team, score in current_scores.items():
203
  if score > previous_scores.get(team, 0):
204
+ team_name = self.game_data['lowerTeam']['longName'] if team == self.game_data['lowerTeam']['name'] else self.game_data['upperTeam']['longName']
205
+ message = f"**{team_name}** SCORED! Current score: {current_scores[self.game_data['lowerTeam']['name']]} - {current_scores[self.game_data['upperTeam']['name']]}"
206
  await user.send(message)
207
 
208
  previous_scores = current_scores.copy()
209
 
210
  if is_final:
211
+ away_score = current_scores.get(self.game_data['lowerTeam']['name'], 0)
212
+ home_score = current_scores.get(self.game_data['upperTeam']['name'], 0)
213
+ winner = self.game_data['lowerTeam']['name'] if away_score > home_score else self.game_data['upperTeam']['name']
 
 
 
 
 
214
 
215
  if winner == self.team:
216
  winnings = bet_amount * 2
 
249
  game_description = f"{game['lowerTeam']['longName']} vs {game['upperTeam']['longName']}"
250
  start_time = game['eventTime']
251
  score = f"{game['lowerTeam'].get('score', 'N/A')} - {game['upperTeam'].get('score', 'N/A')}"
252
+ 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>"
253
 
254
  embed.add_field(
255
  name=f"Bet {i}: {league}",
 
265
  )
266
 
267
  view = discord.ui.View()
 
 
 
 
 
 
 
 
 
 
268
  cancel_select = discord.ui.Select(
269
  placeholder="Select a bet to cancel",
270
  min_values=1,
271
  max_values=1,
272
+ options=[
273
+ discord.SelectOption(label=f"Bet {i}", value=str(i-1)) for i in range(1, len(user_bets[user_id]) + 1)
274
+ ]
275
  )
276
+ view.add_item(cancel_select)
277
+
278
+ async def cancel_callback(interaction_cancel: discord.Interaction):
279
+ if interaction_cancel.user.id != user_id:
280
+ await interaction_cancel.response.send_message("You cannot cancel other users' bets.", ephemeral=False)
281
+ return
282
 
283
+ bet_index = int(cancel_select.values[0])
284
+ cancelled_bet = user_bets[user_id][bet_index]
285
+ start_time = datetime.fromisoformat(cancelled_bet['game_data']['eventTime'].replace('Z', '+00:00'))
286
+
287
+ if datetime.now(timezone.utc) >= start_time:
288
+ await interaction_cancel.response.send_message("You cannot cancel your bet as the game has already started.", ephemeral=False)
289
+ return
290
+
291
+ user_cash[user_id] += cancelled_bet['amount']
292
+ user_bets[user_id].pop(bet_index)
293
+ await interaction_cancel.response.send_message(f"Bet cancelled. **${cancelled_bet['amount']}** has been refunded.", ephemeral=False)
294
+ if not user_bets[user_id]:
295
+ del user_bets[user_id]
296
 
297
  cancel_select.callback = cancel_callback
 
298
 
299
  await interaction.response.send_message(embed=embed, view=view, ephemeral=False)
300
 
301
+ @app_commands.command(name="sportbet", description="Bet on sports games")
302
+ async def sportbet(interaction: discord.Interaction):
303
+ view = SportBetView()
304
+ await interaction.response.send_message("Select a sport to bet on:", view=view, ephemeral=False)