-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbot.py
More file actions
192 lines (174 loc) · 6.33 KB
/
bot.py
File metadata and controls
192 lines (174 loc) · 6.33 KB
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
import os
from dotenv import load_dotenv
from telegram import Update
from telegram.ext import ApplicationBuilder, CommandHandler, ContextTypes
import requests
from datetime import datetime, timedelta
load_dotenv()
TOKEN = os.getenv("BOT_TOKEN")
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
print("Received /start command")
await update.message.reply_text("RimAlertBot is live from AWS!\nHi Lods!\n\nFeatures:\n1. /score(YYYY-MM-DD) - shows all the completed NBA games on that day.\n/score (no dates) will show games completed today.\n\n2./live - shows all currently live/in progress NBA games today.\n\n3./team - shows current games & scheduled games of a specific team.\n\n4./schedule - shows all the scheduled games for the next 7 days. ")
async def score(update: Update, context: ContextTypes.DEFAULT_TYPE):
api_key = os.getenv("BALLDONTLIE_API_KEY")
if context.args:
date_input = context.args[0]
try:
datetime.strptime(date_input,"%Y-%m-%d")
except ValueError:
await update.message.reply_text("Invalid date format. Use YYYY-MM-DD.")
return
else:
date_input = datetime.now().strftime("%Y-%m-%d")
url = "https://api.balldontlie.io/v1/games"
headers = {
"Authorization": f"Bearer {api_key}"
}
params = {
"dates[]":date_input
}
response = requests.get(url, headers=headers, params=params)
if response.status_code != 200:
await update.message.reply_text("Error fetching games.")
return
data = response.json()
games = data.get("data",[])
if not games:
await update.message.reply_text(f"No NBA games on {date_input}")
return
message = f"NBA Games on {date_input}:\n\n"
for game in games:
home = game["home_team"]["full_name"]
away = game["visitor_team"]["full_name"]
home_score = game["home_team_score"]
away_score = game["visitor_team_score"]
status = game["status"]
message += f"{away} {away_score} - {home_score} {home}\n"
message += f"Status: {status}\n\n"
await update.message.reply_text(message)
async def live(update: Update, context: ContextTypes.DEFAULT_TYPE):
api_key = os.getenv("BALLDONTLIE_API_KEY")
today = datetime.now().strftime("%Y-%m-%d")
url = "https://api.balldontlie.io/v1/games"
headers = {
"Authorization": f"Bearer {api_key}"
}
params = {
"dates[]": today
}
response = requests.get(url, headers=headers, params=params)
if response.status_code != 200:
await update.message.reply_text("Error fetching live games.")
return
data = response.json()
games = data.get("data",[])
live_games = []
for game in games:
if game["status"] not in ["Final","Scheduled"]:
live_games.append(game)
if not live_games:
await update.message.reply_text("No live NBA games right now")
return
message = "Live NBA games:\n\n"
for game in live_games:
home = game["home_team"]["full_name"]
away = game["visitor_team"]["full_name"]
home_score = game["home_team_score"]
away_score = game["visitor_team_score"]
status = game["status"]
message += f"{away} {away_score} - {home_score} {home}\n"
message += f"Status: {status}\n\n"
await update.message.reply_text(message)
async def team(update:Update, context: ContextTypes.DEFAULT_TYPE):
if not context.args:
await update.message.reply_text("Please provide a team name. Example: /team Lakers")
return
original_query = " ".join(context.args)
team_query = original_query.lower()
api_key = os.getenv("BALLDONTLIE_API_KEY")
today = datetime.now().strftime("%Y-%m-%d")
url = "https://api.balldontlie.io/v1/games"
headers = {
"Authorization": f"Bearer {api_key}"
}
dates_list = [
(datetime.now() + timedelta(days=i)).strftime("%Y-%m-%d")
for i in range(7)
]
params = [("dates[]",date) for date in dates_list]
response = requests.get(url, headers=headers,params=params)
if response.status_code != 200:
await update.message.reply_text("Error fetching games")
return
data = response.json()
games = data.get("data",[])
today_match = None
future_match = None
for game in games:
home = game["home_team"]["full_name"]
away = game["visitor_team"]["full_name"]
game_date = game["date"][:10]
if team_query in home.lower() or team_query in away.lower():
if game_date == today:
today_match = game
break
elif game_date > today and future_match is None:
future_match = game
if today_match:
home = today_match["home_team"]["full_name"]
away = today_match["visitor_team"]["full_name"]
home_score = today_match["home_team_score"]
away_score = today_match["visitor_team_score"]
status = today_match["status"]
message = f"{away} {away_score} - {home_score} {home}\n"
message += f"Status: {status}"
await update.message.reply_text(message)
return
if future_match:
home = future_match["home_team"]["full_name"]
away = future_match["visitor_team"]["full_name"]
game_date = future_match["date"][:10]
message = f"Next Game:\n{away} vs {home}\nDate: {game_date}"
await update.message.reply_text(message)
return
await update.message.reply_text(f"No upcoming games found for {original_query}.")
async def schedule(update: Update, context: ContextTypes.DEFAULT_TYPE):
api_key = os.getenv("BALLDONTLIE_API_KEY")
url = "https://api.balldontlie.io/v1/games"
headers = {
"Authorization": f"Bearer {api_key}"
}
dates_list = [
(datetime.now() + timedelta(days=i)).strftime("%Y-%m-%d")
for i in range(7)
]
params = [("dates[]", date) for date in dates_list]
response = requests.get(url, headers=headers,params=params)
if response.status_code !=200:
await udpate.message.reply_text("Error fetching schedule.")
return
data = response.json()
games = data.get("data",[])
if not games:
await update.message.reply_text("No scheduled games in the next 7 days.")
return
games_sorted = sorted(games, key=lambda g: g["date"])
message = "NBA Schedule (Next 7 days):\n\n"
for game in games_sorted:
full_datetime = game["date"]
date_part = full_datetime[:10]
home = game["home_team"]["full_name"]
away = game["visitor_team"]["full_name"]
message += f"{date_part} - {away} vs {home}\n"
await update.message.reply_text(message)
def main():
app = ApplicationBuilder().token(TOKEN).build()
app.add_handler(CommandHandler("start", start))
app.add_handler(CommandHandler("score", score))
app.add_handler(CommandHandler("live", live))
app.add_handler(CommandHandler("team", team))
app.add_handler(CommandHandler("schedule",schedule))
print("Bot is running...")
app.run_polling()
if __name__ == "__main__":
main()