Spaces:
Paused
Paused
Update sportbet.py
Browse files- sportbet.py +159 -207
sportbet.py
CHANGED
|
@@ -3,76 +3,128 @@ from discord import app_commands
|
|
| 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
|
| 24 |
-
def __init__(self
|
| 25 |
-
|
| 26 |
-
|
|
|
|
|
|
|
|
|
|
| 27 |
|
| 28 |
-
|
| 29 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 30 |
options = [
|
| 31 |
discord.SelectOption(
|
| 32 |
-
label=f"{game['
|
| 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=
|
| 45 |
return
|
| 46 |
-
await interaction.response.edit_message(content="Select a team to bet on:", view=
|
|
|
|
|
|
|
|
|
|
| 47 |
|
| 48 |
class TeamSelect(discord.ui.View):
|
| 49 |
-
def __init__(self, game):
|
| 50 |
super().__init__()
|
| 51 |
-
|
| 52 |
-
|
|
|
|
| 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.
|
|
|
|
| 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,14 +135,14 @@ class BetModal(discord.ui.Modal, title="Place Your Bet"):
|
|
| 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=
|
| 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=
|
| 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['
|
| 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)
|
|
@@ -99,223 +151,119 @@ class BetModal(discord.ui.Modal, title="Place Your Bet"):
|
|
| 99 |
if self.user_id not in user_bets:
|
| 100 |
user_bets[self.user_id] = []
|
| 101 |
user_bets[self.user_id].append({
|
| 102 |
-
"league":
|
| 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=
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 112 |
|
| 113 |
-
async def monitor_game(self, interaction):
|
| 114 |
previous_scores = {
|
| 115 |
-
self.game_data['
|
| 116 |
-
self.game_data['
|
| 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 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
|
|
|
|
|
|
| 130 |
break
|
| 131 |
-
if
|
| 132 |
break
|
| 133 |
-
|
| 134 |
-
if not current_game:
|
| 135 |
await asyncio.sleep(60)
|
| 136 |
continue
|
| 137 |
|
|
|
|
| 138 |
current_scores = {
|
| 139 |
-
|
| 140 |
-
|
| 141 |
}
|
|
|
|
| 142 |
|
| 143 |
-
|
| 144 |
-
for
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
|
|
|
| 148 |
|
| 149 |
previous_scores = current_scores.copy()
|
| 150 |
|
| 151 |
-
if
|
| 152 |
-
away_score = current_scores
|
| 153 |
-
home_score = current_scores
|
| 154 |
-
|
| 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 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
|
|
|
| 195 |
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 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 |
-
|
| 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 |
-
|
| 270 |
-
|
| 271 |
-
|
| 272 |
-
|
| 273 |
-
await interaction.response.send_message("No NFL games available for betting this week.", ephemeral=True)
|
| 274 |
-
return
|
| 275 |
|
| 276 |
-
|
| 277 |
-
|
|
|
|
| 278 |
|
| 279 |
-
|
| 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=
|
| 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 |
-
|
| 295 |
-
|
| 296 |
-
|
| 297 |
-
|
| 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=(
|
| 312 |
-
|
| 313 |
-
|
| 314 |
-
|
| 315 |
-
|
| 316 |
-
|
| 317 |
-
|
| 318 |
-
|
|
|
|
|
|
|
| 319 |
|
| 320 |
view = discord.ui.View()
|
| 321 |
cancel_select = discord.ui.Select(
|
|
@@ -323,14 +271,14 @@ async def viewbets(interaction: discord.Interaction):
|
|
| 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=
|
| 334 |
return
|
| 335 |
|
| 336 |
bet_index = int(cancel_select.values[0])
|
|
@@ -338,16 +286,20 @@ async def viewbets(interaction: discord.Interaction):
|
|
| 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=
|
| 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=
|
| 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=
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
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)
|
|
|
|
| 151 |
if self.user_id not in user_bets:
|
| 152 |
user_bets[self.user_id] = []
|
| 153 |
user_bets[self.user_id].append({
|
| 154 |
+
"league": self.league,
|
| 155 |
"team": self.team,
|
| 156 |
"amount": bet_amount,
|
| 157 |
"game_data": self.game_data
|
| 158 |
})
|
| 159 |
|
| 160 |
+
asyncio.create_task(self.monitor_game(interaction, bet_amount))
|
|
|
|
| 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 |
+
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:
|
| 171 |
+
await asyncio.sleep(sleep_duration)
|
| 172 |
+
|
| 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
|
| 218 |
+
user_cash[self.user_id] += winnings
|
| 219 |
+
await user.send(f"🎉 **Congratulations!** Your team **{self.team}** won! You won **${winnings}**!")
|
| 220 |
+
else:
|
| 221 |
+
await user.send(f"😞 **Sorry!** Your team **{self.team}** lost. Better luck next time!")
|
| 222 |
|
| 223 |
+
# Remove the completed bet
|
| 224 |
+
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)]
|
| 225 |
+
break
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 226 |
|
| 227 |
+
await asyncio.sleep(60) # Check every minute
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 228 |
|
| 229 |
+
class SportBetView(discord.ui.View):
|
| 230 |
+
def __init__(self):
|
| 231 |
+
super().__init__()
|
| 232 |
+
self.add_item(SportSelect())
|
|
|
|
|
|
|
| 233 |
|
| 234 |
+
@discord.ui.button(label="View Bets", style=discord.ButtonStyle.secondary)
|
| 235 |
+
async def view_bets(self, interaction: discord.Interaction, button: discord.ui.Button):
|
| 236 |
+
await show_current_bets(interaction)
|
| 237 |
|
| 238 |
+
async def show_current_bets(interaction: discord.Interaction):
|
|
|
|
| 239 |
user_id = interaction.user.id
|
|
|
|
| 240 |
if user_id not in user_bets or not user_bets[user_id]:
|
| 241 |
+
await interaction.response.send_message("You have no active bets.", ephemeral=False)
|
| 242 |
return
|
| 243 |
|
| 244 |
embed = discord.Embed(title="Your Current Bets", color=0x787878)
|
|
|
|
| 245 |
for i, bet in enumerate(user_bets[user_id], 1):
|
| 246 |
league = bet['league']
|
| 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}",
|
| 257 |
+
value=(
|
| 258 |
+
f"**Team:** {team}\n"
|
| 259 |
+
f"**Amount:** ${amount}\n"
|
| 260 |
+
f"**Game:** {game_description}\n"
|
| 261 |
+
f"**Status:** {status}\n"
|
| 262 |
+
f"**Current Score:** {score}\n"
|
| 263 |
+
f"**Start Time:** <t:{int(datetime.fromisoformat(start_time.replace('Z', '+00:00')).timestamp())}:F>"
|
| 264 |
+
),
|
| 265 |
+
inline=False
|
| 266 |
+
)
|
| 267 |
|
| 268 |
view = discord.ui.View()
|
| 269 |
cancel_select = discord.ui.Select(
|
|
|
|
| 271 |
min_values=1,
|
| 272 |
max_values=1,
|
| 273 |
options=[
|
| 274 |
+
discord.SelectOption(label=f"Bet {i}", value=str(i-1)) for i in range(1, len(user_bets[user_id]) + 1)
|
| 275 |
]
|
| 276 |
)
|
| 277 |
view.add_item(cancel_select)
|
| 278 |
|
| 279 |
async def cancel_callback(interaction_cancel: discord.Interaction):
|
| 280 |
if interaction_cancel.user.id != user_id:
|
| 281 |
+
await interaction_cancel.response.send_message("You cannot cancel other users' bets.", ephemeral=False)
|
| 282 |
return
|
| 283 |
|
| 284 |
bet_index = int(cancel_select.values[0])
|
|
|
|
| 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=False)
|
| 290 |
return
|
| 291 |
|
| 292 |
user_cash[user_id] += cancelled_bet['amount']
|
| 293 |
user_bets[user_id].pop(bet_index)
|
| 294 |
+
await interaction_cancel.response.send_message(f"Bet cancelled. **${cancelled_bet['amount']}** has been refunded.", ephemeral=False)
|
|
|
|
| 295 |
if not user_bets[user_id]:
|
| 296 |
del user_bets[user_id]
|
| 297 |
|
| 298 |
cancel_select.callback = cancel_callback
|
| 299 |
|
| 300 |
+
await interaction.response.send_message(embed=embed, view=view, ephemeral=False)
|
| 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)
|