def _itchat_send_file(self, *args, **kwargs): def _itchat_send_fn(self, fileDir, toUserName=None, mediaId=None, filename=None): from itchat.returnvalues import ReturnValue from itchat import config import os, time, json if toUserName is None: toUserName = self.storageClass.userName if mediaId is None: r = self.upload_file(fileDir) if r: mediaId = r['MediaId'] else: return r fn = filename or os.path.basename(fileDir) url = '%s/webwxsendappmsg?fun=async&f=json' % self.loginInfo['url'] data = { 'BaseRequest': self.loginInfo['BaseRequest'], 'Msg': { 'Type': 6, 'Content': ("<appmsg appid='wxeb7ec651dd0aefa9' sdkver=''><title>%s</title>" % fn + "<des></des><action></action><type>6</type><content></content><url></url><lowurl></lowurl>" + "<appattach><totallen>%s</totallen><attachid>%s</attachid>" % (str(os.path.getsize(fileDir)), mediaId) + "<fileext>%s</fileext></appattach><extinfo></extinfo></appmsg>" % os.path.splitext(fn)[1].replace('.', '')), 'FromUserName': self.storageClass.userName, 'ToUserName': toUserName, 'LocalID': int(time.time() * 1e4), 'ClientMsgId': int(time.time() * 1e4), }, 'Scene': 0, } headers = { 'User-Agent': config.USER_AGENT, 'Content-Type': 'application/json;charset=UTF-8', } r = self.s.post(url, headers=headers, data=json.dumps(data, ensure_ascii=False).encode('utf8')) return ReturnValue(rawResponse=r) try: return _itchat_send_fn(self.itchat, *args, **kwargs) except Exception as e: raise EFBMessageError(repr(e))
def send_message(self, msg): """Send a message to WeChat. Supports text, image, sticker, and file. Args: msg (channel.EFBMsg): Message Object to be sent. Returns: This method returns nothing. Raises: EFBMessageTypeNotSupported: Raised when message type is not supported by the channel. """ UserName = self.get_UserName(msg.destination['uid']) if UserName is None or UserName is False: raise EFBChatNotFound r = None self.logger.info("Sending message to WeChat:\n" "Target-------\n" "uid: %s\n" "UserName: %s\n" "NickName: %s\n" "Type: %s\n" "Text: %s" % (msg.destination['uid'], UserName, msg.destination['name'], msg.type, msg.text)) if msg.type in [MsgType.Text, MsgType.Link]: if msg.target: if msg.target['type'] == TargetType.Member: msg.text = "@%s\u2005 %s" % ( msg.target['target'].member['alias'], msg.text) elif msg.target['type'] == TargetType.Message: maxl = self._flag("max_quote_length", -1) qt_txt = "%s" % msg.target['target'].text if maxl > 0: tgt_text = qt_txt[:maxl] if len(qt_txt) >= maxl: tgt_text += "…" tgt_text = "「%s」" % tgt_text elif maxl < 0: tgt_text = "「%s」" % qt_txt else: tgt_text = "" if UserName.startswith( "@@") and msg.target['target'].member: tgt_alias = "@%s\u2005 " % msg.target['target'].member[ 'alias'] else: tgt_alias = "" msg.text = "%s%s\n\n%s" % (tgt_alias, tgt_text, msg.text) r = self._itchat_send_msg(msg.text, UserName) elif msg.type in [MsgType.Image, MsgType.Sticker]: self.logger.info("Image/Sticker %s, %s", msg.type, msg.path) if msg.mime in ["image/gif", "image/jpeg"]: try: if os.path.getsize(msg.path) > 5 * 2**20: raise EFBMessageError( "Image sent is too large. (IS01)") self.logger.debug("Sending %s (image) to ItChat.", msg.path) r = self._itchat_send_image(msg.path, UserName) os.remove(msg.path) except FileNotFoundError: pass else: # Convert Image format img = Image.open(msg.path) try: alpha = img.split()[3] mask = Image.eval(alpha, lambda a: 255 if a <= 128 else 0) except IndexError: mask = Image.eval(img.split()[0], lambda a: 0) img = img.convert('RGB').convert('P', palette=Image.ADAPTIVE, colors=255) img.paste(255, mask) img.save("%s.gif" % msg.path, transparency=255) msg.path = "%s.gif" % msg.path self.logger.info('Image converted to GIF: %s', msg.path) self.logger.debug("Sending %s (image) to ItChat.", msg.path) r = self._itchat_send_image(msg.path, UserName) os.remove(msg.path) if msg.text: self._itchat_send_msg(msg.text, UserName) self.logger.info('Image sent with result %s', r) if not msg.mime == "image/gif": try: os.remove('.'.join(msg.path.split('.')[:-1])) except FileNotFoundError: pass elif msg.type in (MsgType.File, MsgType.Audio): self.logger.info( "Sending %s to WeChat\nCaption: %s\nPath: %s\nFilename: %s", msg.type, msg.text, msg.path, msg.filename) r = self._itchat_send_file(msg.path, toUserName=UserName, filename=msg.filename) if msg.text: self._itchat_send_msg(msg.text, toUserName=UserName) os.remove(msg.path) elif msg.type == MsgType.Video: self.logger.info("Sending video to WeChat\nCaption: %s\nPath: %s", msg.text, msg.path) r = self._itchat_send_video(msg.path, UserName) if msg.text: self._itchat_send_msg(msg.text, UserName) os.remove(msg.path) else: raise EFBMessageTypeNotSupported() if isinstance( r, dict) and r.get('BaseResponse', dict()).get('Ret', -1) != 0: if r.get('BaseResponse', dict()).get('Ret', -1) == 1101: self.itchat.logout() raise EFBMessageError(str(r)) else: msg.uid = r.get("MsgID", None) return msg
def _itchat_send_video(self, *args, **kwargs): try: return self.itchat.send_video(*args, **kwargs) except Exception as e: raise EFBMessageError(repr(e))