Spaces:
Building
Building
Update sportbet.py
Browse files- sportbet.py +127 -146
sportbet.py
CHANGED
@@ -18,17 +18,14 @@ async def fetch_nhl_scores():
|
|
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 |
-
|
28 |
-
|
29 |
-
|
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,7 +54,8 @@ class SportSelect(discord.ui.Select):
|
|
57 |
if not scores:
|
58 |
await interaction.followup.send("No NFL games available for betting this week.", ephemeral=False)
|
59 |
return
|
60 |
-
|
|
|
61 |
if not upcoming_games:
|
62 |
await interaction.followup.send("No NFL games available for betting this week.", ephemeral=False)
|
63 |
return
|
@@ -159,154 +157,137 @@ class BetModal(discord.ui.Modal, title="Place Your Bet"):
|
|
159 |
"game_data": self.game_data
|
160 |
})
|
161 |
|
162 |
-
asyncio.create_task(self.monitor_game(interaction
|
|
|
163 |
except ValueError as e:
|
164 |
await interaction.response.send_message(str(e), ephemeral=False)
|
165 |
|
166 |
-
async def monitor_game(self, interaction
|
167 |
-
game_start = datetime.fromisoformat(self.game_data['eventTime'].replace('Z', '+00:00'))
|
168 |
-
event_id = self.game_data['id']
|
169 |
|
170 |
-
|
171 |
-
"NHL": fetch_nhl_scores,
|
172 |
-
"NFL": fetch_nfl_scores,
|
173 |
-
# Add other leagues here as needed.
|
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 |
-
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 |
-
|
244 |
-
|
245 |
-
|
246 |
-
@discord.ui.button(label
|
247 |
-
async def view_bets
|
248 |
-
|
249 |
-
|
250 |
-
async def show_current_bets
|
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 |
if interaction_cancel.user.id !=user_id :
|
291 |
-
await interaction_cancel.response.send_message("You cannot cancel other users' bets.",
|
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
|
297 |
-
|
298 |
-
if datetime.now(timezone.utc)
|
299 |
-
await interaction_cancel.response.send_message("You cannot cancel your bet as the game has already started.",
|
300 |
-
return
|
301 |
-
|
302 |
-
user_cash[user_id]
|
303 |
-
user_bets[user_id].pop(bet_index
|
304 |
-
await interaction_cancel.response.send_message(f"Bet cancelled. **${cancelled_bet ['amount']}** has been refunded.",
|
305 |
-
|
306 |
-
|
307 |
-
|
308 |
-
|
309 |
-
|
310 |
-
|
311 |
-
|
312 |
-
|
|
|
|
|
|
|
|
|
|
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):
|
|
|
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
|
|
|
157 |
"game_data": self.game_data
|
158 |
})
|
159 |
|
160 |
+
asyncio.create_task(self.monitor_game(interaction))
|
161 |
+
|
162 |
except ValueError as e:
|
163 |
await interaction.response.send_message(str(e), ephemeral=False)
|
164 |
|
165 |
+
async def monitor_game(self, interaction):
|
|
|
|
|
166 |
|
167 |
+
# Fetch initial scores and set up monitoring loop
|
|
|
|
|
|
|
|
|
168 |
|
169 |
+
previous_scores = {
|
170 |
+
self.game_data['lowerTeam']['name']: None,
|
171 |
+
self.game_data['upperTeam']['name']: None,
|
172 |
+
}
|
173 |
+
|
174 |
+
while True:
|
175 |
+
scores_response = await fetch_nhl_scores() if self.league == "NHL" else fetch_nfl_scores()
|
176 |
+
event_list_key='events' if 'events' in scores_response.get('sectionList', [{}])[0] else 'games'
|
177 |
+
current_game=None
|
178 |
+
|
179 |
+
for section in scores_response.get('sectionList', []):
|
180 |
+
for event in section.get(event_list_key , []):
|
181 |
+
if event['id'] == self.game_data['id']:
|
182 |
+
current_game=event
|
183 |
+
break
|
184 |
+
|
185 |
+
if not current_game:
|
186 |
+
await asyncio.sleep(60)
|
187 |
+
continue
|
188 |
+
|
189 |
+
current_scores={
|
190 |
+
current_game['lowerTeam']['name']: current_game['lowerTeam'].get('score'),
|
191 |
+
current_game['upperTeam']['name']: current_game['upperTeam'].get('score'),
|
192 |
+
}
|
193 |
+
|
194 |
+
score_changed=False
|
195 |
+
|
196 |
+
for team_name,current_score in current_scores.items():
|
197 |
+
previous_score=previous_scores[team_name]
|
198 |
+
|
199 |
+
if previous_score is None or current_score!=previous_score:
|
200 |
+
score_changed=True
|
201 |
+
|
202 |
+
previous_scores=current_scores.copy()
|
203 |
+
|
204 |
+
if score_changed:
|
205 |
+
away_score=current_scores[self.game_data['lowerTeam']['name']] or 'N/A'
|
206 |
+
home_score=current_scores[self.game_data['upperTeam']['name']] or 'N/A'
|
207 |
+
message=f"Current score update: {away_score} - {home_score}"
|
208 |
+
user=await interaction.client.fetch_user(self.user_id)
|
209 |
+
await user.send(message)
|
210 |
+
|
211 |
+
event_status=current_game.get('eventStatus')
|
212 |
+
|
213 |
+
if event_status==3:
|
214 |
+
break
|
215 |
+
|
216 |
+
await asyncio.sleep(60)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
217 |
|
218 |
class SportBetView(discord.ui.View):
|
219 |
def __init__(self):
|
220 |
+
super().__init__()
|
221 |
+
self.add_item(SportSelect())
|
222 |
+
|
223 |
+
@discord.ui.button(label="View Bets", style=discord.ButtonStyle.secondary)
|
224 |
+
async def view_bets(self ,interaction:discord.Interaction ,button :discord.ui.Button ):
|
225 |
+
await show_current_bets(interaction)
|
226 |
+
|
227 |
+
async def show_current_bets(interaction:discord.Interaction ):
|
228 |
+
user_id=interaction.user.id
|
229 |
+
|
230 |
+
if user_id not in user_bets or not user_bets[user_id]:
|
231 |
+
await interaction.response.send_message("You have no active bets." ,ephemeral=False )
|
232 |
+
return
|
233 |
+
|
234 |
+
embed=discord.Embed(title ="Your Current Bets" ,color=0x787878 )
|
235 |
+
|
236 |
+
for i ,bet in enumerate(user_bets[user_id] ,1 ):
|
237 |
+
league=bet ['league']
|
238 |
+
team=bet ['team']
|
239 |
+
amount=bet ['amount']
|
240 |
+
game=bet ['game_data']
|
241 |
+
away_score='N/A' if 'score' not in game ['lowerTeam'] else str(game ['lowerTeam']['score'])
|
242 |
+
home_score='N/A' if 'score' not in game ['upperTeam'] else str(game ['upperTeam']['score'])
|
243 |
+
status='Final' if 'score' in game ['upperTeam'] else f"Starts <t:{int(datetime.fromisoformat(game ['eventTime'].replace('Z','+00:00')).timestamp())}:R>"
|
244 |
+
|
245 |
+
embed.add_field(
|
246 |
+
name=f"Bet {i}: {league}" ,
|
247 |
+
value=(f"**Team:** {team}\n"
|
248 |
+
f"**Amount:** ${amount}\n"
|
249 |
+
f"**Game:** {game ['lowerTeam']['longName']} vs {game ['upperTeam']['longName']}\n"
|
250 |
+
f"**Status:** {status}\n"
|
251 |
+
f"**Current Score:** {away_score} - {home_score}\n"
|
252 |
+
f"**Start Time:** <t:{int(datetime.fromisoformat(game ['eventTime'].replace('Z','+00:00')).timestamp())}:F>"),
|
253 |
+
inline=False )
|
254 |
+
|
255 |
+
view=discord.ui.View()
|
256 |
+
cancel_select=discord.ui.Select(
|
257 |
+
placeholder ="Select a bet to cancel",
|
258 |
+
min_values=1 ,
|
259 |
+
max_values=1 ,
|
260 |
+
options=[
|
261 |
+
discord.SelectOption(label=f"Bet {i}" ,value=str(i-1)) for i in range(1 ,len(user_bets[user_id])+1 )
|
262 |
+
]
|
263 |
+
)
|
264 |
+
view.add_item(cancel_select)
|
265 |
+
|
266 |
+
async def cancel_callback(interaction_cancel :discord.Interaction ):
|
267 |
if interaction_cancel.user.id !=user_id :
|
268 |
+
await interaction_cancel.response.send_message("You cannot cancel other users' bets." ,ephemeral=False )
|
269 |
+
return
|
270 |
|
271 |
bet_index=int(cancel_select.values[0])
|
272 |
cancelled_bet=user_bets[user_id][bet_index]
|
273 |
+
start_time=datetime.fromisoformat(cancelled_bet ['game_data']['eventTime'].replace('Z','+00:00'))
|
274 |
+
|
275 |
+
if datetime.now(timezone.utc)>=start_time :
|
276 |
+
await interaction_cancel.response.send_message("You cannot cancel your bet as the game has already started." ,ephemeral=False )
|
277 |
+
return
|
278 |
+
|
279 |
+
user_cash[user_id]+=cancelled_bet ['amount']
|
280 |
+
user_bets[user_id].pop(bet_index)
|
281 |
+
await interaction_cancel.response.send_message(f"Bet cancelled. **${cancelled_bet ['amount']}** has been refunded." ,ephemeral=False )
|
282 |
+
|
283 |
+
if not user_bets[user_id]:
|
284 |
+
del user_bets[user_id]
|
285 |
+
|
286 |
+
cancel_select.callback=cancel_callback
|
287 |
+
|
288 |
+
await interaction.response.send_message(embed=embed ,view=view ,ephemeral=False )
|
289 |
+
|
290 |
+
@app_commands.command(name ="sportbet" ,description ="Bet on sports games")
|
291 |
+
async def sportbet(interaction :discord.Interaction ):
|
292 |
+
view=SportBetView()
|
293 |
+
await interaction.response.send_message("Select a sport to bet on:" ,view=view ,ephemeral=False )
|