coollsd commited on
Commit
5a642ea
·
verified ·
1 Parent(s): d478ceb

Update sportbet.py

Browse files
Files changed (1) hide show
  1. sportbet.py +265 -211
sportbet.py CHANGED
@@ -3,128 +3,76 @@ 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
- 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}"
15
- async with aiohttp.ClientSession() as session:
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):
32
- options = [
33
- discord.SelectOption(label="NHL", description="Bet on NHL games"),
34
- discord.SelectOption(label="NFL", description="Bet on NFL games")
35
- ]
36
- super().__init__(placeholder="Select a sport to bet on", min_values=1, max_values=1, options=options)
37
 
38
- async def callback(self, interaction: discord.Interaction):
39
- selected_sport = self.values[0]
40
- await interaction.response.edit_message(content=f"Selected Sport: {selected_sport}. Fetching games...", view=None)
41
- await asyncio.sleep(1) # Brief pause for better UX
42
-
43
- if selected_sport == "NHL":
44
- scores = await fetch_nhl_scores()
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
-
79
- class GameOptionSelect(discord.ui.Select):
80
- def __init__(self, options, league, games):
81
- super().__init__(placeholder="Select a game", min_values=1, max_values=1, options=options)
82
- self.league = league
83
- self.games = games
84
 
85
  async def callback(self, interaction: discord.Interaction):
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
 
109
  class TeamOptionSelect(discord.ui.Select):
110
- def __init__(self, options, league, game):
111
  super().__init__(placeholder="Select a team to bet on", min_values=1, max_values=1, options=options)
112
- self.league = league
113
  self.game = game
114
 
115
  async def callback(self, interaction: discord.Interaction):
116
  selected_team = self.values[0]
117
- await interaction.response.send_modal(BetModal(selected_team, interaction.user.id, self.game, self.league))
118
 
119
  class BetModal(discord.ui.Modal, title="Place Your Bet"):
120
  bet_amount = discord.ui.TextInput(label="Bet Amount", placeholder="Enter bet amount", required=True)
121
 
122
- def __init__(self, team, user_id, game_data, league):
123
  super().__init__()
124
  self.team = team
125
  self.user_id = user_id
126
  self.game_data = game_data
127
- self.league = league
128
 
129
  async def on_submit(self, interaction: discord.Interaction):
130
  try:
@@ -135,14 +83,14 @@ class BetModal(discord.ui.Modal, title="Place Your Bet"):
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)
142
- embed.add_field(name="League", value=self.league, inline=False)
143
  embed.add_field(name="Team", value=self.team, inline=False)
144
  embed.add_field(name="Amount", value=f"${bet_amount}", inline=False)
145
- game_description = f"{self.game_data['lowerTeam']['longName']} vs {self.game_data['upperTeam']['longName']}"
146
  start_time = self.game_data['eventTime']
147
  embed.add_field(name="Game", value=game_description, inline=False)
148
  embed.add_field(name="Start Time", value=f"<t:{int(datetime.fromisoformat(start_time.replace('Z', '+00:00')).timestamp())}:F>", inline=False)
@@ -150,150 +98,256 @@ class BetModal(discord.ui.Modal, title="Place Your Bet"):
150
 
151
  if self.user_id not in user_bets:
152
  user_bets[self.user_id] = []
153
-
154
- # Initialize previous scores to None to track changes only when they occur.
155
  user_bets[self.user_id].append({
156
- "league": self.league,
157
  "team": self.team,
158
  "amount": bet_amount,
159
- "game_data": self.game_data,
160
- "previous_scores": {
161
- "away": None,
162
- "home": None,
163
- }
164
  })
165
 
166
  asyncio.create_task(self.monitor_game(interaction))
167
 
168
  except ValueError as e:
169
- await interaction.response.send_message(str(e), ephemeral=False)
170
 
171
  async def monitor_game(self, interaction):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
172
 
173
- previous_scores={
174
- "away": None,
175
- "home": None,
176
- }
177
-
178
- while True:
179
- scores_response=await fetch_nhl_scores() if self.league =="NHL" else fetch_nfl_scores()
180
- event_list_key='events' if 'events' in scores_response.get('sectionList', [{}])[0] else 'games'
181
- current_game=None
182
-
183
- for section in scores_response.get('sectionList', []):
184
- for event in section.get(event_list_key , []):
185
- if event['id']==self.game_data['id']:
186
- current_game=event
187
- break
188
-
189
- if not current_game:
190
- await asyncio.sleep(60)
191
- continue
192
-
193
- current_scores={
194
- "away": current_game['lowerTeam'].get('score'),
195
- "home": current_game['upperTeam'].get('score'),
196
- }
197
-
198
- score_changed=False
199
-
200
- for key in ["away","home"]:
201
- current_score=current_scores[key]
202
- previous_score=previous_scores[key]
203
-
204
- # Only notify when the score changes from a non-None state.
205
- if previous_score is not None and current_score!=previous_score:
206
- score_changed=True
207
-
208
- previous_scores=current_scores.copy()
209
-
210
- if score_changed:
211
- away_score=current_scores["away"] or 'N/A'
212
- home_score=current_scores["home"] or 'N/A'
213
- message=f"Score update: {away_score} - {home_score}"
214
- user=await interaction.client.fetch_user(self.user_id)
215
- await user.send(message)
216
-
217
- event_status=current_game.get('eventStatus')
218
-
219
- if event_status==3:
220
- break
221
-
222
- await asyncio.sleep(60)
223
-
224
- class SportBetView(discord.ui.View):
225
- def __init__(self):
226
- super().__init__()
227
- self.add_item(SportSelect())
228
-
229
- @discord.ui.button(label="View Bets", style=discord.ButtonStyle.secondary)
230
- async def view_bets(self ,interaction:discord.Interaction ,button :discord.ui.Button ):
231
- await show_current_bets(interaction)
232
-
233
- async def show_current_bets(interaction:discord.Interaction ):
234
- user_id=interaction.user.id
235
-
236
- if user_id not in user_bets or not user_bets[user_id]:
237
- await interaction.response.send_message("You have no active bets." ,ephemeral=False )
238
- return
239
-
240
- embed=discord.Embed(title ="Your Current Bets" ,color=0x787878 )
241
-
242
- for i ,bet in enumerate(user_bets[user_id] ,1 ):
243
- league=bet ['league']
244
- team=bet ['team']
245
- amount=bet ['amount']
246
- game=bet ['game_data']
247
- away_score='N/A' if 'score' not in game ['lowerTeam'] else str(game ['lowerTeam']['score'])
248
- home_score='N/A' if 'score' not in game ['upperTeam'] else str(game ['upperTeam']['score'])
249
- status='Final' if 'score' in game ['upperTeam'] else f"Starts <t:{int(datetime.fromisoformat(game ['eventTime'].replace('Z','+00:00')).timestamp())}:R>"
250
-
251
- embed.add_field(
252
- name=f"Bet {i}: {league}" ,
253
- value=(f"**Team:** {team}\n"
254
- f"**Amount:** ${amount}\n"
255
- f"**Game:** {game ['lowerTeam']['longName']} vs {game ['upperTeam']['longName']}\n"
256
- f"**Status:** {status}\n"
257
- f"**Current Score:** {away_score} - {home_score}\n"
258
- f"**Start Time:** <t:{int(datetime.fromisoformat(game ['eventTime'].replace('Z','+00:00')).timestamp())}:F>"),
259
- inline=False )
260
-
261
- view=discord.ui.View()
262
- cancel_select=discord.ui.Select(
263
- placeholder ="Select a bet to cancel",
264
- min_values=1 ,
265
- max_values=1 ,
266
- options=[
267
- discord.SelectOption(label=f"Bet {i}" ,value=str(i-1)) for i in range(1 ,len(user_bets[user_id])+1 )
268
- ]
269
- )
270
- view.add_item(cancel_select)
271
-
272
- async def cancel_callback(interaction_cancel :discord.Interaction ):
273
- if interaction_cancel.user.id !=user_id :
274
- await interaction_cancel.response.send_message("You cannot cancel other users' bets." ,ephemeral=False )
275
- return
276
-
277
- bet_index=int(cancel_select.values[0])
278
- cancelled_bet=user_bets[user_id][bet_index]
279
- start_time=datetime.fromisoformat(cancelled_bet ['game_data']['eventTime'].replace('Z','+00:00'))
280
-
281
- if datetime.now(timezone.utc)>=start_time :
282
- await interaction_cancel.response.send_message("You cannot cancel your bet as the game has already started." ,ephemeral=False )
283
- return
284
-
285
- user_cash[user_id]+=cancelled_bet ['amount']
286
- user_bets[user_id].pop(bet_index)
287
- await interaction_cancel.response.send_message(f"Bet cancelled. **${cancelled_bet ['amount']}** has been refunded." ,ephemeral=False )
288
-
289
- if not user_bets[user_id]:
290
- del user_bets[user_id]
291
-
292
- cancel_select.callback=cancel_callback
293
-
294
- await interaction.response.send_message(embed=embed ,view=view ,ephemeral=False )
295
-
296
- @app_commands.command(name ="sportbet" ,description ="Bet on sports games")
297
- async def sportbet(interaction :discord.Interaction ):
298
- view=SportBetView()
299
- await interaction.response.send_message("Select a sport to bet on:" ,view=view ,ephemeral=False )
 
3
  import aiohttp
4
  import asyncio
5
  from datetime import datetime, timezone, timedelta
6
+ from cash import user_cash
7
 
8
  user_bets = {}
9
 
10
  API_KEY = "jE7yBJVRNAwdDesMgTzTXUUSx1It41Fq"
11
 
 
 
 
 
 
 
 
12
  async def fetch_nfl_scores():
13
  current_year = datetime.now().year
14
+ for week in range(1, 18):
15
  url = f"https://api.foxsports.com/bifrost/v1/nfl/scoreboard/segment/{current_year}-{week}-1?apikey={API_KEY}"
16
  async with aiohttp.ClientSession() as session:
17
  async with session.get(url) as response:
18
  data = await response.json()
19
  if data['sectionList'][0]['events'][0]['eventStatus'] == 2:
20
  return data
21
+ return None
 
 
 
 
 
 
 
 
22
 
23
+ class NFLBetView(discord.ui.View):
24
+ def __init__(self, games):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25
  super().__init__()
26
+ self.add_item(GameSelect(games))
27
+
28
+ class GameSelect(discord.ui.Select):
29
+ def __init__(self, games):
30
  options = [
31
  discord.SelectOption(
32
+ label=f"{game['upperTeam']['longName']} vs {game['lowerTeam']['longName']}",
33
  value=game['id'],
34
  description=f"Start time: <t:{int(datetime.fromisoformat(game['eventTime'].replace('Z', '+00:00')).timestamp())}:F>"
35
  ) for game in games
36
  ]
37
+ super().__init__(placeholder="Select a game to bet on", min_values=1, max_values=1, options=options)
38
  self.games = {game['id']: game for game in games}
 
 
 
 
 
 
 
39
 
40
  async def callback(self, interaction: discord.Interaction):
41
  selected_game_id = self.values[0]
42
  game_data = self.games.get(selected_game_id)
43
  if not game_data:
44
+ await interaction.response.send_message("Selected game data not found.", ephemeral=True)
45
  return
46
+ await interaction.response.edit_message(content="Select a team to bet on:", view=TeamSelect(game_data))
 
 
 
47
 
48
  class TeamSelect(discord.ui.View):
49
+ def __init__(self, game):
50
  super().__init__()
51
+ away_team = game['upperTeam']
52
+ home_team = game['lowerTeam']
 
53
  options = [
54
  discord.SelectOption(label=away_team['longName'], value=away_team['name']),
55
  discord.SelectOption(label=home_team['longName'], value=home_team['name'])
56
  ]
57
+ self.add_item(TeamOptionSelect(options, game))
 
58
 
59
  class TeamOptionSelect(discord.ui.Select):
60
+ def __init__(self, options, game):
61
  super().__init__(placeholder="Select a team to bet on", min_values=1, max_values=1, options=options)
 
62
  self.game = game
63
 
64
  async def callback(self, interaction: discord.Interaction):
65
  selected_team = self.values[0]
66
+ await interaction.response.send_modal(BetModal(selected_team, interaction.user.id, self.game))
67
 
68
  class BetModal(discord.ui.Modal, title="Place Your Bet"):
69
  bet_amount = discord.ui.TextInput(label="Bet Amount", placeholder="Enter bet amount", required=True)
70
 
71
+ def __init__(self, team, user_id, game_data):
72
  super().__init__()
73
  self.team = team
74
  self.user_id = user_id
75
  self.game_data = game_data
 
76
 
77
  async def on_submit(self, interaction: discord.Interaction):
78
  try:
 
83
  raise ValueError("Insufficient balance. Please check your balance and try again.")
84
 
85
  user_cash[self.user_id] -= bet_amount
86
+ await interaction.response.send_message(f"Bet placed on **{self.team}** for **${bet_amount}**.", ephemeral=True)
87
 
88
  user = await interaction.client.fetch_user(self.user_id)
89
  embed = discord.Embed(title="Bet Placed", color=0x787878)
90
+ embed.add_field(name="League", value="NFL", inline=False)
91
  embed.add_field(name="Team", value=self.team, inline=False)
92
  embed.add_field(name="Amount", value=f"${bet_amount}", inline=False)
93
+ game_description = f"{self.game_data['upperTeam']['longName']} vs {self.game_data['lowerTeam']['longName']}"
94
  start_time = self.game_data['eventTime']
95
  embed.add_field(name="Game", value=game_description, inline=False)
96
  embed.add_field(name="Start Time", value=f"<t:{int(datetime.fromisoformat(start_time.replace('Z', '+00:00')).timestamp())}:F>", inline=False)
 
98
 
99
  if self.user_id not in user_bets:
100
  user_bets[self.user_id] = []
 
 
101
  user_bets[self.user_id].append({
102
+ "league": "NFL",
103
  "team": self.team,
104
  "amount": bet_amount,
105
+ "game_data": self.game_data
 
 
 
 
106
  })
107
 
108
  asyncio.create_task(self.monitor_game(interaction))
109
 
110
  except ValueError as e:
111
+ await interaction.response.send_message(str(e), ephemeral=True)
112
 
113
  async def monitor_game(self, interaction):
114
+ previous_scores = {
115
+ self.game_data['upperTeam']['name']: None,
116
+ self.game_data['lowerTeam']['name']: None,
117
+ }
118
+
119
+ while True:
120
+ scores_response = await fetch_nfl_scores()
121
+ if not scores_response:
122
+ await asyncio.sleep(60)
123
+ continue
124
+
125
+ current_game = None
126
+ for section in scores_response.get('sectionList', []):
127
+ for event in section.get('events', []):
128
+ if event['id'] == self.game_data['id']:
129
+ current_game = event
130
+ break
131
+ if current_game:
132
+ break
133
+
134
+ if not current_game:
135
+ await asyncio.sleep(60)
136
+ continue
137
+
138
+ current_scores = {
139
+ current_game['upperTeam']['name']: current_game['upperTeam'].get('score'),
140
+ current_game['lowerTeam']['name']: current_game['lowerTeam'].get('score'),
141
+ }
142
+
143
+ score_changed = False
144
+ for team_name, current_score in current_scores.items():
145
+ previous_score = previous_scores[team_name]
146
+ if previous_score is None or current_score != previous_score:
147
+ score_changed = True
148
+
149
+ previous_scores = current_scores.copy()
150
+
151
+ if score_changed:
152
+ away_score = current_scores[self.game_data['upperTeam']['name']] or 'N/A'
153
+ home_score = current_scores[self.game_data['lowerTeam']['name']] or 'N/A'
154
+ message = f"Current score update: {away_score} - {home_score}"
155
+ user = await interaction.client.fetch_user(self.user_id)
156
+ await user.send(message)
157
+
158
+ event_status = current_game.get('eventStatus')
159
+ if event_status == 3:
160
+ winner = self.game_data['upperTeam']['name'] if current_scores[self.game_data['upperTeam']['name']] > current_scores[self.game_data['lowerTeam']['name']] else self.game_data['lowerTeam']['name']
161
+ bet_result = "won" if winner == self.team else "lost"
162
+ final_message = f"Game over! Final score: {away_score} - {home_score}. You {bet_result} your bet on {self.team}."
163
+ user = await interaction.client.fetch_user(self.user_id)
164
+ await user.send(final_message)
165
+ break
166
+
167
+ await asyncio.sleep(60)
168
+
169
+ @app_commands.command(name="nflbet", description="Bet on NFL games")
170
+ async def nflbet(interaction: discord.Interaction):
171
+ scores = await fetch_nfl_scores()
172
+ if not scores:
173
+ await interaction.response.send_message("No NFL games available for betting this week.", ephemeral=True)
174
+ return
175
+
176
+ events = scores.get('sectionList', [])[0].get('events', [])
177
+ upcoming_games = [game for game in events if game.get('eventStatus') == 2]
178
+
179
+ if not upcoming_games:
180
+ await interaction.response.send_message("No NFL games available for betting this week.", ephemeral=True)
181
+ return
182
+
183
+ view = NFLBetView(upcoming_games)
184
+ await interaction.response.send_message("Select a game to bet on:", view=view, ephemeral=True)
185
+
186
+ @app_commands.command(name="viewbets", description="View your current bets")
187
+ async def viewbets(interaction: discord.Interaction):
188
+ user_id = interaction.user.id
189
+
190
+ if user_id not in user_bets or not user_bets[user_id]:
191
+ await interaction.response.send_message("You have no active bets.", ephemeral=True)
192
+ return
193
+
194
+ embed = discord.Embed(title="Your Current Bets", color=0x787878)
195
+
196
+ for i, bet in enumerate(user_bets[user_id], 1):
197
+ league = bet['league']
198
+ team = bet['team']
199
+ amount = bet['amount']
200
+ game = bet['game_data']
201
+ away_score = 'N/A' if 'score' not in game['upperTeam'] else str(game['upperTeam']['score'])
202
+ home_score = 'N/A' if 'score' not in game['lowerTeam'] else str(game['lowerTeam']['score'])
203
+ start_time = datetime.fromisoformat(game['eventTime'].replace('Z', '+00:00'))
204
+ current_time = datetime.now(timezone.utc)
205
+
206
+ if current_time < start_time:
207
+ status = f"Starts <t:{int(start_time.timestamp())}:R>"
208
+ elif 'score' in game['lowerTeam']:
209
+ status = 'Final'
210
+ winner = game['upperTeam']['name'] if game['upperTeam']['score'] > game['lowerTeam']['score'] else game['lowerTeam']['name']
211
+ bet_result = "Won" if winner == team else "Lost"
212
+ else:
213
+ status = "In Progress"
214
+ bet_result = "Pending"
215
+
216
+ embed.add_field(
217
+ name=f"Bet {i}: {league}",
218
+ value=(f"**Team:** {team}\n"
219
+ f"**Amount:** ${amount}\n"
220
+ f"**Game:** {game['upperTeam']['longName']} vs {game['lowerTeam']['longName']}\n"
221
+ f"**Status:** {status}\n"
222
+ f"**Current Score:** {away_score} - {home_score}\n"
223
+ f"**Start Time:** <t:{int(start_time.timestamp())}:F>\n"
224
+ f"**Bet Result:** {bet_result}"),
225
+ inline=False)
226
+
227
+ view = discord.ui.View()
228
+ cancel_select = discord.ui.Select(
229
+ placeholder="Select a bet to cancel",
230
+ min_values=1,
231
+ max_values=1,
232
+ options=[
233
+ discord.SelectOption(label=f"Bet {i}", value=str(i-1)) for i in range(1, len(user_bets[user_id])+1)
234
+ ]
235
+ )
236
+ view.add_item(cancel_select)
237
+
238
+ async def cancel_callback(interaction_cancel: discord.Interaction):
239
+ if interaction_cancel.user.id != user_id:
240
+ await interaction_cancel.response.send_message("You cannot cancel other users' bets.", ephemeral=True)
241
+ return
242
+
243
+ bet_index = int(cancel_select.values[0])
244
+ cancelled_bet = user_bets[user_id][bet_index]
245
+ start_time = datetime.fromisoformat(cancelled_bet['game_data']['eventTime'].replace('Z', '+00:00'))
246
+
247
+ if datetime.now(timezone.utc) >= start_time:
248
+ await interaction_cancel.response.send_message("You cannot cancel your bet as the game has already started.", ephemeral=True)
249
+ return
250
+
251
+ user_cash[user_id] += cancelled_bet['amount']
252
+ user_bets[user_id].pop(bet_index)
253
+ await interaction_cancel.response.send_message(f"Bet cancelled. **${cancelled_bet['amount']}** has been refunded.", ephemeral=True)
254
+
255
+ if not user_bets[user_id]:
256
+ del user_bets[user_id]
257
+
258
+ cancel_select.callback = cancel_callback
259
+
260
+ await interaction.response.send_message(embed=embed, view=view, ephemeral=True)
261
+
262
+ @app_commands.command(name="nflbet", description="Bet on NFL games")
263
+ async def nflbet(interaction: discord.Interaction):
264
+ scores = await fetch_nfl_scores()
265
+ if not scores:
266
+ await interaction.response.send_message("No NFL games available for betting this week.", ephemeral=True)
267
+ return
268
+
269
+ events = scores.get('sectionList', [])[0].get('events', [])
270
+ upcoming_games = [game for game in events if game.get('eventStatus') == 2]
271
+
272
+ if not upcoming_games:
273
+ await interaction.response.send_message("No NFL games available for betting this week.", ephemeral=True)
274
+ return
275
+
276
+ view = NFLBetView(upcoming_games)
277
+ await interaction.response.send_message("Select a game to bet on:", view=view, ephemeral=True)
278
+
279
+ @app_commands.command(name="viewbets", description="View your current bets")
280
+ async def viewbets(interaction: discord.Interaction):
281
+ user_id = interaction.user.id
282
+
283
+ if user_id not in user_bets or not user_bets[user_id]:
284
+ await interaction.response.send_message("You have no active bets.", ephemeral=True)
285
+ return
286
+
287
+ embed = discord.Embed(title="Your Current Bets", color=0x787878)
288
+
289
+ for i, bet in enumerate(user_bets[user_id], 1):
290
+ league = bet['league']
291
+ team = bet['team']
292
+ amount = bet['amount']
293
+ game = bet['game_data']
294
+ away_score = 'N/A' if 'score' not in game['upperTeam'] else str(game['upperTeam']['score'])
295
+ home_score = 'N/A' if 'score' not in game['lowerTeam'] else str(game['lowerTeam']['score'])
296
+ start_time = datetime.fromisoformat(game['eventTime'].replace('Z', '+00:00'))
297
+ current_time = datetime.now(timezone.utc)
298
 
299
+ if current_time < start_time:
300
+ status = f"Starts <t:{int(start_time.timestamp())}:R>"
301
+ elif 'score' in game['lowerTeam']:
302
+ status = 'Final'
303
+ winner = game['upperTeam']['name'] if game['upperTeam']['score'] > game['lowerTeam']['score'] else game['lowerTeam']['name']
304
+ bet_result = "Won" if winner == team else "Lost"
305
+ else:
306
+ status = "In Progress"
307
+ bet_result = "Pending"
308
+
309
+ embed.add_field(
310
+ name=f"Bet {i}: {league}",
311
+ value=(f"**Team:** {team}\n"
312
+ f"**Amount:** ${amount}\n"
313
+ f"**Game:** {game['upperTeam']['longName']} vs {game['lowerTeam']['longName']}\n"
314
+ f"**Status:** {status}\n"
315
+ f"**Current Score:** {away_score} - {home_score}\n"
316
+ f"**Start Time:** <t:{int(start_time.timestamp())}:F>\n"
317
+ f"**Bet Result:** {bet_result}"),
318
+ inline=False)
319
+
320
+ view = discord.ui.View()
321
+ cancel_select = discord.ui.Select(
322
+ placeholder="Select a bet to cancel",
323
+ min_values=1,
324
+ max_values=1,
325
+ options=[
326
+ discord.SelectOption(label=f"Bet {i}", value=str(i-1)) for i in range(1, len(user_bets[user_id])+1)
327
+ ]
328
+ )
329
+ view.add_item(cancel_select)
330
+
331
+ async def cancel_callback(interaction_cancel: discord.Interaction):
332
+ if interaction_cancel.user.id != user_id:
333
+ await interaction_cancel.response.send_message("You cannot cancel other users' bets.", ephemeral=True)
334
+ return
335
+
336
+ bet_index = int(cancel_select.values[0])
337
+ cancelled_bet = user_bets[user_id][bet_index]
338
+ start_time = datetime.fromisoformat(cancelled_bet['game_data']['eventTime'].replace('Z', '+00:00'))
339
+
340
+ if datetime.now(timezone.utc) >= start_time:
341
+ await interaction_cancel.response.send_message("You cannot cancel your bet as the game has already started.", ephemeral=True)
342
+ return
343
+
344
+ user_cash[user_id] += cancelled_bet['amount']
345
+ user_bets[user_id].pop(bet_index)
346
+ await interaction_cancel.response.send_message(f"Bet cancelled. **${cancelled_bet['amount']}** has been refunded.", ephemeral=True)
347
+
348
+ if not user_bets[user_id]:
349
+ del user_bets[user_id]
350
+
351
+ cancel_select.callback = cancel_callback
352
+
353
+ await interaction.response.send_message(embed=embed, view=view, ephemeral=True)