Spaces:
Building
Building
Update sportbet.py
Browse files- sportbet.py +149 -142
sportbet.py
CHANGED
@@ -18,14 +18,17 @@ async def fetch_nhl_scores():
|
|
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 |
-
|
27 |
-
|
28 |
-
|
|
|
|
|
29 |
|
30 |
class SportSelect(discord.ui.Select):
|
31 |
def __init__(self):
|
@@ -54,8 +57,7 @@ class SportSelect(discord.ui.Select):
|
|
54 |
if not scores:
|
55 |
await interaction.followup.send("No NFL games available for betting this week.", ephemeral=False)
|
56 |
return
|
57 |
-
|
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
|
@@ -161,145 +163,150 @@ class BetModal(discord.ui.Modal, title="Place Your Bet"):
|
|
161 |
except ValueError as e:
|
162 |
await interaction.response.send_message(str(e), ephemeral=False)
|
163 |
|
164 |
-
async def monitor_game(self, interaction, bet_amount):
|
165 |
game_start = datetime.fromisoformat(self.game_data['eventTime'].replace('Z', '+00:00'))
|
166 |
event_id = self.game_data['id']
|
167 |
-
|
168 |
-
|
169 |
-
|
170 |
-
|
171 |
-
|
172 |
-
|
173 |
-
|
174 |
-
|
175 |
-
|
176 |
-
|
177 |
-
|
178 |
-
|
179 |
-
|
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 |
-
|
206 |
-
|
207 |
-
|
208 |
-
|
209 |
-
|
210 |
-
|
211 |
-
|
212 |
-
|
213 |
-
|
214 |
-
|
215 |
-
|
216 |
-
|
217 |
-
|
218 |
-
|
219 |
-
|
220 |
-
|
221 |
-
|
222 |
-
|
223 |
-
|
224 |
-
|
225 |
-
|
226 |
-
|
227 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
228 |
|
229 |
class SportBetView(discord.ui.View):
|
230 |
def __init__(self):
|
231 |
-
|
232 |
-
|
233 |
-
|
234 |
-
|
235 |
-
|
236 |
-
|
237 |
-
|
238 |
-
async def show_current_bets(interaction:
|
239 |
-
|
240 |
-
|
241 |
-
|
242 |
-
|
243 |
-
|
244 |
-
|
245 |
-
|
246 |
-
|
247 |
-
|
248 |
-
|
249 |
-
|
250 |
-
|
251 |
-
|
252 |
-
|
253 |
-
|
254 |
-
|
255 |
-
|
256 |
-
|
257 |
-
|
258 |
-
|
259 |
-
|
260 |
-
|
261 |
-
|
262 |
-
|
263 |
-
|
264 |
-
|
265 |
-
|
266 |
-
|
267 |
-
|
268 |
-
|
269 |
-
|
270 |
-
|
271 |
-
|
272 |
-
|
273 |
-
|
274 |
-
|
275 |
-
|
276 |
-
|
277 |
-
|
278 |
-
|
279 |
-
|
280 |
-
|
281 |
-
|
282 |
-
|
283 |
-
|
284 |
-
|
285 |
-
|
286 |
-
|
287 |
-
|
288 |
-
|
289 |
-
|
290 |
-
|
291 |
-
|
292 |
-
|
293 |
-
|
294 |
-
|
295 |
-
|
296 |
-
|
297 |
-
|
298 |
-
|
299 |
-
|
300 |
-
|
301 |
-
|
302 |
-
@app_commands.command(name="sportbet", description="Bet on sports games")
|
303 |
-
async def sportbet(interaction: discord.Interaction):
|
304 |
-
view = SportBetView()
|
305 |
-
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 |
+
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 |
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
|
|
|
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 )
|
|
|
|
|
|
|
|
|
|