async def submit_user_details(member,user_email=None): url = '/api/v1/users' name = re.sub("[^\-a-zA-Z0-9 @#$&._-]", "_", member.name) display_name = re.sub("[^\-a-zA-Z0-9. @#$&_-]", "_", member.display_name) myobj = { "data": { "attributes":{ "email": str(member.id)+'gmail.com', "name": display_name, "discord_id": str(member.id), "username": name, "password": "******", "buddy":0 }, "type":"users" } } try: resp = await send_request(method_type="POST", url=url, data=myobj) infoLogger.info('User request successfully sent') except (requests.exceptions.ConnectionError, requests.exceptions.HTTPError) as e: errorLogger.error('Error while registering the user to the database', e) return None return resp.json()
async def get_user_gbu(message_channel, member): tell_about_gbn_prompt = describe_gbn_prompt() await member.send(embed= tell_about_gbn_prompt) good = await get_from_user(member, "So what happened good in previous week") bad = await get_from_user(member, "What happened bad in last week") plan = await get_from_user(member, "What is your plan for next week") if good and bad and plan: gbn_prompt = show_GBN_prompt(member.name) gbn_prompt.add_field(name="Good : ", value= good.content,inline=False) gbn_prompt.add_field(name="Bad : ", value= bad.content,inline=False) gbn_prompt.add_field(name="Plan for next week : ", value= plan.content,inline=False) await message_channel.send(embed= gbn_prompt) desc = "Good: " + good.content + " Bad: " + bad.content + " Ugly: " + plan.content payload = { "data": { "attributes": { "discord_id": str(member.id), "description": desc, "week": 1 }, "type":"writeups" } } try: await send_request(method_type="POST", url="api/v1/writeups/", data=payload) infoLogger.info('User writeup is successfully sent to the database') except (requests.exceptions.ConnectionError, requests.exceptions.HTTPError) as e: errorLogger.error('Error while sending writeup to database', e)
async def get_leaderboard_embed(url, message, page=1): reactions = ['🔼', '🔽'] try: res = await send_request(method_type="GET", url=url+'?page='+str(page)) infoLogger.info('leaderboard is successfully retrieved') except (requests.exceptions.ConnectionError, requests.exceptions.HTTPError) as e: errorLogger.error('Error while getting the leaderboard', exc_info=e) res = None if not res: asyncio.ensure_future(data_not_found( message.channel, "Insufficient data to create leaderboard !")) return False res = res.json() #** from res global total_leaderboard_pages total_pages = res['count'] total_leaderboard_pages=total_pages embed = discord.Embed( title='Leaderboard', description='Here are the top performers. Keep going👍') embed = embed_leaderboard(embed, res['scoreboard']) leaderboard_png = 'https://thumbs.gfycat.com/EthicalPerfumedAsiaticwildass-size_restricted.gif' embed.set_thumbnail(url=leaderboard_png) embed.set_footer(text='Page : '+str(page)+'/'+str(total_pages)) return embed
async def show_user_report(resp, message, days): ch = message.channel if not resp: asyncio.ensure_future(data_not_found(ch, "No Submissions Present !")) errorLogger.error('The report request failed with an empty response') return prompt = get_prompt_report(days) prompt.add_field(name="Total questions solved", value=str(resp["total_solved_ques"]), inline=False) prompt.add_field(name="Total number of questions:", value=str(resp["total_ques"]), inline=False) resp.pop("total_ques") resp.pop("total_solved_ques") report = "" if len(resp) > 0: for topic, cnt in resp.items(): report += "\n" + '`' + topic.capitalize() + '`' + " : " + str( cnt) prompt.add_field(name="Question solved per topic: ", value=report, inline=False) asyncio.ensure_future(message.channel.send(embed=prompt))
async def assign_mentor_to_new_user(resp): user_discord_id = resp["data"]["attributes"]["discord_id"] mentor_discord_id = resp["data"]["attributes"]["mentor_discord_id"] try: user = await client.fetch_user(int(user_discord_id)) infoLogger.info('User id is successfully retrieved from the discord') except: errorLogger.error('Error while retrieving the user from the discord') return try: mentor = await client.fetch_user(int(mentor_discord_id)) infoLogger.info('Mentor id is successfully retrieved from the discord') except: errorLogger.error('Error while retrieving the mentor from the discord') return user_msg = 'Welcome to Devsnest community. This is a world of peer learning. \n You can use dn-help command to get access to various options and play with the bot and make your learning ahead fun. \n \n Here we follow a mentor-mentee system so that everyone has access to someone who can clear doubts. Your initial mentor is: {0.mention}'.format( mentor ) + '\n Feel free to schedule sessions weekly along with the mentor and get your doubts resolved weekly. Let the learning begin!👍 ' mentor_msg = 'Hope you are having a great time! \n New Member has joined the channel now. {0.mention}'.format( user ) + '\n He is your mentee for this week. \n You are required to help him with the server and give a dedicated amount of time to your mentee and help user to get doubts resolved. Continue learning 👍 ' user_prompt = get_basic_prompt(user_msg) mentor_prompt = get_basic_prompt(mentor_msg) asyncio.ensure_future(user.send(embed=user_prompt)) asyncio.ensure_future(mentor.send(embed=mentor_prompt))
async def on_member_join(member): resp = await new_member_joined(member, int(os.getenv('GREETING_CHANNEL'))) if resp: asyncio.ensure_future(assign_mentor_to_new_user(resp)) infoLogger.info('Mentor assigned the the new user') else: errorLogger.error( 'Error while assigning mentor to the particular user')
async def get_report_from_db(message, days): url = '/api/v1/users/report?discord_id=' + str( message.author.id) + '&days=' + str(days) try: resp = await send_request(method_type="GET", url=url) resp = resp.json() except (requests.exceptions.ConnectionError, requests.exceptions.HTTPError) as e: errorLogger.error('Error while getting the report from the server', e) resp = None return resp
async def post_groups_to_channel(self): try: groups_list = await send_request(method_type="GET", url="api/v1/groupcalls") infoLogger.info('Groups received from database') except (requests.exceptions.ConnectionError, requests.exceptions.HTTPError) as e: errorLogger.error('Error while getting the groups', e) groups_list = None if groups_list is None: return groups_list = groups_list.json() if groups_list == [[]]: print(self.client.get_channel(int(self.channel_id))) asyncio.ensure_future( data_not_found(self.client.get_channel(int(self.channel_id)), "No one accepted the group invite this week !")) return groups = {} for idx, data in enumerate(groups_list): # user_id, idx = data if idx not in groups: groups[idx] = [] for user in data: groups[idx].append(int(user["discord_id"])) getMentionStr = lambda x: f"<@{str(x)}>" getAssignedGroupPromptDescription = lambda \ grp: f"**Group Lead**: {getMentionStr(grp[0])}\n" + "**Members**: " + " ".join( list(map(getMentionStr, grp))) prompt = discord.Embed( title='Group Meet Assigned Groups', description= "Pls, find your respected groups for this week's Group Meeting. \n \n The group meeting is scheduled at 9 pm tonight. Group leaders are required to moderate it." ).set_thumbnail( url='https://media1.giphy.com/media/VEhMiI26CCXVK6mixx/giphy.gif') for idx, grp in enumerate(groups.values()): prompt.add_field( name= f"-------------------'Group-{str(idx + 1).zfill(2)}'-------------------\n \n", value=getAssignedGroupPromptDescription(grp), inline=False) asyncio.ensure_future( self.client.get_channel(int(self.channel_id)).send(embed=prompt))
def extract_content(sample): content = [] try: for _content in sample['data']: temp = {'name': _content['attributes']['name'], 'unique_id': _content['attributes']['unique_id']} if not _content['attributes']['link'] == "null": temp['link'] = _content['attributes']['link'] else: temp['link'] = None content.append(temp) except: # Cannot get curriculums errorLogger.error('Cannot get curriculums') content = False return content
async def mark_ques_status(user, command, status): ch = command.channel try: unique_id = command.content.split(' ')[1] infoLogger.info('Question unique id is received') except IndexError as e: errorLogger.error( 'No unique_id is received from the command', exc_info=e) asyncio.ensure_future(data_not_found( ch, "No question id is mentioned, Please enter correct one!")) return res = await update_submissions(user, unique_id, status) if not res: asyncio.ensure_future(data_not_found( ch, "Invalid question id, Please enter correct one!")) return res res = res.json() if status == 0: desc = "Congratulations‼ \n This question has been marked as done. Keep Going 😄" elif status == 1: desc = "Hey, This question has been marked as undone. Try solving it. All the best‼ 😎" elif status == 2: desc = "Seems like, you're Stuck‼ 😶 \n This question has been marked as doubt. \n Try solving, Incase you are not able to solve, feel free to contact your mentor. Let this not hinder your learning 👍 " embed = discord.Embed( title='Question status marked successfully 👍 ', description=desc, ) if not res["data"]["id"]: asyncio.ensure_future(data_not_found( ch, "Invalid question id, Please enter correct one!")) errorLogger.error('Invalid question id') else: content = extract_content(res) if not content: asyncio.ensure_future(ch.send(embed=embed)) if status == 0: asyncio.ensure_future(send_done_in_channel(user, unique_id)) return True asyncio.ensure_future(prompt_and_check(user, embed, content, False))
async def add_users_to_db(self, user_id, choice): payload = { "data": { "attributes": { "discord_id": str(user_id), "choice": choice } } } try: await send_request(method_type="POST", url="api/v1/groupcalls/", data=payload) infoLogger.info( 'User response for the groupcall has been recorded') except (requests.exceptions.ConnectionError, requests.exceptions.HTTPError) as e: errorLogger.error( 'Error while recording user response for groupcall', e)
async def update_submissions(user, unique_id, status): id = user.id url = '/api/v1/submissions' payload = { "data": { "attributes": { "discord_id": id, "question_unique_id": unique_id, "status": status }, "type": "submissions" } } try: response = await send_request(method_type="POST", url=url, data=payload) infoLogger.info('send_request: submissions updated successfully') except (requests.exceptions.ConnectionError, requests.exceptions.HTTPError) as e: errorLogger.error('Error while submitting the response', exc_info=e) response = None return response
async def send_request(method_type, url, data=None): url = os.getenv('BASE_URL') + url headers = { 'Content-Type': 'application/vnd.api+json', 'Authorization': 'Bearer ' + os.getenv('TOKEN') } try: response = requests.request(method_type, url, headers=headers, json=data) except ConnectionError as e: # Backend down or bad url errorLogger.error('Error in connecting to backend server : ' + str(e)) raise ConnectionError try: response.raise_for_status() except requests.exceptions.HTTPError as e: # Whoops it wasn't a 200 errorLogger.error('Error in getting response : ' + str(e)) raise requests.exceptions.HTTPError return response
async def send_done_in_channel(user, unique_id): ch = client.get_channel(int(os.getenv('STATUS_CHANNEL'))) url = '/api/v1/contents?filter[unique_id]=' + unique_id res = await send_request(method_type="GET", url=url) res = res.json() # Error in sending data to channel # if len(res["data"])==0: try: question_name = res['data'][0]['attributes']['name'] question_link = res['data'][0]['attributes']['link'] infoLogger.info('update-submissions: data successfully parsed') except: errorLogger.error('Error while parsing data') return False embed = discord.Embed( title='Status Update', description='{0} has solved Question `{1}`'.format( user.mention, question_name) ) embed.add_field(name="You can too give it a shot now!", value="Try it [here]({0})".format( question_link), inline=False) # embed.add_field(name="Unique ID", value=( # "Question Unique ID : "+'`'+unique_id+'`'), inline=False) confetti_png = str( 'https://media1.tenor.com/images/ed2bcee37ffb2944ecafec3e852d6014/tenor.gif?itemid=10369910') embed.set_thumbnail(url=confetti_png) asyncio.ensure_future(ch.send(embed=embed)) infoLogger.info('Question Status: Embed sent to the channel')
async def fetch(message): ch = message.channel command = message.content.split(' ') if len(command) > 1: return await fetch_content(command[1], ch) embed = discord.Embed( title='Topics 💻', description='Welcome to the world of learning! Here is the list of questions for you to practice. Choose the resource by typing out the name. \n \n For example: If you wish to solve a question of array, type dn-fetch Arrays \n \n', ) payload = {} try: response = await send_request(method_type="GET", url='/api/v1/contents?filter[parent_id]=algo', data=payload) infoLogger.info('topics fetched') except (requests.exceptions.ConnectionError, requests.exceptions.HTTPError) as e: errorLogger.error('Error while getting the fetch response', exc_info=e) response = None if not response: asyncio.ensure_future(data_not_found(ch, "No topics present !")) errorLogger.error('The request failed with an empty response') return False resp = response.json() if len(resp["data"]) == 0: asyncio.ensure_future(data_not_found(ch, "No topics present !")) errorLogger.error('Fetch request failed with an empty data') return False curriculums = extract_content(resp) if not curriculums: asyncio.ensure_future(data_not_found(ch, "No topics present !")) errorLogger.error('No topics found while parsing curriculum') return False embed = embed_content(embed, curriculums) asyncio.ensure_future(ch.send(embed=embed)) infoLogger.info('Fetch Data: Embed sent to the channel') return True
async def fetch_content(unique_id, ch): url = '/api/v1/contents?filter[parent_id]=' + unique_id embed = discord.Embed( title=unique_id + ' Questions 💻', description='Let us solve some questions now. Here is a list of questions for you to solve. Reach out to these questions using below link. \n \n Once you start solving the question you can mark the status as done, undone or doubt using command dn-mark-[status] [Question no.]. \n \n For example if you want to mark Q1 as done enter command dn-mark-done Q1. \n Happy Learning 😀', ) payload = {} try: response = await send_request(method_type="GET", url=url, data=payload) infoLogger.info('Fetch request is successful') except (requests.exceptions.ConnectionError, requests.exceptions.HTTPError) as e: errorLogger.error('Error while getting response', exc_info=e) response = None if not response: asyncio.ensure_future(data_not_found(ch, "Invalid topic name!")) errorLogger.error('Content not found') return False resp = response.json() if len(resp["data"]) == 0: asyncio.ensure_future(data_not_found(ch, "Invalid topic name!")) errorLogger.error('The topic does not exist in the database') return False else: content = extract_content(resp) if not content: errorLogger.error('invalid content') return False embed = embed_content(embed, content) asyncio.ensure_future(ch.send(embed=embed)) return True