예제 #1
0
    async def handle(self):
        qa: QueueAuthority = QueueAuthority(self.guild)
        request = "[Student did not supply text]"
        if " " in self.message.content:
            # remove the !request from the front of the message
            request = " ".join(self.message.content.split()[1:])

        ca: ChannelAuthority = ChannelAuthority(self.guild)

        # Build embedded message
        color = discord.Colour(0).blue()
        embeddedMsg = discord.Embed(description=request,
                                    timestamp=dt.now(),
                                    colour=color)

        author: Member = self.message.author
        embeddedMsg.set_author(name=command.name(author))
        embeddedMsg.add_field(name="Accept request by typing",
                              value="!accept")
        embeddedMsg.add_field(name="Reject request by typing",
                              value="!reject {} [text to be sent to student]".format(author.id))
        # Send embedded message
        announcement = await ca.queue_channel.send(embed=embeddedMsg)
        qa.add_to_queue(author, request, announcement)
        await self.message.delete()
        logger.info("{} added to queue with request text: {}".format(
            command.name(author),
            request
        ))
예제 #2
0
    async def handle(self):
        qa: QueueAuthority = QueueAuthority(self.guild)
        ca: ChannelAuthority = ChannelAuthority(self.guild)
        # Remove TA from list of available TAs.

        if "force" in self.message.content:
            qa.force_close_office_hours()
            await ca.queue_channel.send(
                command.name(self.message.author) + " has forced OH to close.")
            await ca.waiting_channel.send(
                "Ok, y'all.  Office hours have ended for now.  An announcement will appear here when they have reopened."
            )
            return

        is_open, was_removed, ta_count = qa.close_office_hours(
            self.message.author.id)
        if ta_count > 0 and is_open and was_removed:
            await ca.queue_channel.send(
                command.name(self.message.author) +
                " has checked out of office hours.")
        # Last TA was removed, or TA queue was empty when called
        elif ta_count <= 0 and is_open:
            await qa.remove_all()
            await ca.queue_channel.send(
                command.name(self.message.author) +
                " has closed office hours!")
            await ca.waiting_channel.send(
                "Ok, y'all.  Office hours have ended for now.  An announcement will appear here when they have reopened."
            )
            logger.info("Office hours closed by {}".format(
                command.name(self.message.author)))
예제 #3
0
 async def handle(self):
     qa: QueueAuthority = QueueAuthority(self.guild)
     ca: ChannelAuthority = ChannelAuthority(self.guild)
     # Add TA to list of available TAs. Return True if fresh opening, True if newly added TA
     fresh_open, is_new_ta = qa.open_office_hours(self.message.author.id)
     if fresh_open:
         await ca.queue_channel.send("Office hours are live!")
         await ca.waiting_channel.send(
             "Office hours are live.  Get in line with !request")
         logger.info("Office hours opened by {}".format(
             command.name(self.message.author)))
     if is_new_ta:
         await ca.queue_channel.send(
             command.name(self.message.author) +
             " has checked into office hours!")
예제 #4
0
파일: client.py 프로젝트: bagamernew/labs
    def __init__(self, ip='localhost', port='5555'):
        self.client_commands = {}
        for cmd in (command.UndoCommand,
                    command.RedoCommand,
                    command.HistoryCommand,
                    command.FutureCommand,
                    command.CommandsCommand,
                    command.ClsCommand,
                    command.ExitCommand):
            self.client_commands[command.name(cmd)] = cmd

        # Outgoing channel
        self.requests = context.socket(zmq.REQ)
        self.requests_ip = ip
        self.requests_port = port

        # Incoming channel
        self.results = context.socket(zmq.REP)
        self.results_port = None

        # Commands run upon launch
        self.init_commands = []

        self.connect()
        self.listen()
        self.init_shell()
예제 #5
0
    async def handle(self):
        qa: QueueAuthority = QueueAuthority(self.guild)
        if not qa.is_ta_on_duty(self.message.author.id):
            await self.message.channel.send("You must be on duty to accept a request!")
            return
        # get oldest queue item (and also remove it)
        session: OHSession = await qa.dequeue(self.message.author)
        if not session:
            msg = await self.message.channel.send("No one is in the queue.  Perhaps you're lonely?\n"
                                                  "https://giphy.com/gifs/30-rock-liz-lemon-jack-donaghy-VuWtVHkMjrz2w")
            await msg.delete(delay=7)
            await self.message.delete()
            return
        # create role for channel
        role: Role = await self.guild.create_role(name="{}'s OH session".format(command.name(session.member)), hoist=True)
        num_roles = len(self.guild.roles)
        # todo find bot role insert this underneath
        # await role.edit(position=num_roles-2)
        session.role = role
        await session.member.add_roles(session.role)
        await self.message.author.add_roles(session.role)

        # create channel
        ra: RoleAuthority = RoleAuthority(self.guild)
        session_category: CategoryChannel = await self.guild.create_category_channel(
            "Session for {}".format(command.name(session.member)),
            overwrites={
                role: PermissionOverwrite(read_messages=True, attach_files=True, embed_links=True),
                ra.student: PermissionOverwrite(read_messages=False),
                ra.un_authenticated: PermissionOverwrite(read_messages=False)
            })
        text_channel: TextChannel = await session_category.create_text_channel("Text Cat")
        await session_category.create_voice_channel("Voice chat")
        session.room = session_category
        # attach user ids and channel ids to OH room info in channel authority
        ca: ChannelAuthority = ChannelAuthority(self.guild)
        await session.announcement.delete()
        await self.message.delete()
        ca.add_oh_session(session)
        await text_channel.send("Hi, {} and {}!  Let the learning commence!  Type !close to end the session!".format(
            session.member.mention,
            session.ta.mention,
        ))
        logger.info("OH session for {} accepted by {}".format(
            command.name(session.member),
            command.name(self.message.author)))
예제 #6
0
    async def handle(self):
        await self.message.channel.send("Closing")
        ca: ChannelAuthority = ChannelAuthority(self.guild)
        category_channel: CategoryChannel = None

        # find the correct session
        this_session = None
        for session in await ca.get_oh_sessions():
            if self.message.channel in session.room.channels:
                this_session = session
                category_channel = session.room

        # delete the role
        await this_session.role.delete()

        # delete the channels
        for room in category_channel.channels:
            await room.delete()
        await category_channel.delete()

        # remove the session from mongo
        ca.remove_oh_session(category_channel.id)
        logger.info("OH session in room {} closed by {}".format(
            category_channel.id, command.name(self.message.author)))
예제 #7
0
파일: server.py 프로젝트: bagamernew/labs
def do(cmd_obj, args, func, blocking, client_id):
    """Asynchronously run `cmd`

    Args:
        cmd_obj (object): Command object to do
        args (list): Arguments passed to command
        func (str): to `do` or `undo`
        client_id (str): Unique identifier for client, for undo/redo

    """

    cmd_name = command.name(cmd_obj.__class__)
    log.info("    executing %r.." % cmd_name)

    # Assume failure of command, until proven otherwise.
    output = {
        command.STATUS: command.FAIL,
        command.INFO: None
    }

    # Interpret command
    #  ___________
    # |           |
    # |    ???    |
    # |___________|

    try:
        if func == 'undo':
            # Signal that this command has now been undone.
            # The client will receive this message and remove
            # it from its local history.
            undo_id = args.pop()
            output[command.UNDO] = undo_id

        if func == 'redo':
            # Signal that this command has now been redone.
            # The client will receive this message and remove
            # it from its local trash.
            redo_id = args.pop()
            output[command.REDO] = redo_id

        # Execute command
        #  ___________
        # |           |
        # |    ...    |
        # |___________|

        retval = getattr(cmd_obj, func)(*args)
        command_id = str(uuid.uuid4())

        output[command.STATUS] = command.OK
        output[command.INFO] = retval
        output[command.COMMAND] = cmd_name
        output[command.BLOCKING] = blocking

        # Only track commands that support undo.
        if hasattr(cmd_obj, 'undo'):
            output[command.ID] = command_id

        # Store and associate client with command, for undo/redo
        if not client_id in executed_commands:
            executed_commands[client_id] = {}

        command_msg = {
            'obj': cmd_obj,
            'time': time.time()
        }

        executed_commands[client_id][command_id] = command_msg

    except (command.Exists,
            command.InvalidSignature,
            command.Full,
            command.Length) as e:
        output[command.INFO] = str(e)

    except Exception as e:
        # In the event of an unexpected exception,
        # notify the user and include traceback server-side.
        output[command.INFO] = str(e)
        print "\n%s" % traceback.format_exc()

    # Transmit results
    #  ___________        ___________
    # |           | ---> |           |
    # |           |      |           |
    # |___________|      |___________|

    try:
        results_channel = clients[client_id][RESULTS]
    except KeyError:
        # The client sending requests isn't connected to this
        # instance of the server. What probably happened was
        # that the client connected, then the server restarted
        # and thus lost track of clients.
        log.error("ERR The client sending requests is "
                  "not registered and must be reconnected.")
        return

    log.info("--> command executed: sending..")

    # Message-type: Result
    results_channel.send_json(output)

    # Await confirmation
    #  ___________        ___________
    # |           | <--- |           |
    # |           |      |           |
    # |___________|      |___________|

    log.info("<-- command executed: receiving confirmation..")
    msg = results_channel.recv()
    log.info("    command executed: confirmation ok")
    log.info("    ready")

    unpacked_msg = json.loads(msg)
    if not unpacked_msg[command.STATUS] == command.OK:
        print unpacked_msg[command.INFO]
예제 #8
0
 async def handle(self):
     ca: ChannelAuthority = ChannelAuthority(self.guild)
     await ca.start_lab(self.message)
     logger.info("Lab started by {}".format(
         command.name(self.message.author)))