def send_message(): content = request.get_json(force=True) Message.send_message(content.get('content'), content.get('sender_id'), content.get('company_id')) return jsonify({"message_sent": True})
def on_join_rooms(message): uid_from = message['uid_from'] room_from = message['room_from'] join_room(room_from) joined_rooms = rooms() app.logger.error('{}--join_room--{}--joined_rooms_is---{}'.format(uid_from, room_from, joined_rooms)) text = message['text'] msg_type = message['type'] is_send_to_server = message['is_send_to_server'] time_client = message['time_client'] room_to = message['room_to'] message = Message(text, msg_type, is_send_to_server, time_client, room_from, room_to, uid_from, uid_from) message.save() message_id = message.id app.logger.error('message_id-{}--{}--saved to db'.format(message_id, message.text)) if room_from in joined_rooms: update_sid_uid_map(sid=request.sid, uid=uid_from) add_online_uids(uid_from) data = { 'id': message_id, 'text': 'join_room_ok', 'room_from': room_from, 'type': MESSAGE_TYPE.MESSAGE_ACK.value, 'uid_from': uid_from, } async_emit_msg.delay('join_room', data, broadcast=True)
def handleMessage(tag: Tag, chat: Chat, prev_tag: Tag = None): if not prev_tag: txt = tag.find('div', attrs={'class': 'text'}) reply_to = tag.find('div', attrs={'class': 'reply_to_details'}) fromUser = tag.find('div', attrs={ 'class': 'from_name' }).getText().strip() chat.push( Message( int(tag.get('id').replace('message', '')), chat.extractUserAndBotNameFromMessage(fromUser) if chat.isAViaBotMessage(fromUser) else (fromUser, None), txt.getText().strip() if txt else None, tag.find('div', attrs={ 'class': 'pull_right date details' }).get('title'), int(reply_to.a.get('href')) if reply_to else None)) chat.updateUserRecords(fromUser, int(tag.get('id').replace('message', ''))) else: txt = prev_tag.find('div', attrs={'class': 'text'}) fromUser = prev_tag.find('div', attrs={ 'class': 'from_name' }).getText().strip() chat.push( Message( int(tag.get('id').replace('message', '')), chat.extractUserAndBotNameFromMessage(fromUser) if chat.isAViaBotMessage(fromUser) else (fromUser, None), txt.getText().strip() if txt else None, tag.find('div', attrs={ 'class': 'pull_right date details' }).get('title'))) chat.updateUserRecords(fromUser, int(tag.get('id').replace('message', '')))
def parseMessagesFromFile(filePath, limit=0, startDate=None, endDate=None): messages = [] senders = set([]) if startDate: startDate = datetime.strptime(startDate, Message.DATE_FORMAT) if endDate: endDate = datetime.strptime(endDate, Message.DATE_FORMAT) try: with open(filePath, 'r', encoding="utf8") as f: for line in f: date, time, sender, text = line.split(' ', 3) if startDate or endDate: thisDate = datetime.strptime(date, Message.DATE_FORMAT) if (not startDate or thisDate >= startDate) and ( not endDate or thisDate <= endDate): messages.append( Message(date, time, sender, text.strip())) else: messages.append(Message(date, time, sender, text.strip())) senders.add(sender) if limit != 0 and len(messages) >= limit: break except IOError: logger.warning("No such file: " + filePath) return messages, senders
def spy(): logging.info("Spy cron") client = TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN) ''' Get all ALIVE spies ''' alive_spies = Player.query(Player.role == "SPY").fetch() logging.info("Alive Spies:") logging.info(alive_spies) ''' For each spy, make and send hint ''' for spy in alive_spies: if spy.state == "DEAD": continue response = Player.spy_hint(spy) msg = Message(From=SERVER_NUMBER, To=spy.key.id(), Body=response) msg.put() client.messages.create( to=spy.key.id(), from_=SERVER_NUMBER, body=response) logging.info("SPY CRON: completed send to {}".format(alive_spies)) return "Ok"
def handle_send_message_event(data): timestamp = datetime.now().strftime('%H:%M') # unpack the delivered json object try: input_data = json.load(data) message_object = input_data['child'] username = message_object['username'] room = message_object['room'] content = message_object['message'] except: socketio.emit(500) # log that a message was sent app.logger.info("{} to {} @ {}: {}".format(username, room, timestamp, content)) # create a new message object with a json accordingly new_message = Message(username, room, content, timestamp) new_message_json = new_message.get_json() # put this new message in the database and send it out save_message(new_message) socketio.emit(new_message_json)
def messages(): params = {} for key, val in request.args.items(): if key in ('limit', 'offset'): params[key] = val thread_tss = [] messages = Message.get_messages(**params) for msg in messages: thread_tss.append(msg.thread_ts) reply_users = defaultdict(set) reply_counts = defaultdict(int) for reply in Message.get_replies(thread_tss): if reply.is_thread: reply_users[reply.thread_ts].add(reply.user_id) reply_counts[reply.thread_ts] += 1 resp = {'messages': []} for msg in messages: if 'thread_ts' in msg.__dict__ and msg.thread_ts != None: temp = msg.__dict__ temp['reply_count'] = reply_counts[msg.thread_ts] temp['reply_users'] = list(reply_users[msg.thread_ts]) resp['messages'].append(temp) else: resp['messages'].append(msg.__dict__) return resp
def ask_message(self, user): """ Function that runs in a Thread to keep asking the host for the message to send. :param user: host username to include as sender :return: response message """ print "=======================" print "| HOST CHAT |" print "=======================" while True: text = raw_input("Write the message: ") if "#" not in text: to = raw_input("Receiver: ") data = Message(user, to, text).to_dict() response = self.send(data) else: data = Message(user, None, text, 'b').to_dict() response = self.send(data) if response["status"] == -1: print "" print response["msg"] print ""
def _process_message(self, ch, method, properties, message): print(f'A new message was received: {message}') msg_type = ['incoming', 'outgoing'] storage = BigQuery() message = Message(f'1', '1', random.choice(msg_type), message.decode('utf-8')) storage.insert_message(message) print('message send at ', datetime.utcnow())
def handle_message(data): app.logger.info('received message: %s', data) app.logger.info('message %s', data.get('message')) data = data.get('message') message = Message(data.get('username'), data.get('message')) message.save() # app.logger.info("test %s", data.message) emit('add_message', 'message recu')
def on_disconnect(): sid = request.sid uid = get_uid_with_sid(sid) remove_online_uids(uid) user = UserModel.find_by_id(uid) print('Client disconnected--{}--{}--{}'.format(sid, uid, user.to_json())) message = Message('disconnect_broadcast', MESSAGE_TYPE.MESSAGE_BROADCAST.value, False, int(round(time.time() * 1000)), user.room_private, user.room_private, uid, uid) message.save() async_emit_msg.delay('disconnect_broadcast', message.to_json(), broadcast=True)
def on_message(message): uid_from = message['uid_from'] room_from = message['room_from'] text = message['text'] msg_type = message['type'] is_send_to_server = message['is_send_to_server'] time_client = message['time_client'] room_to = message['room_to'] message = Message(text, msg_type, is_send_to_server, time_client, room_from, room_to, uid_from, uid_from) message.save() message_id = message.id app.logger.error('message_id-{}--{}--saved to db '.format(message_id, message.text)) async_emit_msg.delay('message', message.to_json(), room=room_to)
def message_event_handler(**payload): logger.debug(f"payload : {payload}") data = payload['data'] sub_type = data.get('subtype', None) if sub_type is not None: return web_client = payload['web_client'] rtm_client = payload['rtm_client'] if 'text' in data: message = Message(data) is_mention, message.bot_id = check_mention(message.text) commands = message.parse_message(is_mention) logger.debug(f"message {commands}") _parse_command(web_client, message, commands)
async def process_command(self, command): """ Process a command from the user. """ self.log.info(f"process_command({command=})") try: # Get input args = command.split(' ') # Do input if args[0] == 'hero': hero_name = args[1] args = args[2:] self.log.info(f"hero command {hero_name=}, {args=}") hero = next( filter(lambda h: h.name == hero_name, self.gamestate.heroes), None) if not hero: raise Complaint(Message('nosuchhero', hero_name)) if args[0] == 'play': # Forces card into a lower case string to prevent capitalization issues with input card = args[1].lower() await self.play_card(hero, card) elif args[0] == 'discard': card = args[1].lower() await self.discard_card(hero, card) elif args[0] == 'draw': await self.draw_card(hero) else: raise Complaint(Message('error', 'invalidcommand')) # TODO: Add hero abilities else: raise Complaint(Message('error', 'invalidcommand')) # break out when all enemies isded if self.gamestate.door_deck.is_defeated: await self.emit(Message('state', 'won')) except (Complaint, Exception) as e: if isinstance(e, Complaint): await self.emit(e.msg) else: await self.emit(Message('error', str(e)))
def add(self, dict): with Db.get() as self._db: dict["date"] = datetime.now() message = Message.add(self._db, dict) self._db.commit() self._db.refresh(message) return message
def send_message(): """ Sends message to user :param sent_by :param sent_to :param message_body :param from_admin :return: """ sent_by = request.form.get('sent_by') sent_to = request.form.get('sent_to') message_body = request.form.get('message_body') from_admin = True if request.form.get('from_admin') == 'True' else False listing_id = request.form.get('listing_id') new_message = Message(sent_by=sent_by, sent_to=sent_to, message_body=message_body, from_admin=from_admin, timestamp=datetime.datetime.now(), listing_id=listing_id) db.session.add(new_message) db.session.commit() return jsonify({ 'message_id': new_message.message_id, 'timestamp': new_message.timestamp })
def register(): request.get_json(force=True) request_json = request.json name = escape(request_json.get('name')) email = request_json.get('email') message = escape(request_json.get('message')) try: new_message = Message(name=name, email=email, message=message) db.session.add(new_message) db.session.commit() message_mail = MessageMail( 'Portfolio Contato', recipients=[os.environ.get('EMAIL_TO')], body=message, ) mail.send(message_mail) data = {'status': 'success'} except Exception as error: return {'error': str(error)}, 500 return jsonify(data), 201
def _msg_data(self, msg): """ 统一返回格式 - 带上 comment, item """ data = Message._msg_data(msg) if data['link_id']: topic = Topic.get(data['link_id']) topic = Topic._topic_data(topic) data['topic'] = topic tmp_user = model.user.get_user(user_id=topic['user_id']) # 消息来源用户 if not tmp_user: return None data['topic_user'] = { 'id': tmp_user['id'], 'nick': tmp_user['nick'], 'portrait': tmp_user['portrait'], 'type': tmp_user['user_type'], } if tmp_user else {} if data['from_uid']: tmp_user = model.user.get_user(user_id=data['from_uid']) # 消息来源用户 if not tmp_user: return None data['from_user'] = { 'id': tmp_user['id'], 'nick': tmp_user['nick'], 'portrait': tmp_user['portrait'], 'type': tmp_user['user_type'], } if tmp_user else {} data['class'] = 'message' return data
def new_slack_msg(self): rtm_client = self.slack_helper.create_rtm_client() if rtm_client.rtm_connect(): while True: try: rtv = rtm_client.rtm_read() if len(rtv) != 0: logger.debug(rtv[0]) if not rtv[0].get('subtype') and rtv[0].get( 'type') == 'message': # compose a message gid = rtv[0].get('channel') content = rtv[0].get('text') dest, type = self.get_src_id_and_type_from_sessions( gid) if dest is False: logger.warn('dest is false ' + str(gid)) message = Message(type, gid, None, dest, content) self.mq_pub( json.loads( json.dumps(message, default=lambda o: o.__dict__))) time.sleep(1) except Exception as e: logger.warn(e) rtm_client.rtm_connect() else: logger.error('rtm_client cant connect')
async def discard_card(self, hero, card): """ Move the given card to the discard pile. """ self.log.info(f'discard_card({hero=}, {card=})') hero.discard(card) await self.emit(Message('discard', [hero, card]))
def create_msg(self, msg_type, user, item): #建立消息 to_uid = item['user_id'] uid = user['_id'] if uid == to_uid: #如果赞的是自己 不存消息 return {} if msg_type == 'TL': m_type = "心得" content = user['nick'] + "赞了你的"+m_type + " \"%s\""%item['content'] if msg_type == 'CL': m_type = "评论" if item['c_type'] == 'audio': content = user['nick'] + "赞了你的语音"+m_type else: content = user['nick'] + "赞了你的"+m_type + " \"%s\""%item['content'] msg = Message.set_message(to_uid, msg_type, uid, content, item['topic_id']) msg = Message._msg_data(msg) return msg
async def draw_card(self, hero): """ Make the given hero draw a card. """ self.log.info(f'draw_card({hero=})') card = hero.draw_card() await self.emit(Message('draw', [hero, card]))
def _msg_number(self, user_id): """ 获取用户未读消息数量 """ #return str(Message.unread_num(user_id=user_id)) return { 'class': 'number', 'number': Message.unread_num(user_id=user_id) }
def load_messages(): company_id = request.args.get('company_id') print(company_id) company_chat = Message.load_messages_for(company_id) print(company_chat) return jsonify(company_chat)
def __parse_plain_message_block( blockchain_message_block: BlockchainMessageBlock, timestamp: int, compression_algorithm: CompressionAlgorithm, encoding: Encoding) -> Message: public_key_algorithm = Constants.PUBLIC_KEY_ALGORITHM() message_block_as_bytes = blockchain_message_block.data byte_index = Constants.FLAGS_LENGTH signature_length = public_key_algorithm.signature_length() signature = message_block_as_bytes[byte_index:byte_index + signature_length] byte_index += signature_length message_content = message_block_as_bytes[:Constants. FLAGS_LENGTH] # flags message_content += message_block_as_bytes[byte_index:] compressed_data = message_block_as_bytes[byte_index:] decompressed_data = Compressor.decompress( algorithm=compression_algorithm, data=compressed_data) byte_index = 0 message_type_bytes = decompressed_data[byte_index:byte_index + Constants.MESSAGE_TYPE_LENGTH] byte_index += Constants.MESSAGE_TYPE_LENGTH message_type_value = struct.unpack('!B', message_type_bytes)[0] message_type = MessageType(message_type_value) public_key_length = public_key_algorithm.get_public_key_class( ).key_length() sender_bytes = decompressed_data[byte_index:byte_index + public_key_length] byte_index += public_key_length sender = public_key_algorithm.get_public_key_class().parse( sender_bytes) nonce_timestamp = GeneralUtils.decode_unix_timestamp( decompressed_data[byte_index:byte_index + Constants.TIMESTAMP_LENGTH]) byte_index += Constants.TIMESTAMP_LENGTH message_bytes = decompressed_data[byte_index:] encoding_str = Encoding.get_str(encoding) message = message_bytes.decode(encoding_str) MessageBlockParser.__check_signature(message=message_content, public_key=sender, signature=signature) return Message(block_hash=blockchain_message_block.block_hash, sender=sender, message_type=message_type, message=message, timestamp=timestamp, nonce_timestamp=nonce_timestamp)
def send_message(data): app.logger.info('received message: %s', data) messages = Message.find_all() app.logger.info('received message: %s', messages) mess = [] for message in messages: mess.append(message.json()) app.logger.info(jsonify(mess)) emit('send_message', mess)
def test_clean(self): peer1 = ConversationPeer( peer=User(user_key=UserPK(user_id='stub', platform=UserPK.PLATFORM_TELEGRAM), username='******'), assigned_profile=PersonProfile(sentences=['stub profile'])) peer2 = ConversationPeer( peer=Bot(token='stub', bot_name='Dummy'), assigned_profile=PersonProfile(sentences=['stub profile 2'])) peers = [peer1, peer2] for p in peers: p.peer.save(cascade=True) p.assigned_profile.save(cascade=True) n_msg = 10 start_time = datetime.now() end_time = start_time + timedelta(hours=n_msg - 1) msgs = list( map( lambda x: Message(msg_id=x, text=str(x), sender=peers[x % 2].peer, time=start_time + timedelta(hours=x)), range(10))) test_conv = Conversation(conversation_id=1) test_conv.participant1 = peers[0] test_conv.participant2 = peers[1] with self.assertRaises(mongoengine.ValidationError): test_conv.save() test_conv.participant1 = None test_conv.participant2 = None test_conv.messages = msgs with self.assertRaises(mongoengine.ValidationError): test_conv.save() test_conv.participant1 = peers[0] test_conv.participant2 = peers[1] raised = False error_msg = '' try: test_conv.save() except Exception as e: raised = True error_msg = 'Unexpected exception: {}'.format(e) self.assertFalse(raised, error_msg) self.assertEqual(test_conv.start_time, start_time) self.assertEqual(test_conv.end_time, end_time)
def load_message(self, messagelist): message = Message() message.send = messagelist[0] message.text = messagelist[1] message.timestamp = messagelist[2] message.uuid = messagelist[3] message.seq = messagelist[4] return message
def read_block(path): __block = [] for filename in listdir(path): with open(join(path, filename)) as f: lines = f.readlines() __subject = np.array(map(int, lines[0].strip().split(' ')[1:])) __text = np.array(map(int, lines[2].strip().split(' '))) __type = __message_type_from_filename(filename) __block.append(Message(__subject, __text, __type)) return __block
def post(self, **kwargs): """ 接口: 1. 标记消息为已读-read 2. 设置系统消息-sys """ type = kwargs.get('type') msg_id = kwargs.get('msg_id') # self.write({'read msg_id':msg_id}) # return if type == 'read' and msg_id: result = Message.mark_read(user_id=kwargs['uid'], msg_id=msg_id) elif type == 'sys' and (kwargs['uid'] == 'admin' or configs['test_mode']): # todo 系统用户才能设置系统消息 data = json_decode(self.request.body) content = data.get('content') if content: result = Message.set_message(type=Message._type_sys, content=content) else: raise HTTPError(404, 'not support post method or user not support') self.write(result.dictify()) self.set_status(201)
def on_pubmsg(self, conn, event): """ archive public message """ session = self.sessionmaker() message = Message(user=event.source.split("!")[0], message=event.arguments[0].strip()) session.add(message) session.commit() print(event.type, event.source, event.target, event.arguments)
def discard(self, card): """ Method to remove a card from the hero's hand """ # Checks if the card is held by the hero if self.get_card_from_hand(card): # If it is a valid card to remove, remove it self.hand.remove(card) else: raise Complaint(Message('error', 'nocard'))
def twil(): client = TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN) from_ = request.form.get("From", WEI_HAN) body = request.form.get("Body", default="") picture = request.form.get("MediaUrl{1}", default="") message_id = request.form.get("MessageSid", default="") log = "IN: MessageSid = {}, From = {}, Body = {}".format(message_id, from_, body) logging.info(log) message = Message(From=from_, To=SERVER_NUMBER, Body=body, id=message_id) message.put() ''' Pass message into action builder.''' response_list = [] try: response_list = CommandHandler.handler(message) except (CommandError, DbError, TeamError, MeError, TargetError, TimeError,\ ReplyError) as message: logging.exception("Error {}".format(message.message)) response_num_list = [from_] response = "[ERR] {}".format(message.message) response_list = [(response_num_list, response)] except: logging.exception("Unknown Error") response_num_list = [from_] response = "[ERR] Unknown Error" response_list = [(response_num_list, response)] for response_num_list, response in response_list: for response_number in response_num_list: logging.info("Making message {} for {} with num_list {}".format(response, response_number, response_num_list)) '''Make message''' outgoing_message = Message(From=SERVER_NUMBER, To=response_number, Body=response) outgoing_message.put() logging.info(response) '''Send message''' client.messages.create( to=response_number, from_=SERVER_NUMBER, body=response) logging.info(response) return "Welcome to SAMSU assassins. The site is up and working.\
def _delete_all(self, user_id): """删除用户所有未读信息 """ n = Message.delete_all(user_id=user_id) if n ==0: status = 1 else: status = 0 return { 'class': 'delete', 'status': status }
def send(self, acquisitions): self.acquisitions = acquisitions if self.client is None: self.client = MQTTClient() self.client.connect_mqtt() if self.encryption is None: self.encryption = Encryption() for acquisition in acquisitions: message = Message(acquisition) jsonMessage = self.JSONConverter(message) self.client.publish(self.encryption.encrypt(jsonMessage))
def disarm_worker(): ''' Get disarm id''' req_key = request.form.get("id", "") disarm = Disarm.get_by_id(int(req_key)) ''' No disarm found ''' if not disarm: logging.error("DISARM worker: no DISARM found") raise Exception() '''Disarm deprecated''' if disarm.deprecated: logging.info("DISARM Worker: Disarm deprecated. No action.") return "DISARM Worker: deprecated" client = TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN) disarmed_player = Player.get_by_id(disarm.victim) disarmed_player.disarm = False disarmed_player.put() disarm.deprecated = True disarm.put() logging.info("DISARM Worker: Turning off disarmed state for {}".format(\ disarm.victim)) response = "You are no longer DISARMED. Go ahead and kill people." msg = Message(From=SERVER_NUMBER, To=disarm.victim, Body=response) msg.put() client.messages.create( to=disarm.victim, from_=SERVER_NUMBER, body=response) return "DISARM WORKER"
def _get_msgs(self, user_id, type, page=0): """ 获取用户的未读消息 """ page = int(page) if page is not None else page msgs = Message.get_message(user_id=user_id, type=type, page=page) datas = [] for m in msgs: data = self._msg_data(m) if data: datas.append(data) return { 'class': 'message', 'msgs': datas, 'type': type, 'next_page': str(page+1) }
def index(): client = TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN) if request.method == 'POST': ''' Parse request store as message ''' message = Message(From=request.form["From"], To=request.form["To"], Body=request.form["Body"], Picture=request.form["Picture"], id=request.form["MessageSid"]) message.put() ''' Pass message into action builder.''' try: ab = ActionBuilder(message) action_key, action = ab.make_action() rb = ResponseBuilder(action_key, action) response_num_list, response = rb.build_response() except ActionError as message: response_num_list = [action.attacker] response = "[ERR] {}".format(message) except: response_num_list = [action.attacker] response = "[ERR] Unknown Error" for response_number in response_num_list: '''Make message''' outgoing_message = Message(From=SERVER_NUMBER, To=response_number, Body=response) outgoing_message.put() '''Send message''' client.messages.create( to=response_number, from_=SERVER_NUMBER, body=response) return "Samsu Assassins Running!"
def post(self, **kwargs): """ 新建一个评论 需要用户登录 """ token = self._get_token() uid = token['_id'] user = hqby.user.get_user_info(uid=uid) if not user: raise HTTPError(403, 'can not found this user') try: params = json_decode(self.request.body) except ValueError: params = self.get_form() comment_type = params.get('comment_type', False) self.check_comment_type(comment_type) self.check_topic(params['topic_id']) params['user_id'] = uid # 添加一个新的评论 comm = self.create_comment(params,comment_type) # self.write('haha = %s'%comm) #return data = self._comment_data(comm) data['is_liked'] = 0 topic = Topic.update_topic(data['topic_id'],False,True) topic_data = Topic._topic_data(topic) if data['to_user_id']: to_uid = data['to_user_id'] msg_type = 'CC' content = user['nick'] + '回复了你的评论 ' else: to_uid = topic_data['user_id'] msg_type = 'TC' content = user['nick'] + "评论了你的心得 " + " \"%s\""%topic_data['content'] if uid != to_uid: msg = Message.set_message(to_uid, msg_type, uid, content, topic_data['topic_id']) #link_id 是topic的id msg = Message._msg_data(msg) else: msg = 'you reply yourself' #给被回复者发送通知 baidu_apiKey = baidu_push_configs['apiKey'] baidu_secretKey = baidu_push_configs['secretKey'] bind_info = hqby.user.get_bind_info(to_uid) baidu_uid, baidu_cid = bind_info.get('baidu_uid'), bind_info.get('baidu_cid') if baidu_uid and baidu_cid and uid != to_uid: message = { 'title': '读经', 'description': '%s回复了你,快去看看吧' % user['nick'].encode('utf8'), 'open_type': 2, "aps": { "alert": '%s回复了你,快去看看吧' % user['nick'].encode('utf8'), "sound":"", "badge":0 }, } message = json.dumps(message) message_key = "sys" c = Channel(baidu_apiKey, baidu_secretKey, arr_curlOpts=dict(TIMEOUT=3, CONNECTTIMEOUT=5)) push_type = 1 # 1-单个人, 2-一群人, 3-全部人 optional = dict() optional[Channel.USER_ID] = baidu_uid optional[Channel.CHANNEL_ID] = int(baidu_cid) optional[Channel.MESSAGE_TYPE] = 1 # 0-消息, 1-通知 optional['device_types'] = [3, 4] # 4-ios, 3-安卓, 5-wp设备, 2-pc, 1-浏览器 optional['deploy_status'] = 1 if configs['debug'] else 2 # 1-开发, 2-生产 #job = c.pushMessage(push_type, message, message_key, optional) job = rq_client.default_queue.enqueue(c.pushMessage, push_type, message, message_key, optional) #logging.info('log for baidu pusher: %s', str(job)) self.write({'comment':data,'topic':topic_data,'msg':msg}) self.set_status(200) self.set_header('Content-Type', self._ct('json'))
def invul_worker(): ''' Get invul id''' req_key = request.form.get("id", "") inv = Invul.get_by_id(int(req_key)) ''' No Inv found ''' if not inv: logging.error("INV worker: no INV found") raise Exception() '''Inv deprecated''' if inv.deprecated: logging.info("INV Worker: Inv deprecated. No action.") return "INVUL Worker: Deprecated" client = TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN) '''Target dead. Report back to medic''' logging.info(inv) target_num = inv.target logging.info(target_num) target = Player.get_by_id(target_num) medic = Player.get_by_id(inv.medic) logging.info(medic) if not target: logging.error("INV worker: cannot find target {}".format(target_num)) return if target.state == "DEAD": logging.error("INV worker: Target {} has died. Cannot grant INVUL".format(target.codename)) response = "Your INVUL target has died. Cannot grant dead people INVUL." msg = Message(From=SERVER_NUMBER, To=inv.medic, Body=response) msg.put() client.messages.create( to=inv.medic, from_=SERVER_NUMBER, body=response) return "INVUL Worker" '''Target alive. If INVUL not yet in effect, trigger''' if not inv.in_effect: logging.info("INVUL worker: Triggering 8 hour INVUL for target {} at {}".format(target.codename, datetime.now())) inv.in_effect = True inv_key = inv.put() task = taskqueue.Task(url="/invul", params={"id": inv_key.id()}, eta=inv.end_time) task.add(queue_name="invul") logging.info("Task queue okay") logging.info(target) target.invul = True target.put() logging.info("target set okay") logging.info(medic) medic.can_set_after = Util.next_day() medic.put() logging.info("medic set okay") response = "You have been granted INVUL for 8 hour from {} to {}".\ format(Util.utc_to_chi(inv.start_time).strftime("%m-%d %I:%M%p"),\ Util.utc_to_chi(inv.end_time).strftime("%m-%d %I:%M%p")) msg = Message(From=SERVER_NUMBER, To=inv.target, Body=response) msg.put() client.messages.create( to=inv.target, from_=SERVER_NUMBER, body=response) logging.info("message set okay") return "INVUL Worker" else: logging.info("INVUL worker: END 8 hour INVUL for target {} at {}".format(target.codename, datetime.now())) inv.deprecated = True inv.put() target.invul = False target.put() response = "Your INVUL period has ended. You are no longer INVUL." msg = Message(From=SERVER_NUMBER, To=inv.target, Body=response) msg.put() client.messages.create( to=inv.target, from_=SERVER_NUMBER, body=response) return "INVUL Worker"
def bomb_worker(): ''' Get bomb id ''' req_key = request.form.get('id', "") bomb = Bomb.get_by_id(int(req_key)) ''' ERROR: no bomb found by id ''' if not bomb: logging.error("BOMB Worker: No bomb found by key {}".format(req_key)) raise Exception() ''' Bomb deprecated no action ''' if bomb.deprecated: logging.info("BOMB Worker: Bomb with key {} deprecated. No explosion".format(req_key)) return "BOMB Worker: Deprecated Bomb" ''' Trigger bomb ''' logging.info("BOMB: triggered at {} UTC {} Chicago".format( datetime.now(), Util.utc_to_chi(datetime.now().replace(tzinfo=pytz.utc)))) client = TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN) attacker = Player.get_by_id(bomb.attacker) attacker.can_set_after = Util.next_day() attacker.put() bomb.trigger = True bomb_key = bomb.put() action = Action() action.attacker = bomb.attacker action.action = "BOMB" action.victim = "*" action.datetime = datetime.now() action.place = bomb.place action_key = action.put() response_num_list = [key.id() for key in Player.query(ndb.AND(Player.state=="ALIVE",\ Player.invul==False) ).fetch(keys_only=True)] response = "{} has been bombed at {}. If you were there, [REPLY {}] Y.".format( action.place, Util.utc_to_chi(action.datetime).strftime("%m-%d %I:%M%p"), action_key.id()) for response_number in response_num_list: logging.info("Making message {} for {} with num_list {}".format( response, response_number, response_num_list)) '''Make message''' outgoing_message = Message(From=SERVER_NUMBER, To=response_number, Body=response) outgoing_message.put() '''Send message''' client.messages.create( to=response_number, from_=SERVER_NUMBER, body=response) return "Bomb triggered at {}".format(bomb.place)