File size: 15,630 Bytes
aad95f7
 
 
 
94166cb
5a642ea
aad95f7
7917f65
 
94166cb
 
29254f8
 
5a642ea
23567d4
 
 
 
4d35aef
 
5a642ea
94166cb
5a642ea
 
87c1a2c
5a642ea
 
 
 
29254f8
 
5a642ea
29254f8
 
 
 
5a642ea
87c1a2c
94166cb
 
87c1a2c
 
 
5a642ea
87c1a2c
5a642ea
94166cb
 
5a642ea
94166cb
5a642ea
 
29254f8
 
 
 
5a642ea
94166cb
 
5a642ea
94166cb
87c1a2c
94166cb
 
 
5a642ea
7917f65
23567d4
a4b7e80
7917f65
5a642ea
23567d4
7917f65
 
 
 
 
 
 
 
94166cb
7917f65
94166cb
7917f65
 
5a642ea
a4b7e80
23567d4
 
5a642ea
23567d4
 
5a642ea
23567d4
 
 
 
 
 
 
 
5a642ea
7917f65
 
5a642ea
7917f65
a4b7e80
4d35aef
 
7917f65
5a642ea
aad95f7
4d35aef
5a642ea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e56e420
5a642ea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
import discord
from discord import app_commands
import aiohttp
import asyncio
from datetime import datetime, timezone, timedelta
from cash import user_cash

user_bets = {}

API_KEY = "jE7yBJVRNAwdDesMgTzTXUUSx1It41Fq"

async def fetch_nfl_scores():
    current_year = datetime.now().year
    for week in range(1, 18):
        url = f"https://api.foxsports.com/bifrost/v1/nfl/scoreboard/segment/{current_year}-{week}-1?apikey={API_KEY}"
        async with aiohttp.ClientSession() as session:
            async with session.get(url) as response:
                data = await response.json()
                if data['sectionList'][0]['events'][0]['eventStatus'] == 2:
                    return data
    return None

class NFLBetView(discord.ui.View):
    def __init__(self, games):
        super().__init__()
        self.add_item(GameSelect(games))

class GameSelect(discord.ui.Select):
    def __init__(self, games):
        options = [
            discord.SelectOption(
                label=f"{game['upperTeam']['longName']} vs {game['lowerTeam']['longName']}",
                value=game['id'],
                description=f"Start time: <t:{int(datetime.fromisoformat(game['eventTime'].replace('Z', '+00:00')).timestamp())}:F>"
            ) for game in games
        ]
        super().__init__(placeholder="Select a game to bet on", min_values=1, max_values=1, options=options)
        self.games = {game['id']: game for game in games}

    async def callback(self, interaction: discord.Interaction):
        selected_game_id = self.values[0]
        game_data = self.games.get(selected_game_id)
        if not game_data:
            await interaction.response.send_message("Selected game data not found.", ephemeral=True)
            return
        await interaction.response.edit_message(content="Select a team to bet on:", view=TeamSelect(game_data))

class TeamSelect(discord.ui.View):
    def __init__(self, game):
        super().__init__()
        away_team = game['upperTeam']
        home_team = game['lowerTeam']
        options = [
            discord.SelectOption(label=away_team['longName'], value=away_team['name']),
            discord.SelectOption(label=home_team['longName'], value=home_team['name'])
        ]
        self.add_item(TeamOptionSelect(options, game))

class TeamOptionSelect(discord.ui.Select):
    def __init__(self, options, game):
        super().__init__(placeholder="Select a team to bet on", min_values=1, max_values=1, options=options)
        self.game = game

    async def callback(self, interaction: discord.Interaction):
        selected_team = self.values[0]
        await interaction.response.send_modal(BetModal(selected_team, interaction.user.id, self.game))

class BetModal(discord.ui.Modal, title="Place Your Bet"):
    bet_amount = discord.ui.TextInput(label="Bet Amount", placeholder="Enter bet amount", required=True)

    def __init__(self, team, user_id, game_data):
        super().__init__()
        self.team = team
        self.user_id = user_id
        self.game_data = game_data

    async def on_submit(self, interaction: discord.Interaction):
        try:
            bet_amount = int(self.bet_amount.value)
            if bet_amount <= 0:
                raise ValueError("Bet amount must be greater than 0.")
            if bet_amount > user_cash.get(self.user_id, 0):
                raise ValueError("Insufficient balance. Please check your balance and try again.")

            user_cash[self.user_id] -= bet_amount
            await interaction.response.send_message(f"Bet placed on **{self.team}** for **${bet_amount}**.", ephemeral=True)

            user = await interaction.client.fetch_user(self.user_id)
            embed = discord.Embed(title="Bet Placed", color=0x787878)
            embed.add_field(name="League", value="NFL", inline=False)
            embed.add_field(name="Team", value=self.team, inline=False)
            embed.add_field(name="Amount", value=f"${bet_amount}", inline=False)
            game_description = f"{self.game_data['upperTeam']['longName']} vs {self.game_data['lowerTeam']['longName']}"
            start_time = self.game_data['eventTime']
            embed.add_field(name="Game", value=game_description, inline=False)
            embed.add_field(name="Start Time", value=f"<t:{int(datetime.fromisoformat(start_time.replace('Z', '+00:00')).timestamp())}:F>", inline=False)
            await user.send(embed=embed)

            if self.user_id not in user_bets:
                user_bets[self.user_id] = []
            user_bets[self.user_id].append({
                "league": "NFL",
                "team": self.team,
                "amount": bet_amount,
                "game_data": self.game_data
            })

            asyncio.create_task(self.monitor_game(interaction))
            
        except ValueError as e:
            await interaction.response.send_message(str(e), ephemeral=True)

    async def monitor_game(self, interaction):
        previous_scores = {
            self.game_data['upperTeam']['name']: None,
            self.game_data['lowerTeam']['name']: None,
        }
        
        while True:
            scores_response = await fetch_nfl_scores()
            if not scores_response:
                await asyncio.sleep(60)
                continue

            current_game = None
            for section in scores_response.get('sectionList', []):
                for event in section.get('events', []):
                    if event['id'] == self.game_data['id']:
                        current_game = event
                        break
                if current_game:
                    break

            if not current_game:
                await asyncio.sleep(60)
                continue

            current_scores = {
                current_game['upperTeam']['name']: current_game['upperTeam'].get('score'),
                current_game['lowerTeam']['name']: current_game['lowerTeam'].get('score'),
            }

            score_changed = False
            for team_name, current_score in current_scores.items():
                previous_score = previous_scores[team_name]
                if previous_score is None or current_score != previous_score:
                    score_changed = True

            previous_scores = current_scores.copy()

            if score_changed:
                away_score = current_scores[self.game_data['upperTeam']['name']] or 'N/A'
                home_score = current_scores[self.game_data['lowerTeam']['name']] or 'N/A'
                message = f"Current score update: {away_score} - {home_score}"
                user = await interaction.client.fetch_user(self.user_id)
                await user.send(message)

            event_status = current_game.get('eventStatus')
            if event_status == 3:
                winner = self.game_data['upperTeam']['name'] if current_scores[self.game_data['upperTeam']['name']] > current_scores[self.game_data['lowerTeam']['name']] else self.game_data['lowerTeam']['name']
                bet_result = "won" if winner == self.team else "lost"
                final_message = f"Game over! Final score: {away_score} - {home_score}. You {bet_result} your bet on {self.team}."
                user = await interaction.client.fetch_user(self.user_id)
                await user.send(final_message)
                break

            await asyncio.sleep(60)

@app_commands.command(name="nflbet", description="Bet on NFL games")
async def nflbet(interaction: discord.Interaction):
    scores = await fetch_nfl_scores()
    if not scores:
        await interaction.response.send_message("No NFL games available for betting this week.", ephemeral=True)
        return

    events = scores.get('sectionList', [])[0].get('events', [])
    upcoming_games = [game for game in events if game.get('eventStatus') == 2]
    
    if not upcoming_games:
        await interaction.response.send_message("No NFL games available for betting this week.", ephemeral=True)
        return

    view = NFLBetView(upcoming_games)
    await interaction.response.send_message("Select a game to bet on:", view=view, ephemeral=True)

@app_commands.command(name="viewbets", description="View your current bets")
async def viewbets(interaction: discord.Interaction):
    user_id = interaction.user.id

    if user_id not in user_bets or not user_bets[user_id]:
        await interaction.response.send_message("You have no active bets.", ephemeral=True)
        return

    embed = discord.Embed(title="Your Current Bets", color=0x787878)

    for i, bet in enumerate(user_bets[user_id], 1):
        league = bet['league']
        team = bet['team']
        amount = bet['amount']
        game = bet['game_data']
        away_score = 'N/A' if 'score' not in game['upperTeam'] else str(game['upperTeam']['score'])
        home_score = 'N/A' if 'score' not in game['lowerTeam'] else str(game['lowerTeam']['score'])
        start_time = datetime.fromisoformat(game['eventTime'].replace('Z', '+00:00'))
        current_time = datetime.now(timezone.utc)
        
        if current_time < start_time:
            status = f"Starts <t:{int(start_time.timestamp())}:R>"
        elif 'score' in game['lowerTeam']:
            status = 'Final'
            winner = game['upperTeam']['name'] if game['upperTeam']['score'] > game['lowerTeam']['score'] else game['lowerTeam']['name']
            bet_result = "Won" if winner == team else "Lost"
        else:
            status = "In Progress"
            bet_result = "Pending"
        
        embed.add_field(
            name=f"Bet {i}: {league}",
            value=(f"**Team:** {team}\n"
                   f"**Amount:** ${amount}\n"
                   f"**Game:** {game['upperTeam']['longName']} vs {game['lowerTeam']['longName']}\n"
                   f"**Status:** {status}\n"
                   f"**Current Score:** {away_score} - {home_score}\n"
                   f"**Start Time:** <t:{int(start_time.timestamp())}:F>\n"
                   f"**Bet Result:** {bet_result}"),
            inline=False)

    view = discord.ui.View()
    cancel_select = discord.ui.Select(
        placeholder="Select a bet to cancel",
        min_values=1,
        max_values=1,
        options=[
            discord.SelectOption(label=f"Bet {i}", value=str(i-1)) for i in range(1, len(user_bets[user_id])+1)
        ]
    )
    view.add_item(cancel_select)

    async def cancel_callback(interaction_cancel: discord.Interaction):
        if interaction_cancel.user.id != user_id:
            await interaction_cancel.response.send_message("You cannot cancel other users' bets.", ephemeral=True)
            return

        bet_index = int(cancel_select.values[0])
        cancelled_bet = user_bets[user_id][bet_index]
        start_time = datetime.fromisoformat(cancelled_bet['game_data']['eventTime'].replace('Z', '+00:00'))

        if datetime.now(timezone.utc) >= start_time:
            await interaction_cancel.response.send_message("You cannot cancel your bet as the game has already started.", ephemeral=True)
            return

        user_cash[user_id] += cancelled_bet['amount']
        user_bets[user_id].pop(bet_index)
        await interaction_cancel.response.send_message(f"Bet cancelled. **${cancelled_bet['amount']}** has been refunded.", ephemeral=True)

        if not user_bets[user_id]:
            del user_bets[user_id]

    cancel_select.callback = cancel_callback

    await interaction.response.send_message(embed=embed, view=view, ephemeral=True)

@app_commands.command(name="nflbet", description="Bet on NFL games")
async def nflbet(interaction: discord.Interaction):
    scores = await fetch_nfl_scores()
    if not scores:
        await interaction.response.send_message("No NFL games available for betting this week.", ephemeral=True)
        return

    events = scores.get('sectionList', [])[0].get('events', [])
    upcoming_games = [game for game in events if game.get('eventStatus') == 2]
    
    if not upcoming_games:
        await interaction.response.send_message("No NFL games available for betting this week.", ephemeral=True)
        return

    view = NFLBetView(upcoming_games)
    await interaction.response.send_message("Select a game to bet on:", view=view, ephemeral=True)

@app_commands.command(name="viewbets", description="View your current bets")
async def viewbets(interaction: discord.Interaction):
    user_id = interaction.user.id

    if user_id not in user_bets or not user_bets[user_id]:
        await interaction.response.send_message("You have no active bets.", ephemeral=True)
        return

    embed = discord.Embed(title="Your Current Bets", color=0x787878)

    for i, bet in enumerate(user_bets[user_id], 1):
        league = bet['league']
        team = bet['team']
        amount = bet['amount']
        game = bet['game_data']
        away_score = 'N/A' if 'score' not in game['upperTeam'] else str(game['upperTeam']['score'])
        home_score = 'N/A' if 'score' not in game['lowerTeam'] else str(game['lowerTeam']['score'])
        start_time = datetime.fromisoformat(game['eventTime'].replace('Z', '+00:00'))
        current_time = datetime.now(timezone.utc)
        
        if current_time < start_time:
            status = f"Starts <t:{int(start_time.timestamp())}:R>"
        elif 'score' in game['lowerTeam']:
            status = 'Final'
            winner = game['upperTeam']['name'] if game['upperTeam']['score'] > game['lowerTeam']['score'] else game['lowerTeam']['name']
            bet_result = "Won" if winner == team else "Lost"
        else:
            status = "In Progress"
            bet_result = "Pending"
        
        embed.add_field(
            name=f"Bet {i}: {league}",
            value=(f"**Team:** {team}\n"
                   f"**Amount:** ${amount}\n"
                   f"**Game:** {game['upperTeam']['longName']} vs {game['lowerTeam']['longName']}\n"
                   f"**Status:** {status}\n"
                   f"**Current Score:** {away_score} - {home_score}\n"
                   f"**Start Time:** <t:{int(start_time.timestamp())}:F>\n"
                   f"**Bet Result:** {bet_result}"),
            inline=False)

    view = discord.ui.View()
    cancel_select = discord.ui.Select(
        placeholder="Select a bet to cancel",
        min_values=1,
        max_values=1,
        options=[
            discord.SelectOption(label=f"Bet {i}", value=str(i-1)) for i in range(1, len(user_bets[user_id])+1)
        ]
    )
    view.add_item(cancel_select)

    async def cancel_callback(interaction_cancel: discord.Interaction):
        if interaction_cancel.user.id != user_id:
            await interaction_cancel.response.send_message("You cannot cancel other users' bets.", ephemeral=True)
            return

        bet_index = int(cancel_select.values[0])
        cancelled_bet = user_bets[user_id][bet_index]
        start_time = datetime.fromisoformat(cancelled_bet['game_data']['eventTime'].replace('Z', '+00:00'))

        if datetime.now(timezone.utc) >= start_time:
            await interaction_cancel.response.send_message("You cannot cancel your bet as the game has already started.", ephemeral=True)
            return

        user_cash[user_id] += cancelled_bet['amount']
        user_bets[user_id].pop(bet_index)
        await interaction_cancel.response.send_message(f"Bet cancelled. **${cancelled_bet['amount']}** has been refunded.", ephemeral=True)

        if not user_bets[user_id]:
            del user_bets[user_id]

    cancel_select.callback = cancel_callback

    await interaction.response.send_message(embed=embed, view=view, ephemeral=True)