Spaces:
Building
Building
Update sportbet.py
Browse files- sportbet.py +32 -14
sportbet.py
CHANGED
@@ -2,23 +2,41 @@ 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 |
async with aiohttp.ClientSession() as session:
|
12 |
async with session.get("https://nhl-score-api.herokuapp.com/api/scores/latest") as response:
|
13 |
return await response.json()
|
14 |
|
|
|
|
|
|
|
15 |
class GameSelect(discord.ui.Select):
|
16 |
def __init__(self, games):
|
17 |
options = [
|
18 |
discord.SelectOption(
|
19 |
label=f"{game['teams']['away']['teamName']} vs {game['teams']['home']['teamName']}",
|
20 |
value=f"{game['teams']['away']['abbreviation']}_{game['teams']['home']['abbreviation']}",
|
21 |
-
description=f"Start
|
22 |
) for game in games
|
23 |
]
|
24 |
super().__init__(placeholder="Select a game", options=options)
|
@@ -46,7 +64,7 @@ class BetModal(discord.ui.Modal, title="Place Your Bet"):
|
|
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("
|
50 |
|
51 |
user_cash[self.user_id] -= bet_amount
|
52 |
await interaction.response.send_message(f"Bet placed on {self.team} for ${bet_amount}")
|
@@ -56,7 +74,7 @@ class BetModal(discord.ui.Modal, title="Place Your Bet"):
|
|
56 |
embed.add_field(name="Team", value=self.team, inline=False)
|
57 |
embed.add_field(name="Amount", value=f"${bet_amount}", inline=False)
|
58 |
embed.add_field(name="Game", value=f"{self.game_data['teams']['away']['teamName']} vs {self.game_data['teams']['home']['teamName']}", inline=False)
|
59 |
-
embed.add_field(name="Start Time", value=self.game_data['startTime'], inline=False)
|
60 |
await user.send(embed=embed)
|
61 |
|
62 |
if self.user_id not in user_bets:
|
@@ -85,29 +103,29 @@ class BetModal(discord.ui.Modal, title="Place Your Bet"):
|
|
85 |
if game['teams'][winner]['abbreviation'] == self.team:
|
86 |
winnings = bet_amount * 2
|
87 |
user_cash[self.user_id] += winnings
|
88 |
-
await interaction.user.send(f"
|
89 |
else:
|
90 |
-
await interaction.user.send(f"Sorry, your team lost
|
91 |
|
92 |
user_bets[self.user_id] = [bet for bet in user_bets[self.user_id] if bet['game_data'] != self.game_data]
|
93 |
break
|
94 |
|
95 |
await asyncio.sleep(300)
|
96 |
|
97 |
-
@app_commands.command(name="sportbet", description="
|
98 |
async def sportbet(interaction: discord.Interaction):
|
99 |
scores = await fetch_nhl_scores()
|
100 |
upcoming_games = [game for game in scores['games'] if game['status']['state'] == 'PREVIEW']
|
101 |
|
102 |
if not upcoming_games:
|
103 |
-
await interaction.response.send_message("No
|
104 |
return
|
105 |
|
106 |
view = discord.ui.View()
|
107 |
game_select = GameSelect(upcoming_games)
|
108 |
view.add_item(game_select)
|
109 |
|
110 |
-
await interaction.response.send_message("
|
111 |
|
112 |
async def game_callback(interaction: discord.Interaction):
|
113 |
selected_game = next(game for game in upcoming_games if f"{game['teams']['away']['abbreviation']}_{game['teams']['home']['abbreviation']}" == game_select.values[0])
|
@@ -116,7 +134,7 @@ async def sportbet(interaction: discord.Interaction):
|
|
116 |
team_select = TeamSelect(selected_game['teams']['away'], selected_game['teams']['home'])
|
117 |
team_view.add_item(team_select)
|
118 |
|
119 |
-
await interaction.response.edit_message(content="
|
120 |
|
121 |
async def team_callback(interaction: discord.Interaction):
|
122 |
selected_team = team_select.values[0]
|
@@ -126,11 +144,11 @@ async def sportbet(interaction: discord.Interaction):
|
|
126 |
|
127 |
game_select.callback = game_callback
|
128 |
|
129 |
-
@app_commands.command(name="currentbets", description="
|
130 |
async def currentbets(interaction: discord.Interaction):
|
131 |
user_id = interaction.user.id
|
132 |
if user_id not in user_bets or not user_bets[user_id]:
|
133 |
-
await interaction.response.send_message("You have no
|
134 |
return
|
135 |
|
136 |
embed = discord.Embed(title="Your Current Bets", color=0x787878)
|
@@ -151,7 +169,7 @@ async def currentbets(interaction: discord.Interaction):
|
|
151 |
bet_index = int(cancel_select.values[0])
|
152 |
cancelled_bet = user_bets[user_id].pop(bet_index)
|
153 |
user_cash[user_id] += cancelled_bet['amount']
|
154 |
-
await interaction.response.send_message(f"Bet cancelled. ${cancelled_bet['amount']} has been refunded
|
155 |
|
156 |
cancel_select.callback = cancel_callback
|
157 |
|
|
|
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 load_database():
|
11 |
+
global user_cash
|
12 |
+
try:
|
13 |
+
with open("database.txt", "r") as f:
|
14 |
+
for line in f:
|
15 |
+
parts = line.strip().split()
|
16 |
+
if len(parts) == 2 and parts[1].startswith("cash(") and parts[1].endswith(")"):
|
17 |
+
user_id = int(parts[0])
|
18 |
+
cash = int(parts[1][5:-1])
|
19 |
+
user_cash[user_id] = cash
|
20 |
+
except FileNotFoundError:
|
21 |
+
print("No database found. Creating a new one.")
|
22 |
+
|
23 |
+
load_database()
|
24 |
+
|
25 |
async def fetch_nhl_scores():
|
26 |
async with aiohttp.ClientSession() as session:
|
27 |
async with session.get("https://nhl-score-api.herokuapp.com/api/scores/latest") as response:
|
28 |
return await response.json()
|
29 |
|
30 |
+
def format_discord_timestamp(dt):
|
31 |
+
return f"<t:{int(dt.timestamp())}:R>"
|
32 |
+
|
33 |
class GameSelect(discord.ui.Select):
|
34 |
def __init__(self, games):
|
35 |
options = [
|
36 |
discord.SelectOption(
|
37 |
label=f"{game['teams']['away']['teamName']} vs {game['teams']['home']['teamName']}",
|
38 |
value=f"{game['teams']['away']['abbreviation']}_{game['teams']['home']['abbreviation']}",
|
39 |
+
description=f"Start: {format_discord_timestamp(datetime.fromisoformat(game['startTime'].replace('Z', '+00:00')))}"
|
40 |
) for game in games
|
41 |
]
|
42 |
super().__init__(placeholder="Select a game", options=options)
|
|
|
64 |
if bet_amount <= 0:
|
65 |
raise ValueError("Bet more than 0 dollars")
|
66 |
if bet_amount > user_cash.get(self.user_id, 0):
|
67 |
+
raise ValueError("poor")
|
68 |
|
69 |
user_cash[self.user_id] -= bet_amount
|
70 |
await interaction.response.send_message(f"Bet placed on {self.team} for ${bet_amount}")
|
|
|
74 |
embed.add_field(name="Team", value=self.team, inline=False)
|
75 |
embed.add_field(name="Amount", value=f"${bet_amount}", inline=False)
|
76 |
embed.add_field(name="Game", value=f"{self.game_data['teams']['away']['teamName']} vs {self.game_data['teams']['home']['teamName']}", inline=False)
|
77 |
+
embed.add_field(name="Start Time", value=format_discord_timestamp(datetime.fromisoformat(self.game_data['startTime'].replace('Z', '+00:00'))), inline=False)
|
78 |
await user.send(embed=embed)
|
79 |
|
80 |
if self.user_id not in user_bets:
|
|
|
103 |
if game['teams'][winner]['abbreviation'] == self.team:
|
104 |
winnings = bet_amount * 2
|
105 |
user_cash[self.user_id] += winnings
|
106 |
+
await interaction.user.send(f"WOO YOUR TEAM WON you won ${winnings}!")
|
107 |
else:
|
108 |
+
await interaction.user.send(f"Sorry, your team lost booo!")
|
109 |
|
110 |
user_bets[self.user_id] = [bet for bet in user_bets[self.user_id] if bet['game_data'] != self.game_data]
|
111 |
break
|
112 |
|
113 |
await asyncio.sleep(300)
|
114 |
|
115 |
+
@app_commands.command(name="sportbet", description="bet on sports game")
|
116 |
async def sportbet(interaction: discord.Interaction):
|
117 |
scores = await fetch_nhl_scores()
|
118 |
upcoming_games = [game for game in scores['games'] if game['status']['state'] == 'PREVIEW']
|
119 |
|
120 |
if not upcoming_games:
|
121 |
+
await interaction.response.send_message("No games for betting.")
|
122 |
return
|
123 |
|
124 |
view = discord.ui.View()
|
125 |
game_select = GameSelect(upcoming_games)
|
126 |
view.add_item(game_select)
|
127 |
|
128 |
+
await interaction.response.send_message("game to bet on:", view=view)
|
129 |
|
130 |
async def game_callback(interaction: discord.Interaction):
|
131 |
selected_game = next(game for game in upcoming_games if f"{game['teams']['away']['abbreviation']}_{game['teams']['home']['abbreviation']}" == game_select.values[0])
|
|
|
134 |
team_select = TeamSelect(selected_game['teams']['away'], selected_game['teams']['home'])
|
135 |
team_view.add_item(team_select)
|
136 |
|
137 |
+
await interaction.response.edit_message(content="team to bet on:", view=team_view)
|
138 |
|
139 |
async def team_callback(interaction: discord.Interaction):
|
140 |
selected_team = team_select.values[0]
|
|
|
144 |
|
145 |
game_select.callback = game_callback
|
146 |
|
147 |
+
@app_commands.command(name="currentbets", description="view your bets")
|
148 |
async def currentbets(interaction: discord.Interaction):
|
149 |
user_id = interaction.user.id
|
150 |
if user_id not in user_bets or not user_bets[user_id]:
|
151 |
+
await interaction.response.send_message("You have no bets.")
|
152 |
return
|
153 |
|
154 |
embed = discord.Embed(title="Your Current Bets", color=0x787878)
|
|
|
169 |
bet_index = int(cancel_select.values[0])
|
170 |
cancelled_bet = user_bets[user_id].pop(bet_index)
|
171 |
user_cash[user_id] += cancelled_bet['amount']
|
172 |
+
await interaction.response.send_message(f"Bet cancelled. ${cancelled_bet['amount']} has been refunded.")
|
173 |
|
174 |
cancel_select.callback = cancel_callback
|
175 |
|