coollsd commited on
Commit
4d79003
·
verified ·
1 Parent(s): 2ac4d55

Update sportbet.py

Browse files
Files changed (1) hide show
  1. sportbet.py +13 -55
sportbet.py CHANGED
@@ -5,39 +5,20 @@ import asyncio
5
  from datetime import datetime, timezone
6
  from cash import user_cash
7
 
8
- user_cash = {}
9
  user_bets = {}
10
 
11
- def load_database():
12
- global user_cash
13
- try:
14
- with open("database.txt", "r") as f:
15
- for line in f:
16
- parts = line.strip().split()
17
- if len(parts) == 2 and parts[1].startswith("cash(") and parts[1].endswith(")"):
18
- user_id = int(parts[0])
19
- cash = int(parts[1][5:-1])
20
- user_cash[user_id] = cash
21
- except FileNotFoundError:
22
- print("No database found. Creating a new one.")
23
-
24
- load_database()
25
-
26
  async def fetch_nhl_scores():
27
  async with aiohttp.ClientSession() as session:
28
  async with session.get("https://nhl-score-api.herokuapp.com/api/scores/latest") as response:
29
  return await response.json()
30
 
31
- def format_discord_timestamp(dt):
32
- return f"<t:{int(dt.timestamp())}:R>"
33
-
34
  class GameSelect(discord.ui.Select):
35
  def __init__(self, games):
36
  options = [
37
  discord.SelectOption(
38
  label=f"{game['teams']['away']['teamName']} vs {game['teams']['home']['teamName']}",
39
  value=f"{game['teams']['away']['abbreviation']}_{game['teams']['home']['abbreviation']}",
40
- description=f"Start: {format_discord_timestamp(datetime.fromisoformat(game['startTime'].replace('Z', '+00:00')))}"
41
  ) for game in games
42
  ]
43
  super().__init__(placeholder="Select a game", options=options)
@@ -65,7 +46,7 @@ class BetModal(discord.ui.Modal, title="Place Your Bet"):
65
  if bet_amount <= 0:
66
  raise ValueError("Bet more than 0 dollars")
67
  if bet_amount > user_cash.get(self.user_id, 0):
68
- raise ValueError("poor")
69
 
70
  user_cash[self.user_id] -= bet_amount
71
  await interaction.response.send_message(f"Bet placed on {self.team} for ${bet_amount}")
@@ -75,7 +56,7 @@ class BetModal(discord.ui.Modal, title="Place Your Bet"):
75
  embed.add_field(name="Team", value=self.team, inline=False)
76
  embed.add_field(name="Amount", value=f"${bet_amount}", inline=False)
77
  embed.add_field(name="Game", value=f"{self.game_data['teams']['away']['teamName']} vs {self.game_data['teams']['home']['teamName']}", inline=False)
78
- embed.add_field(name="Start Time", value=format_discord_timestamp(datetime.fromisoformat(self.game_data['startTime'].replace('Z', '+00:00'))), inline=False)
79
  await user.send(embed=embed)
80
 
81
  if self.user_id not in user_bets:
@@ -104,21 +85,22 @@ class BetModal(discord.ui.Modal, title="Place Your Bet"):
104
  if game['teams'][winner]['abbreviation'] == self.team:
105
  winnings = bet_amount * 2
106
  user_cash[self.user_id] += winnings
107
- await interaction.user.send(f"WOO YOUR TEAM WON you won ${winnings}!")
108
  else:
109
- await interaction.user.send(f"Sorry, your team lost booo!")
110
 
111
  user_bets[self.user_id] = [bet for bet in user_bets[self.user_id] if bet['game_data'] != self.game_data]
112
  break
113
 
114
  await asyncio.sleep(300)
115
 
116
- async def show_game_selection(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()
@@ -144,7 +126,8 @@ async def show_game_selection(interaction: discord.Interaction):
144
 
145
  game_select.callback = game_callback
146
 
147
- async def show_current_bets(interaction: discord.Interaction):
 
148
  user_id = interaction.user.id
149
  if user_id not in user_bets or not user_bets[user_id]:
150
  await interaction.response.send_message("You have no active bets.")
@@ -156,7 +139,7 @@ async def show_current_bets(interaction: discord.Interaction):
156
  game = next((g for g in scores['games'] if g['teams']['away']['abbreviation'] == bet['game_data']['teams']['away']['abbreviation'] and
157
  g['teams']['home']['abbreviation'] == bet['game_data']['teams']['home']['abbreviation']), None)
158
 
159
- embed.add_field(name=f"Bet {i+1}", value=f"Team: {bet['team']}\nAmount: ${bet['amount']}\nGame: {bet['game_data']['teams']['away']['teamName']} vs {bet['game_data']['teams']['home']['teamName']}\nStart Time: {format_discord_timestamp(datetime.fromisoformat(bet['game_data']['startTime'].replace('Z', '+00:00')))}\nCurrent Score: {game['scores']['away']} - {game['scores']['home']}", inline=False)
160
 
161
  view = discord.ui.View()
162
  cancel_select = discord.ui.Select(placeholder="Select a bet to cancel", options=[
@@ -168,33 +151,8 @@ async def show_current_bets(interaction: discord.Interaction):
168
  bet_index = int(cancel_select.values[0])
169
  cancelled_bet = user_bets[user_id].pop(bet_index)
170
  user_cash[user_id] += cancelled_bet['amount']
171
- await interaction.response.send_message(f"Bet cancelled. ${cancelled_bet['amount']} has been refunded.")
172
 
173
  cancel_select.callback = cancel_callback
174
 
175
- await interaction.response.send_message(embed=embed, view=view)
176
-
177
- @app_commands.command(name="sportbet", description="bet on sports game or view current bets")
178
- async def sportbet(interaction: discord.Interaction):
179
- user_id = interaction.user.id
180
- has_bets = user_id in user_bets and len(user_bets[user_id]) > 0
181
-
182
- view = discord.ui.View()
183
- bet_button = discord.ui.Button(style=discord.ButtonStyle.primary, label="Bet Again" if has_bets else "Place Bet")
184
- view.add_item(bet_button)
185
-
186
- if has_bets:
187
- view_bets_button = discord.ui.Button(style=discord.ButtonStyle.secondary, label="View Bets")
188
- view.add_item(view_bets_button)
189
-
190
- async def view_bets_callback(interaction: discord.Interaction):
191
- await show_current_bets(interaction)
192
-
193
- view_bets_button.callback = view_bets_callback
194
-
195
- async def bet_callback(interaction: discord.Interaction):
196
- await show_game_selection(interaction)
197
-
198
- bet_button.callback = bet_callback
199
-
200
- await interaction.response.send_message("What would you like to do?", view=view)
 
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 time: <t:{int(datetime.fromisoformat(game['startTime'].replace('Z', '+00:00')).timestamp())}:R>"
22
  ) for game in games
23
  ]
24
  super().__init__(placeholder="Select a game", options=options)
 
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("Insufficient funds")
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
  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=f"<t:{int(datetime.fromisoformat(self.game_data['startTime'].replace('Z', '+00:00')).timestamp())}:R>", inline=False)
60
  await user.send(embed=embed)
61
 
62
  if self.user_id not in user_bets:
 
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"Congratulations! Your team won. You won ${winnings}!")
89
  else:
90
+ await interaction.user.send(f"Sorry, your team lost. Better luck next time!")
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="Bet on sports games")
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 upcoming games available for betting.")
104
  return
105
 
106
  view = discord.ui.View()
 
126
 
127
  game_select.callback = game_callback
128
 
129
+ @app_commands.command(name="currentbets", description="View your current bets")
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 active bets.")
 
139
  game = next((g for g in scores['games'] if g['teams']['away']['abbreviation'] == bet['game_data']['teams']['away']['abbreviation'] and
140
  g['teams']['home']['abbreviation'] == bet['game_data']['teams']['home']['abbreviation']), None)
141
 
142
+ embed.add_field(name=f"Bet {i+1}", value=f"Team: {bet['team']}\nAmount: ${bet['amount']}\nGame: {bet['game_data']['teams']['away']['teamName']} vs {bet['game_data']['teams']['home']['teamName']}\nCurrent Score: {game['scores']['away']} - {game['scores']['home']}\nStart Time: <t:{int(datetime.fromisoformat(bet['game_data']['startTime'].replace('Z', '+00:00')).timestamp())}:R>", inline=False)
143
 
144
  view = discord.ui.View()
145
  cancel_select = discord.ui.Select(placeholder="Select a bet to cancel", options=[
 
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 to your balance.")
155
 
156
  cancel_select.callback = cancel_callback
157
 
158
+ await interaction.response.send_message(embed=embed, view=view)