Spaces:
Building
Building
Update sportbet.py
Browse files- sportbet.py +122 -134
sportbet.py
CHANGED
@@ -157,149 +157,137 @@ class BetModal(discord.ui.Modal, title="Place Your Bet"):
|
|
157 |
"game_data": self.game_data
|
158 |
})
|
159 |
|
160 |
-
asyncio.create_task(self.monitor_game(interaction
|
|
|
161 |
except ValueError as e:
|
162 |
await interaction.response.send_message(str(e), ephemeral=False)
|
163 |
|
164 |
-
async def monitor_game(self, interaction
|
165 |
-
|
166 |
-
|
167 |
-
|
168 |
-
|
169 |
-
|
170 |
-
|
171 |
-
|
172 |
-
|
173 |
-
|
174 |
-
|
175 |
-
|
176 |
-
|
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 |
-
|
230 |
-
|
231 |
-
|
232 |
-
|
|
|
233 |
|
234 |
-
|
235 |
-
|
236 |
-
|
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(
|
270 |
-
placeholder="Select a bet to cancel",
|
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 |
-
|
280 |
-
|
281 |
-
|
282 |
-
|
283 |
|
284 |
-
|
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 |
-
|
289 |
-
|
290 |
-
return
|
291 |
|
292 |
-
|
293 |
-
|
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 |
-
|
299 |
|
300 |
-
|
|
|
|
|
|
|
|
|
|
|
301 |
|
302 |
-
|
303 |
-
|
304 |
-
|
305 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 )
|