Example #1
0
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()
Example #2
0
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
Example #3
0
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))
Example #4
0
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)
Example #5
0
File: utils.py Project: zuston/fedb
def gen_table_meta_file(meta, filepath):
    s = ''
    for key, value in meta.items():
        if isinstance(value, str):
            s += key + ": \"" + value + "\"\n"
        elif isinstance(value, int):
            s += key + ": " + str(value) + "\n"
        elif isinstance(value, list):
            for item in value:
                if isinstance(item, dict):
                    s += key + " {\n"
                    for k, v in item.items():
                        if isinstance(v, str):
                            if v == "true" or v == "false":
                                s += "  " + k + ": " + v + "\n"
                            else:
                                s += "  " + k + ": \"" + v + "\"\n"
                        elif isinstance(v, int):
                            s += "  " + k + ": " + str(v) + "\n"
                        elif isinstance(v, list):
                            for value in v:
                                s += "  " + k + ": \"" + str(value) + "\"\n"
                    s += "}\n"
                else:
                    s += key + ": \"" + item + "\"\n"

    write(s, filepath, 'w')
    infoLogger.info(read(filepath))
Example #6
0
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')
Example #7
0
File: utils.py Project: zuston/fedb
def gen_table_metadata_file(metadata, filepath):
    s = ''
    for basic in metadata[0]:
        s += '{}:{}\n'.format(basic[0], basic[1])
    for tp in metadata[1:]:
        s += tp[0] + ' {\n'
        for i in tp[1]:
            s += '{}:{}\n'.format(i[0], i[1])
        s += '}\n'
    write(s, filepath, 'w')
    infoLogger.info(read(filepath))
Example #8
0
async def listExistingMembers():
    res = await getAllMembers()
    d = {}
    for i in res['data']:
        d[int(i['attributes']['discord_id'])] = 1
    for member in client.get_all_members():
        if not member.bot:
            if member.id not in d:
                infoLogger.info('database call to create ' + str(member.name) +
                                ' with id ' + str(member.id) + ' is sent.')
                await submit_user_details(member)
Example #9
0
    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))
Example #10
0
File: utils.py Project: zuston/fedb
def gen_table_metadata_ssd(name, ttl_type, ttl, seg_cnt, *table_partitions):
    metadata = []
    basic_info_schema = ('name', 'ttl_type', 'ttl', 'seg_cnt')
    basic_info = zip(basic_info_schema, (name, ttl_type, ttl, seg_cnt))
    metadata.append([(i[0], i[1]) for i in basic_info if i[1] is not None])
    if table_partitions[0] is not None:
        for tp in table_partitions:
            ele_schema = conf.table_meta_ele[tp[0]]
            if tp is not None:
                ele_info = zip(ele_schema, tp[1:])
                infoLogger.info(ele_info)
                metadata.append((tp[0], [(i[0], i[1]) for i in ele_info if i[1] is not None]))
            else:
                metadata.append({})
    return metadata
Example #11
0
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
Example #12
0
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))
Example #13
0
    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)
Example #14
0
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
Example #15
0
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
Example #16
0
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')