def _on_schedule(self): """ This method is called repeatedly from an event loop """ return # sender/receiver/stream id's are automatically translated by the base class Connector # when calling methods _pop_message_to_send() and _push_received_message() # example of incoming message for the bot in private message = Message.build('Hi @globot please ask for service #sample') channel = Channel(11, 0, None, self.get_name()) self._push_received_message(message, channel) # example of incoming message for the bot in chatroom message = Message.build('Hi @globot please ask for service #sample') channel = Channel(60, 0, 777, self.get_name()) self._push_received_message(message, channel) # example of incoming message in chatroom for another agent message = Message.build('Hi folks nothing new today') channel = Channel(11, 60, 777, self.get_name()) self._push_received_message(message, channel) # example of outgoing message while True: ret = self._pop_message_to_send() if ret is None: break (message, channel) = ret
def match_line(message): request = message.text.lower()[len(KEYWORD):].strip().splitlines()[0] matches = [(i+1,line) for (i,line) in enumerate(open(TEXT_FILE)) if request in line.lower()] match_wav_file = NO_MATCH_WAV_FILE if matches: matched_line = "line %d: %s" % matches[0] for name in os.listdir(WAV_BASE): bounds = re.findall("\d+", name) if(len(bounds) == 2 and int(bounds[0]) <= matches[0][0] and int(bounds[1]) >= matches[0][0]): match_wav_file = os.path.join(WAV_BASE, name) else: matched_line = "no match!" print "Sending line from Beowulf to %s: %s" % (message.from_num, matched_line) call_all_thread([message.from_num], [match_wav_file]) # Place the call, wait for call to end. #what happens if we try to start before we're finished with another call? reply = Message(id="beowulf",to_num = message.from_num, from_num = message.to_num, text = matched_line) reply.connection = message.connection reply.send() #TODO: a generalized way to alter messages so we can mark it read #--though apparently GV eventually marks something as read if it has been replied to #so this tends to send twice only? Log(message).save(); Log(reply).save();
def listen(self): while self.isConnected: bunch = self.ircSock.recv(4096) if not bunch: continue try: msg = decode(bunch) msgs = msg.split("\r\n") except UnicodeDecodeError: msg = str(bunch) bounding = msg[1] msg = msg[2:len(msg) - 5].replace("\\" + bounding, bounding).replace("\\\\", "\\") msgs = msg.split("\\r\\n") # for each message within received bunch ... for m in msgs: if not m: continue # ... generate Message-object, ... message = Message(self, m) self.logger.info("Received %s" % str(message)) # ... run built-in commands and ... if len(message.cmd): self.check_commands(message) # ... trigger events for plugins for event in message.get_events(): self.trigger(event, message) if self.shouldReconnect: self.connect()
async def plantCommand(app: App, e: GroupMessageRecvEvent): groupId = e.group.id masterId = settings['master'] if not existElem(settings['enabled_groups'], groupId): return if e.group.permission == PermissionType.Member: app.sendGroupMessage( groupId, Message.phrase(RefMsg(target=e.sender.id), " 需要管理员权限才能执行该指令嗷~")) return if (masterId == 0 and e.sender.permission == PermissionType.Member) \ or (masterId != 0 and masterId != e.sender.id): app.sendGroupMessage( groupId, Message.phrase(RefMsg(target=e.sender.id), " 你没有权限哟~")) return if len(e.msg.msgChain) == 0: app.sendGroupMessage( groupId, Message.phrase(RefMsg(target=e.sender.id), " 格式是\"赐名 @成员 头衔\"哦~")) return atCodes = e.msg.getAtCodes() if (len(atCodes) != 1): app.sendGroupMessage( groupId, Message.phrase(RefMsg(target=e.sender.id), " 格式不对喔~")) return app.setSpecialTitle(groupId, atCodes[0].target, str(e.msg.msgChain[2]).strip()) app.sendGroupMessage(groupId, Message.phrase(RefMsg(target=e.sender.id), " 操作成功~"))
async def onCommand(app: App, e: GroupMessageRecvEvent): groupId = e.group.id argument = str(e.msg).strip() if e.group.permission == PermissionType.Member: return if not existElem(settings['enabled_groups'], groupId): return if len(argument) == 0: app.sendGroupMessage( groupId, Message.phrase(RefMsg(target=e.sender.id), ("欢迎来玩转轮手枪~\n" "嘎嘎嘎~这是一个恐怖的游戏!\n" f"{app.nickname}会为一把六发左轮的弹舱随机装入一发弹药\n" f"使用“{app.commandHead}扣扳机”来参加比赛 嘻嘻嘻\n" "与赛的各位,依次把枪口调向自己,扣动扳机,直到...砰——子弹出膛!"))) if groupInfo[groupId.id].idle: app.sendGroupMessage( groupId, Message.phrase(RefMsg(target=e.sender.id), "已经重新装填弹药咯!")) else: app.sendGroupMessage( groupId, Message.phrase(RefMsg(target=e.sender.id), "本轮比赛还没有结束哟~"))
async def groupViewTrees(app: App, e: GroupMessageRecvEvent): name = '你' msg = e.msg msg.chain() record = userdb(userid=e.sender.id) empty = True if len(record) > 0: reply = "你的树林里有以下树木👇\n" bag = record[0]['bag'] ids = list(bag.keys()) ids.sort(reverse=True) for treeId in bag: cnt = bag[treeId] if cnt > 0: empty = False item = getItemDetail(treeId) reply += f" 【{getQualityDescription(item['quality'])}】{item['name']}×{cnt}\n" reply = reply[:-1] if empty: app.sendGroupMessage( e.group.id, Message.phrase(RefMsg(target=e.sender.id), "哎呀,你的树林空空如也呢,快去种树吧~")) else: app.sendGroupMessage(e.group.id, Message.phrase(RefMsg(target=e.sender.id), reply))
def test_pop_outdated(self): q = MessageQueue(2) m = Message('this message will be ignored', 'sender', 5, 1, 10, {}) q.put(m, verbose=False) m.added_date = datetime(1970, 1, 1) q.put(Message('this message will be poped!', 'sender', 5, 1, 10, {}), verbose=False) self.assertEquals(q.pop().contents, 'this message will be poped!')
def test_put_pop_users(self): q = MessageQueue(2) self.assertEquals(len(q.users.keys()), 0) q.put(Message('contents', 'sender', 5, 1, 10, {}), verbose=False) self.assertTrue('sender' in q.users) self.assertEquals(q.users['sender'].message_count, 1) q.put(Message('contents', 'sender2', 5, 1, 10, {}), verbose=False) self.assertTrue('sender2' in q.users) self.assertEquals(q.users['sender2'].message_count, 1) q.pop(verbose=False) self.assertEquals(q.users['sender'].message_count, 0) q.pop(verbose=False) self.assertEquals(q.users['sender2'].message_count, 0)
def act(self): # get human reply reply = Message({ 'id': self.getID(), 'label_candidates': self.fixedCands_txt, 'episode_done': False, }) reply_text = self.get_reply() # check if human reply is offensive self.self_offensive = self.check_offensive(reply_text) while self.self_offensive: print(OFFENSIVE_USER_REPLY) reply_text = self.get_reply() # check if human reply is offensive self.self_offensive = self.check_offensive(reply_text) # check for episode done if '[DONE]' in reply_text or self.opt.get('single_turn', False): raise StopIteration # set reply text reply['text'] = reply_text # check if finished if '[EXIT]' in reply_text: self.finished = True raise StopIteration return reply
def from_dict(cls, data: dict, magicnumber: str = None) -> 'Block': """ Convert from dictionary for deserialize. """ parent = None if data['parent'] is not None: parent = DummyBlock( data['index'] - 1, magicnumber, base64.b64decode(data['parent']), ) result = cls(parent) if data['key'] is not None: result.key = base64.b64decode(data['key']) if data['closer'] is not None: result.closer = User.from_pem(data['closer']) result.timestamp = data['timestamp'] if data['signature'] is not None: result.signature = base64.b64decode(data['signature']) result.messages = [Message.from_dict(m) for m in data['messages']] return result
async def Solo(app: App, e: GroupMessageRecvEvent): arguments = str(e.msg).strip() if len(arguments) == 0: app.sendGroupMessage( e.group, Message.phrase(RefMsg(target=e.sender.id), ("" "")))
def main(): global driver # Parse args from cmd. config = parse_arguments() # Set default values. set_default_repeat(config["ttr"]) set_default_ttl(config["ttl"]) set_default_duration(config["ttd"]) # Create the message queue. message_queue = MessageQueue(config["limit"]) # Load module, driver and animation according to args. module_class = load_module_from_conf(config) driver_class = load_driver_from_conf(config) driver = driver_class() animation_class = load_animation_from_conf(config) animation = animation_class(driver) # Create the message manager and start the thread. message_manager = QueueManager(message_queue, module_class, animation) message_manager_thread = threading.Thread(target=message_manager.manage) message_manager_thread.daemon = True message_manager_thread.start() # Start the web server. webserver_thread = threading.Thread(target=run, args=(message_queue, config["ptl"])) webserver_thread.daemon = True webserver_thread.start() # Advertise user that everything is working: # In cmd. print("Daemon ready!") # On the screen. started_message = Message("Daemon ready!", "lcd_daemon", 1, 1, 5, {}) message_queue.put(started_message, verbose=False) webserver_thread.join()
def get(self, episode_idx, entry_idx): sample = self.data[episode_idx] sample['label_candidates'] = self.label_candidates sample['episode_done'] = True sample['labels'] = [ self.label_candidates[int(sample['is_sensitive']) - 1] ] return Message(sample)
def __init__(self, data: dict) -> None: self.sender: Contact self.msg: Message super().__init__(EventType.ContactMessageEvent) self.msg = Message(chain=data['messageChain']) senderInfo = data['sender'] id = senderInfo['id'] nickname = senderInfo['nickname'] remark = senderInfo['remark'] fromGroup = None if 'group' in senderInfo: fromGroup = senderInfo['group']['id'] self.msg = Message(chain=data['messageChain']) self.sender = Contact(id=id, nickname=nickname, remark=remark, fromGroup=fromGroup)
def process(self): """ TODO, Handle request 1] open to RMS websocket 2] New waitingQueue and runningQueue and defines maximum size 3] Launch comsumer thread, then monitor runningQueue 4] Two thread do their work How to use Queue? MainThread 1] new a waitingQueue, like a proceduer, everytime, main thread receives client request, then put it into waitintQueue 2] Everytime, main thread receives client release, call RMS release resources, then remove resource from runningQueue, How to remove resources from runningQueue, need to talk with RMSs CosumerThread 2] new a runningQuueu, like a consumer, its has maximum size, when runningQueue reaches its maximun size, consumer thread sleep 1 second, then poll again when runningQueue resources -1, consumer thread get a new resource from waiting queue, if this unit is BUSY by RMS, put it to the end of the waiting queue, then loop get next if this unit is Y/N by RMS, put it to the runningQueue + 1, then return it to client Need to talk RMS """ self.wsRms.connect() self.scheduler = Scheduler(self) self.scheduler.setDaemon(True) self.scheduler.start() while not self.stop: json = self.wsEngine.receive() if json == None: time.sleep(1) continue print "------->Receive from lib: %s" %json message = Message().restore(json) if message.getCmd() == Message.CMD_REGISTER: self.waitingQueue.append(message) elif message.getCmd() == Message.CMD_RELEASE: self.wsRms.release(message.getRes()) self.runningQueue.remove(message) self.scheduler.stop()
def parley(self): """ Agent 0 goes first. Alternate between the two agents. """ if self.turn_cnt == 0: self.p1, self.p2 = self.get_contexts() acts = self.acts agents = self.agents if self.turn_cnt == 0 and self.p1 != '': # add the context on to the first message to agent 0 context_act = Message({ 'id': 'context', 'text': self.p1, 'episode_done': False }) agents[0].observe(validate(context_act)) try: act = deepcopy(agents[0].act()) except StopIteration: self.reset() self.finalize_episode() self.turn_cnt = 0 return acts[0] = act if self.turn_cnt == 0 and self.p2 != '': # add the context on to the first message to agent 1 context_act = Message({ 'id': 'context', 'text': self.p2, 'episode_done': False }) agents[1].observe(validate(context_act)) agents[1].observe(validate(act)) acts[1] = agents[1].act() agents[0].observe(validate(acts[1])) self.update_counters() self.turn_cnt += 1 if act['episode_done']: self.finalize_episode() self.turn_cnt = 0
def parley(self): if self.episode_done(): self.turn_cnt = 0 self.episode_cnt += 1 self.contexts = None self.seed_utterances = None agents = self.get_agents() for a in agents: a.reset() if self.turn_cnt == 0: self.acts = [None, None] # get the beginning of the conversation, which can include contexts # and/or any number of starting messages self.contexts = self.get_contexts() self.seed_utterances = self._get_seed_utt_acts( self.episode_cnt, self.agents) if self.contexts: assert len(self.contexts) == 2 # initial context for i in range(0, 2): context = Message({ 'text': self.contexts[i], 'episode_done': False, 'id': 'context' }) self.acts[i] = context self.agents[i].observe(validate(context)) # clear contexts so they are only added once per episode self.contexts = None elif self.seed_utterances: # pop the next two seed messages (there may be less or more than 2 total) utts = self.seed_utterances[:2] self.seed_utterances = self.seed_utterances[2:] # process the turn for i in [0, 1]: # if we have a seed utterance, add it to the conversation if len(utts) > i: self.acts[i] = utts[i] if hasattr(self.agents[i], 'self_observe'): self.agents[i].self_observe(self.acts[i]) else: self.acts[i] = self.agents[i].act() self.agents[1 - i].observe(validate(self.acts[i])) else: # do regular loop acts = self.acts agents = self.agents acts[0] = agents[0].act() agents[1].observe(validate(acts[0])) acts[1] = agents[1].act() agents[0].observe(validate(acts[1])) self.update_counters() self.turn_cnt += 1
def received_message(self, json): rmsmsg = Message().restore(json) print "--------->Response from rms: %s" %rmsmsg.getRes() if rmsmsg.getStatus() == Message.STATUS_Y: self.handler.wsEngine.send('Y') message = self.queue.remove(rmsmsg.getId()) self.handler.runningQueue.append(message) elif rmsmsg.getStatus() == Message.STATUS_N: self.handler.wsEngine.send('N') self.queue.remove(rmsmsg.getId()) elif rmsmsg.getStatus() == Message.STATUS_BUSY: message = self.queue.remove(rmsmsg.getId()) self.handler.waitingQueue.append(message)
async def __parse_updates(self, raw: Dict[str, Any]): for raw_msg in raw['messages']: msg = Message(**raw_msg) args = msg.content.split(' ') try: cmd = self._command_handlers[args[0]] await cmd(msg, args) except Exception as e: self.log.error(e)
def from_master(cls, topic_list: List[Tuple[str, str]]): """ Create a node object from a master xml list :param topic_list: A list of topics :return: A list of topic objects """ return_list = [] for topic in topic_list: return_list.append(cls(topic_name=topic[0], message=Message(msg_type=topic[1]), protocol="TCPROS")) return return_list
async def wrapper(app: App, e: GroupMessageRecvEvent): groupId = e.group.id if not existElem(settings['enabled_groups'], groupId): return if not await func(app, e): app.sendGroupMessage( groupId, Message.phrase(RefMsg(target=e.sender.id), ( "使用方法: .(google | baidu | github | bilibili) search_string" )))
def parley(self): """ Loop between wizard and apprentice. Adds knowledge to the wizard observations. Assumes that the model agent is the wizard model. """ if self.cnt == 0: self.topic = self._get_new_topic() self.acts = [None, None] self.human_first = random.choice([0, 1]) # possibly get human act first if self.cnt == 0 and not self.human_first: self.acts[0] = act = Message({'text': '', 'episode_done': False}) act = self.acts[0] else: self.acts[0] = self.human_agent.act() act = deepcopy(self.acts[0]) # model agent observe if self.cnt == 0 and self.topic != NO_TOPIC: # add the chosen_topic to the message act['chosen_topic'] = self.topic act.force_set('text', '\n'.join([self.topic, act.get('text', 'hi')])) # add knowledge to the model observation act = self._add_knowledge_to_act(act) # model observes knowledge and human (apprentice) act self.model_agent.observe(validate(act)) # model agent act self.acts[1] = self.model_agent.act() # add the model reply to the knowledge retriever's dialogue history self.knowledge_agent.observe(self.acts[1], actor_id='wizard') # human (apprentice) agent observes model act self.human_agent.observe(validate(self.acts[1])) self.update_counters() self.cnt += 1 if self.episode_done(): print('[ CHAT DONE ]') print('\n[ Preparing new chat... ]\n') self.cnt = 0 self.model_agent.reset()
def get_sub_list(self, node_name: str): """ Update the local subscriber list :param node_name: Name of the requester to give to the node :return: None """ try: (_, _, topic_list) = self.server.getSubscriptions(node_name) for topic in topic_list: message = Message(msg_type=topic[1]) self.sub_topics.append(Topic(topic_name=topic[0], message=message, protocol="TCPROS")) except xmlrpc.client.Fault as err: print(err)
def act(self): reply = Message() reply['id'] = self.getID() try: reply_text = input(colorize("Enter Your Message:", 'text') + ' ') except EOFError: self.finished = True return {'episode_done': True} reply_text = reply_text.replace('\\n', '\n') reply['episode_done'] = False if self.opt.get('single_turn', False): reply.force_set('episode_done', True) reply['label_candidates'] = self.fixedCands_txt if '[DONE]' in reply_text: # let interactive know we're resetting raise StopIteration reply['text'] = reply_text if '[EXIT]' in reply_text: self.finished = True raise StopIteration return reply
def test_getting_messages(self): apiConnector = ApiConnector() last_initialization = time() apiConnector.initialize() bot = get_bot_by_name("Johnny Five") reinitialize_seconds = 60 * 15 test_time_in_seconds = 60 * 30 num_talkbacks = 10 received_talkbacks = 0 sleep_duration = test_time_in_seconds / num_talkbacks max_wait_in_seconds = 10 start_time = time() last_message_sent = start_time waiting = False while received_talkbacks < num_talkbacks: current = time() if waiting: # check the messages to make sure we get it in the websocket messages = [ Message(m).text for m in apiConnector.check_for_message() ] if text in messages: waiting = False received_talkbacks += 1 logging.info("Received message " + str(text)) else: if current - last_message_sent > max_wait_in_seconds: bot.say("Did not get message " + str(received_talkbacks) + " after " + str(time() - start_time) + " .") logging.error("Did not get message " + str(received_talkbacks) + ".") assert False else: if current - last_message_sent > sleep_duration: text = "Testing " + str(received_talkbacks) bot.say(text) last_message_sent = current waiting = True if current - last_initialization > reinitialize_seconds: apiConnector.initialize() last_initialization = current sleep(.005) else: bot.say("Test successful.") logging.info("Successfully received all " + str(num_talkbacks) + " messages.")
async def Solo(app: App, e: GroupMessageRecvEvent): arguments = str(e.msg).strip() if len(arguments) == 0: app.sendGroupMessage( e.group, Message.phrase(RefMsg(target=e.sender.id), ("欢迎来玩拼点~\n" "“拼点@对方”可以下达战书或者应战\n" "“不拼@对方”可以拒绝对方的挑战\n" "“弃拼”可以放弃挑战\n" "“查战书”可以查看有谁向你发起了挑战\n" "“大拼点n倍@对方”可以向对方发起赌上尊严的挑战(倍率为n哦)!\n" "【注意】已经有等待对方接受的战书后,就不能再发战书了哦~\n" "【注意】大拼点会占用拼点的战书槽,且要用“大拼点@对方”进行应战")))
def plantComplete(app: App, groupId: int, memberId: int, type: str = 'success'): info = db(groupId=groupId, memberId=memberId)[0] if type == 'success': proc = info['duration'] / settings['max_time'] * 100 treeId, quality = lottery(proc) app.sendGroupMessage( groupId, Message.phrase( RefMsg(target=memberId), "的树长大啦!\n" f"{getCongratulations(quality)}" f"你获得了“{getQualityDescription(quality)}”品质的" f"{getItemDetail(treeId)['name']}~")) record = userdb(userid=memberId) if len(record) != 0: record = record[0] if treeId not in record['bag']: record['bag'][treeId] = 1 else: record['bag'][treeId] += 1 record['accumulate'] += info['duration'] else: userdb.insert(userid=memberId, bag={treeId: 1}, accumulate=info['duration']) userdb.commit() elif type == 'cancel': app.sendGroupMessage( groupId, Message.phrase(RefMsg(target=memberId), "取消了种树,树枯萎了...")) app.unmute(groupId, memberId) else: return del db[info['__id__']]
def on_schedule(self): now = datetime.datetime.now() while len(self._incoming_messages) > 0: (message, channel) = self._incoming_messages.pop() logging.debug('service \033[32malarm\033[0m says "{}" {}'.format( message, channel)) seconds = self.extract_time(message) if seconds is not None: self.__alarms.append((now, seconds, channel)) else: channel = self._bot.reply(channel) message = Message.build( '#alarm service does not understand your request') self._outgoing_messages.insert(0, (message, channel)) triggered = list() waiting = list() for (timestamp, seconds, channel) in self.__alarms: alarm_time = timestamp + datetime.timedelta(seconds=seconds) if alarm_time > now: waiting.append((timestamp, seconds, channel)) else: triggered.append((timestamp, seconds, channel)) for (timestamp, seconds, channel) in triggered: message = Message.build( '#alarm service has been requested {} seconds ago'.format( seconds)) channel = self._bot.reply(channel) self._outgoing_messages.insert(0, (message, channel)) logging.debug('service \033[32malarm\033[0m says "{}" {}'.format( message, channel)) self.__alarms = waiting
def evaluate_response(self, observation: Message, labels: List[str]) -> None: """ Compute all required text-based metrics based on an observation and labels. """ prediction = observation.get('text', None) self.add('exs', SumMetric(1)) if prediction is not None: self.add('accuracy', ExactMatchMetric.compute(prediction, labels)) self.add('f1', F1Metric.compute(prediction, labels)) for k in range(1, 5): # 1..4 if f'bleu-{k}' in self._metrics_list: self.add(f'bleu-{k}', BleuMetric.compute(prediction, labels, k)) # if any of the rouges are in the list if self._metrics_list & ROUGE_METRICS: r1, r2, rL = RougeMetric.compute_many(prediction, labels) if 'rouge-1' in self._metrics_list: self.add('rouge-1', r1) if 'rouge-2' in self._metrics_list: self.add('rouge-2', r2) if 'rouge-L' in self._metrics_list: self.add('rouge-L', rL) # Ranking metrics. self._update_ranking_metrics(observation, labels) # User-reported metrics if 'metrics' in observation: for uk, v in observation['metrics'].items(): if uk in ALL_METRICS: # don't let the user override our metrics uk = f'USER_{uk}' assert isinstance(uk, str), type(k) if not isinstance(v, Metric): warn_once( f'Metric {uk} is assumed to be averaged per example.') v = AverageMetric(v) assert isinstance(v, Metric) self.add(uk, v) # always flush at the end of processing this response self.flush()
def act(self): obs = self.observation if obs is None: return {'text': 'Nothing to repeat yet.'} reply = {} reply['id'] = self.getID() labels = obs.get('labels', obs.get('eval_labels', None)) if labels: if random.random() >= self.cantAnswerPercent: if self.returnOneRandomAnswer: reply['text'] = labels[random.randrange(len(labels))] else: reply['text'] = ', '.join(labels) else: # Some 'self.cantAnswerPercent' percentage of the time # the agent does not answer. reply['text'] = self.cantAnswerMessage else: reply['text'] = self.cantAnswerMessage reply['episode_done'] = False return Message(reply)
def join(self): print("Connecting to Groupme pub sub service.") self.connector.initialize() while self.run: try: messages = self.connector.check_for_message() for raw_message in messages: message = Message(raw_message) self.admin_handler.handle(message) for handler in self.handlers: try: handler.handle(message) except Exception as err: logging.exception(err) logging.info("Removing handler " + handler.__class__.__name__) self.handlers.remove(handler) time.sleep(.005) except WebSocketConnectionClosedException: self.connector.initialize() except Exception as exc: logging.exception(exc) logging.error("Error...but run forever.")
def pool(self, message: Message) -> None: """ Pooling new message into this block. >>> user = User.generate() >>> root = Block.make_root(user) The block is empty when created. >>> child = Block(root) >>> len(child.messages) 0 Pooling new message like this. >>> message = Message(user, 'namespace', 'hello') >>> child.pool(message) >>> len(child.messages) 1 >>> child.messages[0] == message True Can't pooling message into a closed block. >>> root.is_closed() True >>> root.pool(message) Traceback (most recent call last): ... core.errors.BlockAlreadyClosedError """ if self.is_closed(): raise errors.BlockAlreadyClosedError() if not message.verify(): raise errors.InvalidSignatureError() self.messages.append(message)