Python itchat.content() Examples

The following are 23 code examples of itchat.content(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module itchat , or try the search function .
Example #1
Source File: wechat.py    From fishroom with GNU General Public License v3.0 6 votes vote down vote up
def handle_message(msg, content):
    global wxHandle, wxRooms, myUid
    room = msg["FromUserName"]
    nick = msg["ActualNickName"]
    if wxRooms.get(room) is None:
        logger.info("Not in rooms to forward!!!")
        return
    if msg["ActualUserName"] == myUid:
        logger.info("My own message:)")
        return

    date, time = get_now_date_time()
    fish_msg = Message(
        ChannelType.Wechat, nick, wxRooms[room], content,
        mtype=MessageType.Text, date=date, time=time)
    wxHandle.send_to_bus(wxHandle,fish_msg) 
Example #2
Source File: wechat_utils.py    From Neural-Headline-Generator-CN with GNU General Public License v3.0 6 votes vote down vote up
def gpu_status(self,av_type_list):
        for t in av_type_list:
            cmd='nvidia-smi -q --display='+t
            #print('\nCMD:',cmd,'\n')
            r=os.popen(cmd)
            info=r.readlines()
            r.close()
            content = " ".join(info)
            #print('\ncontent:',content,'\n')
            index=content.find('Attached GPUs')
            s=content[index:].replace(' ','').rstrip('\n')
            self.t_send(s, toUserName='filehelper')
            time.sleep(.5)
        #th.exit()
#==============================================================================
# 
#============================================================================== 
Example #3
Source File: wechat-anti-revoke-py3.py    From wechat-anti-revoke with Apache License 2.0 6 votes vote down vote up
def note_msg(msg):
    print_msg(get_whole_msg(msg))
    content = HTMLParser().unescape(msg['Content'])
    try:
        content_tree = ETree.fromstring(content)
    except Exception:
        # invent/remove to chatroom
        return
    if content_tree is None:
        return
    revoked = content_tree.find('revokemsg')
    if revoked is None:
        return
    old_msg_id = revoked.find('msgid').text
    old_msg = msg_store.get(old_msg_id)
    if old_msg is None:
        return
    msg_send = get_whole_msg(old_msg, download=True)
    for m in msg_send:
        bot.send(m, toUserName='filehelper')
    clear_timeouted_message() 
Example #4
Source File: wechat-anti-revoke.py    From wechat-anti-revoke with Apache License 2.0 6 votes vote down vote up
def note_msg(msg):
    print_msg(get_whole_msg(msg))
    content = HTMLParser().unescape(msg['Content'])
    try:
        content_tree = ETree.fromstring(content)
    except Exception:
        # invent/remove to chatroom
        return
    if content_tree is None:
        return
    revoked = content_tree.find('revokemsg')
    if revoked is None:
        return
    old_msg_id = revoked.find('msgid').text
    old_msg = msg_store.get(old_msg_id)
    if old_msg is None:
        return
    msg_send = get_whole_msg(old_msg, download=True)
    for m in msg_send:
        bot.send(m, toUserName='filehelper')
    clear_timeouted_message() 
Example #5
Source File: WechatAddGroupHelper.py    From WechatAddGroupHelper with MIT License 6 votes vote down vote up
def add_friends_msg(msg):
    """ 监听添加好友请求 为了自动同意好友请求"""

    if not IS_AUTO_ADD_FRIEND:  # 如果是已关闭添加好友功能,则直接返回
        return
        # print(json.dumps(msg, ensure_ascii=False))

    userid = msg['RecommendInfo']['UserName']
    nickname = msg['RecommendInfo']['NickName']
    # 黑名单用户不能加群
    if userid in black_uuid_list:
        set_note('黑名单用户『{}』不能通过好友请求'.format(nickname))
        return

    content = msg['RecommendInfo']['Content']  # 获取验证消息
    if add_friend_compile.findall(content):
        time.sleep(random.randint(1, 2))  # 随机休眠(1~3)秒,用于防检测机器人
        itchat.add_friend(**msg['Text'])  # 同意加好友请求
        time.sleep(random.randint(1, 2))
        itchat.send(note_first_meet_text, userid)  # 给刚交的朋友发送欢迎语句
        note = '已添加好友:{}'.format(nickname)
        set_note(note)
    else:
        note = '添加好友失败:用户「{}」 发来的验证消息「{}」。'.format(nickname, content)
        set_note(note) 
Example #6
Source File: 29 PythonCeHui.py    From Python-Spider with Apache License 2.0 6 votes vote down vote up
def note_msg(msg):
    print_msg(get_whole_msg(msg))
    content = HTMLParser().unescape(msg['Content'])
    try:
        content_tree = ETree.fromstring(content)
    except Exception:
        # invent/remove to chatroom
        return
    if content_tree is None:
        return
    revoked = content_tree.find('revokemsg')
    if revoked is None:
        return
    old_msg_id = revoked.find('msgid').text
    old_msg = msg_store.get(old_msg_id)
    if old_msg is None:
        return
    msg_send = get_whole_msg(old_msg, download=True)
    for m in msg_send:
        bot.send(m, toUserName='filehelper')
    clear_timeouted_message() 
Example #7
Source File: wechat.py    From fishroom with GNU General Public License v3.0 5 votes vote down vote up
def on_text_message(msg):
    log_message(TEXT, msg)
    content = msg["Content"]
    handle_message(msg, content) 
Example #8
Source File: main.py    From weixinqunzhushou with Apache License 2.0 5 votes vote down vote up
def extract_content(text):
    space_index = text.find(' ')
    if space_index == -1:
        space_index = text.find('\u2005')
    print(space_index)
    content = text[(space_index + 1):]
    return content 
Example #9
Source File: wechat_utils.py    From Neural-Headline-Generator-CN with GNU General Public License v3.0 5 votes vote down vote up
def GetMiddleStr(self,content,startStr,endStr):
        #get the string between two specified strings
        #从指定的字符串之间截取字符串
        try:
          startIndex = content.index(startStr)
          if startIndex>=0:
            startIndex += len(startStr)
          endIndex = content.index(endStr)
          return content[startIndex:endIndex]
        except:
            return ''
#==============================================================================
# 
#============================================================================== 
Example #10
Source File: autoReply.py    From WechatHelper with MIT License 5 votes vote down vote up
def otherReply(msg):
		if not KEYWORDS:
			content = random.choice(RELAYCONTENTS)
			itchat.send(content, msg['FromUserName']) 
Example #11
Source File: autoReply.py    From WechatHelper with MIT License 5 votes vote down vote up
def replyText(msg):
		if not KEYWORDS:
			content = random.choice(RELAYCONTENTS)
			itchat.send(content, msg['FromUserName'])
		else:
			for keyword in KEYWORDS:
				if keyword in msg['Text']:
					content = random.choice(RELAYCONTENTS)
					itchat.send(content, msg['FromUserName'])
					break 
Example #12
Source File: 28 PythonCheHui.py    From Python-Spider with Apache License 2.0 5 votes vote down vote up
def information(msg):
    # 这里如果这里的msg['Content']中包含消息撤回和id,就执行下面的语句
    if '撤回了一条消息' in msg['Content']:
        # 在返回的content查找撤回的消息的id
        old_msg_id = re.search("\<msgid\>(.*?)\<\/msgid\>", msg['Content']).group(1)
        # 获取到消息原文
        old_msg = msg_information.get(old_msg_id)
        # 如果发送的是表情包
        if len(old_msg_id)<11:
            # 发送撤回的提示给文件助手
            itchat.send_file(face_bug,toUserName='filehelper')
        # 把暂时存储的信息可以删除掉,也可以选择不删除
        # os.remove(face_bug)
        else:
            msg_body = old_msg.get('group_name') + old_msg.get('msg_from') +"\n" + old_msg.get('msg_time_rec') \
                + "撤回了:" + "\n" + r"" + old_msg.get('msg_content')
            
            # 如果是分享的文件被撤回了,那么就将分享的url加在msg_body中发送给文件助手
            if old_msg['msg_type'] == "Sharing":
                msg_body += "\n链接是:" + old_msg.get('msg_share_url')
            print msg_body
            # 将撤回消息发给文件助手
            itchat.send_msg(msg_body, toUserName='filehelper')
            
            # 有文件的话也要将文件发送回去
            if old_msg["msg_type"] == "Picture" \
                or old_msg["msg_type"] == "Recording" \
                or old_msg["msg_type"] == "Video" \
                or old_msg["msg_type"] == "Attachment":
                file = '@fil@%s' % (old_msg['msg_content'])
                itchat.send(msg=file, toUserName='filehelper')
                # 把暂时存储的信息可以删除掉,也可以选择不删除
                os.remove(old_msg['msg_content'])
            # 删除字典旧消息
    msg_information.pop(old_msg_id) 
Example #13
Source File: WechatAddGroupHelper.py    From WechatAddGroupHelper with MIT License 5 votes vote down vote up
def send_mail(title, content):
    """
    发送邮件
    :param title: 标题
    :param content: 内容
    """
    if not IS_OPEN_EMAIL_NOTICE:
        return
    try:
        yag.send(to_emails, title, content)
        print('已发送邮件:{}'.format(title))
    except Exception as exception:
        print(str(exception)) 
Example #14
Source File: WechatAddGroupHelper.py    From WechatAddGroupHelper with MIT License 5 votes vote down vote up
def exit_callback():
    """
    微信已经登出
    """
    time_ = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    online_time = get_online_time()
    title = '您服务器上的微信「{}」已离线'.format(wechat_nick_name)
    content = '离线时间:{} \n一共在线时长:{} \n离线原因:未知'.format(time_, online_time)
    send_mail(title, content)
    set_note(title + content, True)
    stop_scheduler()
    stop_system() 
Example #15
Source File: wechat.py    From fishroom with GNU General Public License v3.0 5 votes vote down vote up
def send_msg(self, target, content, sender=None, first=False, **kwargs):
        logger.info("Sending message to " + target)
        roomid = wxRoomNicks[target]
        if sender is not None:
            itchat.send(msg="[{}] {}".format(sender,content), toUserName=roomid)
        else:
            itchat.send(content, toUserName=roomid) 
Example #16
Source File: wechat.py    From fishroom with GNU General Public License v3.0 5 votes vote down vote up
def on_video_message(msg):
    log_message(VIDEO, msg)
    content = "(Video message received)"
    handle_message(msg, content) 
Example #17
Source File: wechat.py    From fishroom with GNU General Public License v3.0 5 votes vote down vote up
def on_voice_message(msg):
    log_message(VOICE, msg)
    content = "(Voice message received)"
    handle_message(msg, content) 
Example #18
Source File: wechat.py    From fishroom with GNU General Public License v3.0 5 votes vote down vote up
def on_recording_message(msg):
    log_message(RECORDING, msg)
    content = "(Recording message received)"
    handle_message(msg, content) 
Example #19
Source File: wechat.py    From fishroom with GNU General Public License v3.0 5 votes vote down vote up
def on_note_message(msg):
    log_message(NOTE, msg)
    content = "(Note message received)"
    handle_message(msg, content) 
Example #20
Source File: wechat.py    From fishroom with GNU General Public License v3.0 5 votes vote down vote up
def on_card_message(msg):
    log_message(CARD, msg)
    content = "(Card message received)"
    handle_message(msg, content) 
Example #21
Source File: wechat.py    From fishroom with GNU General Public License v3.0 5 votes vote down vote up
def on_map_message(msg):
    log_message(MAP, msg)
    content = "(Map message received)"
    handle_message(msg, content) 
Example #22
Source File: wechat-forwarding.py    From wechat-forwarding with Apache License 2.0 4 votes vote down vote up
def process_group(self, msg):
        # get sernder and receiver nicknames
        sender = msg['ActualNickName']
        if sender is None or len(sender) == 0:
            return
        m = self.bot.search_chatrooms(userName=msg['FromUserName'])
        if m is None:
            return
        receiver = m['NickName']
        if receiver is None or len(receiver) == 0:
            return
        sender = html.unescape(sender)
        receiver = html.unescape(receiver)
        if receiver not in self.config:
            return
        # construct messages to send
        prefix = self.config[receiver]['prefix']
        if len(msg['Url']) > 0: # message with urls
            content = msg['Text']
            if len(msg['OriContent']) > 0:
                try: # handle map label
                    content_tree = ETree.fromstring(msg['OriContent'])
                    if content_tree is not None:
                        map_label = content_tree.find('location')
                        if map_label is not None:
                            content += ' ' + map_label.attrib['poiname']
                            content += ' ' + map_label.attrib['label']
                except:
                    pass
            url = html.unescape(msg['Url'])
            content += ' ' + url
            txt = ['%s[%s]: %s' % (prefix, sender, content)]
        elif len(msg['FileName']) > 0: # file as a message
            fn = os.path.join(self.data_path, msg['FileName'])
            # assume the file has already been downloaded
            if not os.path.exists(fn):
                return
            # don't send zero-sized files
            if os.path.getsize(fn) == 0:
                return
            # don't send large files
            if self.max_file_size > 0 and os.path.getsize(fn) > self.max_file_size:
                return
            content = '@%s@%s' % (Const.TYPES.get(msg['Type'], 'fil'), fn)
            txt = ['%s[%s]:' % (prefix, sender), content]
        else: # normal text message
            content = msg['Text']
            if content.startswith('//'): # if a message starts with '//', send as anonymous
                sender = u'匿名'
                content = content[2:].strip()
            txt = ['%s[%s]: %s' % (prefix, sender, content)]
        mq.put((Const.GROUP, self.config[receiver]['sub'], txt)) 
Example #23
Source File: main.py    From weixinqunzhushou with Apache License 2.0 4 votes vote down vote up
def tuling_auto_reply(user, content):
    api_url_v2 = "http://openapi.tuling123.com/openapi/api/v2"
    body = {
      'perception': {
        'inputText': {
          'text': content
        },
        'selfInfo': {
          'location': {
            'city': user['City'],
            'province': user['Province']
          }
        }
      },
      'userInfo': {
        'apiKey': turing123_key,
        "userId": user['_id']
      }
    }
    api_url = "http://www.tuling123.com/openapi/api"
    body = {'key': turing123_key, 'info': content.encode('utf8'), 'userid': user['_id']}
    try:
        r = requests.post(api_url, data=body).json()
    except:
        return u'系统发生异常,请稍后重试'
    if not r['code'] in (100000, 200000, 302000, 308000, 313000, 314000): return
    if r['code'] == 100000:  # 文本类
        return '\n'.join([r['text'].replace('<br>', '\n')])
    elif r['code'] == 200000:  # 链接类
        return '\n'.join([r['text'].replace('<br>', '\n'), r['url']])
    elif r['code'] == 302000:  # 新闻类
        l = [r['text'].replace('<br>', '\n')]
        for n in r['list']: l.append('%s - %s' % (n['article'], n['detailurl']))
        return '\n'.join(l)
    elif r['code'] == 308000:  # 菜谱类
        l = [r['text'].replace('<br>', '\n')]
        for n in r['list']: l.append('%s - %s' % (n['name'], n['detailurl']))
        return '\n'.join(l)
    elif r['code'] == 313000:  # 儿歌类
        return '\n'.join([r['text'].replace('<br>', '\n')])
    elif r['code'] == 314000:  # 诗词类
        return '\n'.join([r['text'].replace('<br>', '\n')])