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()
def webhook(): body = request.json if body is None: return "Done - body is None" # Recoger los campos mínimos que necesitamos message = body["message"] chat_id = message["chat"]["id"] text = message["text"] if text is None: return "Done - no Text" # Decidir qué hacer respuesta = None if text.startswith("/antichiste"): respuesta = antichiste_handler(chat_id) elif text.startswith("/proponer"): respuesta = proponer_handler(message, chat_id) # Mandar lo que hemos decidido if respuesta: Telegram.enviar_mensaje(respuesta) return "Done"
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))
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
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
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
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))
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)
def dispatch(self, telegram: Telegram, delay=0): """Dispatch a message with optional delay""" agents = [] if telegram.receiver_id is None: for agent in self.agents.values(): if agent.agent_id is not telegram.sender_id: agents.append(agent) else: if isinstance(telegram.receiver_id, int): agent = self.get_agent(telegram.receiver_id) if agent is not None: agents.append(agent) else: agents = self.get_agents(telegram.receiver_id) if delay <= 0: for agent in agents: agent.handle_message(telegram) return len(agents) telegram.dispatch_time = self._time + delay self._messages.append(telegram) return 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)
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
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
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
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)
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
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
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)
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)
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)
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)
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
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)
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
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)
def main(): config = ConfigParser() config.read(expanduser("~/.wn.conf")) wndb = WNDB(path=expanduser(config['Database']['path'])) interpreter = Interpreter() telegram = Telegram(config, interpreter) scheduler = Scheduler(wndb, telegram) thread = Thread(target=scheduler.run) thread.start() while True: try: sleep(.1) except (KeyboardInterrupt, SystemExit): break scheduler.shutdown() thread.join() telegram.shutdown() interpreter.shutdown()
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
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))
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 proponer_handler(message, chat): a_proponer = Telegram.texto_a_proponer(message) ok = AntiChistes.proponer(a_proponer) # mensaje = None if ok == 0: mensaje = 'Se propuso "%s" como antichiste.' % a_proponer elif ok == 1: mensaje = "Hubo un problema con el servidor, prueba más tarde..." elif ok == 2: mensaje = "¡Demasiado corto!" usuario = message.get("from") if usuario: nombre = usuario.get("first_name") mensaje = "¡Eso es demasiado corto, %s!" % nombre else: print("Es None") return None return Telegram.crear_mensaje(mensaje, chat) if mensaje else None
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)
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
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)
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)
def antichiste_handler(chat): (uno, dos) = AntiChistes.aleatorio() texto = "%s\n\n%s" % (uno, dos) return Telegram.crear_mensaje(texto, chat)
from flask import Flask, request from telegram import Telegram from message_checker import MessageHandler from data_updater import DataUpdater from message import Message supported_commands = """Supported commands: /help - show this help /catchups <number> - add number of catchups in this day Supported messages: *'<number> catchups'* or *'catchups <number>'* (catch ups is also fine) *'<число> подтягиваний'* or *'подтягиваний <число>'*""" # init telegram bot bot = Telegram() ok = bot.init() if not ok: print("ERROR (bot init): {}".format(bot.get_messages())) exit(1) # init message checker msg_checker = MessageHandler() # init data updater du = DataUpdater() ok = du.init() if not ok: print("ERROR (data updater init): {}".format(du.get_error_message())) exit(1)
import json import urllib import urllib2 import time import sys sys.path.insert(0, '../../common') from telegram import Telegram def callback(instance, a,b,c): print '/start' print 'cmd : ' + a print 'args: ' + b print '' if b == 'end': instance.end_command_sequence() def default(i,a,b,c): print 'seas' def sers(instance, cmd, args, message): chatid = message['message']['chat']['id'] instance.send_message(chatid, "sers") telegram = Telegram('87903508:AAGprAZi7hUopcrkH3t-Aj_xHf5S0rdwxJw') telegram.add_command('/sers', sers) telegram.start()
import time import sys import cleverbot sys.path.insert(0, '../common') from telegram import Telegram cb = cleverbot.Cleverbot() def callback(instance, a,b,c): print '/start' print 'cmd : ' + a print 'args: ' + b print '' if b == 'end': instance.end_command_sequence() def default(i,a,b,c): chatid = c['message']['chat']['id'] i.send_chat_action(chatid, "typing") i.send_message(chatid, cb.ask(c)) def sers(instance, cmd, args, message): chatid = message['message']['chat']['id'] instance.send_message(chatid, "sers") telegram = Telegram('112455179:AAFnbPuWGk2rdINqrKfXF8PPHhHo3g66sfg') telegram.add_default_handler(default) telegram.start()
def tel_init(self, server, port, handlers): connection = Telegram(server, port) for event, handler in handlers.items(): connection.register_handler(event, handler) self.tel_connection = connection