Spaces:
Paused
Paused
Update sportbet.py
Browse files- sportbet.py +65 -144
sportbet.py
CHANGED
|
@@ -9,20 +9,6 @@ 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(timezone.utc)
|
| 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}"
|
|
@@ -30,11 +16,16 @@ async def fetch_nhl_scores():
|
|
| 30 |
async with session.get(url) as response:
|
| 31 |
return await response.json()
|
| 32 |
|
| 33 |
-
async def fetch_nfl_scores(
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 38 |
|
| 39 |
class SportSelect(discord.ui.Select):
|
| 40 |
def __init__(self):
|
|
@@ -59,36 +50,29 @@ class SportSelect(discord.ui.Select):
|
|
| 59 |
view = GameSelect(upcoming_games, "NHL")
|
| 60 |
await interaction.followup.send("Select a game to bet on:", view=view, ephemeral=True)
|
| 61 |
elif selected_sport == "NFL":
|
| 62 |
-
|
| 63 |
-
|
|
|
|
|
|
|
| 64 |
events = scores.get('sectionList', [])[0].get('events', [])
|
| 65 |
upcoming_games = [game for game in events if game.get('eventStatus') == 2]
|
| 66 |
if not upcoming_games:
|
| 67 |
await interaction.followup.send("No NFL games available for betting this week.", ephemeral=True)
|
| 68 |
return
|
| 69 |
view = GameSelect(upcoming_games, "NFL")
|
| 70 |
-
await interaction.followup.send(
|
| 71 |
|
| 72 |
class GameSelect(discord.ui.View):
|
| 73 |
def __init__(self, games, league):
|
| 74 |
super().__init__()
|
| 75 |
self.league = league
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
]
|
| 84 |
-
elif self.league == "NFL":
|
| 85 |
-
options = [
|
| 86 |
-
discord.SelectOption(
|
| 87 |
-
label=f"{game['lowerTeam']['longName']} vs {game['upperTeam']['longName']}",
|
| 88 |
-
value=game['id'],
|
| 89 |
-
description=f"Start time: <t:{int(datetime.fromisoformat(game['eventTime'].replace('Z', '+00:00')).timestamp())}:F>"
|
| 90 |
-
) for game in games
|
| 91 |
-
]
|
| 92 |
self.games = {game['id']: game for game in games}
|
| 93 |
self.add_item(GameOptionSelect(options, self.league, self.games))
|
| 94 |
|
|
@@ -113,20 +97,12 @@ class TeamSelect(discord.ui.View):
|
|
| 113 |
def __init__(self, game, league):
|
| 114 |
super().__init__()
|
| 115 |
self.league = league
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
]
|
| 123 |
-
elif self.league == "NFL":
|
| 124 |
-
away_team = game['lowerTeam']
|
| 125 |
-
home_team = game['upperTeam']
|
| 126 |
-
options = [
|
| 127 |
-
discord.SelectOption(label=away_team['longName'], value=away_team['name']),
|
| 128 |
-
discord.SelectOption(label=home_team['longName'], value=home_team['name'])
|
| 129 |
-
]
|
| 130 |
self.game = game
|
| 131 |
self.add_item(TeamOptionSelect(options, league, game))
|
| 132 |
|
|
@@ -166,12 +142,8 @@ class BetModal(discord.ui.Modal, title="Place Your Bet"):
|
|
| 166 |
embed.add_field(name="League", value=self.league, inline=False)
|
| 167 |
embed.add_field(name="Team", value=self.team, inline=False)
|
| 168 |
embed.add_field(name="Amount", value=f"${bet_amount}", inline=False)
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
start_time = self.game_data['eventTime']
|
| 172 |
-
elif self.league == "NFL":
|
| 173 |
-
game_description = f"{self.game_data['lowerTeam']['longName']} vs {self.game_data['upperTeam']['longName']}"
|
| 174 |
-
start_time = self.game_data['eventTime']
|
| 175 |
embed.add_field(name="Game", value=game_description, inline=False)
|
| 176 |
embed.add_field(name="Start Time", value=f"<t:{int(datetime.fromisoformat(start_time.replace('Z', '+00:00')).timestamp())}:F>", inline=False)
|
| 177 |
await user.send(embed=embed)
|
|
@@ -190,14 +162,9 @@ class BetModal(discord.ui.Modal, title="Place Your Bet"):
|
|
| 190 |
await interaction.response.send_message(str(e), ephemeral=True)
|
| 191 |
|
| 192 |
async def monitor_game(self, interaction, bet_amount):
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
fetch_scores = fetch_nhl_scores
|
| 197 |
-
elif self.league == "NFL":
|
| 198 |
-
game_start = datetime.fromisoformat(self.game_data['eventTime'].replace('Z', '+00:00'))
|
| 199 |
-
event_id = self.game_data['id']
|
| 200 |
-
fetch_scores = lambda: fetch_nfl_scores(get_current_nfl_week())
|
| 201 |
|
| 202 |
sleep_duration = (game_start - datetime.now(timezone.utc)).total_seconds()
|
| 203 |
if sleep_duration > 0:
|
|
@@ -206,80 +173,45 @@ class BetModal(discord.ui.Modal, title="Place Your Bet"):
|
|
| 206 |
user = await interaction.client.fetch_user(self.user_id)
|
| 207 |
await user.send(f"Your team **{self.team}** has started playing!")
|
| 208 |
|
| 209 |
-
previous_scores = {
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
self.game_data['upperTeam']['name']: self.game_data.get('upperTeam', {}).get('score', 0)
|
| 214 |
-
}
|
| 215 |
-
elif self.league == "NFL":
|
| 216 |
-
previous_scores = {
|
| 217 |
-
self.game_data['lowerTeam']['name']: self.game_data.get('lowerTeam', {}).get('score', 0),
|
| 218 |
-
self.game_data['upperTeam']['name']: self.game_data.get('upperTeam', {}).get('score', 0)
|
| 219 |
-
}
|
| 220 |
|
| 221 |
while True:
|
| 222 |
scores = await fetch_scores()
|
| 223 |
-
|
| 224 |
-
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
if evt['id'] == event_id:
|
| 229 |
-
game = evt
|
| 230 |
-
break
|
| 231 |
-
if game:
|
| 232 |
-
break
|
| 233 |
-
if not game:
|
| 234 |
-
await asyncio.sleep(60)
|
| 235 |
-
continue
|
| 236 |
-
event_status = game.get('eventStatus', 2)
|
| 237 |
-
current_scores = {
|
| 238 |
-
game['lowerTeam']['name']: game.get('lowerTeam', {}).get('score', 0),
|
| 239 |
-
game['upperTeam']['name']: game.get('upperTeam', {}).get('score', 0)
|
| 240 |
-
}
|
| 241 |
-
is_final = event_status == 3
|
| 242 |
-
elif self.league == "NFL":
|
| 243 |
-
sections = scores.get('sectionList', [])
|
| 244 |
-
game = None
|
| 245 |
-
for section in sections:
|
| 246 |
-
for evt in section.get('events', []):
|
| 247 |
-
if evt['id'] == event_id:
|
| 248 |
-
game = evt
|
| 249 |
-
break
|
| 250 |
-
if game:
|
| 251 |
break
|
| 252 |
-
if
|
| 253 |
-
|
| 254 |
-
|
| 255 |
-
|
| 256 |
-
|
| 257 |
-
|
| 258 |
-
|
| 259 |
-
|
| 260 |
-
|
|
|
|
|
|
|
|
|
|
| 261 |
|
| 262 |
# Check for score updates
|
| 263 |
for team, score in current_scores.items():
|
| 264 |
if score > previous_scores.get(team, 0):
|
| 265 |
-
team_name = self.team
|
| 266 |
-
|
| 267 |
-
team_name = self.game_data['lowerTeam']['longName'] if team == self.game_data['lowerTeam']['name'] else self.game_data['upperTeam']['longName']
|
| 268 |
-
message = f"**{team_name}** SCORED! Current score: {current_scores[self.game_data['lowerTeam']['name']]} - {current_scores[self.game_data['upperTeam']['name']]}"
|
| 269 |
-
elif self.league == "NFL":
|
| 270 |
-
team_name = self.game_data['lowerTeam']['longName'] if team == self.game_data['lowerTeam']['name'] else self.game_data['upperTeam']['longName']
|
| 271 |
-
message = f"**{team_name}** SCORED! Current score: {current_scores[self.game_data['lowerTeam']['name']]} - {current_scores[self.game_data['upperTeam']['name']]}"
|
| 272 |
await user.send(message)
|
| 273 |
|
| 274 |
previous_scores = current_scores.copy()
|
| 275 |
|
| 276 |
if is_final:
|
| 277 |
-
|
| 278 |
-
|
| 279 |
-
|
| 280 |
-
away_score = current_scores.get(self.game_data['lowerTeam']['name'], 0)
|
| 281 |
-
home_score = current_scores.get(self.game_data['upperTeam']['name'], 0)
|
| 282 |
-
winner = self.game_data['lowerTeam']['name'] if away_score > home_score else self.game_data['upperTeam']['name']
|
| 283 |
|
| 284 |
if winner == self.team:
|
| 285 |
winnings = bet_amount * 2
|
|
@@ -315,16 +247,10 @@ async def show_current_bets(interaction: discord.Interaction):
|
|
| 315 |
team = bet['team']
|
| 316 |
amount = bet['amount']
|
| 317 |
game = bet['game_data']
|
| 318 |
-
|
| 319 |
-
|
| 320 |
-
|
| 321 |
-
|
| 322 |
-
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>"
|
| 323 |
-
elif league == "NFL":
|
| 324 |
-
game_description = f"{game['lowerTeam']['longName']} vs {game['upperTeam']['longName']}"
|
| 325 |
-
start_time = game['eventTime']
|
| 326 |
-
score = f"{game['lowerTeam'].get('score', 'N/A')} - {game['upperTeam'].get('score', 'N/A')}"
|
| 327 |
-
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>"
|
| 328 |
|
| 329 |
embed.add_field(
|
| 330 |
name=f"Bet {i}: {league}",
|
|
@@ -357,12 +283,7 @@ async def show_current_bets(interaction: discord.Interaction):
|
|
| 357 |
|
| 358 |
bet_index = int(cancel_select.values[0])
|
| 359 |
cancelled_bet = user_bets[user_id][bet_index]
|
| 360 |
-
|
| 361 |
-
game = cancelled_bet['game_data']
|
| 362 |
-
if league == "NHL":
|
| 363 |
-
start_time = datetime.fromisoformat(game['eventTime'].replace('Z', '+00:00'))
|
| 364 |
-
elif league == "NFL":
|
| 365 |
-
start_time = datetime.fromisoformat(game['eventTime'].replace('Z', '+00:00'))
|
| 366 |
|
| 367 |
if datetime.now(timezone.utc) >= start_time:
|
| 368 |
await interaction_cancel.response.send_message("You cannot cancel your bet as the game has already started.", ephemeral=True)
|
|
@@ -381,4 +302,4 @@ async def show_current_bets(interaction: discord.Interaction):
|
|
| 381 |
@app_commands.command(name="sportbet", description="Bet on sports games")
|
| 382 |
async def sportbet(interaction: discord.Interaction):
|
| 383 |
view = SportBetView()
|
| 384 |
-
await interaction.response.send_message("
|
|
|
|
| 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}"
|
|
|
|
| 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):
|
|
|
|
| 50 |
view = GameSelect(upcoming_games, "NHL")
|
| 51 |
await interaction.followup.send("Select a game to bet on:", view=view, ephemeral=True)
|
| 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=True)
|
| 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=True)
|
| 61 |
return
|
| 62 |
view = GameSelect(upcoming_games, "NFL")
|
| 63 |
+
await interaction.followup.send("Select a game to bet on:", view=view, ephemeral=True)
|
| 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 |
|
|
|
|
| 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 |
|
|
|
|
| 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)
|
| 149 |
await user.send(embed=embed)
|
|
|
|
| 162 |
await interaction.response.send_message(str(e), ephemeral=True)
|
| 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 |
+
fetch_scores = fetch_nhl_scores if self.league == "NHL" else fetch_nfl_scores
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 168 |
|
| 169 |
sleep_duration = (game_start - datetime.now(timezone.utc)).total_seconds()
|
| 170 |
if sleep_duration > 0:
|
|
|
|
| 173 |
user = await interaction.client.fetch_user(self.user_id)
|
| 174 |
await user.send(f"Your team **{self.team}** has started playing!")
|
| 175 |
|
| 176 |
+
previous_scores = {
|
| 177 |
+
self.game_data['lowerTeam']['name']: self.game_data.get('lowerTeam', {}).get('score', 0),
|
| 178 |
+
self.game_data['upperTeam']['name']: self.game_data.get('upperTeam', {}).get('score', 0)
|
| 179 |
+
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 180 |
|
| 181 |
while True:
|
| 182 |
scores = await fetch_scores()
|
| 183 |
+
game = None
|
| 184 |
+
for section in scores.get('sectionList', []):
|
| 185 |
+
for evt in section.get('events', []):
|
| 186 |
+
if evt['id'] == event_id:
|
| 187 |
+
game = evt
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 188 |
break
|
| 189 |
+
if game:
|
| 190 |
+
break
|
| 191 |
+
if not game:
|
| 192 |
+
await asyncio.sleep(60)
|
| 193 |
+
continue
|
| 194 |
+
|
| 195 |
+
event_status = game.get('eventStatus', 2)
|
| 196 |
+
current_scores = {
|
| 197 |
+
game['lowerTeam']['name']: game['lowerTeam'].get('score', 0),
|
| 198 |
+
game['upperTeam']['name']: game['upperTeam'].get('score', 0)
|
| 199 |
+
}
|
| 200 |
+
is_final = event_status == 3
|
| 201 |
|
| 202 |
# Check for score updates
|
| 203 |
for team, score in current_scores.items():
|
| 204 |
if score > previous_scores.get(team, 0):
|
| 205 |
+
team_name = self.game_data['lowerTeam']['longName'] if team == self.game_data['lowerTeam']['name'] else self.game_data['upperTeam']['longName']
|
| 206 |
+
message = f"**{team_name}** SCORED! Current score: {current_scores[self.game_data['lowerTeam']['name']]} - {current_scores[self.game_data['upperTeam']['name']]}"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 207 |
await user.send(message)
|
| 208 |
|
| 209 |
previous_scores = current_scores.copy()
|
| 210 |
|
| 211 |
if is_final:
|
| 212 |
+
away_score = current_scores.get(self.game_data['lowerTeam']['name'], 0)
|
| 213 |
+
home_score = current_scores.get(self.game_data['upperTeam']['name'], 0)
|
| 214 |
+
winner = self.game_data['lowerTeam']['name'] if away_score > home_score else self.game_data['upperTeam']['name']
|
|
|
|
|
|
|
|
|
|
| 215 |
|
| 216 |
if winner == self.team:
|
| 217 |
winnings = bet_amount * 2
|
|
|
|
| 247 |
team = bet['team']
|
| 248 |
amount = bet['amount']
|
| 249 |
game = bet['game_data']
|
| 250 |
+
game_description = f"{game['lowerTeam']['longName']} vs {game['upperTeam']['longName']}"
|
| 251 |
+
start_time = game['eventTime']
|
| 252 |
+
score = f"{game['lowerTeam'].get('score', 'N/A')} - {game['upperTeam'].get('score', 'N/A')}"
|
| 253 |
+
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>"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 254 |
|
| 255 |
embed.add_field(
|
| 256 |
name=f"Bet {i}: {league}",
|
|
|
|
| 283 |
|
| 284 |
bet_index = int(cancel_select.values[0])
|
| 285 |
cancelled_bet = user_bets[user_id][bet_index]
|
| 286 |
+
start_time = datetime.fromisoformat(cancelled_bet['game_data']['eventTime'].replace('Z', '+00:00'))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 287 |
|
| 288 |
if datetime.now(timezone.utc) >= start_time:
|
| 289 |
await interaction_cancel.response.send_message("You cannot cancel your bet as the game has already started.", ephemeral=True)
|
|
|
|
| 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=True)
|