def reply_message(self): """ 回复消息,对应于最新一条消息的回复 需要的参数包括:parent_message_id (被回复的消息ID) , item_id 或是 recipient_id , body :return: """ channel_id = self.params.get("channel_id", "") body = self.params.get("body", "") with sessionCM() as session: channel = Channel.find_by_id(session, channel_id) ticket_id = channel.origin_id handler = WishTicket(self.shop) result = handler.reply_ticket_by_id(ticket_id, body) print "回复 Ticket ID 为 %s " % channel_id print result if result.get("success", ""): # 是否同步消息 sync_handler = SyncWishCustomer(self.shop) sync_handler.execute(ticket_id=ticket_id) return {"status": 1, "message": "回复消息成功!"} else: return { "status": 0, "message": "回复消息失败!", "errors": result.get("message", "") }
def update_channel_flag(self): """ 更新 channel 的标签 参数:channel_id --> channel 的本地Id rank --> 标志 取值 rank0,rank1,rank2,rank3,rank4,rank5 (白,红,橙,绿,蓝,紫) :return: """ channel_id = self.params.get("channel_id", "") rank = self.params.get("rank", "") with sessionCM() as session: channel = Channel.find_by_id(session, channel_id) if not channel: return {"status": 0, "message": "\"channel_id\"不存在!"} if rank not in ["rank0", "rank1", "rank2", "rank3", "rank4", "rank5"]: return {"status": 0, "message": "\"rank\"参数的值不在合法值列表中"} try: with sessionCM() as session: Channel.update(session, channel, {"flag": rank}) return {"status": 1, "message": "为channel %s 打上了 %s 标签!" % (str(channel_id), str(rank))} except Exception, e: logger.error(traceback.format_exc(e)) return {"status": 0, "message": "打标签失败"}
def update_channel_state(self): """ 更新 channel 的处理状态 (已处理、未处理) 参数:channel_id --> channel 的本地Id state --> 状态 0表示未处理、 1表示已处理 :return: """ channel_id = self.params.get("channel_id", "") state = self.params.get("state", "") with sessionCM() as session: channel = Channel.find_by_id(session, channel_id) if not channel: return {"status": 0, "message": "\"channel id\"不存在!"} if state not in ["1", "0"]: return {"status": 0, "message": "\"state\"值只能是字符串0或1!"} try: with sessionCM() as session: Channel.update(session, channel, {"deal_stat", int(state)}) return {"status": 1, "message": "状态更新成功!"} except Exception, e: logger.error(traceback.format_exc(e)) return {"status": 0, "message": "状态更新失败!"}
def reply_message(self): """ 回复消息,对应于最新一条消息的回复 需要的参数包括:parent_message_id (被回复的消息ID) , item_id 或是 recipient_id , body :return: """ parent_message_id = self.params.get("parent_message_id", "") channel_id = self.params.get("channel_id", "") # recipient_id = self.params.get("recipient_id", "") body = self.params.get("body", "") with sessionCM() as session: channel = Channel.find_by_id(session, channel_id) if not channel: return {"status": 0, "message": "无效的channel_id!"} handler = EbayMessage(self.shop.site_id, self.shop.account) result = handler.add_message_rtq( parent_message_id=parent_message_id, item_id=channel.relation_id, recipient_id=channel.buyer_id, body=body ) print parent_message_id, channel.relation_id, channel.buyer_id, body print result if result.get("Ack", "") == "Success": # 同步消息 with sessionCM() as session: Message.create( session, channel_id=channel.id, origin_id='async', content=body, image_urls="", receive_time=datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"), source='seller', external_message_id='' ) return {"status": 1, "message": "回复消息成功!"} else: return {"status": 0, "message": "回复消息失败!", "errors": result.get("Errors", "")}
def sync_message_detail(self, channel_id, **kwargs): # 第三步获取Message的详细信息 # 首先删除此管道中已经发送的消息, 查询参数:channel_id original_id=async message_ids = kwargs["message_ids"] result = self.msg_handler.get_my_messages("ReturnMessages", message_ids=message_ids) txt_pattern = re.compile('<div id="UserInputtedText">([\s\S]+?)</div>') pic_pattern = re.compile('<img id="previewimage\d+".+?src="(.+?)">') href_pattern = re.compile('(<a[^>]+?)>') with sessionCM() as session: channel = Channel.find_by_id(session, channel_id) # 清除‘异步消息’ session.query(Message).filter(and_(Message.channel_id == channel.id, Message.origin_id == 'async')).delete() message_list = result["Messages"]["Message"] if not isinstance(message_list, list): message_list = [message_list] for message in message_list: # if Message.find_by_origin_id(session, message["MessageID"]): # continue if message["Sender"] == "eBay": href_rs = href_pattern.findall(message["Text"]) for href in href_rs: message["Text"] = message["Text"].replace(href, href + ' target="_blank"') print "创建 Ebay Message ..." Message.create( session, channel_id=channel_id, origin_id=message["MessageID"], image_urls="", content=message["Text"], source="ebay", external_message_id="", receive_time=message["ReceiveDate"].rsplit(".", 1)[0], ) print "创建 Ebay Message 完成!" else: txt_rs = txt_pattern.findall(message["Text"]) content = txt_rs[0] if txt_rs else "" pic_rs = pic_pattern.findall(message["Text"]) print "创建普通消息 ..." Message.create( session, channel_id=channel_id, origin_id=message["MessageID"], image_urls=";".join(pic_rs), content=content, receive_time=message["ReceiveDate"].rsplit(".", 1)[0], external_message_id=message.get("ExternalMessageID", ""), source="seller" if message["Sender"] == channel.seller_id else "buyer" ) print "创建普通消息完成!" if message["MessageID"] == channel.last_msg_id: # ?? Channel.update(session, channel, last_msg_content=content)
def batch_reply_message(self): """ 批量回复消息 :return: """ channel_ids = json.loads(self.params.get("channel_ids", "[]")) content = self.params.get("content") if not content: return {"status": 0, "message": "内容为空!"} total = len(channel_ids) success, failure = list(), list() handler = AliMessage(self.shop) with sessionCM() as session: for channel_id in channel_ids: channel = Channel.find_by_id(session, channel_id) if not channel: failure.append(channel_id) continue result = handler.add_msg(channel_id=channel.origin_id, buyer_id=channel.buyer_id, content=content, msg_sources=channel.msg_source) if result.get("isSuccess", ""): success.append(channel_id) else: failure.append(channel_id) if len(success) == total: return {"status": 1, "message": "批量回复消息完成!"} else: return { "status": 0, "message": "部分回复消息成功!", "success": success, "failure": failure }
def update_channel_read(self): """ 更新通道为已读状态 参数 channel_id --> channel 的本地ID msgSource --> 消息类型 可选参数(message_center/order_msg) :return: """ channel_id = self.params.get("channel_id", "") with sessionCM() as session: channel = Channel.find_by_id(session, channel_id) if not channel: return {"status": 0, "data": "\"channel_id\"不存在!"} try: with sessionCM() as session: Channel.update(session, channel, {"read_stat", 1}) return {"status": 1, "data": "状态更新成功!"} except Exception, e: logger.error(traceback.format_exc(e)) return {"status": 0, "data": "状态更新失败!"}
def close_ticket(self): """ 关闭 ticket :return: """ ticket_id = self.params.get("channel_id", "") if not ticket_id: return {"status": 0, "message": "缺少channel_id!"} handler = WishTicket(self.shop) with sessionCM() as session: ticket = Channel.find_by_id(session, ticket_id) if not ticket: return {"status": 0, "message": "无效的channel_id!"} result = handler.close_ticket_by_id(ticket["origin_id"]) if result.get("success", ""): Channel.update(session, channel=ticket, closed_by="buyer") return {"status": 1, "message": "已关闭!"} else: return {"status": 0, "message": result.get("message", "关闭失败!")}
def sync_message_detail(self, channel_id, msg_source, current_page=1, page_size=100): """ 同步订单留言 :return: """ with sessionCM() as session: channel = Channel.find_by_id(session, channel_id) # if channel: # print "通道id为%d, buyer_name: %s " % (channel.id, channel.buyer_name) additional_flag = False while True: print current_page result = self.msg_handler.get_msg_detail_list( channel.origin_id, msg_source, current_page, page_size) print json.dumps(result, indent=2, encoding='utf8') # raw_input("enter ... ") if not result["success"]: return result["exception"] current_page += 1 for message in result.get("result", []): old_msg = Message.find_by_origin_id(session, message["id"]) if old_msg: continue print "创建新消息..." Message.create( session, channel_id=channel_id, origin_id=message["id"], content=message["content"], image_urls=";".join( [im["sPath"] for im in message["filePath"]]), receive_time=time.strftime( "%Y-%m-%d %H:%M:%S", time.localtime(long( str(message["gmtCreate"])[:-3]))), source="seller" if message["summary"]["senderName"] == channel.seller_name else "buyer", external_message_id="") print "创建消息完成 !" if additional_flag: continue print "设置关联关系..." if not channel.relation_type or not channel.relation_id: print "更新通道..." Channel.update(session, channel, shop_id=self.shop.id, relation_type=message["messageType"], relation_id=message["typeId"]) print "创建Attachment..." Attachment.create( session, channel_id=channel_id, name=message["summary"]["productName"], image_url=message["summary"]["productImageUrl"], product_url=message.get("productDetailUrl", ""), # ??? order_url=message["summary"]["orderUrl"], product_id="", order_id="") channel.update(session, channel, **{}) additional_flag = True print "设置关联完成..." if len(result["result"]) == 0: break