Ejemplo n.º 1
0
def text_reply(msg):
    print msg
    if msg["MsgType"] == 49:
        print "群聊分享文章地址链接Url:" + "---------------------------"
        print msg["Url"]
        
        xmlcontent = lxml.etree.HTML(get_html(msg["Url"]))
        title = xmlcontent.xpath('//h2[@class="rich_media_title"]/text()')
        imgArray = xmlcontent.xpath('//img[@data-type="png"]/@data-src')
        # 来源
        source = xmlcontent.xpath('//span[@class="rich_media_meta rich_media_meta_text rich_media_meta_nickname"]/text()')
        time = xmlcontent.xpath('//em[@class="rich_media_meta rich_media_meta_text"]/text()')
        print "来源"
        print source,time
        # 下载图片
        print "下载图片"
        # print imgArray
        # print title[0]
        get_image(title,imgArray,source,time,msg["Url"])
        
        # print "群聊分享文章类型编号MsgType:" + "---------------------------"
        # print msg["MsgType"]
        # print "群聊分享Content:" + "---------------------------"
        # print msg["Content"]
        # print "群聊分享FromUserName:"******"---------------------------"
        # print msg["FromUserName"]
        # print "群聊分享ToUserName:"******"---------------------------"
        # print msg["ToUserName"]
        # print "群聊分享链接标题FileName:" + "---------------------------"
        # print msg["FileName"]
        print "-------------群--------"
        # itchat.send('%s: %s : %s' % (msg['Type'], msg['Text'], msg['Url']), msg['FromUserName'])
        
        print msg['FromUserName']
        print msg['ToUserName']
        # 这个是需要每次扫码登录都改变的receiver
        receiver = "@4603e5cb2e47b710bba6fd15dfa3ace9ef3be0f3c80b812e0cc97cd7a71b7c96"
        if msg['FromUserName'] == receiver:
            print "----------- 自己在群里发的文章 ------------"
            # 自己在群里发的文章
            print "昵称:"
            print itchat.search_friends(userName=msg['FromUserName'])['NickName']
            print " ----------- "
            print "群名称:"
            print itchat.search_chatrooms(userName=msg['ToUserName'])['NickName']
            chatRoomName = "呵呵各地"
        # if itchat.search_chatrooms(userName=msg['ToUserName'])['NickName'] == chatRoomName:
        #     pass
        # else:
        #     pass
        
        else:
            # 群友发的文章
            print "----------- 群友发的文章 -----------"
            print "昵称:"
            print msg['ActualNickName']
            print " ----------- "
            print "群名称:"
            print itchat.search_chatrooms(userName=msg['FromUserName'])['NickName']
            chatRoomName = "呵呵各地"
Ejemplo n.º 2
0
def get_chatroom(chatroomUserName = '******'):
#    itchat.get_chatrooms(update=True)
    chatrooms = itchat.search_chatrooms(chatroomUserName);
    if chatrooms:
        return chatrooms[0]
    else:
        print("Cannot find the chatroom: "+ chatroomUserName)
        return None
Ejemplo n.º 3
0
def sendmsg_onegroup():
    gname = input("请输入你想发送的的群的名字:")
    msg = input("请输入你想发送的话:")
    room = itchat.search_chatrooms(gname)
    if room is not None:
        username = room[0]['UserName']
        itchat.send_msg(msg, username)
        print("发送成功!")
    else:
        print("未找到该群!")
Ejemplo n.º 4
0
def sendimage_onegroup():
    gname = input("请输入你想发送的的群的名字:")
    image = input("请输入你想发送的图片的路径如'E:/hello/桂东.png'(记得加引号!!!):")
    room = itchat.search_chatrooms(gname)
    if room is not None:
        username = room[0]['UserName']
        itchat.send_image(image, username)
        print("发送成功!")
    else:
        print("未找到该群!")
Ejemplo n.º 5
0
def get_users(chatroomUserName=''):
#    chatroom = itchat.update_chatroom(chatroom['UserName'])
#    itchat.get_chatrooms(update=True)
    chatrooms = itchat.search_chatrooms(chatroomUserName);
    if chatrooms and chatroomUserName:
        return chatrooms[0]['MemberList']
#        for friend in chatroom['MemberList']:
#            yield friend
    else:
        friend = itchat.get_friends(update=True)
        return friend
Ejemplo n.º 6
0
def send_special_wishes(chatroomName='wishgroup'):
    itchat.get_chatrooms(update=True)
    chatrooms = itchat.search_chatrooms(name=chatroomName)
    if chatroomName is None:
        print(u'search result is none')
    else:
        chatroom = itchat.update_chatroom(chatroom[0]['UserName'])
        for friend in chatroom['MemberList']:
            friend = itchat.search_friends(userName=friend['UserName'])
            print(REAL_SINCERE_WISH % (friend['DisplayName'] or friend['NickName']), friend['UserName'])
            time.sleep(.5)
Ejemplo n.º 7
0
def get_nick(userName):
    ''' 通过userName获取nickName '''
    try:
        user = itchat.search_friends(userName=userName)
        if not user:
            user = itchat.search_chatrooms(userName=userName)
            if not user:
                user = itchat.search_mps(userName=userName)
        return user.get('NickName')
    except AttributeError as err:
        print('获取nickName出错啦', err)
        print(user)
        return None
Ejemplo n.º 8
0
def sendMsgInchatromms(chatroomName=u'亲朋好友', REAL_MSG=u'%s这是一条群聊的群发消息,客户端程序'):
    itchat.get_chatrooms(update=True)
    chatrooms = itchat.search_chatrooms(name=chatroomName)
    if chatrooms is None:
        print(u'没有找到群聊:%s' % chatrooms)
    else:
        chatrooms = itchat.update_chatroom(chatrooms[0]['UserName'])
        for friend in chatrooms['MemberList']:
            # 真正发送消息的时候可以将下面的print 替换成itchat.send()
            itchat.send(REAL_MSG %
                        (friend['NickName'] or friend['DisplayName']))

            time.sleep(.5)
Ejemplo n.º 9
0
def get_chatroom_users(qunname, workbook):
    try:
        #根据群聊名称在表单中创建工作薄
        worksheet = workbook.add_sheet(
            qunname,
            cell_overwrite_ok=True)  #.add_worksheet(roomslist[i]['NickName'])
        #添加表头
        worksheet.write(0, 0, "微信名称")
        worksheet.write(0, 1, "群备注")
        worksheet.write(0, 2, "规整群名")
        worksheet.write(0, 3, "铺位号")
        #获取群聊用户列表
        myroom = itchat.search_chatrooms(name=qunname)
        #获取群聊名称
        gsp = itchat.update_chatroom(myroom[0]['UserName'],
                                     detailedMember=True)
        print("\n群名:{} \t 人数:{}".format(qunname, len(gsp['MemberList'])))

        nickname = []
        displayname = []

        for c in gsp['MemberList']:
            nickname.append(c['NickName'])
            displayname.append(c['DisplayName'])

        msg = '请以下业主修改群昵称为"1层3C123姓名"或"1层3D123姓名"格式,不会修改的请亲友或者群友帮忙:\r\n'
        #将用户信息写入相应的工作薄中
        for x in range(len(gsp['MemberList'])):
            worksheet.write(x + 1, 0, nickname[x])
            worksheet.write(x + 1, 1, displayname[x])
            fn = formatname(displayname[x])
            worksheet.write(x + 1, 2, fn)
            if len(fn) < 1:
                fn = nickname[x]
            mm = re.search('3[ABCD]-*\d{2,3}', fn)
            if mm == None:
                if not fn in ['英', '朱勇', '顺其自然']:
                    msg += '@%s ' % fn
                    #print('@%s'%fn)
            else:
                worksheet.write(x + 1, 3, mm.group(0))
        print(msg)
        #itchat.send_msg(msg, toUserName=myroom[0]['UserName'])

        #输出一点提示信息
        print(
            '\n结束.'
        )  #,end='')#            "sheet {} finished".format(roomslist[i]['NickName']))

    except Exception as e:
        print("Error", e)
Ejemplo n.º 10
0
def text_reply(msg):
	date=datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
	#获取发送者与接收者信息
	if msg['FromUserName']==itchat.search_friends()['UserName']:#如果自己是发送方
		user_name=msg['ToUserName']
		sender_name=u'我'
	else:
		user_name=msg['FromUserName']
		sender_name=u'你'

	id=-1
	#群聊
	if user_name[0:2]=='@@':
		friend_name=itchat.search_chatrooms(userName=user_name)['NickName']
		id=save_friend_info(friend_name,user_name,TYPE_GROUP)
		sender_name=msg['ActualNickName']
		if len(sender_name)==0:
			sender_name=u'我'
	elif user_name=='filehelper':#好友
		friend_name=u'文件助手'
		id=save_friend_info(friend_name,user_name,TYPE_FILEHELPER)
	else:
		friend=itchat.search_friends(userName=user_name)
		if not friend:
			return;#避开腾讯的新闻号等
		friend_name=friend['RemarkName']
		if len(friend_name)==0:#此好友没有备注,使用昵称代替
			friend_name=friend['NickName']
		id=save_friend_info(friend_name,user_name,TYPE_FRIEND)

	#获取消息内容
	if msg['Type']==TEXT:
		content=msg['Text']
	elif msg['Type']==SHARING:
		content=msg['Url']
	else:
		if msg['Type']==VOICE:
			content=datetime.datetime.now().strftime('%Y%m%d%H%M%S.mp3')
		else:
			content=msg['FileName']
		msg['Text'](save_url+id+'/'+content)#保存文件
	'''
	if sender_name==u'我':
		print(u'我=>%s:\n%s\n' % (friend_name,content))
	elif sender_name==u'你':
		print(u'%s=>我:\n%s\n' % (friend_name,content))
	else:
		print(u'[%s]%s=>我:\n%s\n' % (friend_name,sender_name,content))
	'''
	save_chat_content(friend_name,sender_name,content,TYPE_CONTENT[msg['Type']],date)#保存到数据库
	save_to_one_txt(friend_name,sender_name,content,date)#保存到文本文件
def get_group_user_name(msg):
    """
    微信群中有文字信息时,针对设置的微信群,按照机器人是否开启的标志,进行应答或忽视
    :param msg: 微信群文字信息
    :return: 微信群id
    """
    context = msg['Content']
    from_user_name = msg['FromUserName']
    if msg['ActualUserName'] == msg['FromUserName']:
        from_user_name = msg['ToUserName']
    itchat.get_chatrooms(update=True)
    for group_name in AUTO_REPLY_GROUPS:
        my_rooms = itchat.search_chatrooms(name=group_name.get("group"))
        ori_switch = group_name.get("switch")
        for room in my_rooms:
            print("UserName: "******"from_user_name: " + from_user_name)
            if room['NickName'] == group_name.get(
                    "group") and room['UserName'] == from_user_name:
                if exist_in_key_word(context, OFF_KEY_WORDS):
                    group_name["switch"] = "off"
                elif exist_in_key_word(context, ON_KEY_WORDS):
                    group_name["switch"] = "on"

                if msg['ActualUserName'] == msg['FromUserName']:
                    if group_name.get(
                            "switch") == "on" and ori_switch == "off":
                        print("myself first time turn on")
                        return room['UserName']
                    elif group_name.get(
                            "switch") == "off" and ori_switch == "on":
                        print("myself first time turn off")
                        return room['UserName']
                    else:
                        print("switch is off")
                        continue
                else:
                    if group_name.get("switch") == "on":
                        print("first time turn on")
                        return room['UserName']
                    elif group_name.get(
                            "switch") == "off" and ori_switch == "on":
                        print("first time turn off")
                        return room['UserName']
                    else:
                        print("turn off")
                        continue
            else:
                print("No groups found!")
                continue
    return ""
Ejemplo n.º 12
0
def SaveMsg(msg):
    # print(msg)
    # 创建可下载消息内容的存放文件夹,并将暂存在当前目录的文件移动到该文件中
    if not os.path.exists(".\\Revocation\\"):
        os.mkdir(".\\Revocation\\")

    itchat.search_chatrooms()
    if re.search(r"\!\[CDATA\[.*撤回了一条消息\]\]", msg['Content']) != None:
        print("撤回Msg", msg)
        if re.search("\<msgid\>(.*?)\<\/msgid\>", msg['Content']) != None:
            old_msg_id = re.search("\<msgid\>(.*?)\<\/msgid\>",
                                   msg['Content']).group(1)
        elif re.search("\;msgid\&gt\;(.*?)\&lt", msg['Content']) != None:
            old_msg_id = re.search("\;msgid\&gt\;(.*?)\&lt",
                                   msg['Content']).group(1)
        old_msg = msg_store.get(old_msg_id, {})

        print(r"撤回的消息", old_msg_id, old_msg)
        if old_msg:
            msg_send = r"您的好友:" \
                       + old_msg.get('msg_from', None) \
                       + r"  在 [" + old_msg.get('msg_time_touser', None) \
                       + r"], 撤回了一条 [" + old_msg.get('msg_type', None) + "] 消息, 内容如下:" \
                       + old_msg.get('msg_content', None)
            if old_msg['msg_type'] == "Sharing":
                msg_send += r", 链接: " + old_msg.get('msg_url', None)
            elif old_msg['msg_type'] in [
                    'Picture', 'Recording', 'Video', 'Attachment'
            ]:
                msg_send += r", 存储在当前目录下Revocation文件夹中"
                shutil.move(r".\\Cache\\" + old_msg['msg_content'],
                            r".\\Revocation\\")
        else:
            msg_send = r"您的好友可能撤回了一个微信表情包,暂时不支持微信表情包,请谅解。"

        itchat.send(msg_send, toUserName='******')  # 将撤回消息的通知以及细节发送到文件助手

        msg_store.pop(old_msg_id)
Ejemplo n.º 13
0
def get_chatroom():
    global chatroom
    if chatroom is None:
        itchat.get_chatrooms(update=True)
        chatrooms = itchat.search_chatrooms(chatroomUserName);
        if chatrooms:
            return chatrooms[0]
        else:
            chatroom = itchat.create_chatroom(itchat.get_friends()[1:4], topic=chatroomUserName)
            if chatroom['BaseResponse']['ErrMsg'] == '':
                chatroom['UserName']=chatroomUserName
                return chatroom
    else:
        return chatroom
Ejemplo n.º 14
0
Archivo: run.py Proyecto: ciknight/wbot
def groupchat_reply(msg):
    groupNmae = itchat.search_chatrooms(userName=msg['FromUserName']).get('NickName')
    logging.info('group {}-{}: {}-{}: send {}'.format(
        groupNmae, msg['FromUserName'], msg['ActualNickName'], msg['ActualUserName'], msg['Content']))

    if msg['Text'][0] == interpreter.PY_SYMBLOE:
        replay_text = interpreter.run_py_cmd(msg['Text'][1:])
    elif msg['isAt']:
        replay_text = tuling.replay_text(msg['Text'], msg['ActualNickName']) or REPLAY_ERROR_TEXT
    else:
        replay_text = ''

    if replay_text:
        itchat.send(replay_text, msg['FromUserName'])
Ejemplo n.º 15
0
def SentChatRoomsMsg(name, context):
    itchat.get_chatrooms(update=True)
    iRoom = itchat.search_chatrooms(name)
    print(iRoom)
    for room in iRoom:
        if room['NickName'] == name:
            userName = room['UserName']
            print("--------=======--------" + userName)
            break
    itchat.send_msg(context, userName)
    print("发送到:" + name + "\n" "发送内容:" + context + "\n")
    print(
        "*********************************************************************************"
    )
Ejemplo n.º 16
0
def SendChatRoomsMsg(gname, context):
    #获取所有群的相关消息,update = True信息更新
    myroom = itchat.get_chatrooms(update=True)
    global username
    #传入指定群名进行搜索,之所以搜索,是因为群员的名称信息也在里面
    myroom = itchat.search_chatrooms(name=gname)
    for room in myroom:
        if room['NickName'] == gname:
            #遍历所有NickName为键值的信息进行匹配群名
            username = room['UserName']
            # 得到群名的唯一标识,进行信息发送
            itchat.send_msg(context, username)
        else:
            print('No groups found')
Ejemplo n.º 17
0
def xyz_reply(msg):
    group_list = [u'我是渣渣辉', u'我是轱天乐', u'探挽懒月']
    group_name = []
    for group in group_list:
        chat = itchat.search_chatrooms(name=group)
        if len(chat) > 0:
            group_name.append(chat[0]['UserName'])
    # 过滤小宇宙新闻
    result = xyz_compile.search(msg['Content'])

    if result is not None:
        if result.group() is not None:
            for group in group_name:
                itchat.send('%s' % (msg['Content']), toUserName=group)
Ejemplo n.º 18
0
    def get_all_info_from_wechat(self):
        itchat.auto_login(enableCmdQR=False)
        # 获取群
        roomslist = itchat.get_chatrooms()
        # 群名称
        itchat.dump_login_status()  # 显示所有的群聊信息,默认是返回保存到通讯录中的群聊
        myroom = itchat.search_chatrooms(name=u'小马飞单市场伙伴群')  # 群聊名称
        gsq = itchat.update_chatroom(myroom[0]['UserName'],
                                     detailedMember=True)

        l = gsq['MemberList']
        for i in l:
            print('昵称:%s 签名:%s 性别:%s ' %
                  (i['NickName'], i['Signature'], i['Sex']))
Ejemplo n.º 19
0
def group_reply_text(msg):

    from_user_name = msg['FromUserName']
    to_user_name = msg['ToUserName']
    print 'from :' + from_user_name
    print 'to :' + to_user_name
    un = from_user_name if u'@@' in from_user_name else to_user_name
    chat_room = itchat.search_chatrooms(userName=un)
    #获取群名称
    chat_room_name = chat_room['NickName'] if chat_room else 'wrong'
    print chat_room_name
    if CHATROOM_NAME in chat_room_name:
        s.handleMsg(msg['Content'], from_user_name, to_user_name)
    print msg['Content']
Ejemplo n.º 20
0
def send_special_wishes(chatroomName='wishgroup'):
    itchat.get_chatrooms(update=True)
    chatrooms = itchat.search_chatrooms(name=chatroomName)
    if chatroomName is None:
        print(u'search result is none')
    else:
        chatroom = itchat.update_chatroom(chatroom[0]['UserName'])
        for friend in chatroom['MemberList']:
            friend = itchat.search_friends(userName=friend['UserName'])
            print(
                REAL_SINCERE_WISH %
                (friend['DisplayName'] or friend['NickName']),
                friend['UserName'])
            time.sleep(.5)
Ejemplo n.º 21
0
def wechat(who='filehelper'):
    itchat.auto_login()

    def to(user):
        itchat.send('Hello, message from python', toUserName=user)

    itchat.send('Hello, message from python', toUserName=who)
    friends = itchat.get_friends()
    to(friends[0])
    rooms = itchat.get_chatrooms()
    to(rooms[0].UserName)
    # itchat.send('Hello, message from python', toUserName='******')
    room = itchat.search_chatrooms(name='股票与基金交流')
    to(room[0].UserName)
Ejemplo n.º 22
0
def sendImg():
    rooms = itchat.get_chatrooms(update=True, contactOnly=True)  #拿到所有的微信群
    rooms = itchat.search_chatrooms(u"指定群聊名称")
    f = "图片地址"
    if rooms is not None:
        username = rooms[0]['UserName']
        itchat.send("又到了签到的时间", toUserName=username)
        itchat.send_image(f, toUserName=username)

        #推送成功签到信息
        requests.post(url, data, headers)

    else:
        print('None group found')
Ejemplo n.º 23
0
def send_special_wishes(chatroomName='wishgroup'):
    itchat.get_chatrooms(update=True)
    chatrooms = itchat.search_chatrooms(name=chatroomName)
    if chatrooms is None:
        print(u'没有找到群聊:' + chatroomName)
    else:
        chatroom = itchat.update_chatroom(chatrooms[0]['UserName'])
        for friend in chatroom['MemberList']:
            friend = itchat.search_friends(userName=friend['UserName'])
            # 如果不是演示目的,把下面的方法改为itchat.send即可
            wish_word = REAL_SINCERE_WISH % (friend['RemarkName'] or friend['NickName'])
            print(wish_word)
            itchat.send(wish_word, friend['UserName'])
            time.sleep(.5)
Ejemplo n.º 24
0
def forwardInfo(msg):
    sources = []
    chatroom = itchat.search_chatrooms(name='dd')
    chatrooms = [chatroom]
    source = itchat.search_mps('Vegout')[0]['UserName']
    sources.append(source)
    if sources.__contains__(msg['FromUserName']):
        print(msg['FromUserName'])
        for chatroom in chatrooms:
            if msg['Type'] == SHARING:
                itchat.send('\n%s\n%s' % (msg['FileName'], msg['Url']), toUserName=chatroom[0]['UserName'])
            elif msg['Type'] == TEXT:
                content = msg['Text']
                itchat.send(content, toUserName=chatroom[0]['UserName'])
Ejemplo n.º 25
0
def morning_evening_task(position, username, individual, morning):
    msg = morning_nightfall_msg(position=position, morning=morning)
    try:
        if individual:
            user = itchat.search_friends(name=username)[0]
            user.send(msg)
        else:
            user = itchat.search_chatrooms(name=username)[0]
            user.send(msg)
    except Exception as morning_err:
        itchat.send("%s cannot receive msg! And error is %s" %
                    (username, str(morning_err)),
                    toUserName='******')
        itchat.send(msg, toUserName='******')
Ejemplo n.º 26
0
def get_chatroom():
    global CHATROOM
    if CHATROOM is None:
        itchat.get_chatrooms(update=True)
        chatrooms = itchat.search_chatrooms(CHATROOM_NAME)
        if chatrooms:
            return chatrooms[0]
        else:
            r = itchat.create_chatroom(itchat.get_friends()[1:4], topic=CHATROOM_NAME)
            if r['BaseResponse']['ErrMsg'] == '':
                CHATROOM = {'UserName': r['ChatRoomName']}
                return CHATROOM
    else:
        return CHATROOM
Ejemplo n.º 27
0
def night_task(username, individual):
    msg = night_msg()
    try:
        if individual:
            user = itchat.search_friends(name=username)[0]
            user.send(msg)
        else:
            user = itchat.search_chatrooms(name=username)[0]
            user.send(msg)
    except Exception as night_err:
        itchat.send("%s cannot receive msg! And error is %s" %
                    (username, str(night_err)),
                    toUserName='******')
        itchat.send(msg, toUserName='******')
Ejemplo n.º 28
0
def get_friend_status(group_name):
    chatroomName = group_name
    itchat.get_chatrooms(update=True)
    chatrooms = itchat.search_chatrooms(name=chatroomName)
    friend = itchat.get_friends()[1]
    r = itchat.add_member_into_chatroom(chatrooms[0]['UserName'], [friend])
    if r['BaseResponse']['ErrMsg'] == '':
        status = r['MemberList'][0]['MemberStatus']
        itchat.delete_member_from_chatroom(chatrooms[0]['UserName'], [friend])
        print({ 3: u'该好友已经将你加入黑名单。',
            4: u'该好友已经将你删除。', }.get(status,
            u'该好友仍旧与你是好友关系。'))
    else:
        print(u'无法获取好友状态,预计已经达到接口调用限制。')
 def get_all_info_from_wechat(self):
     itchat.auto_login(enableCmdQR=False)
     # 获取群
     roomslist = itchat.get_chatrooms()
     # 群名称
     itchat.dump_login_status()  # 显示所有的群聊信息,默认是返回保存到通讯录中的群聊
     myroom = itchat.search_chatrooms(name=u'河南人力资源交流厅')  # 群聊名称
     gsq = itchat.update_chatroom(myroom[0]['UserName'],
                                  detailedMember=True)
     fileName = 'allMember' + time.strftime(
         '%Y-%m-%d %H', time.localtime(time.time())) + '.txt'
     with open(fileName, 'a') as f:
         for c in gsq['MemberList']:
             f.write(c['NickName'] + ":" + c['DisplayName'] + '\n')
Ejemplo n.º 30
0
def get_chatroom():
    global CHATROOM
    if CHATROOM is None:
        itchat.get_chatrooms(update=True)
        chatrooms = itchat.search_chatrooms(CHATROOM_NAME)
        if chatrooms:
            return chatrooms[0]
        else:
            r = itchat.create_chatroom(itchat.get_friends()[1:4], topic=CHATROOM_NAME)
            if r['BaseResponse']['ErrMsg'] == '':
                CHATROOM = {'UserName': r['ChatRoomName']}
                return CHATROOM
    else:
        return CHATROOM
Ejemplo n.º 31
0
def job_function():
    #发送"午安"给文件助手
    iRoom = itchat.search_chatrooms(name='闲置')
    if len(iRoom)==0:
        itchat.send("没找到群。", toUserName="******")
        print('No group found')
        
    else:
        for room in iRoom:
                gn = room['UserName']
                break
        itchat.send_image('/home/moyuge/code/screen.jpg', toUserName=gn)
        itchat.send("320出24寸曲面屏,可刀。", toUserName=gn)
        print('Message has been sent to',room['NickName'])
Ejemplo n.º 32
0
 def GetMsgFrom(self, msg):
     """
     提取消息中的联系人和群组名
     :param msg: 微信消息
     :return: 联系人,群组名
     """
     msg_group = r""
     if itchat.search_friends(userName=msg['FromUserName']):
         if itchat.search_friends(userName=msg['FromUserName'])['RemarkName']:
             msg_from = itchat.search_friends(userName=msg['FromUserName'])['RemarkName']  # 消息发送人备注
         elif itchat.search_friends(userName=msg['FromUserName'])['NickName']:  # 消息发送人昵称
             msg_from = itchat.search_friends(userName=msg['FromUserName'])['NickName']  # 消息发送人昵称
         else:
             msg_from = r"读取发送消息好友失败"
     else:
         msg_from = msg['ActualNickName']
         if msg['ActualUserName'] == itchat.get_friends()[0]['UserName']:
             return
         if itchat.search_chatrooms(userName=msg['FromUserName']):
             msg_group += r'[ '
             msg_group += itchat.search_chatrooms(userName=msg['FromUserName'])['NickName']
             msg_group += r' ]'
     return msg_from, msg_group
def xyz_reply(msg):
    group_list = [u'我是渣渣辉', u'我是轱天乐', u'探挽懒月']
    group_name = []
    for group in group_list:
        chat = itchat.search_chatrooms(name=group)
        if len(chat) > 0:
            group_name.append(chat[0]['UserName'])
    # 过滤小宇宙新闻
    result = xyz_compile.search(msg['Content'])

    if result is not None:
        if result.group() is not None:
            for group in group_name:
                itchat.send('%s' % (msg['Content']), toUserName=group)
def auto_add_member(userName, roomName):
    friend = itchat.search_friends(userName=userName)
    print(friend)
    itchat.get_chatrooms(update=True)
    chatroom = itchat.search_chatrooms(roomName)[0]
    print(chatroom['UserName'])
    #如果群聊人数不满100人,可以去掉useInvitation=True,这样好友发送关键字后会被直接加入群
    r = itchat.add_member_into_chatroom(chatroom['UserName'], [friend],
                                        useInvitation=True)
    print(r)
    if r['BaseResponse']['ErrMsg'] == '请求成功':
        return '自动邀请加入群聊成功!请等待获取加群链接!'
    else:
        return '请求发生错误,请重试!'
Ejemplo n.º 35
0
def SentChatRoomsMsg(name, context):
    itchat.get_chatrooms(update=True)
    iRoom = itchat.search_chatrooms(name)
    for room in iRoom:
        if room['NickName'] == name:
            userName = room['UserName']
            break
    itchat.send_msg(context, userName)
    print("发送时间:" + datetime.now().strftime("%Y-%m-%d %H:%M:%S") + "\n"
          "发送到:" + name + "\n"
          "发送内容:" + context + "\n")
    print(
        "*********************************************************************************"
    )
Ejemplo n.º 36
0
def group_text_reply(msg):
  global autoSendinfoGroup
  ActualNickName=msg['ActualNickName'] #发消息的人
  #msg1= msg['User']
  #msg2=msg1['NickName']
  groupName=msg['User']['NickName'] #这样也可以获取群名称
  print("group#"+groupName+"#"+ActualNickName+":"+msg['Text'])
  if (ActualNickName=="" or ActualNickName=="admin"):#TODO admin
    content1 = msg['Text'][-2:]#截取最后两位
    key = msg['Text'][0:-2].rstrip()
    print("content1=" + content1)
    if(content1=="!R"): #  remove name
      userList.remove(key) #如果没有 会报错 但不影响
    elif(content1=="!W"): # 写入 过滤
      userList.append(key)  # 允许重复记录
    elif(content1 == "!G"): #关闭
      autoSendinfoGroup=False
    elif (content1 == "!K"): #开启
      autoSendinfoGroup = True
  else:#成员
    if (msg['Text']=="false"):  # 写入
      userList.append(ActualNickName)
    elif (msg['Text']=="true"): # remove name
      userList.remove(ActualNickName)  # 如果没有 会报错 但不影响

  #print("group_text_reply  autoSendinfoALL:")
  #print(autoSendinfoGroup)
  if autoSendinfoGroup:
    autoSendinfo = True
    #ActualNickName="@"+ActualNickName
    gname='群名称'#TODO 根据自己微信群调整
    from_group=''
    myroom = itchat.search_chatrooms(name=gname)
    for room in myroom:
      if room['NickName'] == gname:
        from_group = room['UserName']

    if (msg['FromUserName']==from_group):# 针对指定的群 开启自动回复
      if autoSendinfoGroup:
        itchat.send(u'%s' % tuling(msg['Text'])+"。" ,msg['FromUserName'])
    else:# 针对其他群
      if msg['isAt']: #@
        for item in userList:
          if (item == ActualNickName):
            autoSendinfo = False
            break
        if autoSendinfo:
          #print("AUTO")
          itchat.send(u'@%s\u2005 %s' % (msg['ActualNickName'], tuling(msg['Text']) + "。"), msg['FromUserName'])
def xyz_reply(msg):
    group_list = [u'淫意天盛娱乐集团', u'小猪的Python学习交流群']
    group_name = []
    for group in group_list:
        chat = itchat.search_chatrooms(name=group)
        if len(chat) > 0:
            group_name.append(chat[0]['UserName'])
    # 过滤小宇宙新闻
    print(msg['ActualNickName'])
    if msg['ActualNickName'] is not None and "小宇宙" in msg['ActualNickName']:
        result = xyz_compile.search(msg['Content'])
        if result is not None:
            if result.group() is not None:
                for group in group_name:
                    itchat.send('%s' % (msg['Content']), toUserName=group)
Ejemplo n.º 38
0
 def text_to_chatroom(self):
     #print("执行:text_to_chatroom")
     text_send = self.textEdit_text_chatroom.toPlainText()
     text_chatroom = self.lineEdit_text_chatroom.text()
     search_username = itchat.search_chatrooms(text_chatroom)
     if search_username:
         text_username = search_username[0]['UserName']
         itchat.send(text_send, toUserName=text_username)
         self.output_info("成功发送文字至:[%s]" % text_chatroom)
         fromChatroom = True
         message = "Python → " + text_chatroom + ":" + text_send
         send_time = time.time()
         self.write_log(fromChatroom, message, send_time)
     else:
         self.output_info("群聊名称出错了!")
Ejemplo n.º 39
0
def get_chatroom():
    global chatroom
    if chatroom is None:
        itchat.get_chatrooms(update=True)
        chatrooms = itchat.search_chatrooms(chatroomUserName)
        if chatrooms:
            return chatrooms[0]
        else:
            chatroom = itchat.create_chatroom(itchat.get_friends()[1:4],
                                              topic=chatroomUserName)
            if chatroom['BaseResponse']['ErrMsg'] == '':
                chatroom['UserName'] = chatroomUserName
                return chatroom
    else:
        return chatroom
Ejemplo n.º 40
0
def Revocation(msg):
    mytime = time.localtime()
    msg_time_touser = mytime.tm_year.__str__() \
            + '/' + mytime.tm_mon.__str__() \
            + '/' + mytime.tm_mday.__str__() \
            + ' ' + mytime.tm_hour.__str__() \
            + ':' + mytime.tm_min.__str__() \
            + ':' + mytime.tm_sec.__str__()
    print("msg_time_touser = %s" % msg_time_touser)
    msg_id = msg['MsgId']
    msg_time = msg['CreateTime']
    chatroom = itchat.search_chatrooms(userName=msg['FromUserName'])
    msg_chatfrom = None
    if chatroom: msg_chatfrom = chatroom.get('NickName')
    msg_from = msg['ActualNickName']
    msg_type = msg['Type']
    msg_content = None
    msg_url = None
    
    if msg_type == 'Text' or msg_type == 'Friends':
        msg_content = msg['Text']
    elif msg_type == 'Picture' or msg_type == 'Recording' or msg_type == 'Attachment' or msg_type == 'Video':
        msg_content = msg['FileName']
        msg['Text'](msg['FileName'])
    elif msg_type == 'Card':
        msg_content = msg['RecommendInfo']['NickName'] + u'的名片'
    elif msg_type == 'Map':
        x, y, location = re.search('<location x=\"(.*?)\" y=\"(.*?)\".*label=\"(.*?)\".*', msg['OriContent']).group(1, 2, 3)

        if location is None:
            msg_content = u'纬度->' + x.__str__() + u'经度->' + y.__str__()
        else:
            msg_content = u'' + location
    elif msg_type == 'Sharing':
        msg_content = msg['Text']
        msg_url = msg['Url']
    
    msg_dict = {'msg_id': msg_id, 'msg_type': msg_type, 'msg_chatfrom': msg_chatfrom, 'msg_from': msg_from, 'msg_time': msg_time, 'msg_time_touser': msg_time_touser, 'msg_content': msg_content, 'msg_url': msg_url}
    msg_list.append(msg_dict)
    print('msg_list saved is ')
    print(msg_list)
    ClearTimeOutMsg()
Ejemplo n.º 41
0
def get_group_id(group_name):
    group_list = itchat.search_chatrooms(name=group_name)
    return group_list[0]['UserName']
Ejemplo n.º 42
0
def group_id(name):
    print name

    df = itchat.search_chatrooms(name=name)
    return df[0]['UserName']
Ejemplo n.º 43
0
                    logged_errors.add(msgid)
            time.sleep(.5)

def msg_mainloop():
    log('success','微信机器人已启动')
    while not stopped:
        try:
            time.sleep(10)
            send_msgs()
        except Exception as e:
            print('!!! exception: [%s] %s'%(type(e),e))
    log('debug','微信机器人已停止工作')

@itchat.msg_register(itchat.content.TEXT,isGroupChat=True)
def status_indicate(msg):
    if msg['isAt']:
        return '[发呆]'

@itchat.msg_register(itchat.content.TEXT,isGroupChat=False)
def custom_push(msg):
    cmd,_,content=msg['Content'].partition(' ')
    if cmd.lower()=='send':
        return '成功' if itchat.send_msg(content,toUserName=group_name) else '失败'
        
itchat.auto_login(hotReload=True,enableCmdQR=2)

group_name=itchat.search_chatrooms(name=CHAT_NAME)[0]['UserName']
print('wx group username:',group_name)

threading.Thread(target=msg_mainloop).start()
itchat.run()