forked from SuddyN/StartGGDiscordActions
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
158 lines (142 loc) · 4.96 KB
/
app.py
File metadata and controls
158 lines (142 loc) · 4.96 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
import asyncio
import os
import datetime
import pytz
import requests
import pysmashgg
from pysmashgg.api import run_query
STATE = os.environ["STATE"]
TIMEZONE = os.environ["TIMEZONE"]
GAME_ID = os.environ["GAME_ID"]
SHOW_ONLINE_EVENTS = False
WEBHOOK_URL = os.environ["WEBHOOK_URL"]
STARTGG_TOKEN = os.environ["STARTGG_TOKEN"]
CUSTOM_QUERY = """query TournamentsByState($state: String!, $page: Int!, $videogameId: ID!) {
tournaments(query: {
perPage: 32
page: $page
filter: {
past: false
videogameIds: [
$videogameId
]
addrState: $state
}
}) {
nodes {
id
name
addrState
city
countryCode
createdAt
startAt
endAt
hasOfflineEvents
hasOnlineEvents
images {
id
height
width
ratio
type
url
}
isRegistrationOpen
numAttendees
primaryContact
primaryContactType
registrationClosesAt
slug
state
streams {
id
streamName
}
timezone
venueAddress
venueName
}
}
}"""
def tournaments_filter(response, earliestTime: datetime, latestTime: datetime, useCreatedAt: bool):
if response['data']['tournaments'] is None:
return
if response['data']['tournaments']['nodes'] is None:
return
tournaments = []
for node in response['data']['tournaments']['nodes']:
checkDate = node['startAt']
if useCreatedAt:
checkDate = node["createdAt"]
if checkDate < earliestTime.timestamp():
continue
if checkDate > latestTime.timestamp():
continue
tournaments.append(node)
tournaments.sort(key=lambda t: t["startAt"])
return tournaments
def make_embeds(tournament):
profile = None
banner = None
for image in tournament["images"]:
if image["type"] == 'profile':
profile = {"url": image["url"]}
if image["type"] == 'banner':
banner = {"url": image["url"]}
date = datetime.datetime.fromtimestamp(tournament["startAt"], tz=pytz.timezone(TIMEZONE)).strftime('%A, %B %d')
return [
{
"title": tournament["name"],
"url": f'https://start.gg/{tournament["slug"]}',
"color": 102204,
"description": f'{date}\n{tournament["venueAddress"]}\nPrimary Contact: {tournament["primaryContact"]}',
"thumbnail": profile,
"image": banner,
"footer": {"text": "Created by Suddy - LOVE&PEACE"},
}
]
async def main():
"""Start the script."""
tz = pytz.timezone(TIMEZONE)
this_morning = datetime.datetime.combine(datetime.datetime.now(tz).date(), datetime.time(0, 0, tzinfo=tz), tzinfo=tz)
tomorrow = this_morning + datetime.timedelta(days=1)
overmorrow = this_morning + datetime.timedelta(days=2)
next_week = this_morning + datetime.timedelta(days=8)
smash = pysmashgg.SmashGG(STARTGG_TOKEN, True)
variables = {"state": STATE, "page": 1, "videogameId": GAME_ID}
response = run_query(CUSTOM_QUERY, variables, smash.header, smash.auto_retry)
tournaments_tomorrow = tournaments_filter(response, tomorrow, overmorrow, False)
tournaments_created_recently = tournaments_filter(response, this_morning, tomorrow, True)
for tournament in tournaments_tomorrow:
payload = {
"username": "Events Tomorrow",
"avatar_url": "https://miro.medium.com/v2/resize:fit:1400/1*YAC3gljr8cMB4ZPyf3CMLA.png",
"embeds": make_embeds(tournament),
}
await requests.post(WEBHOOK_URL, json=payload)
tournaments_this_week = []
if this_morning.weekday() == 5:
tournaments_this_week = tournaments_filter(response, tomorrow, next_week, False)
for tournament in tournaments_this_week:
if tournaments_tomorrow.count(tournament) > 0:
continue
payload = {
"username": "Events Later This Week",
"avatar_url": "https://miro.medium.com/v2/resize:fit:1400/1*YAC3gljr8cMB4ZPyf3CMLA.png",
"embeds": make_embeds(tournament),
}
await requests.post(WEBHOOK_URL, json=payload)
for tournament in tournaments_created_recently:
if tournaments_tomorrow.count(tournament) > 0:
continue
if tournaments_this_week.count(tournament) > 0:
continue
payload = {
"username": "Events Created Today",
"avatar_url": "https://miro.medium.com/v2/resize:fit:1400/1*YAC3gljr8cMB4ZPyf3CMLA.png",
"embeds": make_embeds(tournament),
}
await requests.post(WEBHOOK_URL, json=payload)
if __name__ == "__main__":
asyncio.run(main())