예제 #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 = "呵呵各地"
예제 #2
0
def save_jpg():
	city_list = ['xiamentianqi','beijingtianqi']
	for index,city in enumerate(city_list):
		time.sleep(1)
		encode_city = quote(city)
		url = 'https://www.baidu.com/s?ie=UTF-8&wd=%s'%encode_city	
		picName = '%s.png'%index		
		browser = webdriver.PhantomJS(executable_path=r'/usr/local/bin/phantomjs')
		browser.get(url)
		browser.maximize_window()
		browser.save_screenshot(picName)#保存截图		
		
		#获取天气模板的位置、尺寸大小
		imgelement = browser.find_element_by_xpath('//*[@id="1"]/div[1]')
		location = imgelement.location#获取天气x,y轴坐标
		size = imgelement.size#获取天气的长宽
		
		rangle = (int(location['x']),int(location['y']),int(location['x']+size['width']),int(location['y']+size['height']-20))
		i = Image.open(picName)	#打开0.png
		tinaqi = i.crop(rangle)#使用Image的crop函数,从截图中再次截取我们需要的		
		tinaqi.save('send_%s.png'%index)		
		browser.close()	
		
		
		#发送
		user_content = itchat.search_friends(name=u'雨一直下')
		userName = user_content[0]['UserName']
		itchat.send_image('send_%s.png'%index,toUserName = userName)
		
		if city == 'xiamentianqi':
			user_content_baby = itchat.search_friends(name=u'徐莹')
			userName_baby = user_content_baby[0]['UserName']
			itchat.send_image('send_%s.png'%index,toUserName = userName_baby)
예제 #3
0
def get_fund():
	'''
	162605景顺长城鼎益混合(LOF)
	160505博时主题行业混合(LOF)
	002121广发沪港深新起点股票
	000011华夏大盘精选混合
	163402兴全趋势投资混合(LOF)
	070032
	217027
	165312
	519066
	110022
	
	'''
	#fund_list = ['110022','160505','163402','162605','002121','000011','070032','217027','165312','519066','110022']
	#fund_list = ['162605','160505','002121','000011','163402','070032','217027','165312','519066','110022']
	fund_list = ['dapan',]
	
	for index,fund in enumerate(fund_list):
		fund_id = str(fund)		
		url = 'https://www.baidu.com/s?ie=UTF-8&wd=%s'%str(fund_id)
		#url = 'http://fund.eastmoney.com/%s.html'%str(fund_id)			
		picName = 'fund_%s.png'%index
		browser = webdriver.PhantomJS(executable_path=r'/usr/local/bin/phantomjs')
		browser.get(url)
		browser.maximize_window()
		browser.save_screenshot(picName)#保存截图	
		
		
		imgelement = browser.find_element_by_xpath('//*[@id="1"]/div[1]')
		'''
		if fund_id == '002121':
			imgelement = browser.find_element_by_xpath('//*[@id="2"]')
		'''
		location = imgelement.location#获取x,y轴坐标
		size = imgelement.size#获取长宽
		
		rangle = (int(location['x']),int(location['y']),int(location['x']+size['width']),int(location['y']+size['height']-20))
		i = Image.open(picName)	#打开
		tinaqi = i.crop(rangle)#使用Image的crop函数,从截图中再次截取我们需要的		
		tinaqi.save('send_fund_%s.png'%index)		
		browser.close()	
		
		
		#发送
		user_content = itchat.search_friends(name=u'雨一直下')
		userName = user_content[0]['UserName']
		itchat.send_image('send_fund_%s.png'%index,toUserName = userName)
		
		
		
		user_content_baby = itchat.search_friends(name=u'徐莹')
		userName_baby = user_content_baby[0]['UserName']
		itchat.send_image('send_fund_%s.png'%index+1,toUserName = userName_baby)		
예제 #4
0
파일: wxrobot.py 프로젝트: Wangab/weixin
def save_msg(msg):
    fromu = itchat.search_friends(userName = msg.get("FromUserName", ""))
    if fromu is not None:
        print(fromu["NickName"])
        print fromu["RemarkName"]
    print(msg["Text"])
    db.Message.save(msg)
예제 #5
0
def  main():
	#登陆微信
	itchat.auto_login(hotReload=True)
	user_content = itchat.search_friends(name=u'雨一直下')
	userName = user_content[0]['UserName']
	itchat.send(getWeather(000),toUserName = userName)#
	itchat.send(getWeather(000),toUserName = userName)#
예제 #6
0
def send_news():
    try:
        # 登陆你的微信账号,会弹出网页二维码,扫描即可
        itchat.auto_login(hotReload=True)
        # 获取你对应的好友备注,这里的小明我只是举个例子
        # 改成你最心爱的人的名字。
        my_friend = itchat.search_friends(name=u'小明')
        # 获取对应名称的一串数字
        XiaoMing = my_friend[0]["UserName"]
        # 获取金山字典的内容
        message1 = str(get_news()[0])
        content = str(get_news()[1][17:])
        message2 = str(content)
        message3 = "来自你最爱的人"
        # 发送消息
        itchat.send(message1, toUserName=XiaoMing)
        itchat.send(message2, toUserName=XiaoMing)
        itchat.send(message3, toUserName=XiaoMing)
        # 每86400秒(1天),发送1次,
        # 不用linux的定时任务是因为每次登陆都需要扫描二维码登陆,
        # 很麻烦的一件事,就让他一直挂着吧
        # t = time(86400, send_news())
        # t.start()
    except:
        message4 = u"今天最爱你的人出现了 bug /(ㄒoㄒ)/~~"
        itchat.send(message4, toUserName=XiaoMing)
예제 #7
0
def get_friend_status(friend):
    ownAccount = itchat.get_friends(update=True)[0]
    if friend['UserName'] == ownAccount['UserName']:
        return u'Own account'
    elif itchat.search_friends(userName=friend['UserName']) is None:
        return u'Not a friend'
    else:
        room = chatroom or get_chatroom()
        r = itchat.add_member_into_chatroom(room['UserName'], [friend])
#       r = itchat.update_chatroom(chatroom)
        if r['BaseResponse']['ErrMsg'] == u'请求成功':
            if len(r['MemberList']) == 0:
                return u'No member in the chatroom'
            else:
                status = r['MemberList'][0]['MemberStatus']
                itchat.delete_member_from_chatroom(room['UserName'], [friend])
                return { 3: u'该好友已经将你加入黑名单。',
                         4: u'该好友已经将你删除。', }.get(status,u'该好友仍旧与你是好友关系。')
#                if status == 3:
#                    return u'该好友已经将你加入黑名单。'
#                elif status == 4:
#                    return u'该好友已经将你删除。'
#                else:
#                    return get(status) + u'该好友仍旧与你是好友关系。'
        else:
            return r['BaseResponse']['ErrMsg'] + u'无法获取好友状态,预计已经达到接口调用限制'
예제 #8
0
def itchat_send():

    sms = get_hyper_links_rmrb()
    sms_text = "\n".join(sms)
    itchat.auto_login()
    name = itchat.search_friends(name = 'Mao')
    Mao = name[0]["UserName"]
    itchat.send_msg(sms_text, toUserName = Mao)
예제 #9
0
def clockFunc():
    account=itchat.search_friends('杨雨婷')
    userName = account[0]['UserName']
    morningTime = 3600 * 3 - 900
    time.sleep(morningTime)
    print('haha')
    itchat.send("哈哈哈,我又来啦~~~,起床啦起床啦!", toUserName=userName)
    print(account)
예제 #10
0
def print_content(msg):
    NickName = msg['User']['NickName']
    user = itchat.search_friends(name=NickName)[0]
    text = msg['Text']

    if text in message_dict.keys():
        user.send(message_dict[text])
    else:
        user.send(u"你好啊%s,我目前还不支持这个功能"%NickName)
예제 #11
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)
예제 #12
0
def reply_text(msg):

    print (msg)
    res = getData(msg.text)
    username = itchat.search_friends(userName=msg['FromUserName'])['NickName']
    defaultReq = u'Hello:' + username + ',我是微信个人助手,你可以和我说话了^-^'
    if username in said:
        msg.user.send(res)
    else:
        said.append(username)
        msg.user.send(defaultReq)
예제 #13
0
def text_reply(msg):
    print msg
        # 微信里,每个用户和群聊,都使用很长的ID来区分
        if msg["MsgType"] == 49:
            print "个人分享文章地址链接Url:" + "---------------------------"
                
                xmlcontent = lxml.etree.HTML(get_html(msg["Url"]))
                print xmlcontent
                    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 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 "------------个人"
                                                                # 获取到的信息是某某人和登录者之间的通讯,如果不是和登录这通讯就获取不到
                                                                print itchat.search_friends(userName=msg['FromUserName'])['NickName']
                                                                print itchat.search_friends(userName=msg['ToUserName'])['NickName']
                                                                    
                                                                    else:
                                                                        print "不是个人分享的文章"
예제 #14
0
 def GetUserName(self, Comment):
     '''
     通过备注获取到用户的UserName
     :return:
     '''
     userDict =  itchat.search_friends(name=Comment)
     if(userDict):
         return userDict[0]['UserName']
     else:
         my = userDict['UserName']
         itchat.send(u"向用户[%s]发送失败,请检查是否存在该好友!"%(Comment), my)
         return None
예제 #15
0
def get_newusers(chatroom):
    chatroom = itchat.update_chatroom(chatroom['UserName'])
    newusers = []
    for friend in chatroom['MemberList']:
        #print("friend name is : %s " % (friend['DisplayName'] or friend['NickName']))
        existfriend = itchat.search_friends(userName=friend['UserName'])
        if existfriend is not None:
            print('%s is in the friend list' % (friend['DisplayName'] or friend['NickName']))
            pass
        else:
            newusers.append(friend)
    return newusers
def tick():
    users = itchat.search_friends(name=u'七七') # 找到你女朋友的名称
    userName = users[0]['UserName']
    meetDate = dt.date(2012,4,22)  # 这是你跟你女朋友相识的日期
    now = dt.datetime.now()     # 现在的时间
    nowDate = dt.date.today()  # 今天的日期
    passDates = (nowDate-meetDate).days # 你跟你女朋友认识的天数
    itchat.send(u'今天是我们在一起第%d天,%s, 亲亲小媳妇'%(passDates,random.sample(greetList,1)[0]),toUserName=userName) # 发送问候语给女朋友
#     itchat.send(u'就问你服不服,%s'%(random.sample(greetList,1)[0]),toUserName=userName) 
    nextTickTime = now + dt.timedelta(days=1)
#     nextTickTime = now + dt.timedelta(seconds=2)
    nextTickTime = nextTickTime.strftime("%Y-%m-%d 00:00:00") 
    my_scheduler(nextTickTime) # 设定一个新的定时任务,明天零点准时问候
예제 #17
0
def get_friends_status(friend):
    ownAccount = itchat.get_friends(update=True)[0]
    if friend['UserName'] == ownAccount['UserName']:
        return u'检测到本人账号。'
    elif itchat.search_friends(userName=friend['UserName']) is None:
        return u'该用户不在你的好友列表中。'
    else:
        chatroom = CHATROOM or get_chatroom()
        if chatroom is None: return CHATROOM_MSG
        r = itchat.add_member_into_chatroom(chatroom['UserName'], [friend])
        if r['BaseResponse']['ErrMsg'] == '':
            status = r['MemberList'][0]['MemberStatus']
            itchat.delete_member_from_chatroom(chatroom['UserName'],[friend])
            return { 3: u'该好友已经将你加入黑名单。', 4: u'该好友已经将你删除。', }.get(status, u'该好友仍旧与你是好友关系。')
        else:
            return u'无法获取好友状态,预计已经达到接口调用限制。'
예제 #18
0
def get_prob(msg):
    reply = ''
    friend = itchat.search_friends(userName = msg['FromUserName'])
    ownAccount = itchat.get_friends(update=True)[0]
    if friend['UserName'] == ownAccount['UserName']:
        now = datetime.utcnow()
        now = time.mktime(now.timetuple())
        df_future = pd.read_csv('data/btc_usd_full_next_quarter_future.csv','r',delimiter='\t', index_col=None)
        df_spot = pd.read_csv('data/btc_usd_full_spot.csv','r',delimiter='\t', index_col=None)
        price_f = get_price(now, df_future)
        price_s = get_price(now, df_spot)
        if msg['Text'] == u'diff':
            return str(price_f - price_s)
        if msg['Text'] == u'future':
            return str(price_f)
        if msg['Text'] == u'spot':
            return str(price_s)
예제 #19
0
파일: checks.py 프로젝트: XuQiao/codestudy
def findgroups(friendname):
    chatrooms = itchat.get_chatrooms(update=True)
#    chatrooms = itchat.search_chatrooms(chatroomUserName);
#    chatrooms = pd.DataFrame(chatrooms)
    #print(chatrooms.iloc[0])
    if chatrooms is not None:
       # print chatrooms
        pass
    else:
        print("Cannot find the chatroom: ")
        return None
    friends = itchat.search_friends(name=friendname, userName=None, remarkName=None, nickName=None,wechatAccount=None)
    for friend in friends:
        for chatroom in chatrooms:
            print chatroom
            if friend in chatroom['self']:
                print 'friend ' + friend['username'] + ' is in ' + chatroom['username']
    print friend
예제 #20
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']
    msg_from = itchat.search_friends(userName=msg['FromUserName']).get('NickName')
    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_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()
def text_reply(msg):
    if msg['Type'] == 'Text':
        reply_content = msg['Text']
    elif msg['Type'] == 'Picture':
        reply_content = u"图片: " + msg['FileName']
    elif msg['Type'] == 'Card':
        reply_content = u" " + 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:
            reply_content = u"位置: 纬度->" + x.__str__() + " 经度->" + y.__str__()
        else:
            reply_content = u"位置: " + location
    elif msg['Type'] == 'Note':
        reply_content = u"通知"
    elif msg['Type'] == 'Sharing':
        reply_content = u"分享"
    elif msg['Type'] == 'Recording':
        reply_content = u"语音"
    elif msg['Type'] == 'Attachment':
        reply_content = u"文件: " + msg['FileName']
    elif msg['Type'] == 'Video':
        reply_content = u"视频: " + msg['FileName']
    else:
        reply_content = u"消息"

    friend = itchat.search_friends(userName=msg['FromUserName'])
    itchat.send(u"Friend:%s -- %s    "
                u"Time:%s    "
                u" Message:%s" % (friend['NickName'], friend['RemarkName'], time.ctime(), reply_content),
                toUserName='******')

    itchat.send(u"我已经收到你在【%s】发送的消息【%s】稍后回复。--微信助手(Python版)" % (time.ctime(), reply_content),
                toUserName=msg['FromUserName'])
예제 #22
0
def reply(msg):
    reply = ''
    friend = itchat.search_friends(userName = msg['FromUserName'])
    ownAccount = itchat.get_friends(update=True)[0]
    if friend['UserName'] == ownAccount['UserName']:
        if msg['Text'] == u'price':
            prices = u''
            for product in products:
                price_info = get_price(product)[0]
                bids = price_info['bids'][0][0]
                asks = price_info['asks'][0][0]
                out = 'bids: '+ bids + ' asks: '+ asks + '\n'
                prices = prices + out
            return prices
        else:
            return u'good'
        #return u'Own account'
        #return u'你是那颗星星,我是你旁边的这颗星,我的整个轨迹是被你影响的,即使有一天这颗星星熄灭了,它变成了暗物质,它变成了看不见的东西,它依然在影响着我的轨迹,你的出现永远改变着我的星轨,无论你在哪里。'
#    还是同样的雨天,还是相同的地点,在转角的咖啡馆,我又再一次遇到了那张我永远忘不掉的脸。四目相对,终于,她颤抖地问我,你还可以像以前一样牵着我过马路吗?我说:“奶奶,上次你走到马路中间就躺下了,讹了我几个月的工资啊 !”'
    elif friend is None:
        return u'Not a friend'
    elif friend.get('NickName') in  [u'风早',u'Lemon']:
        reply = ' test autoreply '
    return reply # or defaultReply
예제 #23
0
def handle_receive_msg(msg):
    # print(msg)
    global face_bug
    msg_time_rec = time.strftime("%Y-%m-%d %H:%M:%S",
                                 time.localtime())  #接受消息的时间
    # msg_from = itchat.search_friends(userName=msg['FromUserName'])['NickName']   #在好友列表中查询发送信息的好友昵称
    msg_from_1 = itchat.search_friends(userName=msg['FromUserName'])
    if msg_from_1 is None:
        msg_from_2 = itchat.search_friends(userName=msg['ActualUserName'])
        if msg_from_2 is None:
            msg_from = '未知'
        else:
            msg_from = msg_from_2['NickName']
    else:
        msg_from = msg_from_1['NickName']

    # msg_from = itchat.search_friends(userName=msg['FromUserName'])
    # if msg_from is None:
    #     msg_from = itchat.search_friends(userName=msg['FromUserName'][1:])
    # if not msg_from is None:
    #     msg_from=msg_from['NickName']

    print(msg_from)
    msg_time = msg['CreateTime']  #信息发送的时间
    msg_id = msg['MsgId']  #每条信息的id
    msg_content = None  #储存信息的内容
    msg_share_url = None  #储存分享的链接,比如分享的文章和音乐
    # print(msg['Type'])
    # print(msg['MsgId'])
    if msg['Type'] == 'Text' or msg['Type'] == 'Friends':  #如果发送的消息是文本或者好友推荐
        msg_content = msg['Text']
        # print(msg_content)

    #如果发送的消息是附件、视屏、图片、语音
    elif msg['Type'] == "Attachment" or msg['Type'] == "Video" \
            or msg['Type'] == 'Picture' \
            or msg['Type'] == 'Recording':
        msg_content = msg['FileName']  #内容就是他们的文件名
        msg['Text'](str(msg_content))  #下载文件
    elif msg['Type'] == 'Card':  #如果消息是推荐的名片
        msg_content = msg['RecommendInfo']['NickName'] + '的名片'  #内容就是推荐人的昵称和性别
        if msg['RecommendInfo']['Sex'] == 1:
            msg_content += '性别为男'
        else:
            msg_content += '性别为女'

        print(msg_content)
    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 = r"纬度->" + x.__str__() + " 经度->" + y.__str__(
            )  #内容为详细的地址
        else:
            msg_content = r"" + location
    elif msg['Type'] == 'Sharing':  #如果消息为分享的音乐或者文章,详细的内容为文章的标题或者是分享的名字
        msg_content = msg['Text']
        msg_share_url = msg['Url']  #记录分享的url
        print(msg_share_url)
    face_bug = msg_content

    ##将信息存储在字典中,每一个msg_id对应一条信息
    if msg_from is None:
        msg_from = '未知'
    msg_information.update({
        msg_id: {
            "msg_from": msg_from,
            "msg_time": msg_time,
            "msg_time_rec": msg_time_rec,
            "msg_type": msg["Type"],
            "msg_content": msg_content,
            "msg_share_url": msg_share_url
        }
    })
예제 #24
0
import itchat

# log in
itchat.auto_login(hotReload=True)

friends = []
msg = ""
for friend in friends:
    userfinfo = itchat.search_friends(friend)
    userid = userfinfo[0]["UserName"]
    itchat.send_msg(msg=msg, toUserName=userid)







import itchat

# 自动登录方法,hotReload=True可以缓存,不用每次都登录,但是第一次执行时会出现一个二维码,需要手机微信扫码登录
itchat.auto_login(hotReload=True)

# 搜索好友,search_friends("xxx"),其中"xxx"为好友昵称,备注或微信号不行
userfinfo = itchat.search_friends("智能群管家014")   # "智能群管家014"为好友昵称

# print(userfinfo),获取userinfo中的UserName参数
userid = userfinfo[0]["UserName"]   # 获取用户id

# 调用微信接口发送消息
itchat.send("hello dear", userid)  # 通过用户id发送信息
예제 #25
0
def find_firends(nick_name):
    return itchat.search_friends(nickName=nick_name)
예제 #26
0
itchat.auto_login()

# 获取好友列表
friends = itchat.get_friends(update=True)[0:]

# 初始化计数器,有男有女,当然,有些人是不填的
male = female = other = 0

# 遍历这个列表,列表里第一位是自己,所以从"自己"之后开始计算
# 1表示男性,2女性
for i in friends[1:]:
    sex = i["Sex"]
    if sex == 1:
        male += 1
    elif sex == 2:
        female += 1
    else:
        other += 1

# 总数算上,好计算比例啊~
total = len(friends[1:])

# 好了,打印结果
print u"男性好友:%.2f%%" % (float(male) / total * 100)
print u"女性好友:%.2f%%" % (float(female) / total * 100)
print u"未填性别:%.2f%%" % (float(other) / total * 100)

friends = itchat.search_friends(name='xi')

print friends
예제 #27
0
파일: view.py 프로젝트: lambdahuang/WeAlert
def run_itchat():
    global owner_dict
    itchat.auto_login(hotReload=True, enableCmdQR=2)
    owner_dict = itchat.search_friends()
    itchat.run()
예제 #28
0
파일: wechat.py 프로젝트: dachuanwud/cnn-
def sendGreeting(msg):
    global replied
    friend = itchat.search_friends(userName=msg['FromUserName'])
    itchat.send((friend['RemarkName'] + '这是给你准备的笑话,愿你开心每一天!!!     笑话:' +
                 getRandomGreeting()), msg['FromUserName'])
    replied.append(msg['FromUserName'])
예제 #29
0
파일: Main.py 프로젝트: zoe27/WXRobot
def get_real_user_name(name):
    user_info = itchat.search_friends(name=name)
    if (len(user_info) > 0):
        return user_info[0]['UserName']
    else:
        return ''
예제 #30
0
    answer = data['text']
    return answer


# 对于群聊信息,定义获取想要针对某个群进行机器人回复的群ID函数
def group_id(name):
    df = itchat.search_chatrooms(name=name)
    return df[0]['UserName']


groups.append(group_id(u'库有引力'))
groups.append(group_id(u'大北湖幸福快乐的家'))
groups.append(group_id(u'早睡早起方能养生'))
#groups.append(group_id(u'小伙伴们'))

mygirl = itchat.search_friends(name=u'我方水晶')[0]['UserName']


# 注册文本消息,绑定到text_reply处理函数
# text_reply msg_files可以处理好友之间的聊天回复
@itchat.msg_register([TEXT, MAP, CARD, NOTE, SHARING])
def text_reply(msg):
    if msg['FromUserName'] == mygirl:
        if u'老公' in msg['Text']:
            itchat.send(u'媳妇,有何吩咐!', mygirl)
    else:
        friend = itchat.search_friends(userName=msg['FromUserName'])
        friend_name = friend['RemarkName']
        print('%s said: %s' % (friend_name, msg['Text']))
        itchat.send('%s' % tuling(msg['Text']), msg['FromUserName'])
예제 #31
0
파일: chatbot.py 프로젝트: PhonyLou/chatbot
    def __init__(self, conf=None):
        """
        init methods.
            initialize listen rule, there are three element in it, `onechat`, `groupchat` and
            `mechat`, onechat means private chat, groupchat means a chatroom, mechat means self
            word content.All the rules defined will store in this dict, and in order to reduce 
            code logic to set these three value as defaultdict.

            login wechat client.it set hotReload as True, so you can login without scan QR image
            agin and agin.

            get your information such as nickName and userName, nick name is different from username
            refer from itchat document and itchat support using username to search user information.

            initialize logger module.chatbot use python `logging` module to note the important data.

            initialize chat context.Chat context store the message object and it's relative independence
            in different threading.
        """
        # listen_rule
        # store your listen rules
        # you can add new rule by using `listen` methods or `add_listen_rule` method
        self.listen_rule = {
            "onechat": collections.defaultdict(list), 
            "groupchat": collections.defaultdict(list), 
            "mechat": collections.defaultdict(list)
        }

        # login to wechat client
        if conf is not None:
            login_conf = conf.get('login_conf', {})
        else:
            login_conf = {}
        hotReload           = login_conf.get('hotReload',           False)
        statusStorageDir    = login_conf.get('statusStorageDir',    'chatbot.pkl')
        enableCmdQR         = login_conf.get('enableCmdQR',         False)
        picDir              = login_conf.get('picDir',              None)
        qrCallback          = login_conf.get('qrCallback',          None)
        loginCallback       = login_conf.get('loginCallback',       None)
        exitCallback        = login_conf.get('exitCallback',        None)
        itchat.auto_login(
                        hotReload       =   hotReload, 
                        statusStorageDir=   statusStorageDir,
                        enableCmdQR     =   enableCmdQR,
                        picDir          =   picDir,
                        qrCallback      =   qrCallback,
                        loginCallback   =   loginCallback,
                        exitCallback    =   exitCallback)

        # initialize self information
        # itchat provide `search_friends` methods to search user information by user name
        # if no user name support it return your own infomation, it is useful so save it.
        me = itchat.search_friends()
        self.nickName = me['NickName']
        self.userName = me['UserName']

        # initialize logger module
        # it's important to log while the program is running, chatbot use logging module to
        # log the important data, and it send to stout device
        # TODO: log configurable
        if conf is not None:
            logger_conf = conf.get('logger_conf', {})
        else:
            logger_conf = {}
        level   = logger_conf.get('level',  'DEBUG')
        format  = logger_conf.get('format', '%(asctime)s - %(name)s - %(levelname)s - %(message)s')
        name    = logger_conf.get('name',   __name__)
        path    = logger_conf.get('path',   None)

        if level.upper() == "INFO":
            level = logging.INFO
        elif level.upper() == "WARNING":
            level = logging.WARNING
        elif level.upper() == "ERROR":
            level = logging.ERROR
        elif level.upper() == "FATAL":
            level = logging.FATAL
        else:
            level = logging.DEBUG

        logging.basicConfig(level=level, format=format, filename=path)
        self.logger = logging.getLogger(name)
예제 #32
0
def handle_receive_msg(msg):
    global face_bug
    msg_time_rec = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())  #接受消息的时间 
    fromName = msg['FromUserName'] 
    toUserName = msg['ToUserName']
    nickName = ''
    friend = itchat.search_friends(userName=fromName)
    mp = itchat.search_mps(userName=fromName)
    if friend != None :
        if(friend.RemarkName != ''):
            nickName = friend.RemarkName
        else:
            nickName = friend['NickName'] #在好友列表中查询发送信息的好友昵称 
    elif mp != None: 
        nickName = mp['NickName']
    elif mp == None and friend == None and 'ActualNickName' in msg:
        nickName = msg.ActualNickName
    else:       
        nickName = fromName
    msg_from = nickName
    msg_time = msg['CreateTime']  #信息发送的时间
    msg_id = msg['MsgId']  #每条信息的id
    msg_content = None   #储存信息的内容
    msg_share_url = None  #储存分享的链接,比如分享的文章和音乐 
    #print ('from: %s, type: %s' % (msg_from,msg['Type'])) 
    wechatNickName = "{0} : ".format(msg_from)
    print(wechatNickName)

    if msg['Type'] == 'Text' or msg['Type'] == 'Friends':   #如果发送的消息是文本或者好友推荐
        msg_content = msg['Text'] 
        print(msg_content)
    
    #如果发送的消息是附件、视屏、图片、语音
    elif msg['Type'] == "Attachment" or msg['Type'] == "Video" \
        or msg['Type'] == 'Picture' \
        or msg['Type'] == 'Recording':
        msg_content = msg['FileName']  #内容就是他们的文件名
        msg['Text'](str(msg_content))  #下载文件 
        print("发送了一段{0}. 已经下载, 请查看.".format(msg['Type']))

    elif msg['Type'] == 'Card':  #如果消息是推荐的名片
        msg_content = msg['RecommendInfo']['NickName'] + '的名片'  #内容就是推荐人的昵称和性别
        if msg['RecommendInfo']['Sex'] == 1:
            msg_content += '性别为男'
        else:
            msg_content += '性别为女'
    
        print('推荐了{0}.'.format(msg_content))

    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 = r"纬度->" + x.__str__() + " 经度->" + y.__str__()   #内容为详细的地址
        else:
            msg_content = r"" + location

        print("发布了自己的位置: {}".format(msg_content)) 


    elif msg['Type'] == 'Sharing':   #如果消息为分享的音乐或者文章,详细的内容为文章的标题或者是分享的名字
        msg_content = msg['Text']
        msg_share_url = msg['Url']    #记录分享的url
        print ("发布了一条分享:{}".format(msg_content))
        print ("链接地址: {}".format(msg_share_url))
    
    face_bug=msg_content
 
    if( is_sent_me(toUserName) and robot_enabled and friend):       #如果是发送给我的, 用机器人回复.
        my_reply(msg_content, fromName)
    
    if(toUserName == 'filehelper'):
        msg_content = msg['Text']
        mh = re.search(r'pm:(\w*)', msg_content)
        if(mh) :
            city = mh.group(1)
            send_pm25(city, toUserName)
     
    ##将信息存储在字典中,每一个msg_id对应一条信息
    msg_information.update(
        {
        msg_id: {
            "msg_from": msg_from, "msg_time": msg_time, "msg_time_rec": msg_time_rec,
            "msg_type": msg["Type"],
            "msg_content": msg_content, "msg_share_url": msg_share_url
        }
        }
    )
예제 #33
0
        user.send(message_dict[text])
    else:
        user.send(u"你好啊%s,我目前还不支持这个功能"%NickName)


if __name__ == '__main__':
    itchat.auto_login()
    
    friends = itchat.get_friends(update=True)[0:]#获取好友信息
    friends_list = []

    for friend in friends:
        item = {}
        item['NickName'] = friend['NickName']
        item['HeadImgUrl'] = friend['HeadImgUrl']
        item['Sex'] = sex_dict[str(friend['Sex'])]
        item['Province'] = friend['Province']
        item['Signature'] = friend['Signature']
        item['UserName'] = friend['UserName']

        friends_list.append(item)
        #print(item)

    save_data(friends_list)
    download_images(friends_list)

    
    user = itchat.search_friends(name=u'二胖')[0]
    user.send(u'hello,这是一条来自机器人的消息')
    itchat.run()
예제 #34
0
파일: go.py 프로젝트: hzlRises/hzlgithub
def sharing_reply(msg):
	#print msg['Url']#['url']
	if 'jd.com' in msg['Url'] and 'item' in msg['Url']:
		try:			
			sku_id = jd.getGoodsIdByUrl(msg['Url'])			
			goods_name,price,fanli = jd.getProductInfo(sku_id)		
			click_url = jd.getFanliLink(sku_id)
			message = u'一一一一返 利 信 息一一一一\n'+goods_name+'\n'+u'【商品原价】'+price+'元'+'\n'+u'【商品返利】'+fanli+'元'+'\n'+u'【返利链接】'+jd.getShortUrl(click_url)
		except Exception,e:
			message = u'此商品暂时无返利。'	
	else:
		message = u'请您确定是从京东APP的商品详情页分享的链接哦。'
	itchat.send(message,msg.fromUserName)
	now = time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(time.time()))
	with open('log.txt',r'a+') as my:
		my.write('SHARING,'+itchat.search_friends(userName = msg.fromUserName)['NickName']+','+msg['Url']+','+now+'\n')

'''
#处理群消息
@itchat.msg_register([itchat.content.TEXT, itchat.content.SHARING], isGroupChat=True)
def group_reply_text(msg):
	chatroom_id = msg['FromUserName']
	username = msg['ActualNickName']
	#print username,chatroom_id
	
	if chatroom_id == '@@be5e2eb0246421f5deb6298faa715e046dc4b30a879566d3b233bf7cecb8c343' and msg['Type'] == itchat.content.TEXT:
		url = 'http://yhq.techseo.cn/yhq/?r=l&kw=%s'%(urllib.quote(msg['Text'].encode("utf-8")))
		
		itchat.send(u'一一一一导 购 信 息一一一一\n已为您找到:%s\n点击下方链接查看\n%s'%(msg['Text'],url),'@@a3f3bfafe461ecb368a6c602e42d1cb6f4a26fca1fff90215a69653298af31b5')
'''	
# 处理好友添加请求
예제 #35
0
파일: go.py 프로젝트: hzlRises/hzlgithub
def text_reply(msg):
	message = ''
	key = ''
	print msg['Text']#unicode
	'''
	print type(msg['Text'])#unicode
	msg['Text'].encode("utf-8")  unicode转为 str
	print urllib.quote(msg['Text'].encode("utf-8"))	
	'''
	
	if 'jd.com' in msg['Text'] and 'item' in msg['Text']:
		sku_id = jd.getGoodsIdByUrl(msg['Text'])
		goods_name,price,fanli = jd.getProductInfo(sku_id)		
		click_url = jd.getFanliLink(sku_id)		
		message = u'一一一一返 利 信 息一一一一\n'+goods_name+'\n'+u'【商品原价】'+price+'元'+'\n'+u'【商品返利】'+fanli+'元'+'\n'+u'【返利链接】'+jd.getShortUrl(click_url)
	elif '帮助' in msg['Text']:
		message = '[愉快]【淘宝购物领券】假如你想买鼠标垫,请发送"找鼠标垫"给机器人,机器人会把找到的鼠标垫相关优惠券链接发给你,点进去复制淘口令,再打开淘宝/天猫APP就可以领到优惠券啦。\n[愉快]【京东购物返利】打开京东APP,找到自己想买的商品,点击右上角分享按钮,把商品分享给机器人,就可以看到返利链接啦,确认收货后发送【提现】,等待客服审核就可以啦。\n快试试吧...'
	#回复表情
	elif '[' in msg['Text'] and ']' in msg['Text']:
		message = u'[愉快]'
	elif '提现' in msg['Text']:
		#需要给主人发消息,先获得主人的id,以@符号开头
		user_content = itchat.search_friends(name = u'雨一直下')		
		userName = user_content[0]['UserName']		
		#获取提现申请人的昵称
		friend_content = itchat.search_friends(userName = msg.fromUserName)
		friend_name = friend_content['NickName']
		#给主人发消息提醒
		itchat.send( friend_name+u'申请提现',toUserName = userName)				
		#判断提现人性别
		if friend_content['Sex'] == 1:
			message = friend_name +u' 帅哥请耐心等待,客服确认中'	
		elif friend_content['Sex'] == 0:
			message = friend_name +u'美女请耐心等待,客服确认中'
		else:
			message = friend_name +u'请耐心等待,客服确认中'			
	
	#活动页转链接
	elif 'hzlxy' in msg['Text']:
		link = msg['Text'].encode("utf-8").replace('hzlxy','')
		link = re.sub(r'\?.*','',link)
		r = requests.get(link)
		url = r.url
		duan_url = jd.getSelfCode(url)
		short_url = jd.getShortUrl(duan_url)		
		message = short_url	
	
	elif 'xmtq' in msg['Text'] or '天气预报' in msg['Text']:
		
		if 'xmtq' in msg['Text']:
			key = 'xmtq'
		else:
			key = 'beijingtianqi'
		weather_url = 'https://www.baidu.com/s?ie=UTF-8&wd=%s'%key
		browser = webdriver.PhantomJS(executable_path=r'/usr/local/bin/phantomjs')
		browser.get(weather_url)
		browser.maximize_window()
		browser.save_screenshot('send_auto_answes.png')#保存截图	
		
		#获取天气模板的位置、尺寸大小
		imgelement = browser.find_element_by_xpath('//*[@id="1"]')
		location = imgelement.location#获取天气x,y轴坐标
		size = imgelement.size#获取天气的长宽
		
		
		rangle = (int(location['x']),int(location['y']),int(location['x']+size['width']),int(location['y']+size['height']-20))
		i = Image.open('send_auto_answes.png')	#打开0.png
		tinaqi = i.crop(rangle)#使用Image的crop函数,从截图中再次截取我们需要的		
		tinaqi.save('send_auto_answes_0.png')		
		browser.close()	
		
		itchat.send_image('send_auto_answes_0.png',msg.fromUserName)
		
		'''
		user_content = itchat.search_friends(name=u'雨一直下')
		userName = user_content[0]['UserName']
		itchat.send_image('send_%s.png'%index,toUserName = userName)		
		'''
		
		
	elif '大盘' in msg['Text']:
		#fund_list = ['162605','160505','002121','000011','163402','070032','217027','165312','519066','110022']
		fund_list = ['dapan',]
		for index,fund in enumerate(fund_list):
			fund_id = str(fund)		
			url = 'https://www.baidu.com/s?ie=UTF-8&wd=%s'%str(fund_id)	
			#url = 'http://fund.eastmoney.com/%s.html'%str(fund_id)				
			picName = 'fund_%s.png'%index
			browser = webdriver.PhantomJS(executable_path=r'/usr/local/bin/phantomjs')
			browser.get(url)
			browser.maximize_window()
			browser.save_screenshot(picName)#保存截图	
			
			
			imgelement = browser.find_element_by_xpath('//*[@id="1"]/div[1]')
			'''
			if fund_id == '002121':
				imgelement = browser.find_element_by_xpath('//*[@id="2"]')
			'''
			location = imgelement.location#获取x,y轴坐标
			size = imgelement.size#获取长宽
			
			rangle = (int(location['x']),int(location['y']),int(location['x']+size['width']),int(location['y']+size['height']-20))
			i = Image.open(picName)	#打开
			tinaqi = i.crop(rangle)#使用Image的crop函数,从截图中再次截取我们需要的		
			tinaqi.save('send_fund_%s.png'%index)		
			browser.close()	
			
			
			#发送
			user_content = itchat.search_friends(name=u'雨一直下')
			userName = user_content[0]['UserName']
			itchat.send_image('send_fund_%s.png'%index,toUserName = userName)
			
			'''
			if fund_id in ['070032','217027','165312','519066','110022']:
				user_content_baby = itchat.search_friends(name=u'徐莹')
				userName_baby = user_content_baby[0]['UserName']
				itchat.send_image('send_fund_%s.png'%index,toUserName = userName_baby)					
			'''
	elif '找' in msg['Text']:
		msg['Text'] = msg['Text'].replace('找','')
		url = 'http://techseo.cn/yhq/?r=l&kw=%s'%(urllib.quote(msg['Text'].encode("utf-8")))
		message = u'一一一一导 购 信 息一一一一\n已为您找到:%s\n点击下方链接查看\n%s\n-----------\n发送【帮助】查看使用机器人流程\n更多大额神券商品点击下方链接:\nhttp://t.cn/RYaBrUa'%(msg['Text'],jd.getShortUrl(url))

	else:
		#url = 'http://techseo.cn/yhq/?r=l&kw=%s'%(urllib.quote(msg['Text'].encode("utf-8")))
		#message = u'一一一一导 购 信 息一一一一\n已为您找到:%s\n点击下方链接查看\n%s\n-----------\n发送【帮助】查看使用机器人流程\n更多大额神券商品点击下方链接:\nhttp://t.cn/RYaBrUa'%(msg['Text'],jd.getShortUrl(url))
		#message = '您输入的指令有误,请发送【帮助】查看教程'
		pass
	# if message:
		# print message
	itchat.send(message,msg.fromUserName)
	
	#记录
	now = time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(time.time()))
	with open('log.txt',r'a+') as my:
		my.write('TEXT,'+itchat.search_friends(userName = msg.fromUserName)['NickName']+','+msg['Text']+','+now+'\n')
예제 #36
0
파일: it_main.py 프로젝트: iinux/12306
def wechat_send(who, content):
    if who is None:
        who = u'张群'
    f = itchat.search_friends(who)
    itchat.send(content, f[0]['UserName'])
예제 #37
0
def message_receiver(msg):
    fromuser = itchat.search_friends(userName=msg['FromUserName'])
예제 #38
0
itchat.auto_login()

# 获取好友列表
friends = itchat.get_friends(update=True)[0:]

# 初始化计数器,有男有女,当然,有些人是不填的
male = female = other = 0

# 遍历这个列表,列表里第一位是自己,所以从"自己"之后开始计算
# 1表示男性,2女性
for i in friends[1:]:
    sex = i["Sex"]
    if sex == 1:
        male += 1
    elif sex == 2:
        female += 1
    else:
        other += 1

# 总数算上,好计算比例啊~
total = len(friends[1:])

# 好了,打印结果
print u"男性好友:%.2f%%" % (float(male) / total * 100)
print u"女性好友:%.2f%%" % (float(female) / total * 100)
print u"未填性别:%.2f%%" % (float(other) / total * 100)

friends = itchat.search_friends(name='xi')

print friends
예제 #39
0
# -*- coding:utf-8 -*-
import itchat
itchat.auto_login(hotReload=True)  # 可以暂存登陆状态
friend = itchat.search_friends(u"爱自由")[0]  # 搜索内容的字符串格式需要是unicode
print friend["UserName"]

# 发送内容需要是unicode,发送人也要是unicode
# itchat.send_msg("nihao", friend["UserName"])
# 发送路径需要是unicode,发送人需要是unicode,文件名不可以是中文(如果使用fields.py替换requests包中的文件,可以增加中文支持)
# itchat.send_image("xiaoqiao.jpeg", friend["UserName"])
# 发送路径需要是unicode,发送人需要是unicode,文件名不可以是中文(如果使用fields.py替换requests包中的文件,可以增加中文支持)
# itchat.send_file("xiaoqiao.jpeg", friend["UserName"])
# 发送路径unicode,发送人unicode,文件名不可以是中文,网页版发送大小不能超过20M
# itchat.send_video("你好.mp4".decode("utf-8"), friend["UserName"])
"""
    如果单纯的使用send函数,需要对发送内容进行标注。
    @fil@:在发送内容前添加,表明是发送文件
    @img@:在发送内容前添加,表明是图片文件
    @msg@:在发送内容前添加,表明是消息
    @vid@:在发送内容前添加,表明是视频文件,视频文件要小于20M
    如果什么都没有添加,默认是消息

"""
# itchat.send("nihao", friend["UserName"])
# chatrooms = itchat.get_chatrooms()
# contact = itchat.get_contact()
# mps = itchat.get_mps()
# msg = itchat.get_msg()
# itchat.get_head_img(friend["UserName"], picDir="1.jpg")
itchat.get_QR(enableCmdQR=True)
예제 #40
0
import itchat,time
import requests
import re
# 实现登录和登录状态保存
itchat.auto_login(hotReload=True)
itchat.dump_login_status()
# 保存土味情话前后句
qa = []
#设置发送土味情话的对象 匹配昵称 备注任一即可
send_userid='王武杰'
user_name = itchat.search_friends(name=send_userid)[0]['UserName']
# 第一句开场白
greet = "土味五姐正式上线"
# 发送开场白
itchat.send(greet,user_name)
# 设置再次发送土味的标志
again = False
# 定义发送一句土味情话的方法
def send_sentence(user_name):
    global qa
    response= requests.get("https://api.lovelive.tools/api/SweetNothings")
    texts = response.text
    # 分割语句形成两句话
    qa = re.split("?|,",texts,1)
    if len(qa) > 1:
        itchat.send(qa[0],user_name)
    else:
        itchat.send(texts,user_name)
#调用方法 发送土味情话
send_sentence(user_name)
# 监听对方回复 
예제 #41
0
 def notice_users(cls, text):
     for user in cls.users:
         username = itchat.search_friends(name=user)[0]['UserName']
         itchat.send(text, toUserName=username)
         print('send', text, ' to', user)
def auto_download(msg):
    print(msg)
    msg.download(msg.fileName)
    sender = itchat.search_friends(userName=msg.fromUserName)
    print('get {} from {} sucessfully'.format(msg.fileName, sender.nickName))
    return
예제 #43
0
파일: autofw.py 프로젝트: aha-lin/autofw
    groupname = msg['User']['NickName']

    if msg['Type'] == TEXT:
        content = msg['Content']
    elif msg['Type'] == SHARING:
        content = msg['Text']
    if msg['Type'] == TEXT:
        forward_user.send('[%s][%s]\n%s' %
                          (groupname, username, msg['Content']))
        print('[%s][%s][%s][%s]' % (get_msg_time(
            msg['CreateTime']), groupname, username, msg['Content']))
    elif msg['Type'] == SHARING:
        forward_user.send(
            '[%s][%s]\n%s\n%s' %
            (groupname, username, msg['Text'], replace_html(msg['Url'])))
        print('[%s][%s][%s][%s][%s]' %
              (get_msg_time(msg['CreateTime']), groupname, username,
               msg['Text'], replace_html(msg['Url'])))


# 使用热启动
itchat.auto_login(hotReload=True, enableCmdQR=2)

print forward_user_name

forward_user = itchat.search_friends(
    name=unicode(forward_user_name, 'utf-8'))[0]

itchat.run()
예제 #44
0
def reply(msg):
    reply = ''
    friend = itchat.search_friends(userName = msg['FromUserName'])
    ownAccount = itchat.get_friends(update=True)[0]
    if friend['UserName'] == ownAccount['UserName']:
예제 #45
0
zwz_encoding = face_recognition.face_encodings(zwz_image)[0]


# 人脸识别组件
def recognition(xwj):
    unknown_image = face_recognition.load_image_file("weixinTemp.jpg")
    try:
        unknown_encoding = face_recognition.face_encodings(unknown_image)[0]
        results = face_recognition.compare_faces([zwz_encoding], unknown_encoding)
        labels = ['Zhou Wenzhang']
        print('results:'+str(results))
        for i in range(0, len(results)):
            if results[i] == True:
                print('The person is:' + labels[i])
                xwj.send('The person is:' + labels[i])
            else:
                print('The person is Unknown')
                xwj.send('The person is Unknown')
    except:
        print("There is nobody here.")
        xwj.send("There is nobody here.")
        pass
"""

if __name__ == '__main__':
    itchat.auto_login(hotReload=True, enableCmdQR=True)
    itchat.send(usageMsg, toUserName='******')
    # 特定用户
    # 昵称自行修改nickName
    xwj = itchat.search_friends(nickName='用户昵称')[0]
    itchat.run()
예제 #46
0
def getMeInfo():
    if not config.meInfo:
        config.meInfo = itchat.search_friends()
    return config.meInfo.UserName
예제 #47
0
def is_friend(nick_name):
    friend_lists = itchat.search_friends(nickName=nick_name)
    if friend_lists is None or len(friend_lists) < 1:
        return False
    return True
예제 #48
0
import itchat

itchat.auto_login()

user = itchat.search_friends(name=u'王亚华')[0]
user.send(u'机器人say hello')
예제 #49
0
파일: 100.py 프로젝트: kepengsen/study
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date    : 2018-06-12 09:43:00
# @Author  : kepengsen ([email protected])
# @Link    : http://example.org
# @Version : $Id$

# 给某个好友快速发消息

import itchat
itchat.auto_login(hotReload=True)

name=itchat.search_friends(name=u'路江彪')[0]['UserName']

print name

num=1

while num <= 100:
	
    itchat.send(u'你在干嘛?怎么不说话'+'_'*10+str(num), toUserName=name)
    num += 1


예제 #50
0
def auto_reply(msg):
    global SWITCH_REPLY
    global SWITCH_DELAY
    global DELAY_TIME
    global SWITCH_PREFIX
    global PREFIX_CONTENT
    global REPLY_DICT
    global DELAY_REPLY_DICT
    global Ad_replyed
    global nkname

    if msg['ToUserName'] == 'filehelper':
        args = re.compile(' ').split(msg['Text'])
        try:
            if args[0] == '/help':
                reply_content = '''
                jarvis_v1.0正在为你服务!
                【指令列表】
                1./help             显示功能列表
                2./switch on        打开自动回复
                3./switch off       关闭自动回复
                4./prefix on        打开消息前缀
                5./prefix off       关闭消息前缀
                6./prefix set [T]   设置前缀内容
                7./delay on         打开延迟回复
                8./delay off        关闭延时回复
                9./delay set [T]    设置延迟时间
                10./dict set [F] [T] 定制好友回复
                11./dict show [F]    显示好友回复
                '''

            elif args[0] == '/switch':
                if args[1] == 'on':
                    SWITCH_REPLY = True
                    reply_content = "【Jarvis】自动回复已开启"

                elif args[1] == 'off':
                    SWITCH_REPLY = False
                    reply_content = "【Jarvis】自动回复已关闭"

                else:
                    reply_content = "【Jarvis】未知指令"

            elif args[0] == '/prefix':
                if args[1] == 'on':
                    SWITCH_PREFIX = True
                    reply_content = "【Jarvis】回复前缀已开启"

                elif args[1] == 'off':
                    SWITCH_PREFIX = False
                    reply_content = "【Jarvis】回复前缀已关闭"

                elif args[1] == 'set':
                    PREFIX_CONTENT = "[" + args[2] + "]"
                    reply_content = "【Jarvis】回复前缀已设置为:" + PREFIX_CONTENT

                else:
                    reply_content = "【Jarvis】未知指令"

            elif args[0] == '/delay':
                if args[1] == 'on':
                    SWITCH_DELAY = True
                    reply_content = "【Jarvis】延迟回复已开启"

                elif args[1] == 'off':
                    reply_content = "【Jarvis】延迟回复已关闭"

                elif args[1] == 'set':
                    DELAY_TIME = args[2]
                    reply_content = "【Jarvis】延迟时间被设置为:" + DELAY_TIME

                else:
                    reply_content = "【Jarvis】未知指令"

            elif args[0] == '/dict':
                if args[1] == 'show':
                    if REPLY_DICT.__contains__(args[2]):
                        reply_content = "【Jarvis】好友[" + args[
                            2] + "]的自动回复为:" + REPLY_DICT[args[2]]
                    else:
                        reply_content = "【Jarvis】好友[" + args[2] + "]的自动回复暂未设置"

                elif args[1] == 'set':
                    REPLY_DICT[args[2]] = args[3]
                    reply_content = "【Jarvis】好友[" + args[
                        2] + "的自动回复已设置为:" + REPLY_DICT[args[2]]
                else:
                    reply_content = "【Jarvis】未知指令"
            else:
                reply_content = "【Jarvis】未知指令"

        except:
            reply_content = "【Jarvis】系统异常"
            itchat.send(reply_content, toUserName='******')
            raise

        itchat.send(reply_content, toUserName='******')

    else:
        #获取发送消息的朋友的信息
        target_friend = itchat.search_friends(userName=msg['FromUserName'])
        if target_friend:
            #获取ta的昵称
            nickName = target_friend['NickName']
            nkname = str(nickName)
            if not any(nkname in s for s in Ad_replyed):
                if not REPLY_DICT.__contains__(nickName):
                    #设置默认回复
                    REPLY_DICT[
                        nickName] = "抱歉,包工头看得紧,不让玩手机,不能及时回复,请见谅,如有急事,请电话联系TEL:13126883674(•ω•`)"

                reply_content = REPLY_DICT[nickName]
                #判断自动回复开关
                if SWITCH_REPLY:
                    #判断延时回复开关
                    if SWITCH_DELAY:
                        localtime = time.time()
                        DELAY_REPLY_DICT[nickName] = [
                            localtime, msg['FromUserName']
                        ]
                        print(DELAY_REPLY_DICT)
                        Ad_replyed.append(str(nickName))

                    if not SWITCH_DELAY:
                        #判断消息前缀开关
                        if SWITCH_PREFIX:
                            reply_content = PREFIX_CONTENT + REPLY_DICT[
                                nickName]
                        else:
                            reply_content = REPLY_DICT[nickName]
                        #发送消息
                        itchat.send(reply_content,
                                    toUserName=msg['FromUserName'])
                        print("发送消息")
                        Ad_replyed.append(str(nickName))
예제 #51
0
import itchat
import time

print('扫一下弹出来的二维码')
itchat.auto_login(hotReload=True)
boom_remark_name = input('输入你要轰炸的人的微信备注,按回车建继续')
message = input('输入你要轰炸的内容,按回车键开始轰炸')
boom_obj = itchat.search_friends(remarkName=boom_remark_name)[0]['UserName']

while True:
    time.sleep(0.5)
    print('正在轰炸。。。')
    itchat.send_msg(msg=message, toUserName=boom_obj)
예제 #52
0
def receive_msg(msg):
    global face_bug
    # print("消息是:"+str(msg))
    msg_time_rec = time.strftime("%Y-%m-%d %H:%M:%S",
                                 time.localtime())  # 接收消息的时间
    # ActualNickName : 实际 NickName(昵称) 群消息里(msg)才有这个值
    if 'ActualNickName' in msg:
        from_user = msg['ActualUserName']  # 群消息的发送者,用户的唯一标识
        msg_from = msg['ActualNickName']  # 发送者群内的昵称
        friends = itchat.get_friends(update=True)  # 获取所有好友
        for f in friends:
            if from_user == f['UserName']:  # 如果群消息是好友发的
                if f['RemarkName']:  # 优先使用好友的备注名称,没有则使用昵称
                    msg_from = f['RemarkName']
                else:
                    msg_from = f['NickName']
                break
        groups = itchat.get_chatrooms(update=True)  # 获取所有的群
        for g in groups:
            if msg['FromUserName'] == g[
                    'UserName']:  # 根据群消息的FromUserName匹配是哪个群
                group_name = g['NickName']
                group_menbers = g['MemberCount']
                break
        group_name = group_name + "(" + str(group_menbers) + ")"
    # 否则的话是属于个人朋友的消息
    else:
        if itchat.search_friends(
                userName=msg['FromUserName'])['RemarkName']:  # 优先使用备注名称
            msg_from = itchat.search_friends(
                userName=msg['FromUserName'])['RemarkName']
        else:
            msg_from = itchat.search_friends(
                userName=msg['FromUserName'])['NickName']  # 在好友列表中查询发送信息的好友昵称
        group_name = ""
    msg_time = msg['CreateTime']  # 信息发送的时间
    msg_id = msg['MsgId']  # 每条信息的id
    msg_content = None  # 储存信息的内容
    msg_share_url = None  # 储存分享的链接,比如分享的文章和音乐

    # 如果发送的消息是文本或者好友推荐
    if msg['Type'] == 'Text' or msg['Type'] == 'Friends':
        msg_content = msg['Text']
        print(msg_time_rec + msg_content)

    # 如果发送的消息是附件、视频、图片、语音
    elif msg['Type'] == "Attachment" or msg['Type'] == "Video" \
            or msg['Type'] == 'Picture' \
            or msg['Type'] == 'Recording':
        msg_content = msg['FileName']  # 内容就是他们的文件名
        # msg_content = "F:\\weixininfo\\"+msg['FileName']
        msg['Text'](str(msg_content))  # 下载文件

    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 = r"纬度->" + x.__str__() + " 经度->" + y.__str__(
            )  # 内容为详细的地址
        else:
            msg_content = r"" + location

    elif msg['Type'] == 'Sharing':  # 如果消息为分享的音乐或者文章,详细的内容为文章的标题或者是分享的名字
        msg_content = msg['Text']
        msg_share_url = msg['Url']  # 记录分享的url
    face_bug = msg_content
    # 将信息存储在字典中,每一个msg_id对应一条信息
    time.sleep(2)
    msg_information.update({
        msg_id: {
            "msg_from": msg_from,
            "msg_time": msg_time,
            "msg_time_rec": msg_time_rec,
            "msg_type": msg["Type"],
            "msg_content": msg_content,
            "msg_share_url": msg_share_url,
            "group_name": group_name
        }
    })
    # 自动删除130秒之前的消息,避免数据量太大后引起内存不足
    del_info = []
    for k in msg_information:
        m_time = msg_information[k]['msg_time']  # 取得消息时间
        if int(time.time()) - m_time > 130:
            del_info.append(k)
    if del_info:
        for i in del_info:
            msg_information.pop(i)
예제 #53
0
    msg.user.verify()
    msg.user.send('Nice to meet you!')


@itchat.msg_register(TEXT, isGroupChat=True)
def group_reply(msg):
    defaultReply = 'I receive: ' + msg['Text']
    reply = get_response(msg['Text'])
    return reply or defaultReply


@itchat.msg_register(TEXT)
def tuling_reply(msg):
    defaultReply = 'I receive: ' + msg['Text']
    reply = get_response(msg['Text'])
    return reply or defaultReply


itchat.auto_login(hotReload=True)
msg = u'发给%s的消息'
# myself = itchat.get_friends(update = True)[0] #myself
# itchat.send(msg % (myself['DisplayName'] or myself['NickName']),myself['UserName'])

man = itchat.search_friends(name=u'勇初')[0]
print(man)

for index in range(1):
    man.send('hello this is test msg')
    time.sleep(1)
itchat.run()
예제 #54
0
# -*-coding=utf-8-*-
import itchat

'''
itchat.auto_login()
#name='filehelper'
name='distantance'

itchat.send("hello file helper",toUserName=name)
'''


@itchat.msg_register(itchat.content.TEXT)
def text_reply(msg):
    #return msg['Text']+u',真好玩'
    my_msg = u'帅哥给我发个红包好吗? '
    print(msg['FromUserName'])
    return my_msg


itchat.auto_login()
all_user = itchat.search_friends()
print(all_user)
itchat.run()
예제 #55
0
def Revocation(msg):
    # userInfo = itchat.web_init()
    # myname = userInfo['NickName']


    mytime = time.localtime()  # 这儿获取的是本地时间
    # 获取用于展示给用户看的时间 2017/03/03 13:23:53
    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__()

    msg_id = msg['MsgId'] #消息ID
    msg_time = msg['CreateTime'] #消息时间
    msg_from = itchat.search_friends(userName=msg['FromUserName'])['NickName'] #消息发送人昵称
    msg_type = msg['Type'] #消息类型
    msg_content = None #根据消息类型不同,消息内容不同
    msg_url = None #分享类消息有url
    # 图片 语音 附件 视频,可下载消息将内容下载暂存到当前目录
    if msg['Type'] == 'Text':
        msg_content = msg['Text']
    elif msg['Type'] == 'Picture':
        msg_content = msg['ToUserName']+msg['FileName']
        msg['Text'](msg['ToUserName']+msg['FileName'])
        # msg_content = myname + msg['FileName']
        # msg['Text'](myname + msg['FileName'])
    elif msg['Type'] == 'Card':
        msg_content = msg['RecommendInfo']['NickName'] + r" 的名片"
    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 = r"纬度->" + x.__str__() + " 经度->" + y.__str__()
        else:
            msg_content = r"" + location
    elif msg['Type'] == 'Sharing':
        msg_content = msg['Text']
        msg_url = msg['Url']
    elif msg['Type'] == 'Recording':
        msg_content = msg['FileName']
        msg['Text'](msg['FileName'])
    elif msg['Type'] == 'Attachment':
        msg_content = r"" + msg['FileName']
        msg['Text'](msg['FileName'])
    elif msg['Type'] == 'Video':
        msg_content = msg['FileName']
        msg['Text'](msg['FileName'])
    elif msg['Type'] == 'Friends':
        msg_content = msg['Text']

    #更新字典
    # {msg_id:(msg_from,msg_time,msg_time_touser,msg_type,msg_content,msg_url)}
    msg_dict.update(
        {msg_id: {"msg_from": msg_from, "msg_time": msg_time, "msg_time_touser": msg_time_touser, "msg_type": msg_type,
                  "msg_content": msg_content, "msg_url": msg_url}})


    #清理字典
    ClearTimeOutMsg()
예제 #56
0
    def getText(self, msg):
        wei_info = itchat.search_friends(userName=msg['FromUserName'])
        bot_info = itchat.search_friends(userName=msg['ToUserName'])

        patternURL = re.compile('^((https|http|ftp|rtsp|mms)?:\/\/)[^\s]+')

        pattern_bz = re.compile('^帮助$')
        pattern_profile = re.compile('^个人信息$')
        pattern_tixian = re.compile('^提现$')
        pattern_tuig = re.compile('^推广$')
        pattern_proxy = re.compile('^代理$')

        # 判断是否是URL链接
        if patternURL.search(msg['Text']) == None:

            pattern_s = re.compile('^搜')
            pattern_z = re.compile('^找')
            pattern_m = re.compile('^买')
            if (pattern_s.search(msg['Text']) != None) | (pattern_z.search(
                    msg['Text']) != None) | (pattern_m.search(msg['Text']) !=
                                             None):

                res = ort.ishaveuserinfo(msg)

                if res['res'] == 'not_info':
                    ort.create_user_info(msg, 0, tool=False)

                jdurl = quote("http://jdyhq.ptjob.net/?r=search?kw=" +
                              msg['Text'][1:],
                              safe='/:?=&')

                tburl = quote('http://tbyhq.ptjob.net/index.php?r=l&kw=' +
                              msg['Text'][1:],
                              safe='/:?=&')
                text = '''
一一一一系统消息一一一一

亲,以为您找到所有【%s】优惠券,快快点击领取吧!

京东:%s
淘宝:%s
                        ''' % (msg['Text'][1:], jdurl, tburl)
                itchat.send(text, msg['FromUserName'])

            elif pattern_bz.search(msg['Text']) != None:
                res = ort.ishaveuserinfo(msg)

                if res['res'] == 'not_info':
                    ort.create_user_info(msg, 0, tool=False)

                # 帮助操作
                text = '''
一一一一 系统信息 一一一一

回复【帮助】可查询指信息
回复【提现】申请账户余额提现
回复【推广】可申请机器人代理
回复【个人信息】可看个当前账户信息

回复【买+商品名称】
回复【找+商品名称】
回复【搜+商品名称】查看商品优惠券合集

分享【京东商品链接】或者【淘口令】
精准查询商品优惠券和返利信息!
分享【VIP视频链接】免费查看高清VIP视频!

优惠券使用教程:
http://t.cn/RnAKqWW
跑堂优惠券常见问题:
http://t.cn/RnAK1w0
免费看电影方法:
http://t.cn/RnAKMul
京东优惠券商城:
http://jdyhq.ptjob.net
淘宝优惠券商城:
http://tbyhq.ptjob.net
邀请好友得返利说明:
http://t.cn/RnAKafe
                        '''
                itchat.send(text, msg['FromUserName'])
            elif pattern_tixian.search(msg['Text']) != None:
                res = ort.ishaveuserinfo(msg)

                if res['res'] == 'not_info':
                    ort.create_user_info(msg, 0, tool=False)

                adminuser = itchat.search_friends(nickName="彭波")
                select_user_sql = "SELECT * FROM taojin_user_info WHERE wx_number='" + wei_info[
                    'NickName'] + "';"
                select_user_res = cm.ExecQuery(select_user_sql)

                if select_user_res and float(select_user_res[0][8]) > 0:
                    try:
                        # 修改余额
                        update_sql = "UPDATE taojin_user_info SET withdrawals_amount='0',update_time='" + str(
                            time.time()
                        ) + "' WHERE wx_number='" + wei_info['NickName'] + "';"

                        total_amount = float(select_user_res[0][5]) + float(
                            select_user_res[0][8])
                        update_total_sql = "UPDATE taojin_user_info SET total_rebate_amount='" + str(
                            total_amount
                        ) + "',update_time='" + str(
                            time.time()
                        ) + "' WHERE wx_number='" + wei_info['NickName'] + "';"

                        # 插入提现日志
                        insert_current_log_sql = "INSERT INTO taojin_current_log(wx_bot, username, amount, create_time) VALUES('" + \
                                                 bot_info['NickName'] + "', '" + wei_info['NickName'] + "', '" + str(
                            select_user_res[0][8]) + "', '" + str(time.time()) + "')"

                        to_admin_text = '''
一一一一 提现通知 一一一一

机器人:%s
提现人:%s
提现金额:%s 元
提现时间:%s
                                                ''' % (
                            bot_info['NickName'], wei_info['NickName'],
                            select_user_res[0][8],
                            time.strftime("%Y-%m-%d %H:%M:%S",
                                          time.localtime()))

                        to_user_text = '''
一一一一 提现信息 一一一一

提现成功!
提现金额将以微信红包的形式发放,请耐心等待!

分享【京东商品链接】或者【淘口令】
精准查询商品优惠券和返利信息!

优惠券使用教程:
http://t.cn/RnAKqWW
免费看电影方法:
http://t.cn/RnAKMul
邀请好友得返利:
http://t.cn/RnAKafe
                                            '''
                        itchat.send(to_user_text, msg['FromUserName'])
                        itchat.send(to_admin_text, adminuser[0]['UserName'])

                        cm.ExecNonQuery(update_sql)
                        cm.ExecNonQuery(update_total_sql)
                        cm.ExecNonQuery(insert_current_log_sql)

                        return
                    except Exception as e:
                        text = '''
一一一一 系统信息 一一一一

提现失败,请稍后重试!                        
                                '''
                        print(e)
                        itchat.send(text, msg['FromUserName'])
                        return
                else:
                    text = '''
一一一一 提现信息 一一一一

提现申请失败,请稍后重试!
                                    '''
                    itchat.send(text, msg['FromUserName'])
                    return
            elif pattern_profile.search(msg['Text']) != None:
                res = ort.ishaveuserinfo(msg)

                if res['res'] == 'not_info':
                    ort.create_user_info(msg, 0, tool=False)

                user_sql = "SELECT * FROM taojin_user_info WHERE wx_number='" + wei_info[
                    'NickName'] + "';"

                user_info = cm.ExecQuery(user_sql)

                current = "SELECT sum(amount) FROM taojin_current_log WHERE username='******'NickName'] + "';"

                friends_count_sql = "SELECT count(*) FROM taojin_user_info WHERE lnivter='" + str(
                    user_info[0][4]) + "';"

                current_info = cm.ExecQuery(current)
                friends_count = cm.ExecQuery(friends_count_sql)

                # 如果总提现金额不存在,赋值为0
                if current_info[0][0] == None:
                    current_info = 0
                else:
                    current_info = current_info[0][0]

                text = '''
一一一一 个人信息 一一一一

总返利金额: %s元
京东返利金额: %s元
淘宝返利金额: %s元
可提现余额: %s元
累计提现金额: %s元

累计订单量: %s
京东订单量: %s
淘宝订单量: %s
总好友返利: %s
总好友个数: %s

优惠券使用教程:
http://t.cn/RnAKqWW
免费看电影方法:
http://t.cn/RnAKMul
邀请好友得返利:
http://t.cn/RnAKafe
                                    ''' % (
                    user_info[0][5], user_info[0][6], user_info[0][7],
                    user_info[0][8], current_info, user_info[0][10],
                    user_info[0][11], user_info[0][12], user_info[0][18],
                    friends_count[0][0])
                cm.Close()
                itchat.send(text, msg['FromUserName'])
                return
            elif pattern_tuig.search(msg['Text']) != None:
                res = ort.ishaveuserinfo(msg)

                if res['res'] == 'not_info':
                    ort.create_user_info(msg, 0, tool=False)

                user_sql = "SELECT * FROM taojin_user_info WHERE wx_number='" + wei_info[
                    'NickName'] + "';"

                cm.ExecQuery(user_sql)

                text = '''
一一一一 推广信息 一一一一

将机器人名片分享到群或者好友
好友添加机器人为好友
您和好友都将获取0.3元现金奖励
您将永久享受好友返利提成
邀请好友返利说明:
http://t.cn/RnAKafe
                                '''
                itchat.send(text, msg['FromUserName'])
            elif pattern_proxy.search(msg['Text']) != None:
                res = ort.ishaveuserinfo(msg)

                if res['res'] == 'not_info':
                    ort.create_user_info(msg, 0, tool=False)
                text = '''
一一一一系统消息一一一一

您好!
点击链接:http://t.cn/Rf0LUP0
添加好友备注:跑堂优惠券代理

客服人员将尽快和您取得联系,请耐心等待!
                        '''
                itchat.send(text, msg['FromUserName'])
            elif (',' in msg['Text']) and (
                    msg['Text'].split(',')[1].isdigit()) and (len(
                        msg['Text'].split(',')[1]) == 11):

                res2 = ort.ishaveuserinfo(msg)

                if res2['res'] == 'not_info':
                    ort.create_user_info(msg, 0, tool=False)

                res = mjd.get_jd_order(msg, msg['Text'].split(',')[0],
                                       msg['Text'].split(',')[1], wei_info)

                if res['info'] == 'success':
                    itchat.send(res['user_text'], msg['FromUserName'])
                    itchat.send(res['parent_user_text'], res['parent'])
                elif res['info'] == 'order_exit':
                    itchat.send(res['send_text'], msg['FromUserName'])
                elif res['info'] == 'not_order':
                    itchat.send(res['user_text'], msg['FromUserName'])
                elif res['info'] == 'not_parent_and_success':
                    itchat.send(res['user_text'], msg['FromUserName'])
                elif res['info'] == 'not_info':
                    itchat.send('你当前没有个人账户请发送邀请人的邀请码注册个人账户!',
                                msg['FromUserName'])
                elif res['info'] == 'feild':

                    user_text = '''
一一一一订单信息一一一一

订单返利失败!

失败原因:
【1】未确认收货(打开App确认收货后重新发送)
【2】当前商品不是通过机器人购买
【3】查询格式不正确(正确格式:2018-03-20,73462222028 )
【4】订单完成日期错误,请输入正确的订单查询日期
【6】订单号错误,请输入正确的订单号

请按照提示进行重新操作!            
                                        '''
                    itchat.send(user_text, msg['FromUserName'])
            elif (',' in msg['Text']) and (
                    msg['Text'].split(',')[1].isdigit()) and (len(
                        msg['Text'].split(',')[1]) == 11):
                res2 = ort.ishaveuserinfo(msg)

                if res2['res'] == 'not_info':
                    ort.create_user_info(msg, 0, tool=False)

                res = mjd.get_jd_order(msg, msg['Text'].split(',')[0],
                                       msg['Text'].split(',')[1], wei_info)

                if res['info'] == 'success':
                    itchat.send(res['user_text'], msg['FromUserName'])
                    itchat.send(res['parent_user_text'], res['parent'])
                elif res['info'] == 'order_exit':
                    itchat.send(res['send_text'], msg['FromUserName'])
                elif res['info'] == 'not_order':
                    itchat.send(res['user_text'], msg['FromUserName'])
                elif res['info'] == 'not_parent_and_success':
                    itchat.send(res['user_text'], msg['FromUserName'])
                elif res['info'] == 'not_info':
                    itchat.send('你当前没有个人账户请发送邀请人的邀请码注册个人账户!',
                                msg['FromUserName'])
                elif res['info'] == 'feild':

                    user_text = '''
一一一一订单信息一一一一

订单返利失败!

失败原因:
【1】未确认收货(打开App确认收货后重新发送)
【2】当前商品不是通过机器人购买
【3】查询格式不正确(正确格式:2018-03-20,73462222028 )
【4】订单完成日期错误,请输入正确的订单查询日期
【6】订单号错误,请输入正确的订单号

请按照提示进行重新操作!            
                                        '''

                    itchat.send(user_text, msg['FromUserName'])
            elif (',' in msg['Text']) and (
                    msg['Text'].split(',')[1].isdigit()) and (len(
                        msg['Text'].split(',')[1]) == 18):
                res2 = ort.ishaveuserinfo(msg)

                if res2['res'] == 'not_info':
                    ort.create_user_info(msg, 0, tool=False)

                res = al.get_order(msg, msg['Text'].split(',')[0],
                                   msg['Text'].split(',')[1], wei_info)

                if res['info'] == 'success':
                    itchat.send(res['user_text'], msg['FromUserName'])
                    itchat.send(res['parent_user_text'], res['parent'])
                    return
                elif res['info'] == 'order_exit':
                    itchat.send(res['send_text'], msg['FromUserName'])
                elif res['info'] == 'not_order':
                    itchat.send(res['user_text'], msg['FromUserName'])
                elif res['info'] == 'not_parent_and_success':
                    itchat.send(res['user_text'], msg['FromUserName'])
                elif res['info'] == 'not_info':
                    itchat.send('你当前没有个人账户请发送邀请人的邀请码注册个人账户!',
                                msg['FromUserName'])
                elif res['info'] == 'feild':
                    user_text = '''
一一一一订单信息一一一一

订单返利失败!

失败原因:
【1】未确认收货(打开App确认收货后重新发送)
【2】当前商品不是通过机器人购买
【3】查询格式不正确(正确格式:2018-03-20,73462222028 )
【4】订单完成日期错误,请输入正确的订单查询日期
【6】订单号错误,请输入正确的订单号

请按照提示进行重新操作!            
                                        '''

                    itchat.send(user_text, msg['FromUserName'])
            elif (',' in msg['Text']) and (
                    msg['Text'].split(',')[1].isdigit()) and (len(
                        msg['Text'].split(',')[1]) == 18):
                res2 = ort.ishaveuserinfo(msg)

                if res2['res'] == 'not_info':
                    ort.create_user_info(msg, 0, tool=False)

                res = al.get_order(msg, msg['Text'].split(',')[0],
                                   msg['Text'].split(',')[1], wei_info)

                if res['info'] == 'success':
                    itchat.send(res['user_text'], msg['FromUserName'])
                    itchat.send(res['parent_user_text'], res['parent'])
                    return
                elif res['info'] == 'order_exit':
                    itchat.send(res['send_text'], msg['FromUserName'])
                elif res['info'] == 'not_order':
                    itchat.send(res['user_text'], msg['FromUserName'])
                elif res['info'] == 'not_parent_and_success':
                    itchat.send(res['user_text'], msg['FromUserName'])
                elif res['info'] == 'not_info':
                    itchat.send('你当前没有个人账户请发送邀请人的邀请码注册个人账户!',
                                msg['FromUserName'])
                elif res['info'] == 'feild':
                    user_text = '''
一一一一订单信息一一一一

订单返利失败!

失败原因:
【1】未确认收货(打开App确认收货后重新发送)
【2】当前商品不是通过机器人购买
【3】查询格式不正确(正确格式:2018-03-20,73462222028 )
【4】订单完成日期错误,请输入正确的订单查询日期
【6】订单号错误,请输入正确的订单号

请按照提示进行重新操作!            
                                        '''

                    itchat.send(user_text, msg['FromUserName'])
            elif (',' in msg['Text']) and (is_valid_date(
                    msg['Text'].split(',')[0])):
                user_text = '''
一一一一系统消息一一一一

查询失败!信息格式有误!
正确格式如下:
订单完成时间+逗号+订单号
(京东订单号长度11位,淘宝订单号长度18位)
例如:
2018-03-03,123456765432

请确认修改后重新发送
                                        '''
                itchat.send(user_text, msg['FromUserName'])
            elif (',' in msg['Text']) and (is_valid_date(
                    msg['Text'].split(',')[0])):
                user_text = '''
一一一一系统消息一一一一

查询失败!信息格式有误!
正确格式如下:
订单完成时间+逗号+订单号
(京东订单号长度11位,淘宝订单号长度18位)
例如:
2018-03-03,123456765432

请确认修改后重新发送
                                        '''
                itchat.send(user_text, msg['FromUserName'])
            else:
                msg_text = tu.tuling(msg)
                itchat.send(msg_text, msg['FromUserName'])
                return
        else:
            res2 = ort.ishaveuserinfo(msg)

            if res2['res'] == 'not_info':
                ort.create_user_info(msg, 0, tool=False)

            wx_bot.text_reply(msg, msg['Text'])
예제 #57
0
	def saveReceiveMsg(msg):
		msg_receive_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
		# 获得消息发送者
		if 'ActualNickName' in msg:
			msg_from_nickname = msg['ActualNickName']
			msg_from = msg_from_nickname
			msg_from_username = msg['ActualUserName']
			friends = itchat.get_friends(update=True)
			for friend in friends:
				if msg_from_username == friend['UserName']:
					if friend['RemarkName']:
						msg_from = friend['RemarkName']
					else:
						msg_from = friend['NickName']
					break
			groups = itchat.get_chatrooms(update=True)
			for group in groups:
				if msg['FromUserName'] == group['UserName']:
					group_name = group['NickName']
					group_menber_count = group['MemberCount']
					break
			if not group_name:
				group_name = '未命名群聊'
			group_name = group_name + '(%s人)' % str(group_menber_count)
			msg_from = group_name + '-->' + msg_from
		else:
			try:
				msg_from = itchat.search_friends(userName=msg['FromUserName'])['RemarkName']
				if not msg_from:
					msg_from = itchat.search_friends(userName=msg['FromUserName'])['NickName']
			except:
				msg_from = 'WeChat Official Accounts'
		msg_send_time = msg['CreateTime']
		msg_id = msg['MsgId']
		msg_content = None
		msg_link = None
		# 文本或者好友推荐
		if msg['Type'] == 'Text' or msg['Type'] == 'Friends':
			msg_content = msg['Text']
			print('[Text/Friends]: %s' % msg_content)
		# 附件/视频/图片/语音
		elif msg['Type'] == 'Attachment' or msg['Type'] == "Video" or msg['Type'] == 'Picture' or msg['Type'] == 'Recording':
			msg_content = msg['FileName']
			msg['Text'](str(msg_content))
			print('[Attachment/Video/Picture/Recording]: %s' % msg_content)
		# 位置信息
		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 = r"纬度:" + x.__str__() + ", 经度:" + y.__str__()
			else:
				msg_content = r"" + location
			print('[Map]: %s' % msg_content)
		# 分享的音乐/文章
		elif msg['Type'] == 'Sharing':
			msg_content = msg['Text']
			msg_link = msg['Url']
			print('[Sharing]: %s' % msg_content)
		FACEPACKAGE = msg_content
		MSGINFO.update(
				{
				msg_id: {
					"msg_from": msg_from,
					"msg_send_time": msg_send_time,
					"msg_receive_time": msg_receive_time,
					"msg_type": msg["Type"],
					"msg_content": msg_content,
					"msg_link": msg_link
					}
				}
			)
		antiWithdrawal.updateMsgInfo()
예제 #58
0
    def getGroupText(self, msg):
        wei_info = itchat.search_friends(userName=msg['FromUserName'])

        patternURL = re.compile('^((https|http|ftp|rtsp|mms)?:\/\/)[^\s]+')

        pattern_bz = re.compile('^帮助$')
        pattern_tuig = re.compile('^推广$')
        pattern_proxy = re.compile('^代理$')

        # 判断是否是URL链接
        if patternURL.search(msg['Text']) == None:

            pattern_s = re.compile('^搜')
            pattern_z = re.compile('^找')
            pattern_m = re.compile('^买')
            if (pattern_s.search(msg['Text']) != None) | (pattern_z.search(
                    msg['Text']) != None) | (pattern_m.search(msg['Text']) !=
                                             None):

                jdurl = quote("http://jdyhq.ptjob.net/?r=search?kw=" +
                              msg['Text'][1:],
                              safe='/:?=&')

                tburl = quote('http://tbyhq.ptjob.net/index.php?r=l&kw=' +
                              msg['Text'][1:],
                              safe='/:?=&')
                text = '''
一一一一系统消息一一一一

亲,以为您找到所有【%s】优惠券,快快点击领取吧!

京东:%s
淘宝:%s
                        ''' % (msg['Text'][1:], jdurl, tburl)
                itchat.send(text, msg['FromUserName'])

            elif pattern_bz.search(msg['Text']) != None:
                # 帮助操作
                text = '''
一一一一 系统信息 一一一一

回复【帮助】可查询指信息
回复【提现】申请账户余额提现
回复【推广】可申请机器人代理
回复【个人信息】可看个当前账户信息

回复【买+商品名称】
回复【找+商品名称】
回复【搜+商品名称】查看商品优惠券合集

分享【京东商品链接】或者【淘口令】
精准查询商品优惠券和返利信息!
分享【VIP视频链接】免费查看高清VIP视频!

优惠券使用教程:
http://t.cn/RnAKqWW
跑堂优惠券常见问题:
http://t.cn/RnAK1w0
免费看电影方法:
http://t.cn/RnAKMul
京东优惠券商城:
http://jdyhq.ptjob.net
淘宝优惠券商城:
http://tbyhq.ptjob.net
邀请好友得返利说明:
http://t.cn/RnAKafe
                        '''
                itchat.send(text, msg['FromUserName'])
            elif pattern_tuig.search(msg['Text']) != None:
                text = '''
一一一一 推广信息 一一一一

将机器人名片分享到群或者好友
好友添加机器人为好友
您和好友都将获取0.3元现金奖励
您将永久享受好友返利提成
邀请好友返利说明:
http://t.cn/RnAKafe
                                '''
                itchat.send(text, msg['FromUserName'])
            elif pattern_proxy.search(msg['Text']) != None:
                text = '''
一一一一系统消息一一一一

您好!
点击链接:http://t.cn/Rf0LUP0
添加好友备注:跑堂优惠券代理

客服人员将尽快和您取得联系,请耐心等待!
                        '''
                itchat.send(text, msg['FromUserName'])
            else:
                return
        else:
            ort.text_reply(msg, msg['Text'])
예제 #59
0
itchat.send("Hello World!",toUserName=None) # 讲信息发送给user
ithcat.send("@fil@%s" % '/tmp/test.text')
ithcat.send("@img@%s" % '/tmp/test.png')
ithcat.send("@vid@%s" % '/tmp/test.mkv')

@itchat.msg_register(TEXT)   #这里的TEXT表示如果有人发送文本消息,那么就会调用下面的方法
def simple_reply(msg):
    #这个是向发送者发送消息
    itchat.send_msg('已经收到了文本消息,消息内容为%s'%msg['Text'],toUserName=msg['FromUserName'])
    return "T reveived: %s" % msg["Text"]     #返回的给对方的消息,msg["Text"]表示消息的内容

itchat.get_friends()  返回完整的好友列表、
每个好友为一个字典, 其中第一项为本人的账号信息;
传入 update=True, 将更新好友列表并返回, get_friends(update=True)

# 获取任何一项等于name键值的用户
itchat.search_friends(name='autolife')
获取备注,微信号, 昵称中的任何一项等于name键值的用户. (可以与下一项配置使用.)

get_mps
将返回完整的工作号列表
每个公众号为一个字典,
传入 update=True 将更新公众号列表, 并返回.



get_chatrooms : 返回完整的群聊列表.
search_chatrooms : 群聊搜索.
update_chatroom : 获取群聊用户列表或更新该群聊.
memberList = itchat.update_chatroom('@@abcdefg1234567', detailedMember=True)
예제 #60
0
def get_friend_name(msg):
    from_uid = msg["FromUserName"]
    return itchat.search_friends(userName=from_uid)['NickName'].decode('utf-8')