Example #1
0
    def do_give(self, session, line):
        if not line: session.push(tpl.SYNTAX_GIVE)
        else:
            self.argu = line.lower()
            #if not self.argu.strip(): session.push("> ")
            self.parts = line.split(' ', 3)

            if self.parts[1] == "to":
                try:
                    self.itom = Select.getItemInstance(session.p_id, self.parts[0].lower()) # Given item info

                    # Check if given to a player.
                    self.transf = Select.getPlayerInRoom(session.is_in, self.parts[2].lower())

                    # Check if given to a mob.
                    self.mob = Select.getNpcInRoom(session.is_in, self.parts[2].lower())

                    if self.transf:
                        Update.setItemOwner(self.transf[0], self.itom[0])
                        session.push(tpl.GIVE % (self.parts[0],self.parts[2]))
                        # the following line is commented out -- not sure if I'll tell the whole room + it doesn't work
                        #self.RoomBroadcast(session, session.is_in, " gives %s to %s" % (self.parts[0],self.parts[2]))
                        
                    elif self.mob:
                        Update.setItemNpcOwner(self.mob[0], self.itom[0])
                        session.push(tpl.GIVE % (self.parts[0],self.parts[2]))
                        #Effects.RoomBroadcast(session, session.is_in, " gives %s to %s" % (self.parts[0], self.parts[2]))
                    else: session.push(tpl.PLAYER_NOT_FOUND)

                except: session.push(tpl.SYNTAX_GIVE)

            else: session.push(tpl.SYNTAX_GIVE)
Example #2
0
    def unify_update(self, event: Event, payload: str = None) -> Update:
        """
        Create the internal `Update` type from facebook's `Event`
        """
        ud = Update()
        ud.original_update = event
        ud.client_name = self.client_name
        ud.message_id = event.message_mid
        ud.datetime = datetime.datetime.fromtimestamp(event.timestamp / 1000.0)

        ud.payload = payload

        ud.user, created = User.get_or_create(facebook_id=event.sender_id)
        if created:
            ud.user.save()

        if event.message_attachments:
            try:
                voice = next(x for x in event.message_attachments if x.get('type') == 'audio')
                ud.voice_id = voice['payload']['url']
            except StopIteration:
                pass

        if hasattr(event, 'message_text'):
            ud.message_text = event.message_text
        return ud
Example #3
0
    def add(self, session):
        self.ival = ipsessions.items()

        if session.addr[0] != "127.0.0.1" and session.addr[0] in self.ival: # Allow multiusers for the admin.
            session.push(tpl.LOGIN_ALREADY_IN)
            raise EndSession

        sessions[session.p_id] = session
        ipsessions[session.p_id] = session.addr[0]
        Update.setIP(session.addr[0], session.p_id)
        
        #Store the player's starting location in the socket object.
        session.is_in = 1
        Update.setLocation(session.p_id, 1)

        # Check if the user supports ANSI colors
        if Select.getColors(session.p_id) == "on": Actions.do_setansi(session, "on")
        else: Actions.do_setansi(session, "off")

        for i in sessions:
            try:
                i.push(tpl.ENTER_GAME % (session.pname,))
            except: pass

        print "%s logged in." % session.pname
        Log("%s logged in from %s" % (session.pname,session.addr[0]))
        Actions.do_look(session, '') # To be replaced with something nicer.
        session.push("> ")
Example #4
0
 def do_goto(self, session, line):
     try:
         self.room = Select.getRoom(line)
         Update.setLocation(self.room[0], session.p_id)
         session.is_in = self.room[0]
         session.push(tpl.GOTO)
     except: session.push(tpl.GOTO_ERR)
Example #5
0
    def _process_update(self, bot: BotAPIClient, update: Update) -> None:
        print()  # newline on incoming request makes the logs more readable

        context = self.context_manager.add_incoming_update(update)

        try:
            try:
                next_response = self.planning_agent.build_next_actions(context)
            except ForceReevaluation:
                # Some handlers require to reevaluate the template parameters (only once)
                next_response = self.planning_agent.build_next_actions(context)
            if next_response is None:
                return
            actions = next_response.collect_actions()
        finally:
            context.dialog_states.update_step()

        if self.recorder:
            self.recorder.record_dialog(update, actions, context.dialog_states)

        if settings.NO_DELAYS:
            # No message delays while debugging
            for a in actions:
                a.delay = None

        try:
            bot.perform_actions(actions)
        except Exception as e:
            log.error("Error while performing chat action:")
            log.exception(e)

        context.add_actions(actions)
        update.save()
Example #6
0
    def do_get(self, session, line):
        self.objonfloor = Select.getItem(session.is_in, line.lower())

        try:
            Update.setItemOwner(session.p_id, self.objonfloor[0])
            session.push(tpl.GET % line)
        except:
            session.push(tpl.NOT_HERE)
Example #7
0
 def do_setansi(self, session, arg):
     if arg == "on":
         session.BLACK, session.RED, session.GREEN = '\033[30m', '\033[31m', '\033[32m'
         session.YELLOW, session.BLUE, session.MAGENTA = '\033[33m', '\033[34m', '\033[35m'
         session.CYAN, session.WHITE = '\033[36m', '\033[37m'
         session.RESET, session.BOLD = '\033[0;0m', '\033[1m'
         Update.setColors(session.p_id, arg)
     elif arg == "off": # Empty strings.
         session.BLACK, session.RED, session.GREEN, session.YELLOW, session.BLUE = '','','','',''
         session.MAGENTA, session.CYAN, session.WHITE, session.RESET, session.BOLD = '','','','',''
         Update.setColors(session.p_id, arg)
     else: session.push("Syntax:\r\nsetansi [off|on]\r\n")
Example #8
0
    def get_updates(self):
        """
        Gets all updates relative to the authenticated user
        """
        if (not self._access_token) or (not self._access_token_secret):
            self.error = "You do not have an access token. Plase perform 'accessToken()' method first."
            raise OAuthError(self.error)

        raw_url = "/v1/people/"
        raw_url = raw_url + "~/network/updates"

        response = self._do_normal_query(raw_url)
        error = self._parse_error(response)
        if error:
            self.error = error
            return None

        from StringIO import StringIO
        content = StringIO(response)
        document = parse(content)
        updates = document.getroot()
        result = []
        for update in updates:
            update_type = update.find("update-type").text
            up = Update.create(update,update_type)
            if up is not None:
                result.append(up)

        return result
Example #9
0
    def do_go(self, session, line):
        if not line: session.push(tpl.DONT_GO)
        else:
            try:
                self.isexit = Select.getExit(session.is_in, line.lower())
            except:
                session.push(tpl.NO_EXIT)

            try:
                # Actually move
                Update.setLocation(session.p_id , self.isexit[1])
                #Effects.RoomBroadcast(session, session.is_in, " leaves %s." % str(self.isexit[2]))
                session.is_in = self.isexit[1]
                #Effects.RoomBroadcast(session, session.is_in, " enters the room.")
                self.do_look(session, '') # Force a look, to be replaced by something nicer.

            except:
                session.push(tpl.CANT_MOVE)
Example #10
0
    def do_drop(self, session, line):
        try:
            self.drop = Select.getItemInstance(session.p_id, line.lower())

            self.drop = Update.dropItem(session.is_in, self.drop[0])
            #self.msg = session.pname + " dropped " + line + "."
            #self.RoomBroadcast(session, session.is_in, self.msg)
            session.push(tpl.DROP % (session.pname, line))
        except: session.push(tpl.DROP_CANT)
Example #11
0
    def do_itemdesc(self, session, line):
        try:
            self.splitarg = line.split(' ', 1)
            self.rcount = Update.setItemDescription(self.splitarg[0].lower(), self.splitarg[1])
            if self.rcount == 1:
                session.push(tpl.ITEMDESC % str(self.splitarg[0]).lower())
            else: 
                session.push(tpl.ITEMDESC_ERR)

        except: session.push(tpl.ITEMDESC_ERR)
Example #12
0
def add_updates():
    """Adds fake updates to the system"""

    current_users = db.session.query(User.user_id).all()
    for i in range(5000):
        update = Update(user_id=random.choice(current_users),
                        update_body=faker.text(max_nb_chars=140),
                        posted_at=datetime.now())
        db.session.add(update)
        db.session.commit()
Example #13
0
def submit_update(user_id, body):
    """Creates an update object with the text body and user_id passed in"""

    update = Update(user_id=user_id,
                    update_body=body,
                    posted_at=datetime.now())

    db.session.add(update)
    db.session.commit()

    return update.update_id
Example #14
0
    def handle(self, session, line):
        #Time of last command executed. Will be used for external timeout cleanup.
        Update.setLastAction(time.time(), session.p_id)

        if not line.strip(): session.push("> ")

        # Filter the telnet commands
        self.tiac = TelnetTalk()
        self.ndata = self.tiac.listen(line)
        line = self.ndata[0]

        session.push(self.ndata[1]) # Reply accordingly

        parts = line.split(' ', 1)
        cmd = parts[0]
        if not cmd: pass

        # Easier to do it here, as EndSession is defined outside of action.py
        elif (cmd == "logout") or (cmd == "quit"):
            raise EndSession

        else:
            try: line = parts[1].strip()
            except IndexError: line = ''
            meth = getattr(Actions, 'do_'+cmd, None) # Normal commands, actions.py

            if cmd.find('@') == 0 :
                methadm = getattr(Admincmd, 'do_'+cmd.strip('@'), None) # Admin commands, admin.py
                if session.pname in self.coders and callable(methadm):
                    methadm(session, line)
                    session.push("> ")
                else:
                    self.unknown(session, cmd)
                    session.push("> ")

            elif callable(meth): # Normal command
                meth(session, line)
                session.push("> ")
            else:
                self.unknown(session, cmd)
                session.push("> ")
Example #15
0
    def voice_received(self, bot: BotAPIClient, update: Update):
        bot.show_typing(update.user)

        path = os.path.join(ROOT_DIR, 'tmp')
        filepath = bot.download_voice(update.voice_id, path)

        converted = self.voice.convert_audio_ffmpeg(
            filepath, os.path.join(path, 'voice.flac'))

        text = self.voice.recognize(converted)
        if text is None:
            # TODO: Inform the user about failed SR
            log.warning("Could not recognize user input.")
            return

        update.message_text = text
        log.debug(f"Voice message received: {text}")

        self.text_update_received(bot, update)
    def say(self, text):
        update = Update()
        update.message_text = text
        update.message_id = self.msg_count
        update.datetime = datetime.datetime.now()
        update.user = self.user

        with warnings.catch_warnings():
            warnings.simplefilter("ignore")
            self.nlp.insert_understanding(update)
        context = self.context_manager.add_incoming_update(update)

        next_response = self.planning_agent.build_next_actions(context)

        actions = next_response.collect_actions()

        context.add_actions(actions)

        self.msg_count += 1
        return actions
Example #17
0
import sqlite3
from flask import Flask, render_template
from threading import Thread
from model import Update

html_name = 'index.html'
database_name = 'database.db'
app = Flask(__name__)


@app.route('/')
def index():
    conn = sqlite3.connect(database_name)
    conn.row_factory = sqlite3.Row
    points = conn.execute('SELECT * FROM points').fetchall()
    conn.close()
    return render_template(html_name, points=points)


if __name__ == "__main__":
    thread1 = Thread(target=app.run)
    thread2 = Thread(target=Update().update_24)

    thread1.start()
    thread2.start()
    thread1.join()
    thread2.join()
Example #18
0
 def do_setshort(self, session, line):
     try:
         Update.setShortDesc(session.is_in, line)
         session.push(tpl.SETSHORT)
     except: session.push(tpl.SETSHORT_ERR)
Example #19
0
 def do_unban(self, session, line):
     try:
         Update.unbanPlayer(line.lower())
         session.push(tpl.UNBAN % line)
     except:
         session.push(tpl.UNBAN_ERR)
Example #20
0
class MainServSock(dispatcher):
    # The Server

    def __init__(self, port):
        dispatcher.__init__(self)
        self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
        self.set_reuse_addr()
        self.bind(('', port))
        self.listen(int(config.get("server", "max_users")))
        self.enterg = EnterGame(self)
    def handle_accept(self):
        conn, addr = self.accept()
        SecondServSock(self, conn, addr)

if __name__ == '__main__':
    s = MainServSock(int(config.get("server", "port")))
    Update.resetAllIPs()

    try:
        import actions
        Actions = actions.Actions(sessions)
        Admincmd = AdminCmds(sessions, ipsessions)
        print "Accepting connections..."
        while 1:
            asyncore.loop(timeout=5, count=1) # Timer() called every 5 seconds.
            #Timer(time.time())
    except KeyboardInterrupt: #print
        print

Example #21
0
 def do_setlong(self, session, line):
     try:
         Update.setLongDesc(session.is_in, line)
         session.push(tpl.SETLONG)
     except: session.push(tpl.SETLONG_ERR)
Example #22
0
 def do_description(self, session, line):
     Update.setDescription(session.p_id, line)
     session.push(tpl.DESC_SET)
Example #23
0
 def start_callback(self, bot: BotAPIClient, update: Update):
     update.understanding = MessageUnderstanding(text=update.message_text,
                                                 intent='start')
     self._process_update(bot, update)
Example #24
0
 def media_received(self, bot: BotAPIClient, update: Update):
     update.understanding = MessageUnderstanding(
         None, MEDIA_RECEIVED_INTENT, media_location=update.media_location)
     self._process_update(bot, update)