coollsd commited on
Commit
87c34f0
·
verified ·
1 Parent(s): ee3f308

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +48 -191
app.py CHANGED
@@ -1,195 +1,52 @@
 
1
  import discord
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:
18
- with open("database.txt", "r") as f:
19
- for line in f:
20
- parts = line.strip().split()
21
- if len(parts) == 2 and parts[1].startswith("cash(") and parts[1].endswith(")"):
22
- user_id = int(parts[0])
23
- cash = int(parts[1][5:-1])
24
- user_cash[user_id] = cash
25
- except FileNotFoundError:
26
- print("No database found. Creating a new one.")
27
-
28
- load_database()
29
-
30
- async def fetch_nhl_scores():
31
- async with aiohttp.ClientSession() as session:
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)
59
-
60
- class TeamSelect(discord.ui.Select):
61
- def __init__(self, away_team, home_team):
62
- options = [
63
- discord.SelectOption(label=away_team['teamName'], value=away_team['abbreviation']),
64
- discord.SelectOption(label=home_team['teamName'], value=home_team['abbreviation'])
65
- ]
66
- super().__init__(placeholder="Select a team to bet on", options=options)
67
-
68
- class BetModal(discord.ui.Modal, title="Place Your Bet"):
69
- bet_amount = discord.ui.TextInput(label="Bet Amount", placeholder="Enter bet amount")
70
-
71
- def __init__(self, team, user_id, game_data):
72
- super().__init__()
73
- self.team = team
74
- self.user_id = user_id
75
- self.game_data = game_data
76
-
77
- async def on_submit(self, interaction: discord.Interaction):
78
- try:
79
- bet_amount = int(self.bet_amount.value)
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(f"Insufficient funds. Your balance is ${user_cash.get(self.user_id, 0)}")
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)
90
- embed = discord.Embed(title="Bet Placed", color=0x787878)
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:
98
- user_bets[self.user_id] = []
99
- user_bets[self.user_id].append({
100
- "team": self.team,
101
- "amount": bet_amount,
102
- "game_data": self.game_data
103
- })
104
-
105
- asyncio.create_task(self.monitor_game(interaction, bet_amount))
106
- except ValueError as e:
107
- await interaction.response.send_message(str(e), ephemeral=True)
108
-
109
- async def monitor_game(self, interaction, bet_amount):
110
- game_start = datetime.fromisoformat(self.game_data['startTime'].replace('Z', '+00:00'))
111
- await asyncio.sleep((game_start - datetime.now(timezone.utc)).total_seconds())
112
-
113
- while True:
114
- scores = await fetch_nhl_scores()
115
- game = next((g for g in scores['games'] if g['teams']['away']['abbreviation'] == self.game_data['teams']['away']['abbreviation'] and
116
- g['teams']['home']['abbreviation'] == self.game_data['teams']['home']['abbreviation']), None)
117
-
118
- if game['status']['state'] == 'FINAL':
119
- winner = 'away' if game['scores']['away'] > game['scores']['home'] else 'home'
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"WOO YOUR TEAM WON you won ${winnings}!")
125
- else:
126
- await interaction.user.send(f"Sorry, your team lost booo!")
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 game")
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 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("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])
150
-
151
- team_view = discord.ui.View()
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="team to bet on:", view=team_view)
156
-
157
- async def team_callback(interaction: discord.Interaction):
158
- selected_team = team_select.values[0]
159
- await interaction.response.send_modal(BetModal(selected_team, interaction.user.id, selected_game))
160
-
161
- team_select.callback = team_callback
162
-
163
- game_select.callback = game_callback
164
-
165
- @app_commands.command(name="currentbets", description="view your 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 bets.")
170
- return
171
-
172
- embed = discord.Embed(title="Your Current Bets", color=0x787878)
173
- for i, bet in enumerate(user_bets[user_id]):
174
- scores = await fetch_nhl_scores()
175
- game = next((g for g in scores['games'] if g['teams']['away']['abbreviation'] == bet['game_data']['teams']['away']['abbreviation'] and
176
- g['teams']['home']['abbreviation'] == bet['game_data']['teams']['home']['abbreviation']), None)
177
-
178
- 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']}", inline=False)
179
-
180
- view = discord.ui.View()
181
- cancel_select = discord.ui.Select(placeholder="Select a bet to cancel", options=[
182
- discord.SelectOption(label=f"Bet {i+1}", value=str(i)) for i in range(len(user_bets[user_id]))
183
- ])
184
- view.add_item(cancel_select)
185
-
186
- async def cancel_callback(interaction: discord.Interaction):
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)
 
1
+ # app.py or main.py
2
  import discord
3
  from discord import app_commands
4
+ from fastapi import FastAPI
5
+ import uvicorn
6
  import asyncio
 
7
 
8
+ from shared import user_cash, user_bets, fetch_nhl_scores
9
+ from petsimgo import petsimgo
10
+ from petroll import petroll
11
+ from cash import cash
12
+ from dice import dice
13
+ from admincash import admincash
14
+ from shop import shop
15
+ from cashapp import cashapp
16
+ from database import database
17
+ from sportbet import sportbet
18
+
19
+ app = FastAPI()
20
+ intents = discord.Intents.default()
21
+ intents.message_content = True
22
+ bot = discord.Client(intents=intents)
23
+ tree = app_commands.CommandTree(bot)
24
+
25
+ @app.get("/")
26
+ async def read_root():
27
+ return {"Hello": "World"}
28
+
29
+ tree.add_command(petsimgo)
30
+ tree.add_command(petroll)
31
+ tree.add_command(cash)
32
+ tree.add_command(dice)
33
+ tree.add_command(admincash)
34
+ tree.add_command(shop)
35
+ tree.add_command(cashapp)
36
+ tree.add_command(database)
37
+ tree.add_command(sportbet)
38
+
39
+ @bot.event
40
+ async def on_ready():
41
+ await tree.sync()
42
+ print(f"{bot.user} is now online!")
43
+
44
+ async def run_bot():
45
+ await bot.start("MTI5MjkxMDYzMjg3MzQ5MjU4Mw.GbVmvy.8kEhPZyNLrACzBWYEorT7UqNRME7gp6Lvz6lg8")
46
+
47
+ @app.on_event("startup")
48
+ async def startup_event():
49
+ asyncio.create_task(run_bot())
50
+
51
+ if __name__ == "__main__":
52
+ uvicorn.run("app:app", host="0.0.0.0", port=7860)