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