forked from mathrithms/EngineeringTimes-Contest-Bot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreminder_bot.py
260 lines (206 loc) · 9.45 KB
/
reminder_bot.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
import discord
import os
from discord.ext import commands, tasks
from dotenv import load_dotenv
import psycopg2
from psycopg2 import Error
import datetime
from datetime import datetime as dtime
load_dotenv()
TOKEN = os.getenv("TOKEN")
PASS = os.getenv("PASSWORD")
PORT = os.getenv("PORT")
DB_NAME_CHEF = os.getenv("DB_NAME_CC")
DB_NAME_CODEFORCES = os.getenv("DB_NAME_CF")
DB_NAME_GUILDS = os.getenv("DB_NAME_GUILDS")
# initializing the bot
intents = discord.Intents(messages=True, guilds=True, reactions=True, members=True, presences=True)
client = commands.Bot(command_prefix='!', intents=intents, help_command=None)
# setting up connections to both the databases
conn = psycopg2.connect(f"dbname={DB_NAME_CHEF} host=localhost port={PORT} user=postgres password={PASS}")
conn_forces = psycopg2.connect(f"dbname={DB_NAME_CODEFORCES} host=localhost port={PORT} user=postgres password={PASS}")
conn_info = psycopg2.connect(f"dbname={DB_NAME_GUILDS} host=localhost port={PORT} user=postgres password={PASS}")
# conn_forces=psycopg2.connect(dbname="db_git2", host="localhost", port="9821", user="postgres", password="")
# conn = psycopg2.connect(dbname="db_git", host="localhost", port="9821", user="postgres", password="")
# conn_info = psycopg2.connect("dbname=guild_info.db host=localhost port=9821 user=postgres password= ")
# loading all the commands when bot goes online
@client.command()
async def load(ctx, extension):
client.load_extension(f"cogs.{extension}")
for filename in os.listdir('./cogs'):
if filename.endswith('.py'):
client.load_extension(f'cogs.{filename[:-3]}')
# start the tasks loop when bot goes online
@client.event
async def on_ready():
getlist.start()
print('hey')
# custom event that is triggered every 24 hrs and sends all the codechef contest
@client.event
async def on_reminder_chef(coming, channel):
# get the channel ID from the string passed
channel_code = client.get_channel(channel)
# get today and tomorrows dates
today_date = datetime.date.today()
tom_delta = datetime.timedelta(hours=24)
tom_date = today_date + tom_delta
# function to convert datetimes to dd mmm yyyy hh:mm:ss' format
def dtime_conv(date_time):
date_time = date_time[2][:11] + " " + date_time[2][12:]
date_time = dtime.strptime(date_time, '%d %b %Y %H:%M:%S')
return date_time
# sort all the codechef contests sorted by startime
coming = sorted(coming, key=dtime_conv)
# make an Embed object
embed = discord.Embed(
title='__**Contest Reminder**__',
description='',
colour=discord.Colour.green()
)
embed.set_author(name='Codechef', icon_url='https://static.dribbble.com/users/70628/screenshots/1743345/codechef.png')
# setting header
embed.add_field(name=f'{today_date.strftime("%d %B %Y")}',
value='__***Ongoing & Upcoming Codechef Contests***__', inline=False)
# in case of no contests
if len(coming) == 0:
name = "__***No Upcoming or Ongoing Codechef Contests***__"
val = None
embed.add_field(name=name, value=val, inline=False)
# if contest list is not empty
else:
for i in coming:
start = i[2][:11]
if (dtime.strptime(start, "%d %b %Y").date() == datetime.date.today()):
start = 'Today '
elif (dtime.strptime(start, "%d %b %Y").date() == tom_date):
start = 'Tomorrow '
s_time = i[2][12:]
if (s_time[1] == ':'):
s_time = '0' + s_time
end = i[3][:11]
if (dtime.strptime(end, "%d %b %Y").date() == datetime.date.today()):
end = 'Today'
elif (dtime.strptime(end, "%d %b %Y").date() == tom_date):
end = 'Tomorrow '
e_time = i[3][12:]
if (e_time[1] == ':'):
e_time = '0' + e_time
name = '__***' + i[1] + '***__'
str1 = '```'+'Start time'+' | '+'End time'+'\n'
time1 = '[Go to the contest page]({})'.format(i[6])+'\n'+str1+start+' | '+end+'\n'+s_time+' | '+e_time+'```'
embed.add_field(name=name, value=time1, inline=False)
await channel_code.send(embed=embed)
# custom event that gets triggered every 24 hrs and sends codechef contests
@client.event
async def on_reminder_forces(coming_forces, channel):
# get the channel ID from the string passed
channel_code = client.get_channel(channel)
# get today and tomorrows dates
today_date = datetime.date.today()
tom_delta = datetime.timedelta(hours=24)
tom_date = today_date + tom_delta
# make an Embed object
embed = discord.Embed(
title='__**Contests Reminder**__',
description='',
colour=discord.Colour.red()
)
embed.set_author(name='Codeforces',
icon_url='https://carlacastanho.github.io/Material-de-APC/assets/images/codeforces_icon.png')
# setting header
embed.add_field(name=f'{today_date.strftime("%d %B %Y")}', value='__***Upcoming Codeforces Contests***__', inline=False)
# in case of no contests
if len(coming_forces) == 0:
name = "__***No Upcoming Contests***__"
val = "No Contest Scheduled Today"
embed.add_field(name=name, value=val, inline=False)
# if contest list is not empty
else:
for i in coming_forces:
start = i[1]
s_time = i[1][11:]
if (s_time[1] == ':'):
s_time = '0' + s_time
start = dtime.strptime(start, "%Y-%m-%d %H:%M:%S")
start = start.strftime("%d %b %Y %H:%M:%S")
s_date = start[:11]
if (dtime.strptime(s_date, "%d %b %Y").date() == datetime.date.today()):
s_date = 'Today '
elif (dtime.strptime(s_date, "%d %b %Y").date() == tom_date):
s_date = 'Tomorrow '
end = i[3]
e_time = i[3][11:]
if (e_time[1] == ':'):
e_time = '0' + e_time
end = dtime.strptime(end, "%Y-%m-%d %H:%M:%S")
end = end.strftime("%d %b %Y %H:%M:%S")
e_date = end[:11]
if (dtime.strptime(e_date, "%d %b %Y").date() == datetime.date.today()):
e_date = 'Today'
elif (dtime.strptime(e_date, "%d %b %Y").date() == tom_date):
e_date = 'Tomorrow'
name = '__***'+i[0]+'***__'
time2 = '```'+'Start time'+' | '+'Ends at'+'\n'+s_date+' | '+e_date+'\n'+s_time+' | '+e_time+'```'
embed.add_field(name=name, value=time2, inline=False)
await channel_code.send(embed=embed)
# background task that runs every 24 hours and triggers the custom events
@tasks.loop(hours=24)
async def getlist():
# creating a time delta of 24 hrs
now = dtime.now()
delta = datetime.timedelta(hours=24)
bracket = now + delta
# setting up cursors
c = conn.cursor() # cursor of codechef database
c_forces = conn_forces.cursor() # cursor of codeforces database
# getting server list of the bot
server_list = client.guilds
cursor_info = conn_info.cursor() # cursor of server ID database
# takes each contest in Present Contests table of codechef and each contest in the codeforces table
# sort them according to start time and put them in lists
c.execute("""SELECT * FROM Present_Contests ORDER BY START""")
sorted_events_present = c.fetchall()
# sorted_events = c.fetchall()
c.execute("""SELECT * FROM Future_Contests ORDER BY START""")
sorted_events_future = c.fetchall()
c_forces.execute("SELECT * FROM Present_Contests ORDER BY START")
sorted_events_forces = c_forces.fetchall()
upcoming_chef = [] # stores all ongoing codechef contest
upcoming_forces = [] # stores all codeforces contests that start in the next 24 hours from now
# store all ongoing codechef contests in this list
for event in sorted_events_present:
upcoming_chef.append(event)
# checking if any future codechef events start within 24 hrs
for event in sorted_events_future:
print(dtime.strptime(event[2], '%d %b %Y\n%H:%M:%S')) # prints the codechef contest starttime CAN BE REMOVED
if dtime.strptime(event[2], '%d %b %Y\n%H:%M:%S') < bracket:
upcoming_chef.append(event)
else:
pass
# check which codeforces contest start in next 24 hours
for event in sorted_events_forces:
# print(dtime.strptime(event[1], '%Y-%m-%d %H:%M:%S')) # prints the codeforces contest starttime CAN BE REMOVED
if dtime.strptime(event[1], '%Y-%m-%d %H:%M:%S') < bracket:
upcoming_forces.append(event)
else:
pass
try:
for i in server_list:
# check which channel has been mapped to which server ID
guild_id = str(i.id)
cursor_info.execute("SELECT CHANNEL FROM info WHERE GUILD =%s", (guild_id,))
guild = cursor_info.fetchone()
# if a channel is not found, it means it has not been set up
if guild is None:
print(f'channel has not been set on "{i.name}"')
# if found, send embed
elif guild is not None:
client.dispatch("reminder_chef", upcoming_chef, int(guild[0]))
client.dispatch("reminder_forces", upcoming_forces, int(guild[0]))
conn_info.commit()
except Error as e:
print(e)
conn_info.rollback()
conn.commit()
conn_forces.commit()
client.run(TOKEN)