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