Spaces:
Building
Building
Create sportbet.py
Browse files- sportbet.py +106 -0
sportbet.py
ADDED
@@ -0,0 +1,106 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import discord
|
2 |
+
from discord import app_commands
|
3 |
+
import aiohttp
|
4 |
+
import asyncio
|
5 |
+
from datetime import datetime, timezone
|
6 |
+
|
7 |
+
user_cash = {}
|
8 |
+
|
9 |
+
def load_database():
|
10 |
+
global user_cash
|
11 |
+
try:
|
12 |
+
with open("database.txt", "r") as f:
|
13 |
+
for line in f:
|
14 |
+
parts = line.strip().split()
|
15 |
+
if len(parts) == 2 and parts[1].startswith("cash(") and parts[1].endswith(")"):
|
16 |
+
user_id = int(parts[0])
|
17 |
+
cash = int(parts[1][5:-1])
|
18 |
+
user_cash[user_id] = cash
|
19 |
+
except FileNotFoundError:
|
20 |
+
print("No database found. Creating a new one.")
|
21 |
+
|
22 |
+
load_database()
|
23 |
+
|
24 |
+
async def fetch_nhl_scores():
|
25 |
+
async with aiohttp.ClientSession() as session:
|
26 |
+
async with session.get("https://nhl-score-api.herokuapp.com/api/scores/latest") as response:
|
27 |
+
return await response.json()
|
28 |
+
|
29 |
+
class TeamSelect(discord.ui.Select):
|
30 |
+
def __init__(self, teams):
|
31 |
+
options = [discord.SelectOption(label=f"{team['teamName']} ({team['abbreviation']})", value=team['abbreviation']) for team in teams]
|
32 |
+
super().__init__(placeholder="Select a team", options=options)
|
33 |
+
|
34 |
+
class BetModal(discord.ui.Modal, title="Place Your Bet"):
|
35 |
+
bet_amount = discord.ui.TextInput(label="Bet Amount", placeholder="Enter bet amount")
|
36 |
+
|
37 |
+
def __init__(self, team, user_id, game_data):
|
38 |
+
super().__init__()
|
39 |
+
self.team = team
|
40 |
+
self.user_id = user_id
|
41 |
+
self.game_data = game_data
|
42 |
+
|
43 |
+
async def on_submit(self, interaction: discord.Interaction):
|
44 |
+
try:
|
45 |
+
bet_amount = int(self.bet_amount.value)
|
46 |
+
if bet_amount <= 0:
|
47 |
+
raise ValueError("Bet more than 0 dollars")
|
48 |
+
if bet_amount > user_cash.get(self.user_id, 0):
|
49 |
+
raise ValueError("poor")
|
50 |
+
|
51 |
+
user_cash[self.user_id] -= bet_amount
|
52 |
+
await interaction.response.send_message(f"Bet placed on {self.team} for ${bet_amount}")
|
53 |
+
|
54 |
+
asyncio.create_task(self.monitor_game(interaction, bet_amount))
|
55 |
+
except ValueError as e:
|
56 |
+
await interaction.response.send_message(str(e), ephemeral=True)
|
57 |
+
|
58 |
+
async def monitor_game(self, interaction, bet_amount):
|
59 |
+
game_start = datetime.fromisoformat(self.game_data['startTime'].replace('Z', '+00:00'))
|
60 |
+
await asyncio.sleep((game_start - datetime.now(timezone.utc)).total_seconds())
|
61 |
+
|
62 |
+
while True:
|
63 |
+
scores = await fetch_nhl_scores()
|
64 |
+
game = next((g for g in scores['games'] if g['teams']['away']['abbreviation'] == self.game_data['teams']['away']['abbreviation'] and
|
65 |
+
g['teams']['home']['abbreviation'] == self.game_data['teams']['home']['abbreviation']), None)
|
66 |
+
|
67 |
+
if game['status']['state'] == 'FINAL':
|
68 |
+
winner = 'away' if game['scores']['away'] > game['scores']['home'] else 'home'
|
69 |
+
if game['teams'][winner]['abbreviation'] == self.team:
|
70 |
+
winnings = bet_amount * 2
|
71 |
+
user_cash[self.user_id] += winnings
|
72 |
+
await interaction.user.send(f"WOO YOUR TEAM WON you won ${winnings}!")
|
73 |
+
else:
|
74 |
+
await interaction.user.send(f"Sorry, your team lost booo!")
|
75 |
+
break
|
76 |
+
|
77 |
+
await asyncio.sleep(300) # Check every 5 minutes
|
78 |
+
|
79 |
+
@app_commands.command(name="sportbet", description="Bet on NHL games")
|
80 |
+
async def sportbet(interaction: discord.Interaction):
|
81 |
+
scores = await fetch_nhl_scores()
|
82 |
+
upcoming_games = [game for game in scores['games'] if game['status']['state'] == 'PREVIEW']
|
83 |
+
|
84 |
+
if not upcoming_games:
|
85 |
+
await interaction.response.send_message("No games for betting.")
|
86 |
+
return
|
87 |
+
|
88 |
+
embed = discord.Embed(title="Upcoming NHL Games", color=0x00ff00)
|
89 |
+
for game in upcoming_games:
|
90 |
+
away_team = game['teams']['away']
|
91 |
+
home_team = game['teams']['home']
|
92 |
+
embed.add_field(name=f"{away_team['teamName']} vs {home_team['teamName']}",
|
93 |
+
value=f"Start time: {game['startTime']}", inline=False)
|
94 |
+
|
95 |
+
view = discord.ui.View()
|
96 |
+
team_select = TeamSelect(sum([game['teams'].values() for game in upcoming_games], []))
|
97 |
+
view.add_item(team_select)
|
98 |
+
|
99 |
+
await interaction.response.send_message(embed=embed, view=view)
|
100 |
+
|
101 |
+
async def team_callback(interaction: discord.Interaction):
|
102 |
+
selected_team = team_select.values[0]
|
103 |
+
game = next(game for game in upcoming_games if selected_team in [game['teams']['away']['abbreviation'], game['teams']['home']['abbreviation']])
|
104 |
+
await interaction.response.send_modal(BetModal(selected_team, interaction.user.id, game))
|
105 |
+
|
106 |
+
team_select.callback = team_callback
|