示例#1
0
def ready(app, itchat, current_user):
    init_result = itchat.web_init()
    wechat_init = Process_Wechat(db=db,
                                 app=app,
                                 itchat=itchat,
                                 current_user=current_user)
    wechat_init.process_web_init(init_result)
    # process_web_init(init_result,current_user.id,app)
    global chatroom_list
    chatroom_list = itchat.originInstance.storageClass.chatroomList
    wechat_init.process_chatroom(chatroom_list)
    wechat_init.process_wechatuser(chatroom_list)
    global welcome_list
    welcome_list = wechat_init.load_welcomeinfo()

    # 加载过滤条件
    ad_notifs, ad_uncensor, ad_keywords = wechat_init.load_adv_rule()
    rule['ad_rule'].extend([ad_notifs, ad_uncensor, ad_keywords])
    k_notifs, k_uncensor, k_keyword = wechat_init.load_keyword_rule()
    rule['keyword_rule'].extend([k_notifs, k_uncensor, k_keyword])
    print('rule', rule)

    itchat.show_mobile_login()
    # itchat.get_contact(True)
    itchat.start_receiving()
    itchat.run()
示例#2
0
def monitor_login(itchat):
    isLoggedIn = False
    while 1:
        waiting_time = 0
        while not isLoggedIn:
            status = itchat.check_login()
            waiting_time += 1
            print(waiting_time)
            if status == '200':
                print ("status is 200!")
                isLoggedIn = True
            elif status == '201':
                print ("status is 201!")
                if isLoggedIn is not None: 
                    print ('Please press confirm on your phone.')
                    isLoggedIn = None
            elif status != '408':
                break
            elif waiting_time == 5:
                raise
        if isLoggedIn:
            print ("已经确认登陆了")
            break

    print ("==== here status is ", status)
    itchat.check_login()
    itchat.web_init()
    itchat.show_mobile_login()
    itchat.get_contact(True) 
    # you can do your business here
    itchat.start_receiving()
    itchat.run()
示例#3
0
def main():
    global timer
    uuid = open_QR()
    waitForConfirm = False
    while 1:
        status = itchat.check_login(uuid)
        if status == '200':
            print(status)
            break
        elif status == '201':
            print(status)
            if waitForConfirm:
                output_info('Please press confirm')
                waitForConfirm = True
        elif status == '408':
            print(status)
            output_info('Reloading QR code')
            uuid = open_QR()
            waitForConfirm = False
    userInfo = itchat.web_init()
    itchat.show_mobile_login()
    itchat.get_friends()
    output_info('login successfully with %s' % userInfo['User']['NickName'])
    itchat.start_receiving()

    @itchat.msg_register(TEXT)
    def simple_reply(msg):
        if msg['Type'] == 'Text':
            print('I received: %s' % msg.text)

    timer_fun()
    # time.sleep(20 * 5)
    # timer.cancel()
    itchat.run()
示例#4
0
 def login_wechat(self):
     try:
         uuid = self.open_qr()
         self.outputWritten("请扫描二维码\n")
         waitForConfirm = False
         while 1:
             status = itchat.check_login(uuid)
             if status == '200':
                 break
             elif status == '201':
                 if waitForConfirm:
                     self.outputWritten('请进行确认\n')
                     waitForConfirm = True
             elif status == '408':
                 self.outputWritten('重新加载二维码\n')
                 time.sleep(3)
                 uuid = self.open_qr()
                 waitForConfirm = False
         userInfo = itchat.web_init()
         itchat.show_mobile_login()
         itchat.get_friends(True)
         self.outputWritten('登陆成功!账号为:%s\n' % userInfo['User']['NickName'])
         itchat.start_receiving()
         self.refresh_button.setText("已登录:{}".format(userInfo['User']['NickName']))
         self.exit_button.setEnabled(True)
     except Exception as e:
         print("登录出错:",e)
         self.outputWritten('登陆出错:{}\n'.format(e))
     try:
         # 获取群聊列表
         chatrooms = itchat.get_chatrooms()
         print(type(chatrooms))
         return chatrooms
     except Exception as e:
         self.outputWritten("获取群聊列表出错:{}\n".format(e))
示例#5
0
    def readygo(self):
        init_result = self.itchat.web_init()
        self.itchat.dump_login_status('data/itchat{}.pk1'.format(
            self.current_user.get_id()))
        wechat_init = Process_Wechat(db=self.db,
                                     app=self.app,
                                     itchat=self.itchat,
                                     current_user=self.current_user)
        wechat_init.process_web_init(init_result)
        self.chatroomList = self.itchat.originInstance.storageClass.chatroomList
        wechat_init.process_chatroom(self.chatroomList)
        wechat_init.process_wechatuser(self.chatroomList)
        self.welcome_list = wechat_init.load_welcomeinfo()
        ad_notifs, ad_uncensor, ad_keywords = wechat_init.load_adv_rule()
        self.rule = {'ad_rule': [], 'keyword_rule': []}  #清零
        self.rule['ad_rule'].extend([ad_notifs, ad_uncensor, ad_keywords])
        k_notifs, k_uncensor, k_keyword = wechat_init.load_keyword_rule()
        self.rule['keyword_rule'].extend([k_notifs, k_uncensor, k_keyword])
        print('rule', self.rule)

        self.auto_replies = wechat_init.load_auto_reply()
        self.register()
        itchat.show_mobile_login()
        # itchat.get_contact(True)
        itchat.start_receiving()
        itchat.run()
示例#6
0
def getqrimg(request):
    ul = {}
    print('Getting oepnqr')
    uuid = open_QR()
    waitForConfirm = False
    while 1:
        status = itchat.check_login(uuid)
        if status == '200':
            break
        elif status == '201':
            if waitForConfirm:
                print('Please press confirm')
                waitForConfirm = True
        elif status == '408':
            print('Reloading QR Code')
            uuid = open_QR()
            waitForConfirm = False
        time.sleep(3)
    userInfo = itchat.web_init()
    print("ui", userInfo)
    # itchat.show_mobile_login()
    # itchat.get_contract()
    # print('Login successfully as %s' % userInfo['NickName'])
    itchat.start_receiving()
    return JsonResponse(ul)
示例#7
0
文件: wx.py 项目: wean/coupon-windows
    def login(self, exitCallback, uuid=None):
        def isLoginned(uuid):

            for count in range(10):

                status = int(itchat.check_login(uuid))

                if status is 200:
                    return True

                if status is 201:
                    print 'Wait for confirm in mobile #', count
                    randomSleep(1, 2)
                    continue

                print 'Error status:', status
                return False

            return False

        if uuid is None:

            statusFile = getProperty(self.configFile, 'wechat-status-file')
            itchat.auto_login(hotReload=True, statusStorageDir=statusFile)

        else:

            if not isLoginned(uuid):
                raise Exception('Failed to login with {}'.format(uuid))

            userInfo = itchat.web_init()

            itchat.show_mobile_login()
            itchat.get_friends(True)

            itchat.start_receiving(exitCallback)

        self.me = itchat.search_friends()

        print self.me['NickName'], 'is working'

        self.watchFriends = list()
        names = getProperty(self.configFile, 'wechat-watch-friends').split(';')
        for name in names:
            friends = itchat.search_friends(name=name)
            self.watchFriends.extend(friends)

        self.watchGroups = list()
        names = getProperty(self.configFile, 'wechat-watch-groups').split(';')
        for name in names:
            groups = itchat.search_chatrooms(name=name)
            self.watchGroups.extend(groups)

        self.searchReplyPlate = getProperty(self.configFile,
                                            'search-reply-plate')

        itchat.run(blockThread=False)  # Run in a new thread

        self.run()
示例#8
0
    def login_wechat(self):
        try:
            uuid = self.open_qr()
            self.outputWritten("请扫描二维码 ")
            waitForConfirm = False
            while 1:
                status = itchat.check_login(uuid)
                if status == '200': break
                elif status == '201':
                    if waitForConfirm:
                        self.outputWritten('请进行确认 ')
                        waitForConfirm = True
                    elif status == '408':
                        self.outputWritten('重新加载二维码 ')
                        time.sleep(3)
                    uuid = self.open_qr()
                waitForConfirm = False
                userInfo = itchat.web_init()
            itchat.show_mobile_login()
            print('itchat.show_mobile_login() 执行完成!')
            itchat.get_friends()
            print('itchat.get_friends(update=True)[0:] 执行完成!')
            self.outputWritten('登陆成功!账号为:%s ' % userInfo['User']['NickName'])
            itchat.start_receiving()
            print('itchat.start_receiving() 执行完成!')
            self.refresh_button.setText("已登录:{}".format(
                userInfo['User']['NickName']))
            self.exit_button.setEnabled(True)
        except Exception as e:
            print("登录出错:", e)
            self.outputWritten('登陆出错:{} '.format(e))
            try:
                chatrooms = itchat.get_chatrooms()
                print('chatrooms = itchat.get_chatrooms() 执行完成!')
                print(type(chatrooms))
            except Exception as e:
                self.outputWritten("获取群聊列表出错:{} ".format(e))
                try:
                    friends = itchat.get_friends()
                    print('friends = itchat.get_friends() 执行完成!')
                    print(type(friends))
                except Exception as e:
                    self.outputWritten("获取群聊列表出错:{} ".format(e))
                    try:
                        mps = itchat.get_mps()
                        print('mps = itchat.get_mps() 执行完成!')
                        print(type(mps))
                    except Exception as e:
                        self.outputWritten("获取群聊列表出错:{} ".format(e))
                        if chatrooms and friends and mps:
                            return [chatrooms, friends, mps]

                        def run(self):
                            try:
                                self.refresh_button.setEnabled(False)
                                self.exit_button.setEnabled(True)
                                self.finished_signal.emit(self.login_wechat())
                            except Exception as e:
                                self.outputWritten("运行登录线程出错:{} ".format(e))
示例#9
0
def newWXInstance():
    global friends
    global chatrooms
    userInfo = itchat.web_init()
    itchat.show_mobile_login()

    friends = itchat.get_friends(update=True)
    chatrooms = itchat.get_chatrooms(update=True)
    itchat.start_receiving()
    itchat.run()
    print('itchat end.')
示例#10
0
文件: bot.py 项目: ataouli/wxHelper
 def login(self):
     status = itchat.check_login()
     print(status)
     if status == '200':
         print('logged in')
         itchat.web_init()
         itchat.show_mobile_login()
         itchat.get_contact(True)
         self.is_logging = False
         itchat.start_receiving()
     return status
示例#11
0
def auto_login(uuid):
    uuid = open_QR()
    waitForConfirm = False
    while 1:
        status = itchat.check_login(uuid)
        if status == '200':
            break
        elif status == '201':
            if waitForConfirm:
                output_info('Please press confirm')
                waitForConfirm = True
        elif status == '408':
            output_info('Reloading QR Code')
            uuid = open_QR()
            waitForConfirm = False
    userInfo = itchat.web_init()
    print userInfo
    itchat.show_mobile_login()
    itchat.get_friends(True)
    output_info('Login successfully as %s' % userInfo['NickName'])
    itchat.start_receiving()
示例#12
0
def Login(uuid):
    waitForConfirm = False
    while True:
        status = itchat.check_login(uuid)
        if status=='200':
            break
        elif status=='201':
            if waitForConfirm:
                LogCat("Plase press confrim ....")
                waitForConfirm=True
        elif status == '408':
            LogCat("Reloading QR code....")
            uuid = getUUID()
            print uuid
            getQR(uuid)
            waitForConfirm = False
    itchat.web_init()
    itchat.show_mobile_login()
    itchat.get_contract()
    contract = itchat.get_contractTest()
    itchat.start_receiving()#key
    print contract
    return contract
示例#13
0
    def login(self, uuid):
        '''Login wechat for send message'''
        # uuid = self.open_QR()
        waitForConfirm = False

        while 1:
            status = itchat.check_login(uuid)
            if status == '200':
                break
            elif status == '201':
                if waitForConfirm:
                    log.info('Please press confirm')
                    waitForConfirm = True
            elif status == '408':
                log.info('Reloading QR Code')
                waitForConfirm = False

        userInfo = itchat.web_init()
        itchat.show_mobile_login()
        log.info('Start get contacts, this may take sometime')
        itchat.get_friends(True)
        log.info('Login successfully as %s' % userInfo['User']['NickName'])
        itchat.start_receiving()
示例#14
0
def bot_reply_controller(request):
    global uuid
    print('██wechat_bot_reply_server')
    waitForConfirm = False
    while 1:
        print(uuid)
        status = itchat.check_login(uuid)
        print(status)
        if status == '200':
            break
        elif status == '201':
            if waitForConfirm:
                print('[INFO] Please press confirm')
                waitForConfirm = True
        elif status == '408':
            print('[INFO] Reloading QR Code')
            uuid = auto_reply_service.open_QR()
            waitForConfirm = False

    itchat.web_init()
    itchat.show_mobile_login()
    itchat.get_friends(True)
    print('[INFO] Login successfully')
    itchat.start_receiving()

    if status == '200':
        @itchat.msg_register(TEXT)
        def simple_reply(msg):
            auto_reply_service.auto_reply(msg)
        itchat.run(debug=True)
        itchat.dump_login_status()
    else:
        itchat.auto_login()
        itchat.dump_login_status()
        print('Config stored, so exit.')

    return
示例#15
0
 def login_process(self):
     uuid = self.open_QR()
     waitForConfirm = False
     while 1:
         status = itchat.check_login(uuid)
         if status == '200':
             break
         elif status == '201':
             if waitForConfirm:
                 self.output_info('Please press confirm')
                 waitForConfirm = True
         elif status == '408':
             self.output_info('Reloading QR Code')
             uuid = self.open_QR()
             waitForConfirm = False
     userInfo = itchat.web_init()
     ProgramStatus.my_own_username = userInfo['User']['UserName']
     itchat.show_mobile_login()
     itchat.start_receiving()
     itchat.get_friends(True)
     ProgramStatus.is_login = True
     print('Login successfully as %s' % userInfo['User']['NickName'])
     self.check_names_exist()
     self.programSignal.login_success_signal.emit()
示例#16
0
def login():
    if load_login():
        global if_login
        if_login = True
        logger.info('loan login status success')
        return '200'

    logger.info('begin to login ...')
    status = itchat.check_login(qruuid)
    logger.info('check login status' + status)

    if status == '200':
        if_login = True
        logger.info('check login, status success')
    elif status == '201':
        logger.info('check login, need confirm')
        return status
    elif status == '408':
        logger.info('check login, qrCode timeout')
        get_qr()
        return status

    # 获取登陆人信息
    user_info = itchat.web_init()
    logger.info('Login successfully as %s' % user_info['User']['NickName'])

    # 手机web微信登陆状态显示
    itchat.show_mobile_login()
    logger.info('show mobile login')

    # 获取最新近聊列表
    itchat.get_contact(update=True)
    logger.info('get contact complete')

    # 获取最新好友列表
    itchat.get_friends(update=True)
    logger.info('get friends complete')

    # 获取最新群聊列表
    chat_rooms = itchat.get_chatrooms(update=True)
    logger.info('get chatRooms complete')

    # 更新群聊详细信息(人员列表)
    for chat_room in chat_rooms:
        logger.debug(json.dumps(chat_room))
        itchat.update_chatroom(userName=chat_room['UserName'])
    logger.info('update chatRooms members complete')

    # 保存登陆状态
    itchat.dump_login_status(fileDir=login_status_dir)
    logger.info('save the login success to %s' % login_status_dir)

    # 启动心跳连接
    itchat.start_receiving()
    logger.info('start receiving and heartbeat')

    class WebMessage(object):
        def __init__(self, _msg):
            self._msg = _msg

        def get_msg(self):
            return self._msg

    # 消息注册,好友文本消息
    @itchat.msg_register(TEXT)
    def text_reply(msg):
        logger.debug(json.dumps(msg))

        # q_msg = WebMessage('text', msg)
        # q.put(q_msg)

        msg_time = time.strftime('%Y-%m-%d %H:%M:%S',
                                 time.localtime(msg.createTime))
        msg_from = itchat.search_friends(
            userName=msg['FromUserName'])['NickName']
        msg_to = itchat.search_friends(userName=msg['ToUserName'])['NickName']
        msg_text = msg['Text']

        wx_record = WxRecord(is_group='0',
                             msg_type=msg.type,
                             msg_time=msg_time,
                             msg_from=msg_from,
                             msg_to=msg_to,
                             msg_text=msg_text)
        wx_record.save()

        q.put(
            WebMessage({
                'is_group': '0',
                'msg_type': msg.type,
                'msg_time': msg_time,
                'msg_from': msg_from,
                'msg_to': msg_to,
                'msg_text': msg_text
            }))

        logger.debug(
            "save to db type:%s time:%s from:%-15s  to: %-15s  content:%s" %
            (msg.type, msg_time, msg_from, msg_to, msg_text))

    # 消息注册,好友图片/音频/视频/文件消息
    @itchat.msg_register([PICTURE, RECORDING, ATTACHMENT, VIDEO])
    def download_files(msg):
        msg.download(os.path.join(wx_files_dir, msg.fileName))

        msg_time = time.strftime('%Y-%m-%d %H:%M:%S',
                                 time.localtime(msg.createTime))
        msg_from = itchat.search_friends(
            userName=msg['FromUserName'])['NickName']
        msg_to = itchat.search_friends(userName=msg['ToUserName'])['NickName']
        msg_text = os.path.join(wx_files_dir, msg.fileName)

        wx_record = WxRecord(is_group='0',
                             msg_type=msg.type,
                             msg_time=msg_time,
                             msg_from=msg_from,
                             msg_to=msg_to,
                             msg_text=msg_text)
        wx_record.save()
        q.put(
            WebMessage({
                'is_group': '0',
                'msg_type': msg.type,
                'msg_time': msg_time,
                'msg_from': msg_from,
                'msg_to': msg_to,
                'msg_text': msg_text
            }))
        logger.debug(
            "save to db type:%s time:%s from:%-15s  to: %-15s  content:%s" %
            (msg.type, msg_time, msg_from, msg_to, msg_text))

    # 消息注册,群文本消息
    @itchat.msg_register(TEXT, isGroupChat=True)
    def text_reply(msg):
        logger.debug(json.dumps(msg))

        msg_time = time.strftime('%Y-%m-%d %H:%M:%S',
                                 time.localtime(msg.createTime))
        msg_from = msg['ActualNickName']
        msg_to = msg['User']['NickName']
        msg_text = msg['Text']

        wx_record = WxRecord(is_group='1',
                             msg_type=msg.type,
                             msg_time=msg_time,
                             msg_from=msg_from,
                             msg_to=msg_to,
                             msg_text=msg_text)
        wx_record.save()
        q.put(
            WebMessage({
                'is_group': '1',
                'msg_type': msg.type,
                'msg_time': msg_time,
                'msg_from': msg_from,
                'msg_to': msg_to,
                'msg_text': msg_text
            }))
        logger.debug(
            "save to db type:%s time:%s from:%-15s  to: %-15s  content:%s" %
            ('2', msg_time, msg_from, msg_to, msg_text))

    # 消息注册,群图片/音频/视频/文件消息
    @itchat.msg_register([PICTURE, RECORDING, ATTACHMENT, VIDEO],
                         isGroupChat=True)
    def download_files(msg):
        msg.download(os.path.join(wx_files_dir, msg.fileName))

        msg_time = time.strftime('%Y-%m-%d %H:%M:%S',
                                 time.localtime(msg.createTime))
        msg_from = itchat.search_friends(
            userName=msg['FromUserName'])['NickName']
        msg_to = itchat.search_friends(userName=msg['ToUserName'])['NickName']
        msg_text = os.path.join(wx_files_dir, msg.fileName)

        wx_record = WxRecord(is_group='1',
                             msg_type=msg.type,
                             msg_time=msg_time,
                             msg_from=msg_from,
                             msg_to=msg_to,
                             msg_text=msg_text)
        wx_record.save()
        q.put(
            WebMessage({
                'is_group': '1',
                'msg_type': msg.type,
                'msg_time': msg_time,
                'msg_from': msg_from,
                'msg_to': msg_to,
                'msg_text': msg_text
            }))
        logger.debug(
            "save to db type:%s time:%s from:%-15s  to: %-15s  content:%s" %
            (msg.type, msg_time, msg_from, msg_to, msg_text))

    # 新建线程跑任务
    def new_thread():
        itchat.run()

    threading.Thread(target=new_thread).start()
    logger.info("聊天记录同步中 ... ")
    return status
示例#17
0
            xiaobing_name = wc.search_mps(name='小冰')[0]['UserName']
            logging.info('小冰找到啦!')
            break
        except:
            if time.time() - time_out > 15:
                logging.info('小冰不见啦!请关注小冰公众号,20秒后重试')
                time.sleep(20)
            pass
    return xiaobing_name

if __name__ == '__main__':
    MSGIN = []
    MSGOUT = []
    logging.basicConfig(filename='autoreply.log', level=logging.INFO)
    console = logging.StreamHandler()
    console.setLevel(logging.INFO)
    formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
    console.setFormatter(formatter)
    logging.getLogger('').addHandler(console)

    wc.auto_login(enableCmdQR=2)
    XB = find_xiaobing()
    logging.info('开始自动回复,请在随意对话框输入,开始你的表演')
    logging.info('结束自动回复,请在随意对话框输入,结束你的表演')
    t1 = get_text_msg(MSGIN, MSGOUT, XB)
    t1.start()

    t3 = reply_msg(MSGIN, MSGOUT, XB)
    t3.start()
    wc.start_receiving()
示例#18
0
    r = requests.post(url, data={'name': 'test', 'phone': 139, 'content': '内容'})
    print(r.text.data)
    time.sleep(1)




import itchat

# itchat 微信官方教程:https://itchat.readthedocs.io/zh/latest/
# 微信登录
# 登录时如果断网,则此程序直接停止
# 启动热登录,并且生成 命令行 登录二维码
itchat.auto_login(hotReload=True, enableCmdQR=2)
# 保持心跳状态,防止自动退出登录
itchat.start_receiving()

# 获取群聊,注意群 必须保持到通讯录,否则可能会找不到群
itchat.get_chatrooms(update=True)
room = itchat.search_chatrooms('python')
if len(room) == 0:
    log.error('没有找到群信息')
else:
    try:
        iRoom = room[0]['UserName']
        # 发送消息
        result = itchat.send('send message', iRoom)
        try:
            if result['BaseResponse']['ErrMsg'] == '请求成功':
                print('send wechat success')
        except Exception as e:
示例#19
0
def login():
    uuid = open_QR()
    print('-------get qrcode')
    waitForConfirm = False
    while 1:
        status = itchat.check_login(uuid)
        if status == '200':
            break
        elif status == '201':
            if waitForConfirm:
                output_info('Please press confirm')
                waitForConfirm = True
        elif status == '408':
            output_info('Reloading QR Code')
            uuid = open_QR()
            waitForConfirm = False

    print('-------get login success')

    itchat.login()

    # 保存登陆状态
    itchat.dump_login_status(fileDir=login_status_dir)

    # 获取登陆人信息
    userInfo = itchat.web_init()
    print('Login successfully as %s' % userInfo['User']['NickName'])

    # 手机web微信登陆状态显示
    itchat.show_mobile_login()
    print('-------show mobile login')

    # 获取最新近聊列表
    itchat.get_contact(update=True)
    print('-------get contact complete')

    # 获取最新好友列表
    itchat.get_friends(update=True)
    print('-------get friends complete')

    # 获取最新群聊列表
    chatrooms = itchat.get_chatrooms(update=True)
    print('-------get chatrooms complete')

    # 更新群聊详细信息(人员列表)
    for chatroom in chatrooms:
        # print(json.dumps(chatroom))
        itchat.update_chatroom(userName=chatroom['UserName'])
    print('-------update chatrooms members complete')

    # 启动心跳连接
    itchat.start_receiving()
    print('-------start receiving,itchat class:' + str(itchat))

    # 消息注册 好友消息
    @itchat.msg_register(TEXT)
    def text_reply(msg):
        # print(json.dumps(msg))
        fromuser = itchat.search_friends(
            userName=msg['FromUserName'])['NickName']
        print(itchat.search_friends(userName=msg['ToUserName']))
        touser = itchat.search_friends(userName=msg['ToUserName'])['NickName']
        msgtime = time.strftime('%Y-%m-%d %H:%M:%S',
                                time.localtime(msg.createTime))
        msgtext = msg['Text']
        print('time:%s from:%s  to: %s  content:%s' %
              (msgtime, fromuser, touser, msgtext))

    # 消息注册 群聊消息
    @itchat.msg_register(TEXT, isGroupChat=True)
    def text_reply(msg):
        print(json.dumps(msg))
        # chatgroupname = msg['User']['NickName']
        print(itchat.search_chatrooms(userName=msg['ToUserName']))
        chatgroupname = itchat.search_chatrooms(
            userName=msg['ToUserName'])['NickName']
        chatusername = msg['ActualNickName']
        msgtext = msg['Text']
        msgtime = time.strftime('%Y-%m-%d %H:%M:%S',
                                time.localtime(msg.createTime))
        print('time:%s from:%s  group:%s  content:%s' %
              (msgtime, chatusername, chatgroupname, msgtext))

    @itchat.msg_register([PICTURE, RECORDING, ATTACHMENT, VIDEO])
    def download_files(msg):
        file = msg.download(
            os.path.join(BASE_DIR, 'static\wx_files', msg.fileName))
        typeSymbol = {
            PICTURE: 'img',
            VIDEO: 'vid',
        }.get(msg.type, 'fil')
        return '@%s@%s' % (typeSymbol, msg.fileName)

    # itchat.run(blockThread=False)
    itchat.run()