def get_screenshots(driver): try: screenshots_path = os.path.join(parentDirPath, 'logs\\screenshots') # 如果不存在这个screenshots文件夹,就自动创建一个 if os.path.exists(screenshots_path) and os.path.isdir( screenshots_path): pass else: os.mkdir(screenshots_path) # 文件的命名 now = int(time.time()) # 显示为时间戳 time_array = time.localtime(now) current_time = time.strftime("%Y%m%d%H%M%S", time_array) screenshots_name = os.path.join(screenshots_path, 'error_%s.png' % current_time) driver.get_screenshot_as_file(screenshots_name) Log.info("截图保存路径:%s" % screenshots_name) except Exception as e: Log.error("截图失败:%s" % e)
class Email: def __init__(self, server, sender, password, receiver, title, message=None, path=None): """初始化Email :param title: 邮件标题,必填。 :param message: 邮件正文,非必填。 :param path: 附件路径,可传入list(多附件)或str(单个附件),非必填。 :param server: smtp服务器,必填。 :param sender: 发件人,必填。 :param password: 发件人密码,必填。 :param receiver: 收件人,多收件人用“;”隔开,必填。 """ self.title = title self.message = message self.files = path self.msg = MIMEMultipart('related') self.server = server self.sender = sender self.receiver = receiver self.password = password self.log = Log() def _attach_file(self, att_file): """将单个文件添加到附件列表中""" att = MIMEText(open('%s' % att_file, 'rb').read(), 'plain', 'utf-8') att["Content-Type"] = 'application/octet-stream' file_name = re.split(r'[\\|/]', att_file) att["Content-Disposition"] = 'attachment; filename="%s"' % file_name[-1] self.msg.attach(att) self.log.info('attach file {}'.format(att_file)) def send(self): self.msg['Subject'] = self.title self.msg['From'] = self.sender self.msg['To'] = self.receiver # 邮件正文 if self.message: self.msg.attach(MIMEText(self.message)) # 添加附件,支持多个附件(传入list),或者单个附件(传入str) if self.files: if isinstance(self.files, list): for f in self.files: self._attach_file(f) elif isinstance(self.files, str): self._attach_file(self.files) # 连接服务器并发送 try: smtp_server = smtplib.SMTP(self.server) # 连接sever except (gaierror and error) as e: self.log.error(f'发送邮件失败,无法连接到SMTP服务器,检查网络以及SMTP服务器. {e}') else: try: smtp_server.login(self.sender, self.password) # 登录 except smtplib.SMTPAuthenticationError as e: self.log.error(f'用户名密码验证失败!{e}') else: smtp_server.sendmail(self.sender, self.receiver.split(';'), self.msg.as_string()) # 发送邮件 self.log.info( f'发送邮件"{self.title}"成功! 收件人:{self.receiver}。如果没有收到邮件,请检查垃圾箱,同时检查收件人地址是否正确' ) finally: smtp_server.quit() # 断开连接
if result is False: log.info('JSON格式校验失败!') log.debug('预期结果是%s'%expected_data_dict) log.debug('实际结果是:%s'%res_data) log.debug('预期类型是%s'%type(expected_data_dict)) log.debug('实际类型是%s' % type(res_data)) return False else: log.info('JSON格式校验成功!') log.debug('预期结果是%s' % expected_data_dict) log.debug('实际结果是:%s' % res_data) log.debug('预期类型是%s' % type(expected_data_dict)) log.debug('实际类型是%s' % type(res_data)) return True else: log.info("HTTP返回状态码%s与预期%s不一致" % (str(code), str(case['ExpectedCode']))) return False else: log.error('校验类型不存在!') if __name__ == '__main__': case_data ={'CaseId': 6, 'CaseName': 'approve_allocation_bill', 'APIName': '审批调拨订单', 'Headers': {'Content-Type': 'application/json', 'charset': 'UTF-8'}, 'Path': '/occ-stock/stock/allocation-bill/approveWithoutBpm', 'Method': 'post', 'ParameterType': 'parameter', 'Params': {'billId': 'allocation-create-and-submit2'}, 'CheckType': 'check_json', 'ExpectedCode': 200, 'ExpectedData': {'success': 'success', 'message': '审批通过成功', 'detailMsg': {'data': [{'id': '0xtxaRhbIHPaZOkUgTlO', 'dr': 0, 'ts': 1589447391772, 'creator': 'smq', 'creationTime': 1589447386000, 'modifier': 'smq', 'modifiedTime': 1589447391772, 'persistStatus': 'upd', 'promptMessage': None, 'state': 3, 'approver': 'smq', 'approveTime': 1589447391772, 'approveOpinion': None, 'sycnNCStatus': None, 'sycnOutStatus': None, 'pkOrgId': 'abd7cf79-511d-4307-9bbd-d288b18d0ef9', 'pkOrgCode': '1210', 'pkOrgName': '西安喜马拉雅网络科技有限公司', 'pkOrgInId': 'abd7cf79-511d-4307-9bbd-d288b18d0ef9', 'pkOrgInCode': '1210', 'pkOrgInName': '西安喜马拉雅网络科技有限公司', 'code': 'DBO20200514000037', 'billDate': 1589212800000, 'billType': 'Allocation', 'billTranTypeId': 'Allocation', 'billTranTypeCode': 'Allocation', 'billTranTypeName': '调拨单', 'outStorageId': '1001ZZ100000000DPAP4', 'outStorageCode': 'test030201', 'outStorageName': '测试仓库030201', 'outIfSlotManage': 0, 'inStorageId': '1001ZZ100000000DPAP6', 'inStorageCode': 'test030202', 'inStorageName': 'test030202', 'inIfSlotManage': 0, 'outBizPersonId': None, 'outBizPersonCode': None, 'outBizPersonName': None, 'inBizPersonId': '0mWG6nOSCxjsi1zoKEYs', 'inBizPersonCode': '007', 'inBizPersonName': '师孟奇', 'outDeptId': '0K1ovYvAl1Pk00oCRPjV', 'outDeptCode': '01010102', 'outDeptName': '城市经理', 'inDeptId': None, 'inDeptCode': None, 'inDeptName': None, 'planSendDate': None, 'planArriveDate': None, 'currencyId': 'CURRENCY-01', 'currencyCode': 'RMB', 'currencyName': '人民币', 'totalFactOutNum': None, 'totalFactInNum': None, 'billStatusId': None, 'billStatusCode': None, 'billStatusName': None, 'transferStatusId': '0s21f51c-4d42-4100-dkd0-3254fbq33e6k', 'transferStatusCode': '2', 'transferStatusName': '已提交审批', 'stockBillBelong': None, 'customerId': None, 'customerName': None, 'customerCode': None, 'isClose': 0, 'closer': None, 'closeDate': None, 'closeReason': None, 'remark': '自动化测试新增调拨单', 'transferBillItems': [{'id': '0bf4cJbB8hoao89ctKzG', 'dr': 0, 'ts': 1589447389000, 'creator': 'smq', 'creationTime': 1589447389000, 'modifier': None, 'modifiedTime': None, 'persistStatus': 'nrm', 'promptMessage': None, 'rowNum': 10, 'transferBillId': '0xtxaRhbIHPaZOkUgTlO', 'goodsId': '03e77ae0-469d-4d8a-ba34-733c2ada3749', 'goodsCode': '301020000049', 'goodsName': '小雅AI音箱旗舰版_石墨绿', 'goodsFullName': None, 'goodsBasicUnitName': '个', 'goodsAssistUnitName': '个', 'goodsConversionRate': 1.0, 'enableBatchNumberManage': 0, 'productId': '996cc839-60e8-4500-82c6-9a7c7b95646d', 'productLineId': '13c512df-ad18-48e5-b75d-166a534cc410', 'isOptional': 0, 'unitId': 'UNIT-12', 'unitCode': 'EA', 'unitName': '个', 'transferNum': 30.0, 'onwayNum': None, 'totalOutNum': None, 'totalInNum': None, 'unitPrice': None, 'amountMoney': 0.0, 'remark': None, 'batchNumId': None, 'batchNumCode': None, 'batchNumName': None, 'goodsPositionId': None, 'goodsPositionCode': None, 'goodsPositionName': None, 'receiverAddress': None, 'provinceId': None, 'provinceCode': None, 'provinceName': None, 'cityId': None, 'cityCode': None, 'cityName': None, 'countyId': None, 'countyCode': None, 'countyName': None, 'townId': None, 'townCode': None, 'townName': None, 'detailAddr': None, 'receiver': None, 'receiverPhone': None, 'receiverPhoneSpare': None, 'isClose': 0, 'sourceId': None, 'sourceLineNum': None, 'sourceType': None, 'ext01': None, 'ext02': None, 'ext03': None, 'ext04': None, 'ext05': None, 'ext06': None, 'ext07': None, 'ext08': None, 'ext09': None, 'ext10': None, 'ext11': None, 'ext12': None, 'ext13': None, 'ext14': None, 'ext15': None, 'goodsVersion': '1', 'goodsSelection': None, 'isMotherPiece': None, 'customerId': None, 'customerCode': None, 'customerName': None, 'supplierId': None, 'supplierCode': None, 'supplierName': None, 'projectId': None, 'projectCode': None, 'projectName': None, 'batchCodeId': None, 'batchCodeCode': None, 'stockStateId': None, 'stockStateCode': None, 'stockStateName': None, 'enableBatchNoManage': 0, 'enableInvStatusManage': 0, 'originalGoodsId': None, 'goodsSelectionDescription': None, 'outStorageId': '1001ZZ100000000DPAP4', 'outStorageCode': 'test030201', 'outStorageName': '测试仓库030201', 'outIfSlotManage': 0, 'inStorageId': '1001ZZ100000000DPAP6', 'inStorageCode': 'test030202', 'inStorageName': 'test030202', 'inIfSlotManage': None, 'outPositionId': None, 'outPositionCode': None, 'outPositionName': None}], 'transferBillItemBoms': [{'id': '0wQlvLXAd3FT4TBew4gi', 'dr': 0, 'ts': 1589447389000, 'creator': 'smq', 'creationTime': 1589447389000, 'modifier': None, 'modifiedTime': None, 'persistStatus': 'nrm', 'promptMessage': None, 'rowNum': '10', 'goodsId': '03e77ae0-469d-4d8a-ba34-733c2ada3749', 'goodsCode': '301020000049', 'goodsName': '小雅AI音箱旗舰版_石墨绿', 'goodsFullName': None, 'goodsBasicUnitName': '个', 'goodsAssistUnitName': '个', 'goodsConversionRate': 1.0, 'enableBatchNumberManage': 0, 'productId': '996cc839-60e8-4500-82c6-9a7c7b95646d', 'productLineId': '13c512df-ad18-48e5-b75d-166a534cc410', 'unitId': 'UNIT-12', 'unitCode': 'EA', 'unitName': '个', 'transferNum': 30.0, 'onwayNum': None, 'totalOutNum': None, 'totalInNum': None, 'unitPrice': None, 'amountMoney': 0.0, 'remark': None, 'batchNumId': None, 'batchNumCode': None, 'batchNumName': None, 'goodsPositionId': None, 'goodsPositionCode': None, 'goodsPositionName': None, 'receiverAddress': None, 'provinceId': None, 'provinceCode': None, 'provinceName': None, 'cityId': None, 'cityCode': None, 'cityName': None, 'countyId': None, 'countyCode': None, 'countyName': None, 'townId': None, 'townCode': None, 'townName': None, 'detailAddr': None, 'receiver': None, 'receiverPhone': None, 'receiverPhoneSpare': None, 'isClose': 0, 'sourceId': None, 'sourceLineNum': None, 'sourceType': None, 'ext01': None, 'ext02': None, 'ext03': None, 'ext04': None, 'ext05': None, 'ext06': None, 'ext07': None, 'ext08': None, 'ext09': None, 'ext10': None, 'ext11': None, 'ext12': None, 'ext13': None, 'ext14': None, 'ext15': None, 'goodsVersion': '1', 'goodsSelection': None, 'customerId': None, 'customerCode': None, 'customerName': None, 'supplierId': None, 'supplierCode': None, 'supplierName': None, 'projectId': None, 'projectCode': None, 'projectName': None, 'batchCodeId': None, 'batchCodeCode': None, 'stockStateId': None, 'stockStateCode': None, 'stockStateName': None, 'originalGoodsId': None, 'goodsSelectionDescription': None, 'itemId': '0bf4cJbB8hoao89ctKzG', 'billId': '0xtxaRhbIHPaZOkUgTlO', 'parentGoodsId': '03e77ae0-469d-4d8a-ba34-733c2ada3749', 'parentGoodsCode': '301020000049', 'parentGoodsName': '小雅AI音箱旗舰版_石墨绿', 'parentGoodsdisplayName': None, 'parentRowNum': '10', 'childGoodsQty': None, 'firstBillBomCode': None, 'srcBillBomCode': None, 'outStorageId': '1001ZZ100000000DPAP4', 'outStorageCode': 'test030201', 'outStorageName': '测试仓库030201', 'outIfSlotManage': 0, 'inStorageId': '1001ZZ100000000DPAP6', 'inStorageCode': 'test030202', 'inStorageName': 'test030202', 'inIfSlotManage': None, 'outPositionId': None, 'outPositionCode': None, 'outPositionName': None}], 'ext01': None, 'ext02': None, 'ext03': None, 'ext04': None, 'ext05': None, 'ext06': None, 'ext07': None, 'ext08': None, 'ext09': None, 'ext10': None, 'ext11': None, 'ext12': None, 'ext13': None, 'ext14': None, 'ext15': None, 'isDistribution': None, 'isReturned': None}]}}, 'User': '******', 'DependCase': 'submit_allocation_bill', 'RelevanceList': {'billId': '$..id'}} code = 200 response = {'success': 'success', 'message': '审批通过成功', 'detailMsg': {'data': [{'id': '06MwWrq4k4UuyjQEJpAz', 'dr': 0, 'ts': 1589452159115, 'creator': 'smq', 'creationTime': 1589452152000, 'modifier': 'smq', 'modifiedTime': 1589452159115, 'persistStatus': 'upd', 'promptMessage': None, 'state': 3, 'approver': 'smq', 'approveTime': 1589452159115, 'approveOpinion': None, 'sycnNCStatus': None, 'sycnOutStatus': None, 'pkOrgId': 'abd7cf79-511d-4307-9bbd-d288b18d0ef9', 'pkOrgCode': '1210', 'pkOrgName': '西安喜马拉雅网络科技有限公司', 'pkOrgInId': 'abd7cf79-511d-4307-9bbd-d288b18d0ef9', 'pkOrgInCode': '1210', 'pkOrgInName': '西安喜马拉雅网络科技有限公司', 'code': 'DBO20200514000063', 'billDate': 1589212800000, 'billType': 'Allocation', 'billTranTypeId': 'Allocation', 'billTranTypeCode': 'Allocation', 'billTranTypeName': '调拨单', 'outStorageId': '1001ZZ100000000DPAP4', 'outStorageCode': 'test030201', 'outStorageName': '测试仓库030201', 'outIfSlotManage': 0, 'inStorageId': '1001ZZ100000000DPAP6', 'inStorageCode': 'test030202', 'inStorageName': 'test030202', 'inIfSlotManage': 0, 'outBizPersonId': None, 'outBizPersonCode': None, 'outBizPersonName': None, 'inBizPersonId': '0mWG6nOSCxjsi1zoKEYs', 'inBizPersonCode': '007', 'inBizPersonName': '师孟奇', 'outDeptId': '0K1ovYvAl1Pk00oCRPjV', 'outDeptCode': '01010102', 'outDeptName': '城市经理', 'inDeptId': None, 'inDeptCode': None, 'inDeptName': None, 'planSendDate': None, 'planArriveDate': None, 'currencyId': 'CURRENCY-01', 'currencyCode': 'RMB', 'currencyName': '人民币', 'totalFactOutNum': None, 'totalFactInNum': None, 'billStatusId': None, 'billStatusCode': None, 'billStatusName': None, 'transferStatusId': '0s21f51c-4d42-4100-dkd0-3254fbq33e6k', 'transferStatusCode': '2', 'transferStatusName': '已提交审批', 'stockBillBelong': None, 'customerId': None, 'customerName': None, 'customerCode': None, 'isClose': 0, 'closer': None, 'closeDate': None, 'closeReason': None, 'remark': '自动化测试新增调拨单', 'transferBillItems': [{'id': '0GwdQA5KNiXMMRPCSv59', 'dr': 0, 'ts': 1589452156000, 'creator': 'smq', 'creationTime': 1589452156000, 'modifier': None, 'modifiedTime': None, 'persistStatus': 'nrm', 'promptMessage': None, 'rowNum': 10, 'transferBillId': '06MwWrq4k4UuyjQEJpAz', 'goodsId': '03e77ae0-469d-4d8a-ba34-733c2ada3749', 'goodsCode': '301020000049', 'goodsName': '小雅AI音箱旗舰版_石墨绿', 'goodsFullName': None, 'goodsBasicUnitName': '个', 'goodsAssistUnitName': '个', 'goodsConversionRate': 1.0, 'enableBatchNumberManage': 0, 'productId': '996cc839-60e8-4500-82c6-9a7c7b95646d', 'productLineId': '13c512df-ad18-48e5-b75d-166a534cc410', 'isOptional': 0, 'unitId': 'UNIT-12', 'unitCode': 'EA', 'unitName': '个', 'transferNum': 30.0, 'onwayNum': None, 'totalOutNum': None, 'totalInNum': None, 'unitPrice': None, 'amountMoney': 0.0, 'remark': None, 'batchNumId': None, 'batchNumCode': None, 'batchNumName': None, 'goodsPositionId': None, 'goodsPositionCode': None, 'goodsPositionName': None, 'receiverAddress': None, 'provinceId': None, 'provinceCode': None, 'provinceName': None, 'cityId': None, 'cityCode': None, 'cityName': None, 'countyId': None, 'countyCode': None, 'countyName': None, 'townId': None, 'townCode': None, 'townName': None, 'detailAddr': None, 'receiver': None, 'receiverPhone': None, 'receiverPhoneSpare': None, 'isClose': 0, 'sourceId': None, 'sourceLineNum': None, 'sourceType': None, 'ext01': None, 'ext02': None, 'ext03': None, 'ext04': None, 'ext05': None, 'ext06': None, 'ext07': None, 'ext08': None, 'ext09': None, 'ext10': None, 'ext11': None, 'ext12': None, 'ext13': None, 'ext14': None, 'ext15': None, 'goodsVersion': '1', 'goodsSelection': None, 'isMotherPiece': None, 'customerId': None, 'customerCode': None, 'customerName': None, 'supplierId': None, 'supplierCode': None, 'supplierName': None, 'projectId': None, 'projectCode': None, 'projectName': None, 'batchCodeId': None, 'batchCodeCode': None, 'stockStateId': None, 'stockStateCode': None, 'stockStateName': None, 'enableBatchNoManage': 0, 'enableInvStatusManage': 0, 'originalGoodsId': None, 'goodsSelectionDescription': None, 'outStorageId': '1001ZZ100000000DPAP4', 'outStorageCode': 'test030201', 'outStorageName': '测试仓库030201', 'outIfSlotManage': 0, 'inStorageId': '1001ZZ100000000DPAP6', 'inStorageCode': 'test030202', 'inStorageName': 'test030202', 'inIfSlotManage': None, 'outPositionId': None, 'outPositionCode': None, 'outPositionName': None}], 'transferBillItemBoms': [{'id': '048SYwdIn8hCuu2RFXFr', 'dr': 0, 'ts': 1589452156000, 'creator': 'smq', 'creationTime': 1589452156000, 'modifier': None, 'modifiedTime': None, 'persistStatus': 'nrm', 'promptMessage': None, 'rowNum': '10', 'goodsId': '03e77ae0-469d-4d8a-ba34-733c2ada3749', 'goodsCode': '301020000049', 'goodsName': '小雅AI音箱旗舰版_石墨绿', 'goodsFullName': None, 'goodsBasicUnitName': '个', 'goodsAssistUnitName': '个', 'goodsConversionRate': 1.0, 'enableBatchNumberManage': 0, 'productId': '996cc839-60e8-4500-82c6-9a7c7b95646d', 'productLineId': '13c512df-ad18-48e5-b75d-166a534cc410', 'unitId': 'UNIT-12', 'unitCode': 'EA', 'unitName': '个', 'transferNum': 30.0, 'onwayNum': None, 'totalOutNum': None, 'totalInNum': None, 'unitPrice': None, 'amountMoney': 0.0, 'remark': None, 'batchNumId': None, 'batchNumCode': None, 'batchNumName': None, 'goodsPositionId': None, 'goodsPositionCode': None, 'goodsPositionName': None, 'receiverAddress': None, 'provinceId': None, 'provinceCode': None, 'provinceName': None, 'cityId': None, 'cityCode': None, 'cityName': None, 'countyId': None, 'countyCode': None, 'countyName': None, 'townId': None, 'townCode': None, 'townName': None, 'detailAddr': None, 'receiver': None, 'receiverPhone': None, 'receiverPhoneSpare': None, 'isClose': 0, 'sourceId': None, 'sourceLineNum': None, 'sourceType': None, 'ext01': None, 'ext02': None, 'ext03': None, 'ext04': None, 'ext05': None, 'ext06': None, 'ext07': None, 'ext08': None, 'ext09': None, 'ext10': None, 'ext11': None, 'ext12': None, 'ext13': None, 'ext14': None, 'ext15': None, 'goodsVersion': '1', 'goodsSelection': None, 'customerId': None, 'customerCode': None, 'customerName': None, 'supplierId': None, 'supplierCode': None, 'supplierName': None, 'projectId': None, 'projectCode': None, 'projectName': None, 'batchCodeId': None, 'batchCodeCode': None, 'stockStateId': None, 'stockStateCode': None, 'stockStateName': None, 'originalGoodsId': None, 'goodsSelectionDescription': None, 'itemId': '0GwdQA5KNiXMMRPCSv59', 'billId': '06MwWrq4k4UuyjQEJpAz', 'parentGoodsId': '03e77ae0-469d-4d8a-ba34-733c2ada3749', 'parentGoodsCode': '301020000049', 'parentGoodsName': '小雅AI音箱旗舰版_石墨绿', 'parentGoodsdisplayName': None, 'parentRowNum': '10', 'childGoodsQty': None, 'firstBillBomCode': None, 'srcBillBomCode': None, 'outStorageId': '1001ZZ100000000DPAP4', 'outStorageCode': 'test030201', 'outStorageName': '测试仓库030201', 'outIfSlotManage': 0, 'inStorageId': '1001ZZ100000000DPAP6', 'inStorageCode': 'test030202', 'inStorageName': 'test030202', 'inIfSlotManage': None, 'outPositionId': None, 'outPositionCode': None, 'outPositionName': None}], 'ext01': None, 'ext02': None, 'ext03': None, 'ext04': None, 'ext05': None, 'ext06': None, 'ext07': None, 'ext08': None, 'ext09': None, 'ext10': None, 'ext11': None, 'ext12': None, 'ext13': None, 'ext14': None, 'ext15': None, 'isDistribution': None, 'isReturned': None}]}} check_result(case_data, code, response)
metadata.update({ u'speed': str(int(response.elapsed.total_seconds() * 1000)) }) except Exception, e1: logging.info(e1) continue break except Exception, ex: logging.info(ex) response = None continue if response is None: logging.error(u"{}:请求校验IP的网络错误!".format(moduleName)) return False return True def __validation(self, ip, is_filter, moduleName): '''校验有效IP池中的IP有效性,无效则删除''' now = time.strftime('%Y-%m-%d %H:%M:%S') metadata = {} if not self.__check_ip_validation(ip, metadata, moduleName, is_filter): if is_filter: ip.status = 2 else: if ip.fail < 50: ip.status = 3 else: ip.status = 2
class MsgService(Service): def __init__(self): super().__init__() # 初始化变量 self.config = Config('config.json') self.cookies = self.config.get_cookies() self.log = Log(__name__) self.msg = Msg(self.cookies) self.robot = Robot(self.config.get('api_keys')) self.uid = int(self.cookies['DedeUserID']) self.admin_ids = self.config.get('admin_ids') self.receiver_ids = self.config.get('receiver_ids') self.cookies_str = self.config.get('cookies') self.userList = {} self.groupList = {} self.is_private = self.config.get('is_private') # self.msg.send('start') def run(self): # self.parseMsg() # time.sleep(2) try: self.parseMsg() time.sleep(2) except Exception as e: self.log.error(e) # 解析消息 def parseMsg(self): msgList = self.msg.get() for msg in msgList: self.log.debug(msg) # 私信 if msg['receiver_type'] == 1: if msg['msg_type'] == 1: text = json.loads(msg['content'])['content'].lstrip() self.handler(text, msg['sender_uid'], 0) pass # 应援团 elif msg['receiver_type'] == 2: if (0 in self.receiver_ids or int(msg['receiver_id'] in self.receiver_ids)) \ and msg['msg_type'] == 1: # 检测并处理@ text = json.loads(msg['content'])['content'].lstrip() if text.find('@' + self.getUserName(self.uid)) != -1: text = text.replace('\u0011', '') # IOS客户端的@前后有这两个控制字符 text = text.replace('\u0012', '') text = text.replace('@' + self.getUserName(self.uid), '').lstrip() if 'at_uids' in msg and self.uid in msg['at_uids']: self.handler(text, msg['sender_uid'], msg['receiver_id']) else: self.handler('#冒泡', 0, msg['receiver_id']) pass pass # 消息处理函数 def handler(self, text, user_id, group_id): if group_id not in self.groupList: self.getGroupDetail(group_id) # 命令 if text.find('#') == 0: ot = self.cmd(text, user_id, group_id) # 聊天 else: # 私信关闭状态 if group_id == 0 and self.is_private == 0: return # 睡觉 if self.groupList[group_id]['off'] == 1: return if text == '': text = '?' # 转发消息给机器人 self.log.success('[in][%s][%s] %s' % (self.groupList[group_id]['name'], self.getUserName(user_id), text)) ot = self.robot.send(text, user_id, group_id) self.log.success('[out][%s][%s] %s' % (self.groupList[group_id]['name'], self.getUserName(user_id), ot)) # 回复 # 私信 if group_id == 0: self.msg.send(ot, user_id, receiver_type=1) # 群聊 else: if user_id == 0: self.msg.send(ot, group_id, receiver_type=2) else: self.msg.send('@%s %s' % (self.getUserName(user_id), ot), group_id, receiver_type=2, at_uid=user_id) # 执行命令 def cmd(self, text, user_id, group_id): ot = '你的py值不够,请及时充值[doge]' # 管理员 if user_id in self.admin_ids: if text == '#睡觉': self.groupList[group_id]['off'] = 1 ot = '已准备睡觉,各位晚安~' elif text == '#醒醒': self.groupList[group_id]['off'] = 0 ot = '又是全新的一天,早安!' elif text == '#切换': old = self.robot.swiRobot() ot = '已从%d号切换到%d号(我比前一位聪明哦~)' % (old, self.robot.apiKeyNo) elif text[:4] == '#睡觉:' and text[4:].isdigit() and group_id == 0: group_id = int(text[4:]) print(group_id) if self.getGroupDetail(group_id) == 0: self.groupList[group_id]['off'] = 1 ot = self.groupList[group_id]['name'] + " 已睡觉" elif text[:4] == '#醒醒:' and text[4:].isdigit() and group_id == 0: group_id = int(text[4:]) if self.getGroupDetail(group_id) == 0: self.groupList[group_id]['off'] = 0 ot = self.groupList[group_id]['name'] + " 已睡醒" # 群主 elif user_id == self.groupList[group_id]['admin']: if text == '#睡觉': self.groupList[group_id]['off'] = 1 ot = '已准备睡觉,各位晚安~' elif text == '#醒醒': self.groupList[group_id]['off'] = 0 ot = '又是全新的一天,早安!' pass # 系统 elif user_id == 0: if text == '#冒泡': ot = '敢不敢长按我的头像试试?' pass return ot # 获取用户名 uid -> 昵称 def getUserName(self, user_id): # 每300s(5min)更新一次昵称 if user_id not in self.userList or self.userList[user_id][1] - int( time.time()) > 300: url = 'http://api.live.bilibili.com/user/v2/User/getMultiple' postData = { 'uids[0]': user_id, 'attributes[0]': 'info', 'csrf_token': self.msg.cookies['bili_jct'] } response = requests.post(url, data=postData, cookies=self.cookies).json() self.log.debug('[查询用户]' + str(response)) self.userList[user_id] = [ response['data'][str(user_id)]['info']['uname'], int(time.time()) ] return self.userList[user_id][0] # 获取群信息 群主&勋章名(替代群名) def getGroupDetail(self, group_id): if group_id not in self.groupList: if group_id == 0: self.groupList[group_id] = {'admin': 0, 'name': '私信', 'off': 0} else: url = 'https://api.vc.bilibili.com/link_group/v1/group/detail?group_id=%s' % str( group_id) response = requests.get(url).json() self.log.debug('[查询群]' + str(response)) if response['code'] == 0: self.groupList[group_id] = { 'admin': response['data']['owner_uid'], 'name': response['data']['fans_medal_name'], 'off': 0 } return response['code'] return 0