Spaces:
Building
Building
Update sportbet.py
Browse files- sportbet.py +53 -13
sportbet.py
CHANGED
@@ -2,11 +2,16 @@ 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 |
user_bets = {}
|
9 |
|
|
|
|
|
|
|
|
|
|
|
10 |
def load_database():
|
11 |
global user_cash
|
12 |
try:
|
@@ -27,13 +32,27 @@ async def fetch_nhl_scores():
|
|
27 |
async with session.get("https://nhl-score-api.herokuapp.com/api/scores/latest") as response:
|
28 |
return await response.json()
|
29 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
30 |
class GameSelect(discord.ui.Select):
|
31 |
def __init__(self, games):
|
32 |
options = [
|
33 |
discord.SelectOption(
|
34 |
label=f"{game['teams']['away']['teamName']} vs {game['teams']['home']['teamName']}",
|
35 |
value=f"{game['teams']['away']['abbreviation']}_{game['teams']['home']['abbreviation']}",
|
36 |
-
description=f"Start
|
37 |
) for game in games
|
38 |
]
|
39 |
super().__init__(placeholder="Select a game", options=options)
|
@@ -61,9 +80,10 @@ class BetModal(discord.ui.Modal, title="Place Your Bet"):
|
|
61 |
if bet_amount <= 0:
|
62 |
raise ValueError("Bet more than 0 dollars")
|
63 |
if bet_amount > user_cash.get(self.user_id, 0):
|
64 |
-
raise ValueError("
|
65 |
|
66 |
user_cash[self.user_id] -= bet_amount
|
|
|
67 |
await interaction.response.send_message(f"Bet placed on {self.team} for ${bet_amount}")
|
68 |
|
69 |
user = await interaction.client.fetch_user(self.user_id)
|
@@ -71,7 +91,7 @@ class BetModal(discord.ui.Modal, title="Place Your Bet"):
|
|
71 |
embed.add_field(name="Team", value=self.team, inline=False)
|
72 |
embed.add_field(name="Amount", value=f"${bet_amount}", inline=False)
|
73 |
embed.add_field(name="Game", value=f"{self.game_data['teams']['away']['teamName']} vs {self.game_data['teams']['home']['teamName']}", inline=False)
|
74 |
-
embed.add_field(name="Start Time", value=self.game_data['startTime'], inline=False)
|
75 |
await user.send(embed=embed)
|
76 |
|
77 |
if self.user_id not in user_bets:
|
@@ -100,29 +120,30 @@ class BetModal(discord.ui.Modal, title="Place Your Bet"):
|
|
100 |
if game['teams'][winner]['abbreviation'] == self.team:
|
101 |
winnings = bet_amount * 2
|
102 |
user_cash[self.user_id] += winnings
|
103 |
-
|
|
|
104 |
else:
|
105 |
-
await interaction.user.send(f"Sorry, your team lost
|
106 |
|
107 |
user_bets[self.user_id] = [bet for bet in user_bets[self.user_id] if bet['game_data'] != self.game_data]
|
108 |
break
|
109 |
|
110 |
await asyncio.sleep(300)
|
111 |
|
112 |
-
@app_commands.command(name="sportbet", description="
|
113 |
async def sportbet(interaction: discord.Interaction):
|
114 |
scores = await fetch_nhl_scores()
|
115 |
upcoming_games = [game for game in scores['games'] if game['status']['state'] == 'PREVIEW']
|
116 |
|
117 |
if not upcoming_games:
|
118 |
-
await interaction.response.send_message("No games for betting.")
|
119 |
return
|
120 |
|
121 |
view = discord.ui.View()
|
122 |
game_select = GameSelect(upcoming_games)
|
123 |
view.add_item(game_select)
|
124 |
|
125 |
-
await interaction.response.send_message("game to bet on:", view=view)
|
126 |
|
127 |
async def game_callback(interaction: discord.Interaction):
|
128 |
selected_game = next(game for game in upcoming_games if f"{game['teams']['away']['abbreviation']}_{game['teams']['home']['abbreviation']}" == game_select.values[0])
|
@@ -131,7 +152,7 @@ async def sportbet(interaction: discord.Interaction):
|
|
131 |
team_select = TeamSelect(selected_game['teams']['away'], selected_game['teams']['home'])
|
132 |
team_view.add_item(team_select)
|
133 |
|
134 |
-
await interaction.response.edit_message(content="team to bet on:", view=team_view)
|
135 |
|
136 |
async def team_callback(interaction: discord.Interaction):
|
137 |
selected_team = team_select.values[0]
|
@@ -141,11 +162,11 @@ async def sportbet(interaction: discord.Interaction):
|
|
141 |
|
142 |
game_select.callback = game_callback
|
143 |
|
144 |
-
@app_commands.command(name="currentbets", description="
|
145 |
async def currentbets(interaction: discord.Interaction):
|
146 |
user_id = interaction.user.id
|
147 |
if user_id not in user_bets or not user_bets[user_id]:
|
148 |
-
await interaction.response.send_message("You have no bets.")
|
149 |
return
|
150 |
|
151 |
embed = discord.Embed(title="Your Current Bets", color=0x787878)
|
@@ -166,8 +187,27 @@ async def currentbets(interaction: discord.Interaction):
|
|
166 |
bet_index = int(cancel_select.values[0])
|
167 |
cancelled_bet = user_bets[user_id].pop(bet_index)
|
168 |
user_cash[user_id] += cancelled_bet['amount']
|
|
|
169 |
await interaction.response.send_message(f"Bet cancelled. ${cancelled_bet['amount']} has been refunded.")
|
170 |
|
171 |
cancel_select.callback = cancel_callback
|
172 |
|
173 |
-
await interaction.response.send_message(embed=embed, view=view)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
2 |
from discord import app_commands
|
3 |
import aiohttp
|
4 |
import asyncio
|
5 |
+
from datetime import datetime, timezone, timedelta
|
6 |
|
7 |
user_cash = {}
|
8 |
user_bets = {}
|
9 |
|
10 |
+
def save_database():
|
11 |
+
with open("database.txt", "w") as f:
|
12 |
+
for user_id, cash in user_cash.items():
|
13 |
+
f.write(f"{user_id} cash({cash})\n")
|
14 |
+
|
15 |
def load_database():
|
16 |
global user_cash
|
17 |
try:
|
|
|
32 |
async with session.get("https://nhl-score-api.herokuapp.com/api/scores/latest") as response:
|
33 |
return await response.json()
|
34 |
|
35 |
+
def format_time_difference(start_time):
|
36 |
+
now = datetime.now(timezone.utc)
|
37 |
+
start = datetime.fromisoformat(start_time.replace('Z', '+00:00'))
|
38 |
+
diff = start - now
|
39 |
+
|
40 |
+
if diff < timedelta(0):
|
41 |
+
return "Game has already started"
|
42 |
+
elif diff < timedelta(hours=1):
|
43 |
+
return f"{diff.seconds // 60} minutes from now"
|
44 |
+
elif diff < timedelta(days=1):
|
45 |
+
return f"{diff.seconds // 3600} hours from now"
|
46 |
+
else:
|
47 |
+
return f"{diff.days} days from now"
|
48 |
+
|
49 |
class GameSelect(discord.ui.Select):
|
50 |
def __init__(self, games):
|
51 |
options = [
|
52 |
discord.SelectOption(
|
53 |
label=f"{game['teams']['away']['teamName']} vs {game['teams']['home']['teamName']}",
|
54 |
value=f"{game['teams']['away']['abbreviation']}_{game['teams']['home']['abbreviation']}",
|
55 |
+
description=f"Start: {format_time_difference(game['startTime'])}"
|
56 |
) for game in games
|
57 |
]
|
58 |
super().__init__(placeholder="Select a game", options=options)
|
|
|
80 |
if bet_amount <= 0:
|
81 |
raise ValueError("Bet more than 0 dollars")
|
82 |
if bet_amount > user_cash.get(self.user_id, 0):
|
83 |
+
raise ValueError("Insufficient funds")
|
84 |
|
85 |
user_cash[self.user_id] -= bet_amount
|
86 |
+
save_database()
|
87 |
await interaction.response.send_message(f"Bet placed on {self.team} for ${bet_amount}")
|
88 |
|
89 |
user = await interaction.client.fetch_user(self.user_id)
|
|
|
91 |
embed.add_field(name="Team", value=self.team, inline=False)
|
92 |
embed.add_field(name="Amount", value=f"${bet_amount}", inline=False)
|
93 |
embed.add_field(name="Game", value=f"{self.game_data['teams']['away']['teamName']} vs {self.game_data['teams']['home']['teamName']}", inline=False)
|
94 |
+
embed.add_field(name="Start Time", value=format_time_difference(self.game_data['startTime']), inline=False)
|
95 |
await user.send(embed=embed)
|
96 |
|
97 |
if self.user_id not in user_bets:
|
|
|
120 |
if game['teams'][winner]['abbreviation'] == self.team:
|
121 |
winnings = bet_amount * 2
|
122 |
user_cash[self.user_id] += winnings
|
123 |
+
save_database()
|
124 |
+
await interaction.user.send(f"Congratulations! Your team won. You won ${winnings}!")
|
125 |
else:
|
126 |
+
await interaction.user.send(f"Sorry, your team lost. Better luck next time!")
|
127 |
|
128 |
user_bets[self.user_id] = [bet for bet in user_bets[self.user_id] if bet['game_data'] != self.game_data]
|
129 |
break
|
130 |
|
131 |
await asyncio.sleep(300)
|
132 |
|
133 |
+
@app_commands.command(name="sportbet", description="Bet on sports games")
|
134 |
async def sportbet(interaction: discord.Interaction):
|
135 |
scores = await fetch_nhl_scores()
|
136 |
upcoming_games = [game for game in scores['games'] if game['status']['state'] == 'PREVIEW']
|
137 |
|
138 |
if not upcoming_games:
|
139 |
+
await interaction.response.send_message("No games available for betting.")
|
140 |
return
|
141 |
|
142 |
view = discord.ui.View()
|
143 |
game_select = GameSelect(upcoming_games)
|
144 |
view.add_item(game_select)
|
145 |
|
146 |
+
await interaction.response.send_message("Select a game to bet on:", view=view)
|
147 |
|
148 |
async def game_callback(interaction: discord.Interaction):
|
149 |
selected_game = next(game for game in upcoming_games if f"{game['teams']['away']['abbreviation']}_{game['teams']['home']['abbreviation']}" == game_select.values[0])
|
|
|
152 |
team_select = TeamSelect(selected_game['teams']['away'], selected_game['teams']['home'])
|
153 |
team_view.add_item(team_select)
|
154 |
|
155 |
+
await interaction.response.edit_message(content="Select a team to bet on:", view=team_view)
|
156 |
|
157 |
async def team_callback(interaction: discord.Interaction):
|
158 |
selected_team = team_select.values[0]
|
|
|
162 |
|
163 |
game_select.callback = game_callback
|
164 |
|
165 |
+
@app_commands.command(name="currentbets", description="View your current bets")
|
166 |
async def currentbets(interaction: discord.Interaction):
|
167 |
user_id = interaction.user.id
|
168 |
if user_id not in user_bets or not user_bets[user_id]:
|
169 |
+
await interaction.response.send_message("You have no active bets.")
|
170 |
return
|
171 |
|
172 |
embed = discord.Embed(title="Your Current Bets", color=0x787878)
|
|
|
187 |
bet_index = int(cancel_select.values[0])
|
188 |
cancelled_bet = user_bets[user_id].pop(bet_index)
|
189 |
user_cash[user_id] += cancelled_bet['amount']
|
190 |
+
save_database()
|
191 |
await interaction.response.send_message(f"Bet cancelled. ${cancelled_bet['amount']} has been refunded.")
|
192 |
|
193 |
cancel_select.callback = cancel_callback
|
194 |
|
195 |
+
await interaction.response.send_message(embed=embed, view=view)
|
196 |
+
|
197 |
+
@app_commands.command(name="cash", description="Check your cash balance")
|
198 |
+
async def cash(interaction: discord.Interaction):
|
199 |
+
user_id = interaction.user.id
|
200 |
+
balance = user_cash.get(user_id, 0)
|
201 |
+
|
202 |
+
if balance == 0:
|
203 |
+
user_cash[user_id] = 1000
|
204 |
+
balance = 1000
|
205 |
+
message = "You have no cash. Here's $1,000 to start!"
|
206 |
+
else:
|
207 |
+
message = f"Your current balance is ${balance:,}"
|
208 |
+
|
209 |
+
embed = discord.Embed(title="Cash Balance", description=message, color=0x787878)
|
210 |
+
embed.set_footer(text="Use /sportbet to bet your cash!")
|
211 |
+
|
212 |
+
await interaction.response.send_message(embed=embed)
|
213 |
+
save_database()
|