Skip to content
This repository was archived by the owner on May 17, 2021. It is now read-only.

Commit a9229ab

Browse files
committed
fixes for running out of questions
1 parent 24bebf1 commit a9229ab

File tree

4 files changed

+107
-90
lines changed

4 files changed

+107
-90
lines changed

Diff for: database.py

+10-8
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
import peewee
22
import datetime
3-
import random
43

54

65
class Database:
@@ -149,9 +148,8 @@ def get_day_question(self):
149148
q = self.Question.get_or_none(self.Question.last_date.is_null())
150149

151150
if q is None:
152-
q = self.get_random_question()
151+
q = self.__get_random_helper()
153152

154-
# TODO: also do another is none check and add the furthest date from today. This should cover all bases
155153
q.last_date = datetime.datetime.now().date()
156154
q.save()
157155

@@ -167,11 +165,7 @@ def get_random_question(self, company=None):
167165
:param company: (Optional) Limit random question to one asked by given company
168166
:return: randomly chosen question
169167
"""
170-
171-
if company is None:
172-
q = self.Question.select().order_by(peewee.fn.Random()).get()
173-
else:
174-
q = self.Question.select().where(self.Question.company == company).order_by(peewee.fn.Random()).get()
168+
q = self.__get_random_helper(company)
175169

176170
if q.leetcode is not None:
177171
return q.id, q.company, q.body, q.leetcode
@@ -244,3 +238,11 @@ def remove_question(self, index):
244238
string = target.body
245239
target.delete_instance()
246240
return string
241+
242+
def __get_random_helper(self, company=None):
243+
if company is None:
244+
q = self.Question.select().order_by(peewee.fn.Random()).get()
245+
else:
246+
q = self.Question.select().where(self.Question.company == company).order_by(peewee.fn.Random()).get()
247+
248+
return q

Diff for: main.py

+72-74
Original file line numberDiff line numberDiff line change
@@ -3,15 +3,15 @@
33
import discord
44
import asyncio
55

6-
from discord import Game
6+
from discord import Game, DMChannel
7+
78
from database import Database
89
from datetime import datetime
910
from dotenv import load_dotenv
1011
from os.path import join, dirname
1112
from input_parser import json_parser
1213
from discord.ext.commands import Bot
1314

14-
# This is from rolley
1515
PREFIX = '>'
1616
DQ_CHANNEL = 'daily-coding-challenge'
1717
Q_CHANNEL = 'programming-challenges'
@@ -48,22 +48,49 @@ def update_question():
4848
question_date = datetime.today().date()
4949

5050

51+
def get_embed(base=None):
52+
global question
53+
54+
if base is None:
55+
question_text = "[ *{}* ] Asked by **{}**\n\n{}".format(question[0], question[1], question[2])
56+
57+
if len(question) == 4:
58+
question_text + "\nLeetcode link: {}".format(question[3])
59+
else:
60+
question_text = "[ *{}* ] Asked by **{}**\n\n{}".format(base[0], base[1], base[2])
61+
62+
return discord.Embed(title='Question for **{}**'.format(datetime.today().date()), type='rich',
63+
description=question_text, color=0xffd700)
64+
65+
5166
async def timer_update():
67+
global target_channel
68+
5269
while True:
5370
update_question()
5471
emb = get_embed()
5572

5673
if target_channel is not None:
57-
await bot.send_message(target_channel, embed=emb)
74+
await target_channel.send(embed=emb)
5875

5976
await asyncio.sleep(secs)
6077

6178

79+
def is_mod_or_admin(author, channel, channel_is_private=False):
80+
global db
81+
if not channel_is_private:
82+
perms = author.permissions_in(channel)
83+
if perms.manage_roles or perms.administrator:
84+
return True
85+
86+
return db.is_admin(author.id)
87+
88+
6289
# Bot Events
6390
@bot.event
6491
async def on_ready():
6592
global db
66-
await bot.change_presence(game=Game(name="Hackerrank"))
93+
await bot.change_presence(activity=Game(name="Hackerrank"))
6794
print("Logged in as")
6895
print(bot.user.name)
6996
print(bot.user.id)
@@ -73,54 +100,43 @@ async def on_ready():
73100
asyncio.ensure_future(timer_update(), loop=loop)
74101

75102

76-
def is_mod_or_admin(author, channel_is_private=False):
77-
global db
78-
if not channel_is_private:
79-
perms = author.server_permissions
80-
if perms.manage_roles or perms.administrator:
81-
return True
82-
83-
return db.is_admin(author.id)
84-
85-
86103
@bot.event
87104
async def on_message(message):
88105
global target_channel
89106

90-
if not message.channel.is_private or message.author.bot:
107+
if not isinstance(message.channel, DMChannel) or message.author.bot:
91108
# This is a passive check to update the target channel for showing question
92109
if target_channel is None and message.channel.name == DQ_CHANNEL:
93110
target_channel = message.channel
94111

95112
await bot.process_commands(message)
96113
return
97114

98-
# TODO: add check in DB to see if person is allowed to add
99-
if not is_mod_or_admin(message.author, channel_is_private=True):
115+
if not is_mod_or_admin(message.author, message.channel, channel_is_private=True):
100116
return
101117

102118
if len(message.attachments) == 1:
103119
file_url = message.attachments[0]['url']
104120

105121
if file_url.endswith(".json"):
106-
await bot.send_message(message.author, "Attempting to add bulk question list")
122+
await message.channel.send("Attempting to add bulk question list")
107123
question_list = json_parser(file_url)
108124
db.add_multiple_questions(question_list)
109-
await bot.send_message(message.author, "Added questions in bulk")
125+
await message.channel.send("Added questions in bulk")
110126
return
111127
else:
112-
await bot.send_message("I only support JSON files right now")
128+
await message.channel.send("I only support JSON files right now")
113129
return
114130

115131
if message.author.id in user_cache.keys():
116132
if message.content.upper() == 'Y' or message.content.upper() == 'YES':
117133
arr = user_cache[message.author.id]
118134
if db.add_new_question(arr[1], arr[2], arr[3]) == 1:
119-
await bot.send_message(message.author, "Question added.")
135+
await message.channel.send("Question added.")
120136
else:
121-
await bot.send_message(message.author, "Question already in database.")
137+
await message.channel.send("Question already in database.")
122138
else:
123-
await bot.send_message(message.author, "Question **not** added.")
139+
await message.channel.send("Question **not** added.")
124140

125141
del user_cache[message.author.id]
126142

@@ -130,22 +146,21 @@ async def on_message(message):
130146

131147
if message.author.id in editor_cache.keys():
132148
if update_question_details(message, message.author.id):
133-
await bot.send_message(message.author, content="Question has been updated")
149+
await message.channel.send(content="Question has been updated")
134150
else:
135-
await bot.send_message(message.author, content="Question could not be updated, try again")
151+
await message.channel.send(content="Question could not be updated, try again")
136152
return
137153

138154
if len(lines) < 3:
139-
await bot.send_message(message.author, "Invalid Format. Try Again")
155+
await message.channel.send("Invalid Format. Try Again")
140156
return
141157

142158
# index [0] is just a newline
143159
arr = [1, lines[1], "\n".join(lines[3:])]
144160

145161
emb = get_embed(base=arr)
146162

147-
await bot.send_message(message.author, embed=emb,
148-
content="Type in _YES_ to keep it this way. _NO_ to try format again")
163+
await message.channel.send(embed=emb, content="Type in _YES_ to keep it this way. _NO_ to try format again")
149164

150165
arr.append(lines[2])
151166
user_cache[message.author.id] = arr
@@ -173,57 +188,55 @@ def update_question_details(msg, author_id):
173188
pass_context=True)
174189
async def add_admin(ctx):
175190
if len(ctx.message.mentions) == 0:
176-
await bot.send_message(ctx.message.channel, content='Need to supply users to add')
191+
await ctx.message.channel.send('Need to supply users to add')
177192
return
178193

179-
if not is_mod_or_admin(ctx.message.author):
180-
await bot.send_message(ctx.message.channel, content='You have insufficient perms to do this')
194+
if not is_mod_or_admin(ctx.message.author, ctx.message.channel):
195+
await ctx.message.channel.send(content='You have insufficient perms to do this')
181196
return
182197

183198
for mentioned in ctx.message.mentions:
184199
if db.add_admin(mentioned.id) == 0:
185-
await bot.send_message(ctx.message.channel, content='User {} not found'.format(mentioned.name))
200+
await ctx.message.channel.send(content='User {} not found'.format(mentioned.name))
186201

187-
await bot.send_message(ctx.message.channel, content='Users added')
202+
await ctx.message.channel.send(content='Users added')
188203

189204

190205
@bot.command(name='remove_admin', description='remove admin from table', aliases=['del_admin', 'da'],
191206
brief='delete admin', pass_context=True)
192207
async def remove_admin(ctx):
193208
if len(ctx.message.mentions) == 0:
194-
await bot.send_message(ctx.message.channel, content='Need to supply users to add')
209+
await ctx.message.channel.send(content='Need to supply users to add')
195210
return
196211

197-
if not is_mod_or_admin(ctx.message.author):
198-
await bot.send_message(ctx.message.channel, content='You have insufficient perms to do this')
212+
if not is_mod_or_admin(ctx.message.author, ctx.message.channel):
213+
await ctx.message.channel.send(content='You have insufficient perms to do this')
199214
return
200215

201216
for mentioned in ctx.message.mentions:
202217
if db.remove_admin(mentioned.id) is None:
203-
await bot.send_message(ctx.message.channel, content='User {} not in table'.format(mentioned.name))
218+
await ctx.message.channel.send(content='User {} not in table'.format(mentioned.name))
204219

205-
await bot.send_message(ctx.message.channel, content='Users removed')
220+
await ctx.message.channel.send(content='Users removed')
206221

207222

208223
@bot.command(name='edit_question', description='edits a question', aliases=['edit'], brief='update question',
209224
pass_context=True)
210225
async def edit_question(ctx, *args):
211-
if not is_mod_or_admin(ctx.message.author):
212-
await bot.send_message(ctx.message.channel, content="You have insufficient perms to do this")
226+
if not is_mod_or_admin(ctx.message.author, ctx.message.channel):
227+
await ctx.message.channel.send(content="You have insufficient perms to do this")
213228
return
214229

215230
if len(args) == 0:
216-
await bot.send_message(ctx.message.channel, content="You need to specify a number...")
231+
await ctx.message.channel.send(content="You need to specify a number...")
217232
return
218233

219234
try:
220235
index = int(args[0])
221236
editor_cache[ctx.message.author.id] = index
222-
await bot.send_message(ctx.message.channel,
223-
content="Please enter the question body surrounded by triple backticks")
237+
await ctx.message.channel.send(content="Please enter the question body surrounded by triple backticks")
224238
except ValueError:
225-
await bot.send_message(ctx.message.channel,
226-
content="A number, y'know like 0, or 1, or 1997. This isn't that hard")
239+
await ctx.message.channel.send(content="A number, y'know like 0, or 1, or 1997. This isn't that hard")
227240

228241

229242
@bot.command(name='sample_json', description='show sample of json for input purposes', aliases=['sj', 'json'],
@@ -237,7 +250,7 @@ async def sample_json_format(ctx):
237250

238251
parsed_to_json = json.dumps(questions)
239252

240-
await bot.send_message(ctx.message.author, "```"+parsed_to_json+"```")
253+
await ctx.message.channel.send("```"+parsed_to_json+"```")
241254

242255

243256
@bot.command(name='show_question',
@@ -257,7 +270,7 @@ async def show_question(ctx, *args):
257270
else:
258271
emb = get_embed()
259272

260-
await bot.send_message(ctx.message.channel, embed=emb)
273+
await ctx.message.channel.send(embed=emb)
261274
else:
262275
if ctx.message.channel.name != Q_CHANNEL:
263276
return
@@ -267,11 +280,11 @@ async def show_question(ctx, *args):
267280

268281
if succ is not None:
269282
emb = get_embed(base=succ)
270-
await bot.send_message(ctx.message.channel, embed=emb)
283+
await ctx.message.channel.send(embed=emb)
271284
else:
272-
await bot.send_message(ctx.message.channel, content="could not find question with supplied index")
285+
await ctx.message.channel.send(content="could not find question with supplied index")
273286
except ValueError:
274-
await bot.send_message(ctx.message.channel, content="Please supply **A NUMBER**")
287+
await ctx.message.channel.send(content="Please supply **A NUMBER**")
275288

276289

277290
@bot.command(name='random_question', aliases=['random', 'rq'], brief='get random question from database',
@@ -285,7 +298,7 @@ async def random_question(ctx, *args):
285298
else:
286299
emb = get_embed(db.get_random_question(company=args[0]))
287300

288-
await bot.send_message(ctx.message.channel, embed=emb)
301+
await ctx.message.channel.send(embed=emb)
289302

290303

291304
@bot.command(name='list_questions', description='lists all questions from index provided', aliases=['list', 'lq'],
@@ -305,7 +318,7 @@ async def list_questions(ctx, *args):
305318

306319
string = '```' + string + '```'
307320

308-
await bot.send_message(ctx.message.channel, content=string)
321+
await ctx.message.channel.send(content=string)
309322

310323

311324
@bot.command(name='list_companies', description='lists all companies in database', aliases=['lc'],
@@ -319,20 +332,20 @@ async def list_companies(ctx, *args):
319332
string += "{0:15} | {1:3}\n".format(row.company, row.count)
320333

321334
string = '```' + string + '```'
322-
await bot.send_message(ctx.message.channel, content=string)
335+
await ctx.message.channel.send(content=string)
323336

324337

325338
@bot.command(name='remove_question', description='deletes question based on index, found by using >list',
326339
aliases=['del', 'remove'],
327340
brief='delete question on index', pass_context=True)
328341
async def remove_question(ctx, *args):
329-
if not is_mod_or_admin(ctx.message.author):
330-
await bot.send_message(ctx.message.channel, content="You have insufficient perms to do this")
342+
if not is_mod_or_admin(ctx.message.author, ctx.message.channel):
343+
await ctx.message.channel.send(content="You have insufficient perms to do this")
331344
return
332345

333346
global db, question
334347
if len(args) == 0:
335-
await bot.send_message(ctx.message.channel, content="Please supply index to delete")
348+
await ctx.message.channel.send(content="Please supply index to delete")
336349
return
337350

338351
try:
@@ -341,26 +354,11 @@ async def remove_question(ctx, *args):
341354
if succ is not None:
342355
if question == succ:
343356
question = None
344-
await bot.send_message(ctx.message.channel, content="Successfully deleted")
357+
await ctx.message.channel.send( content="Successfully deleted")
345358
else:
346-
await bot.send_message(ctx.message.channel, content="could not find question with supplied index")
359+
await ctx.message.channel.send(content="could not find question with supplied index")
347360
except ValueError:
348-
await bot.send_message(ctx.message.channel, content="Please supply **A NUMBER**")
349-
350-
351-
def get_embed(base=None):
352-
global question
353-
354-
if base is None:
355-
question_text = "[ *{}* ] Asked by **{}**\n\n{}".format(question[0], question[1], question[2])
356-
357-
if len(question) == 4:
358-
question_text + "\nLeetcode link: {}".format(question[3])
359-
else:
360-
question_text = "[ *{}* ] Asked by **{}**\n\n{}".format(base[0], base[1], base[2])
361-
362-
return discord.Embed(title='Question for **{}**'.format(datetime.today().date()), type='rich',
363-
description=question_text, color=0xffd700)
361+
await ctx.message.channel.send(content="Please supply **A NUMBER**")
364362

365363

366364
if __name__ == '__main__':

Diff for: requirements.txt

+5-4
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,9 @@
1-
aiohttp==1.0.5
1+
aiohttp==3.7.2
22
async-timeout==2.0.1
33
websockets==3.4
4-
discord==0.0.2
5-
discord.py==0.16.12
4+
discord.py==1.5.1
65
peewee>=3.8.0
76
python-dotenv==0.8.2
8-
psycopg2
7+
psycopg2
8+
freezegun>=1.0.0
9+
discord>=0.0.2

0 commit comments

Comments
 (0)