Ejemplo n.º 1
0
    def on_message(self, context, telegram: Telegram):

        sender = context.world.get_agent(telegram.sender_id)

        # Retrieve a meeting invitation, and accept it based on social needs
        if telegram.message == MessageTypes.MSG_MEETING:
            if randint(0, context.social.max) <= context.social.current:
                eta = GotoState.estimate(context, context.location, context.world.get_location(telegram.data))

                if context.location == sender.location:
                    context.say_to(sender, choice(self.meeting_same_location).format(telegram.data.place.capitalize()))
                else:
                    context.say_to(sender, choice(self.meeting_other_location).format(context.state.state_verb, int(60 * eta)))

                reply_msg = Telegram(context.agent_id, telegram.sender_id, MessageTypes.MSG_MEETING_REPLY, True)
                context.world.dispatch(reply_msg)
                telegram.data.join_state(context)
            else:
                context.say(choice(self.meeting_refuse))
                reply_msg = Telegram(context.agent_id, telegram.sender_id, MessageTypes.MSG_MEETING_REPLY, False)
                context.world.dispatch(reply_msg)

        # Chance to greet agents arriving to the same location
        if telegram.message == MessageTypes.MSG_ARRIVAL and telegram.data == context.location and randint(0, 4) == 1:
            context.say_to(sender, choice(self.greetings).format(sender.name))
Ejemplo n.º 2
0
    def check_requirements(self, context):
        """Check resources on context tile, and request more if needed -
        otherwise begin construction"""

        if self.building is not None and not self.has_begun:
            res = context.world.get_resource(context.location, self.resource)

            if res < self.count:
                print("Need {} {}s to build a {}!".format(
                    self.count, self.resource.name, self.building.name))
                data = (self.resource, context.location, self.count)
                mgr = context.world.get_agents_in_state(Manager, 1)

                if mgr is not None:
                    resource_msg = Telegram(context.agent_id, mgr.agent_id,
                                            MessageTypes.MSG_RESOURCE_NEEDED,
                                            data)
                    context.world.dispatch(resource_msg)
            else:
                print("Beginning construction!")
                context.world.add_resource(context.location, self.resource,
                                           -self.count)
                check_msg = Telegram(context.agent_id, context.agent_id,
                                     MessageTypes.MSG_BUILDING_FINISH)
                context.world.dispatch(check_msg, self.time)
                self.has_begun = True
Ejemplo n.º 3
0
 def enter(self, entity):
     work_msg_self = Telegram(entity.ID, entity.ID, MessageTypes.WORK_SELF)
     entity.manager.dispatch_message(work_msg_self,
                                     8)  #tick_size as msg delay
     if entity.location is not Locations.WORKPLACE:
         print('[', str(entity.ID), ']: Walking to work')
         entity.location = Locations.WORKPLACE
Ejemplo n.º 4
0
    def execute(self, context, step):

        if self.state == Actions.Idle:

            count = context.world.get_resource(context.location,
                                               ResourceTypes.Log)

            if count >= COAL_PRODUCE_LOGS:
                context.world.add_resource(context.location, ResourceTypes.Log,
                                           -COAL_PRODUCE_LOGS)
                self.timer = TIME_PRODUCE_COAL
                self.state = Actions.Working
            else:
                self.state = Actions.Waiting
                resource_data = (ResourceTypes.Log, self.location, 10)
                mgr = context.world.get_agents_in_state(Manager, 1)
                if mgr is not None:
                    print(
                        "Need {} Logs to make coal!".format(COAL_PRODUCE_LOGS -
                                                            count))
                    res_msg = Telegram(context.agent_id,
                                       mgr.agent_id,
                                       MessageTypes.MSG_RESOURCE_NEEDED,
                                       data=resource_data)
                    context.world.dispatch(res_msg)

        elif self.state == Actions.Working:
            self.timer -= step
            if self.timer <= 0:
                context.world.add_resource(context.location,
                                           ResourceTypes.Coal)
                self.state = Actions.Waiting
Ejemplo n.º 5
0
    def execute(self, context, step):

        self.fail_timer -= step

        if self.state == PathStates.Idle and self.fail_timer <= 0:
            self.state = PathStates.Waiting
            self.get_random_path(context)

        elif self.state == PathStates.Working:
            super().execute(context, step)

            world = context.world
            mgr = world.get_agents_in_state(Manager, 1)

            if mgr is None:
                return

            for cell in world.reveal(context.location):
                if world.graph.get_terrain(cell) is TerrainTypes.Tree:
                    res_data = (TerrainTypes.Tree, cell)
                    res_msg = Telegram(context.agent_id,
                                       mgr.agent_id,
                                       MessageTypes.MSG_RESOURCE_FOUND,
                                       data=res_data)
                    world.dispatch(res_msg)
Ejemplo n.º 6
0
    def enter(self, context):
        if self.count == 1:
            meet_msg = Telegram(context.agent_id, None, MessageTypes.MSG_MEETING, self)
            self._invitations = context.world.dispatch(meet_msg)

        if self._place is not None and not context.is_at(self._place):
            context.goto(self._place)
Ejemplo n.º 7
0
def main():
    parser = ArgumentParser()
    parser.add_argument("-c",
                        "--config",
                        help="yaml config file name",
                        default="config.yaml")
    args = parser.parse_args()

    config = Config()
    try:
        config.load(args.config)
    except:
        logging.error('Unable to open "{}" file.'.format(options.config))
        return

    level = TRACE
    logging.addLevelName(TRACE, "TRACE")
    logger = logging.getLogger()
    logger.setLevel(level)
    formatter = logging.Formatter(
        "%(asctime)s [%(name)s] %(levelname)s: %(message)s")
    handler = logging.handlers.RotatingFileHandler(config["log"],
                                                   maxBytes=16000000,
                                                   backupCount=2)
    handler.setLevel(level)
    handler.setFormatter(formatter)
    logger.addHandler(handler)
    handler = logging.StreamHandler()
    handler.setFormatter(formatter)
    handler.setLevel(level)
    logger.addHandler(handler)

    telegram = Telegram(config['telegram'])
    telegram.Run()
Ejemplo n.º 8
0
    def execute(self, context, step):

        # print("MEETING: {} in party, host agent_id {}, {} invitations, {} replies\n[{}]".format(
        #     self.count, self.host_id, self._invitations, self._replies, ", ".join(list(agent.name for agent in self._party))
        # ))

        # If agent is alone in group after receiving all replies from all, leave the group
        if self._replies >= self._invitations and self.count == 1:
            context.say(choice(self._disband_group))
            self.leave_state(context, SleepState())
            return

        # If agent is socially satisfied, leave the group and broadcast your departure
        if context.social.is_min and self.host_id is not context.agent_id:
            context.say(choice(self._leave_group))
            leave_msg = Telegram(context.agent_id, self.host_id, MessageTypes.MSG_MEETING_LEAVING)
            context.world.dispatch(leave_msg)
            self.leave_state(context, SleepState())
            return

        # If more than one person is in the group, perform a conversation
        if self.count > 1:
            partner = self._party[randint(0, self.count - 1)]
            if partner is not context and partner.is_near(context):
                phrase = self._phrases[randint(0, len(self._phrases) - 1)]
                context.say_to(partner, phrase[0])
                partner.say_to(context, choice(phrase[1]))
                context.social.sub(2)
                partner.social.sub(2)
            return
Ejemplo n.º 9
0
    def on_message(self, context, telegram):

        if telegram.message == MessageTypes.MSG_BUILDING_NEEDED:
            self.request_construction(context, telegram.data)

        elif telegram.message == MessageTypes.MSG_RESOURCE_NEEDED:
            self.request_collection(context, 3, telegram.data)

        elif telegram.message == MessageTypes.MSG_BUILDING_DONE:
            building, location = telegram.data

            if building == BuildingTypes.Kiln:
                worker = context.world.get_agents_in_state(Worker, 1)

                if worker is not None:
                    training_data = (BuildingTypes.Kiln, TIME_TRAIN_KILNER,
                                     Kilner(location))
                    worker.change_state(Training(*training_data))

                if len(context.world.get_locations(
                        BuildingTypes.Kiln)) < TARGET_KILN:
                    next_kiln = Telegram(context.agent_id, telegram.sender_id,
                                         MessageTypes.MSG_BUILDING_NEEDED,
                                         BuildingTypes.Kiln)
                    context.world.dispatch(next_kiln,
                                           randint(0, BUILD_KILN_DELAY))
Ejemplo n.º 10
0
    def enter(self, context):

        # make camp where manager stands
        context.world.add_location(context.location, BuildingTypes.Camp)

        # get free workers
        worker_pool = context.world.get_agents_in_state(Worker)

        # create initial scouts
        for i in range(INIT_SCOUT):
            scout_state = ScoutBehind() if i == 0 else Scout()
            worker_pool[i].change_state(
                Training(None, TIME_TRAIN_SCOUT + randint(0, 10), scout_state))

        # create initial loggers
        for j in range(INIT_LOGGER):
            worker_pool[i + j + 1].change_state(Logger())

        # create a builder and request a kiln
        worker_pool[-1].change_state(
            Training(None, TIME_TRAIN_BUILDER, Builder()))
        kiln_msg = Telegram(context.agent_id, worker_pool[-1].agent_id,
                            MessageTypes.MSG_BUILDING_NEEDED,
                            BuildingTypes.Kiln)
        context.world.dispatch(kiln_msg, TIME_TRAIN_BUILDER + 1)
Ejemplo n.º 11
0
async def listen_telegrams():
    try:
        conn = psycopg2.connect(**db_config)

        cursor = conn.cursor()
        query = "SELECT * FROM inka_app WHERE app_activo = 1"
        cursor.execute(query)
        rows = cursor.fetchall()

        conn.close()

        for row in rows:
            app_name = str(row[2]).strip().replace("\n", "")
            if (app_name.lower() == str(
                    os.getenv("TELEGRAM_VALUE")).lower().strip()):
                app_key = str(row[4]).strip().replace("\n", "")
                phone = str(row[5]).strip().replace("\n", "")
                api_id = str(row[6]).strip().replace("\n", "")
                api_hash = str(row[7]).strip().replace("\n", "")
                host = str(row[10]).strip().replace("\n", "")
                tg = Telegram(app_key, phone, api_id, api_hash, host,
                              on_client_message)
                tgs.append(tg)

        tasks = []

        for tg in tgs:
            tasks.append(tg.start())

        await asyncio.gather(*tasks)

    except:
        logger.error('Error inesperado: %s', sys.exc_info())
        raise
Ejemplo n.º 12
0
 def enter(self, entity):
     alarm_clock_msg = Telegram(entity.ID, entity.ID,
                                MessageTypes.ALARM_CLOCK)
     entity.manager.dispatch_message(alarm_clock_msg,
                                     8)  #tick_size as msg delay
     if entity.location is not Locations.HOME:
         print('[', str(entity.ID), ']: Walking home to Sleep')
         entity.change_location(Locations.HOME)
Ejemplo n.º 13
0
 def on_message(self, entity, msg):
     if msg.message_type is MessageTypes.SOCIAL_REQUEST and not entity.is_hungry(
     ):
         entity.change_state(Socialize())
         reply = Telegram(entity.ID, msg.sender, MessageTypes.ACCEPT)
         entity.manager.dispatch_message(reply)
         return True
     return False
Ejemplo n.º 14
0
 def enter(self, entity):
     social_msg_self = Telegram(entity.ID, entity.ID,
                                MessageTypes.SOCIAL_SELF)
     entity.manager.dispatch_message(social_msg_self,
                                     4)  #tick_size as msg delay
     if entity.location is not Locations.CAFE:
         print('[', str(entity.ID), ']: Walking to Cafe')
         entity.location = Locations.CAFE
Ejemplo n.º 15
0
    def _abort(self, context):
        """Call if agent failed pathing, to revert states appropriately"""
        if self._on_fail is not None:
            context.change_state(self._on_fail)
        else:
            context.revert_state()

        arrive_msg = Telegram(context.agent_id, None, MessageTypes.MSG_PATH_FAIL, context.location)
        context.world.dispatch(arrive_msg)
Ejemplo n.º 16
0
    def _finish(self, context):
        """Call once agent is finished with path, to change state appropriately"""
        if self._on_arrive is not None:
            context.change_state(self._on_arrive)
        else:
            context.revert_state()

        arrive_msg = Telegram(context.agent_id, None, MessageTypes.MSG_ARRIVAL, context.location)
        context.world.dispatch(arrive_msg)
Ejemplo n.º 17
0
 def enter(self, context):
     if context.is_at(context.home):
         # Dispatch delayed message to self in order to wake up in time for work
         wakeup_time = WorkState.start_hour - GotoState.estimate(context, context.location, context.world.get_location(context.work)) - 0.25
         context.say(choice(self.starting_sleep))
         context.say(choice(self.set_alarm).format(World.time_format_24(wakeup_time)))
         alarm = Telegram(context.agent_id, context.agent_id, MessageTypes.MSG_WAKEUP)
         context.world.dispatch_scheduled(wakeup_time, alarm)
     else:
         context.goto(context.home)
Ejemplo n.º 18
0
    def on_message(self, context, telegram: Telegram):

        sender = context.world.get_agent(telegram.sender_id)

        # Deny meeting requests on account of being at work
        if telegram.message == MessageTypes.MSG_MEETING:
            context.say_to(sender, choice(self.meeting_refuse))
            reply = Telegram(context.agent_id, telegram.sender_id, MessageTypes.MSG_MEETING_REPLY, False)
            context.world.dispatch(reply)
            return True
        return False
Ejemplo n.º 19
0
    def DispatchMessage(self, delay, senderID, receiverID, msg, extraInfo):
        receiver = self.gm.GetEntity(receiverID)
        telegram = Telegram(0, senderID, receiverID, msg, extraInfo)

        if (delay <= 0):
            self.__Discharge(receiver, telegram)
        else:
            currentLoop = self.gm.GetLoop()
            telegram.dispatchTime = currentLoop + delay
            key = str(senderID) + str(msg) + str(receiverID)
            self.priorityQ[key] = telegram
Ejemplo n.º 20
0
    def on_message(self, context, telegram: Telegram):

        sender = context.world.get_agent(telegram.sender_id)

        # Deny meeting messages while walking, just to avoid issues when "blipping" states several times
        # Might be removed in the future
        if telegram.message == MessageTypes.MSG_MEETING:
            context.say_to(sender, choice(self.meeting_refuse))
            reply_msg = Telegram(context.agent_id, telegram.sender_id, MessageTypes.MSG_MEETING_REPLY, False)
            context.world.dispatch(reply_msg)
            return True
        return False
Ejemplo n.º 21
0
    def on_finish(self, context):
        """Call once agent is finished with path, to change state appropriately"""

        self.state = PathStates.Idle
        if self.on_arrive is not None:
            context.change_state(self.on_arrive)
        else:
            context.revert_state()

        arrive_msg = Telegram(context.agent_id, None,
                              MessageTypes.MSG_PATH_DONE, context.location)
        context.world.dispatch(arrive_msg)
Ejemplo n.º 22
0
    def request_construction(self, context, building_data):
        """Request a building to be constructed,
        using building data following MSG_BUILDING_NEEDED format"""

        builder = context.world.get_agents_in_state(Builder, 1)

        # if no builder was found, look for one in training
        if builder is None:
            trainees = context.world.get_agents_in_state(Training)

            if trainees is not None:
                # filter out units training to become a builder
                trainees = list(
                    filter(lambda L: L.after_train is Builder, trainees))

                if len(trainees) > 0:
                    first = trainees[0]
                    build_msg = Telegram(context.agent_id, first.agent_id,
                                         MessageTypes.MSG_BUILDING_NEEDED,
                                         building_data)
                    context.world.dispatch(build_msg, first.time + 1)
                    return

            # if no units are training to become a builder, train a new one
            builder_state = Builder()
            worker = context.world.get_agents_in_state(Worker, 1)

            # if a unit is available, send a message for construction
            if worker is not None:
                worker.change_state(
                    Training(None, TIME_TRAIN_BUILDER, builder_state))
                build_msg = Telegram(context.agent_id, worker.agent_id,
                                     MessageTypes.MSG_BUILDING_NEEDED,
                                     building_data)
                context.world.dispatch(build_msg, TIME_TRAIN_BUILDER + 1)
        else:
            build_msg = Telegram(context.agent_id, builder.agent_id,
                                 MessageTypes.MSG_BUILDING_NEEDED,
                                 building_data)
            context.world.dispatch(build_msg)
Ejemplo n.º 23
0
    def on_message(self, context, telegram: Telegram):
        if telegram.message == MessageTypes.MSG_MEETING:
            context.describe("briefly awoken by his phone")
            reply_msg = Telegram(context.agent_id, telegram.sender_id, MessageTypes.MSG_MEETING_REPLY, False)
            context.world.dispatch(reply_msg)
            return True
        if telegram.message == MessageTypes.MSG_WAKEUP:
            if not EVAL_MODE:
                print(choice(self.alarm))

            context.say(choice(self.stopping_sleep))
            context.change_state(WorkState())
            return True
        return False
Ejemplo n.º 24
0
    def end_construction(self, context):
        """Add the building to the world and move away.
        Also sends a broadcast with information about the new building"""

        context.world.add_location(context.location, self.building)
        done_msg = Telegram(context.agent_id,
                            None,
                            MessageTypes.MSG_BUILDING_DONE,
                            data=(self.building, context.location))
        context.world.dispatch(done_msg)
        self.building = None
        self.has_begun = False
        t = context.world.get_random_cell(context.location, 2)
        context.change_state(Goto(t, on_arrive=self))
Ejemplo n.º 25
0
 def dispatch_message(self, telegram, tick_delay=0):
     if telegram.receiver is None:
         for agent in self.entities.values():
             if agent == telegram.sender:
                 continue
             unicast = Telegram(telegram.sender, agent.ID,
                                telegram.message_type, telegram.extra_info)
             self.dispatch_message(unicast, tick_delay)
         return
     # check if message has delay
     if tick_delay > 0:
         telegram.tick_delay = self.current_ticks + tick_delay
         self.message_q.append(telegram)
     else:
         self.discharge(telegram)
    def dispatch_message(self, delay, sender, receiver, message_type,
                         extra_info):
        if receiver is None:
            print('No receiver')
            return

        telegram = Telegram(sender, receiver, message_type,
                            datetime.datetime.now(), extra_info)

        if delay <= 0:
            print(
                'Instant telegram dispatched at time: {} by {} for {} and message is: {}'
                .format(datetime.datetime.now(), sender.id, receiver.id,
                        message_type_to_string(message_type)))

            self.discharge(receiver, telegram)
Ejemplo n.º 27
0
    def on_message(self, context, telegram: Telegram):

        sender = context.world.get_agent(telegram.sender_id)

        # Decline meeting invitations on account of already being with friends
        if telegram.message == MessageTypes.MSG_MEETING:
            context.say_to(sender, choice(self._meeting_refuse))
            reply_msg = Telegram(context.agent_id, sender.agent_id, MessageTypes.MSG_MEETING_REPLY, False)
            context.world.dispatch(reply_msg)
            return True

        # Count replies to your invitation
        if telegram.message == MessageTypes.MSG_MEETING_REPLY:
            self._replies += 1
            if telegram.data:
                if self.count == 1:
                    context.say(choice(self._meeting_accepted_first))
                else:
                    context.say(choice(self._meeting_accepted_multi))
            else:
                context.say(choice(self._meeting_refused))
            return True

        # Remove cancelled invitations
        if telegram.message == MessageTypes.MSG_MEETING_CANCEL:
            self._invitations -= 1
            context.say_to(sender, choice(self._meeting_refused))
            return True

        # Greet new arrivals to the group
        if telegram.message == MessageTypes.MSG_ARRIVAL and telegram.data == context.location and sender in self._party:
            context.say_to(sender, choice(self._meeting_welcome).format(sender.name))
            return True

        # Say goodbye to departing members, and return to previous state if now alone
        if telegram.message == MessageTypes.MSG_MEETING_LEAVING and sender in self._party:
            if self.count == 1:
                context.say(choice(self._disband_group))
                self.leave_state(context)
            else:
                context.say_to(sender, choice(self._meeting_goodbye))
            return True

        return False
Ejemplo n.º 28
0
    def check_building(self, context):
        """If a building is needed, check if one exists and move to it,
        or request the construction of one if none exists"""

        target = context.world.get_locations(self.location_type)

        if target is None:
            print("Need a {} to train for this!".format(self.location_type))
            manager = context.world.get_agents_in_state(Manager, 1)
            build_msg = Telegram(context.agent_id, manager.agent_id,
                                 MessageTypes.MSG_BUILDING_NEEDED,
                                 self.location_type)
            context.world.dispatch(build_msg)
        else:
            if context.location == target[0]:
                self.begun = True
                print("Training at {} ({})".format(self.location_type.name,
                                                   type(self.after_train)))
            else:
                goto = Goto(target[0], on_arrive=self)
                context.change_state(goto, False)
Ejemplo n.º 29
0
 def check(self, directory):
     files = os.listdir(directory)
     hostname = config['main']['hostname']
     list_names = []
     for file in files:
         name = re.findall(r'dump\-\d+\-\d+\-\d+T\d+:\d+:\d+', str(file))
         if name:
             list_names.append(str(name))
     list_names.sort()
     last_file = list_names[len(list_names) - 1]
     result = re.search(r'\d+\-\d+\-\d+T\d+:\d+:\d+', str(last_file))
     a = str(result.group(0))
     timestamp_last_file = time.mktime(
         datetime.datetime.strptime(a, "%Y-%m-%dT%H:%M:%S").timetuple())
     if (time.time() - timestamp_last_file) > int(
             config['dump']['time_for_alerting_dump']):
         Telegram().sendMessage("Last dump file in %s ALARM hostname: %s" %
                                (a, hostname))
         Email().sendMessage("Last dump file in %s ALARM hostname: %s" %
                             (a, hostname))
         return "Last dump file in %s this ALARM" % (a)
     else:
         return "Last dump file in %s this OK" % (a)
Ejemplo n.º 30
0
    def enter(self, context):

        if self.is_carrying and context.location == self.to_tile:
            # Place carried item
            self.is_carrying = False
            count = context.world.add_resource(context.location, self.resource)

            msg_res = Telegram(context.agent_id,
                               None,
                               MessageTypes.MSG_RESOURCE_CHANGE,
                               data=(self.resource, self.to_tile, count))
            context.world.dispatch(msg_res)

            if count < self.count:
                goto = Goto(self.from_tile, on_arrive=self)
                context.change_state(goto)
            else:
                state = self.on_finish if self.on_finish is not None else Worker(
                )
                context.change_state(state)

        elif context.location == self.from_tile:
            # Grab item to carry
            if context.world.get_resource(context.location, self.resource) > 0:
                context.world.add_resource(context.location, self.resource, -1)
                self.is_carrying = True
                goto = Goto(self.to_tile, on_arrive=self)
                context.change_state(goto)
            else:
                state = self.on_finish if self.on_finish is not None else Worker(
                )
                context.change_state(state)
        else:
            # Goto pickup site for items
            goto = Goto(self.from_tile, on_arrive=self)
            context.change_state(goto)