-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
269 lines (215 loc) · 6.35 KB
/
main.py
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
import multiprocessing # multiprocessing (builtin)
import os # os (builtin)
import random # random (builtin)
import socket # socket (builtin)
import sys # sys (builtin)
import time # time (builtin)
import discord # pycord (py-cord)
import pytz # pytz (pytz)
import requests # requests (requests)
import wikipedia # wikipedia (wikipedia)
from datetime import datetime # datetime (builtin)
from discord.commands import Option
from termcolor import cprint # termcolor (termcolor)
# region SETTINGS
DEBUG = False
MAX_EVENTS = 10
# endregion
# region CONSTANTS
MONTHS = [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December",
]
TOPGG_URL = "https://top.gg/api/bots/804445656088576002/stats"
PORT = 8080
# endregion
# region GLOBALS
NUM_GUILDS = multiprocessing.Value("i", 0)
# BACKGROUND_TASKS = []
# endregion
if DEBUG:
DEBUG_GUILDS = [520039773667328003]
BOT_TOKEN = os.environ["TEST_TOKEN"]
else:
DEBUG_GUILDS = None # global
BOT_TOKEN = os.environ["TOKEN"]
bot = discord.Bot(debug_guilds=DEBUG_GUILDS)
sys.stdout.reconfigure(line_buffering=True)
def post_guild_count(num_guilds: multiprocessing.Value):
"""Posts guild count to top.gg."""
while True:
try:
while num_guilds.value <= 0:
print("Waiting for bot to start ...")
time.sleep(10)
requests.post(
TOPGG_URL,
data={"server_count": str(num_guilds.value)},
headers={"Authorization": os.environ["TOPGG_TOKEN"]},
)
cprint(
"%s :: Posted guild count! COUNT=%d"
% (time_now(), num_guilds.value),
"green",
"on_grey",
)
except Exception as err:
cprint(
"%s :: Could not post guild count (COUNT=%d). %s: %s"
% (time_now(), num_guilds.value, type(err).__name__, err),
"red",
"on_grey",
)
finally:
time.sleep(1800) # 30 minutes
def time_now():
"""Returns current time (for debug logs)."""
return datetime.now(pytz.timezone("US/Pacific")).strftime(
"%H:%M:%S %b %d %Y"
)
async def send_events(ctx, month, day, count):
"""Gets the events to send when !otd is called.
NOTE: January is month 1, not 0."""
page = wikipedia.page(
title=MONTHS[month - 1] + " " + str(day), auto_suggest=False
).content.split("\n")
events = []
i = 0
while "".join(page[i].split()) != "==Events==":
i += 1
i += 1
while not (page[i].startswith("==") and not page[i].startswith("===")):
if not page[i] or page[i].startswith("==="):
i += 1
else:
if page[i].startswith("0"):
page[i] = page[i][1:]
events.append(" ".join(page[i].split()))
i += 1
# NOTE: The '–' character IS supposed to be in the code: for some reason,
# NOTE: Wikipedia uses it instead of a hyphen.
await ctx.respond(
"**%s %d**\n\n" % (MONTHS[month - 1], day)
+ "\n".join(
sorted(
random.sample(events, count),
key=lambda s: int(s[: s.find("–") - 1].lower().strip("adbc")),
)
)
+ "\n\nSee more at <https://en.wikipedia.org/wiki/%s_%d>."
% (MONTHS[month - 1], day)
)
def random_date():
"""Returns a random date."""
cumulative_days = [
0,
31,
60,
91,
121,
152,
182,
213,
244,
274,
305,
335,
366,
]
day_num = random.randint(1, 366)
month = 1
while day_num > cumulative_days[month]:
month += 1
day = day_num - cumulative_days[month - 1]
return month, day
# region "@bot.event"s
@bot.event
async def on_ready():
global NUM_GUILDS
NUM_GUILDS.value = len(bot.guilds)
cprint("%s :: Ready!" % time_now(), "green")
# if not DEBUG:
# cprint(
# "%s :: Current guild count is %d" % (time_now(), NUM_GUILDS.value),
# "blue",
# )
@bot.event
async def on_guild_join(guild):
global NUM_GUILDS
NUM_GUILDS.value = len(bot.guilds)
cprint(
"%s :: Joined %s! ID=%d" % (time_now(), guild.name, guild.id),
"green",
)
@bot.event
async def on_guild_remove(guild):
global NUM_GUILDS
NUM_GUILDS.value = len(bot.guilds)
cprint(
"%s :: Left %s. ID=%d" % (time_now(), guild.name, guild.id),
"red",
)
# endregion
# region "@bot.slash_command"s
@bot.slash_command(
name="otd", description="Get random events on a specific date."
)
async def otd(
ctx,
month: Option(int, "month", required=False, default=-1),
day: Option(int, "day", required=False, default=-1),
count: Option(int, "number of events", required=False, default=3),
):
if count < 1 or count > MAX_EVENTS:
await ctx.respond(
f"The number of events must be between 1 and {MAX_EVENTS}, inclusive."
)
return
if month == -1 or day == -1:
today = datetime.now()
month, day = today.month, today.day
await send_events(ctx, month, day, count)
@bot.slash_command(
name="random", description="Get random events on a random date."
)
async def random_otd(
ctx,
count: Option(int, "number of events", required=False, default=3),
):
if count < 1 or count > MAX_EVENTS:
await ctx.respond(
f"The number of events must be between 1 and {MAX_EVENTS}, inclusive."
)
return
month, day = random_date()
await send_events(ctx, month, day, count)
# endregion
def fake_socket():
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(("", PORT))
s.listen(1)
# l = []
while True:
c, a = s.accept()
# l.append(c)
# print('%d: connection from %s' % (len(l), a))"""
if __name__ == "__main__":
post_count_process = multiprocessing.Process(
target=post_guild_count, args=(NUM_GUILDS,)
)
fake_socket_process = multiprocessing.Process(target=fake_socket)
# BACKGROUND_TASKS.append(post_count_process)
post_count_process.start()
fake_socket_process.start()
cprint(f"PROCESS ID: {os.getpid()}", "yellow")
bot.run(BOT_TOKEN)