coollsd commited on
Commit
94166cb
1 Parent(s): a4b7e80

Update sportbet.py

Browse files
Files changed (1) hide show
  1. sportbet.py +229 -115
sportbet.py CHANGED
@@ -2,73 +2,145 @@ import discord
2
  from discord import app_commands
3
  import aiohttp
4
  import asyncio
5
- from datetime import datetime, timezone
6
- from cash import user_cash
7
 
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)
28
-
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
 
37
  class BetModal(discord.ui.Modal, title="Place Your Bet"):
38
  bet_amount = discord.ui.TextInput(label="Bet Amount", placeholder="Enter bet amount", required=True)
39
 
40
- def __init__(self, team, user_id, game_data):
41
  super().__init__()
42
  self.team = team
43
  self.user_id = user_id
44
  self.game_data = game_data
 
45
 
46
  async def on_submit(self, interaction: discord.Interaction):
47
  try:
48
  bet_amount = int(self.bet_amount.value)
49
  if bet_amount <= 0:
50
- raise ValueError("Bet more than 0 dollars")
51
  if bet_amount > user_cash.get(self.user_id, 0):
52
- raise ValueError("You are too poor. Check your balance and try again")
53
 
54
  user_cash[self.user_id] -= bet_amount
55
- await interaction.response.send_message(f"Bet placed on {self.team} for ${bet_amount}")
56
 
57
  user = await interaction.client.fetch_user(self.user_id)
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:
66
  user_bets[self.user_id] = []
67
  user_bets[self.user_id].append({
 
68
  "team": self.team,
69
  "amount": bet_amount,
70
- "game_data": self.game_data,
71
- "bet_time": datetime.now(timezone.utc)
72
  })
73
 
74
  asyncio.create_task(self.monitor_game(interaction, bet_amount))
@@ -76,7 +148,10 @@ class BetModal(discord.ui.Modal, title="Place Your Bet"):
76
  await interaction.response.send_message(str(e), ephemeral=True)
77
 
78
  async def monitor_game(self, interaction, bet_amount):
79
- game_start = datetime.fromisoformat(self.game_data['eventTime'].replace('Z', '+00:00'))
 
 
 
80
  sleep_duration = (game_start - datetime.now(timezone.utc)).total_seconds()
81
  if sleep_duration > 0:
82
  await asyncio.sleep(sleep_duration)
@@ -84,32 +159,61 @@ class BetModal(discord.ui.Modal, title="Place Your Bet"):
84
  user = await interaction.client.fetch_user(self.user_id)
85
  await user.send(f"Your team {self.team} has started playing!")
86
 
87
- previous_scores = {self.game_data['lowerTeam']['name']: 0, self.game_data['upperTeam']['name']: 0}
 
 
 
 
88
 
89
  while True:
90
- scores = await fetch_nhl_scores()
91
- events = scores.get('sectionList', [])[0].get('events', [])
92
- game = next((g for g in events if g['lowerTeam']['name'] == self.game_data['lowerTeam']['name'] and
93
- g['upperTeam']['name'] == self.game_data['upperTeam']['name']), None)
94
-
95
- if game is None or game['eventStatus'] < 2:
 
 
 
 
 
 
96
  await asyncio.sleep(60)
97
  continue
98
 
99
- current_scores = {
100
- game['lowerTeam']['name']: game.get('score', 0),
101
- game['upperTeam']['name']: game.get('score', 0)
102
- }
103
-
104
- for team in [self.game_data['lowerTeam']['name'], self.game_data['upperTeam']['name']]:
105
- if current_scores[team] > previous_scores[team]:
106
- team_name = self.game_data['lowerTeam']['longName'] if team == self.game_data['lowerTeam']['name'] else self.game_data['upperTeam']['longName']
107
- await user.send(f"{team_name} SCORED! Current score: {current_scores[self.game_data['lowerTeam']['name']]} - {current_scores[self.game_data['upperTeam']['name']]}")
 
 
 
 
 
 
 
 
 
 
 
 
 
108
 
109
  previous_scores = current_scores.copy()
110
 
111
- if game['eventStatus'] == 3:
112
- 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']
 
 
 
 
 
 
113
  if winner == self.team:
114
  winnings = bet_amount * 2
115
  user_cash[self.user_id] += winnings
@@ -120,89 +224,100 @@ class BetModal(discord.ui.Modal, title="Place Your Bet"):
120
  user_bets[self.user_id] = [bet for bet in user_bets[self.user_id] if bet['game_data'] != self.game_data]
121
  break
122
 
123
- await asyncio.sleep(60) # Check for updates every minute
124
 
125
  class SportBetView(discord.ui.View):
126
  def __init__(self):
127
  super().__init__()
128
-
129
- @discord.ui.button(label="Bet Again", style=discord.ButtonStyle.primary)
130
- async def bet_again(self, interaction: discord.Interaction, button: discord.ui.Button):
131
- await show_game_selection(interaction)
132
 
133
  @discord.ui.button(label="View Bets", style=discord.ButtonStyle.secondary)
134
  async def view_bets(self, interaction: discord.Interaction, button: discord.ui.Button):
135
  await show_current_bets(interaction)
136
 
137
  async def show_game_selection(interaction: discord.Interaction):
138
- scores = await fetch_nhl_scores()
139
- events = scores.get('sectionList', [])[0].get('events', [])
140
- upcoming_games = [game for game in events if game['eventStatus'] == 2]
141
 
142
- if not upcoming_games:
143
- await interaction.response.send_message("No games available for betting.")
144
- return
145
-
146
- view = discord.ui.View()
147
- game_select = GameSelect(upcoming_games)
148
- view.add_item(game_select)
149
-
150
- await interaction.response.send_message("Select a game to bet on:", view=view)
151
-
152
- async def game_callback(interaction: discord.Interaction):
153
- selected_game = next(game for game in upcoming_games if f"{game['lowerTeam']['name']}_{game['upperTeam']['name']}" == game_select.values[0])
154
-
155
- team_view = discord.ui.View()
156
- team_select = TeamSelect(selected_game['lowerTeam'], selected_game['upperTeam'])
157
- team_view.add_item(team_select)
158
 
159
- await interaction.response.edit_message(content="Select a team to bet on:", view=team_view)
 
 
 
 
 
 
160
 
161
- async def team_callback(interaction: discord.Interaction):
162
- selected_team = team_select.values[0]
163
- await interaction.response.send_modal(BetModal(selected_team, interaction.user.id, selected_game))
 
 
 
 
 
 
 
164
 
165
- team_select.callback = team_callback
 
 
166
 
167
- game_select.callback = game_callback
 
 
 
168
 
169
  async def show_current_bets(interaction: discord.Interaction):
170
  user_id = interaction.user.id
171
  if user_id not in user_bets or not user_bets[user_id]:
172
- await interaction.response.send_message("You have no active bets.")
173
  return
174
 
175
- embed = discord.Embed(title="Your Current Bets", color=0x787878)
176
- scores = await fetch_nhl_scores()
177
- events = scores.get('sectionList', [])[0].get('events', [])
178
-
179
- for i, bet in enumerate(user_bets[user_id]):
180
- game = next((g for g in events if g['lowerTeam']['name'] == bet['game_data']['lowerTeam']['name'] and
181
- g['upperTeam']['name'] == bet['game_data']['upperTeam']['name']), None)
182
-
183
- start_time = datetime.fromisoformat(bet['game_data']['eventTime'].replace('Z', '+00:00'))
184
- current_time = datetime.now(timezone.utc)
185
-
186
- if current_time < start_time:
187
- status = f"Starts <t:{int(start_time.timestamp())}:R>"
188
- score = "N/A"
189
- else:
190
- status = "FINAL" if game and game['eventStatus'] == 3 else "In Progress"
191
- score = f"{game.get('lowerTeam', {}).get('score', 'Unknown')} - {game.get('upperTeam', {}).get('score', 'Unknown')}" if game else "Unknown"
192
-
193
- embed.add_field(name=f"Bet {i+1}", value=(
194
- f"**Team:** {bet['team']}\n"
195
- f"**Amount:** ${bet['amount']}\n"
196
- f"**Game:** {bet['game_data']['lowerTeam']['longName']} vs {bet['game_data']['upperTeam']['longName']}\n"
197
- f"**Status:** {status}\n"
198
- f"**Current Score:** {score}\n"
199
- f"**Start Time:** <t:{int(start_time.timestamp())}:F>"
200
- ), inline=False)
 
 
 
 
201
 
202
  view = discord.ui.View()
203
- cancel_select = discord.ui.Select(placeholder="Select a bet to cancel", options=[
204
- discord.SelectOption(label=f"Bet {i+1}", value=str(i)) for i in range(len(user_bets[user_id]))
205
- ])
 
 
 
 
 
206
  view.add_item(cancel_select)
207
 
208
  async def cancel_callback(interaction: discord.Interaction):
@@ -212,27 +327,26 @@ async def show_current_bets(interaction: discord.Interaction):
212
 
213
  bet_index = int(cancel_select.values[0])
214
  cancelled_bet = user_bets[user_id][bet_index]
 
215
  game = cancelled_bet['game_data']
216
- current_time = datetime.now(timezone.utc)
217
- game_start = datetime.fromisoformat(game['eventTime'].replace('Z', '+00:00'))
 
 
218
 
219
- if current_time >= game_start:
220
  await interaction.response.send_message("You cannot cancel your bet as the game has already started.", ephemeral=True)
221
  return
222
 
223
- user_cash[user_id] += cancelled_bet['amount']
224
  user_bets[user_id].pop(bet_index)
225
- await interaction.response.send_message(f"Bet cancelled. ${cancelled_bet['amount']} has been refunded.")
 
 
226
 
227
  cancel_select.callback = cancel_callback
228
-
229
- await interaction.response.send_message(embed=embed, view=view)
230
 
231
  @app_commands.command(name="sportbet", description="Bet on sports games")
232
  async def sportbet(interaction: discord.Interaction):
233
- user_id = interaction.user.id
234
- if user_id in user_bets and user_bets[user_id]:
235
- view = SportBetView()
236
- await interaction.response.send_message("What would you like to do?", view=view)
237
- else:
238
- await show_game_selection(interaction)
 
2
  from discord import app_commands
3
  import aiohttp
4
  import asyncio
5
+ from datetime import datetime, timezone, timedelta
6
+ from cash import user_cash # Ensure you have a 'cash.py' module managing user_cash as a dictionary
7
 
8
  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()
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}"
29
+ async with aiohttp.ClientSession() as session:
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()
39
 
40
+ class SportSelect(discord.ui.Select):
41
+ def __init__(self):
42
+ options = [
43
+ discord.SelectOption(label="NHL", description="Bet on NHL games"),
44
+ discord.SelectOption(label="NFL", description="Bet on NFL games")
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)
103
 
104
+ def __init__(self, team, user_id, game_data, league):
105
  super().__init__()
106
  self.team = team
107
  self.user_id = user_id
108
  self.game_data = game_data
109
+ self.league = league
110
 
111
  async def on_submit(self, interaction: discord.Interaction):
112
  try:
113
  bet_amount = int(self.bet_amount.value)
114
  if bet_amount <= 0:
115
+ raise ValueError("Bet amount must be greater than 0.")
116
  if bet_amount > user_cash.get(self.user_id, 0):
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)
124
+ embed.add_field(name="League", value=self.league, inline=False)
125
  embed.add_field(name="Team", value=self.team, inline=False)
126
  embed.add_field(name="Amount", value=f"${bet_amount}", inline=False)
127
+ if self.league == "NHL":
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)
136
 
137
  if self.user_id not in user_bets:
138
  user_bets[self.user_id] = []
139
  user_bets[self.user_id].append({
140
+ "league": self.league,
141
  "team": self.team,
142
  "amount": bet_amount,
143
+ "game_data": self.game_data
 
144
  })
145
 
146
  asyncio.create_task(self.monitor_game(interaction, bet_amount))
 
148
  await interaction.response.send_message(str(e), ephemeral=True)
149
 
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)
 
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()
208
 
209
+ if is_final:
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
 
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
228
 
229
  class SportBetView(discord.ui.View):
230
  def __init__(self):
231
  super().__init__()
232
+ self.add_item(SportSelect())
 
 
 
233
 
234
  @discord.ui.button(label="View Bets", style=discord.ButtonStyle.secondary)
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]:
278
+ await interaction.response.send_message("You have no active bets.", ephemeral=True)
279
  return
280
 
281
+ embed = discord.Embed(title="Your Current Bets", color=0xFF5733)
282
+ for i, bet in enumerate(user_bets[user_id], 1):
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}",
301
+ value=(
302
+ f"**Team:** {team}\n"
303
+ f"**Amount:** ${amount}\n"
304
+ f"**Game:** {game_description}\n"
305
+ f"**Status:** {status}\n"
306
+ f"**Current Score:** {score}\n"
307
+ f"**Start Time:** <t:{int(datetime.fromisoformat(start_time.replace('Z', '+00:00')).timestamp())}:F>"
308
+ ),
309
+ inline=False
310
+ )
311
 
312
  view = discord.ui.View()
313
+ cancel_select = discord.ui.Select(
314
+ placeholder="Select a bet to cancel",
315
+ min_values=1,
316
+ max_values=1,
317
+ options=[
318
+ discord.SelectOption(label=f"Bet {i}", value=str(i-1)) for i in range(1, len(user_bets[user_id]) + 1)
319
+ ]
320
+ )
321
  view.add_item(cancel_select)
322
 
323
  async def cancel_callback(interaction: discord.Interaction):
 
327
 
328
  bet_index = int(cancel_select.values[0])
329
  cancelled_bet = user_bets[user_id][bet_index]
330
+ league = cancelled_bet['league']
331
  game = cancelled_bet['game_data']
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)