Ejemplo n.º 1
0
def test_wxpy():
    """
    """
    n_ret = ERR_FAIL
    n_ret_api = 0    
    desc = ""
    
    for nwf in [1]:
        
        try:
          
            # 导入模块
            from wxpy import Bot, MALE
            # 初始化机器人,扫码登陆
            bot = Bot()
            
            # 搜索名称含有 "游否" 的男性深圳好友
            my_friend = bot.friends().search('郑小霞', sex=MALE, city="深圳")[0]
            
            # 发送文本给好友
            my_friend.send('robot 男人的长寿是女人给的')
            # 发送图片
            my_friend.send_image('d:/frog.jpg')            
                  
                  
                                    
        except Exception as e:            
            logging.exception("An exception was thrown!")            
                        
    return n_ret
Ejemplo n.º 2
0
def get_bot():
    qr_callback = callback_for_get_bot()
    bot = Bot('bot.pkl', qr_path=os.path.join(
        here, '../static/img/qr_code.png'
    ), console_qr=True, qr_callback=qr_callback)
    bot.enable_puid()
    bot.messages.max_history = 0
    return bot
Ejemplo n.º 3
0
def save_picture(path):
    bot = Bot()
    freinds = bot.friends(update=True)  #:rtype: :class:`wxpy.Chats`
    for freind in freinds:
        freind_name = freind.name
        # 获取每个好友的头像,以名称命名的话,同名的情况下会替换
        freind.get_avatar(path + '{}.jpg'.format(freind_name))
    print('微信头像获取完成!')
Ejemplo n.º 4
0
def get_cache_bot(request):
    alive = get_bot_alive(request)
    assert alive == ALIVE, '微信号不在线!无法使用缓存登陆'

    cache_path = get_cache_path(request)
    bot = Bot(cache_path=cache_path)
    puid_path = get_puid_path(request)
    bot.enable_puid(puid_path)
    return bot
Ejemplo n.º 5
0
 def __init__(self, bot: Bot, app: models.AppModel):
     self.bot = bot
     self.app = app
     # 存储pkl
     pkl_path = app.puid_pkl
     bot.enable_puid(pkl_path)
     self._user = bot.self
     self.message_helper = get_message_helper()
     self.action = SimpleAction(bot=self.bot)
     self.get_current_user()
     self.register()
Ejemplo n.º 6
0
def _update_single_app_info(app):
    cache_path_name = f'{app.app_id}_cache.pkl'
    cache_path = os.path.join(pkl_path, cache_path_name)
    if not os.path.exists(cache_path):
        print(f'{cache_path_name}不存在!')
        return

    bot = Bot(cache_path=cache_path)

    bot.enable_puid(f'{app.app_id}.pkl')

    update_app(bot, app)
Ejemplo n.º 7
0
 def __init__(self, interval=0.5):
     self.db = MessageDb()
     self.bot = Bot(console_qr=True)
     self.bot.enable_puid("/tmp/wxpy_puid.pkl")
     self.interval = interval
     self.mwin = MainWindow(curses.initscr(), self.db)
     self.loop = asyncio.get_event_loop()
     self.executor = ThreadPoolExecutor()
     self.friends = self.bot.friends()
     self.groups = self.bot.groups()
     self.friends.extend(self.groups)
     self.mwin.rwin.friends = self.friends
Ejemplo n.º 8
0
def main():
    # 登录微信
    bot = Bot(cache_path=True)

    # 获取好友列表
    friends = bot.friends()

    # 下载好友头像
    down_img(friends)

    # 拼接好友头像
    show_img()
def main():
    bot = Bot()  #登录微信的命令
    my_friend = bot.friends()  #发给所有好友

    @bot.register(my_friend)
    def SHARING_Msg(msg):
        if msg.type == 'Sharing':

            msg.reply(msg.url)
        else:
            print('waiting......')

    embed()  #保持监听状态
Ejemplo n.º 10
0
def main():
    bot = Bot(cache_path=True, console_qr=2)
    bot.enable_puid('wxpy_puid.pkl')
    # 在 Web 微信中把自己加为好友
    # bot.self.add()
    # bot.self.accept()
    mygroup = bot.groups().search(group_name)[0]
    myfriend = bot.friends().search(u'明月')[0]

    @bot.register(mygroup)
    def print_group(msg):
        # msg.forward(myfriend)
        if msg.type == TEXT:
            # print msg
            username = msg.member.name
            en_from = msg.text.encode('utf-8')
            print '收到消息:', en_from
            if not isCN(en_from):
                cn_from = bd_translate(en_from, 'en', 'zh')
                cn_chatbot = xiaoi_chatbot(cn_from, username)
                cn_chatbot = cn_chatbot.replace('\n', ' ')
                en_chatbot = bd_translate(cn_chatbot, 'zh', 'en')
                # print '翻译结果:', en_chatbot
                save_record(username, en_from, cn_from, cn_chatbot, en_chatbot)
                return en_chatbot + '\n' + '(翻译:' + cn_chatbot + ')'

    bot.join()
Ejemplo n.º 11
0
def main():
    bot = Bot(cache_path=True)#扫描二维码登陆微信 #issue1195 avoiding scanning again shortly
    my_friend = bot.friends()#回复对象为所有好友
    @bot.register(my_friend)
    @bot.register(msg_types='Sharing')#监听好友分享的消息 why 'Sharing'expression? SHARING got errors why oh why? input distinguish problems again?
    def auto_reply(msg):
        response = requests.get(msg.url)#msg.url为分享的网址
        document = PyQuery(response.text)
        content = document('#js_content').text()
        #像d11一样处理文本
        result = sw.stats_text_cn(content,count=10)
        wechat_word = ''.join(str(i)for i in result) # seems better str this type in case causing trouble in reading
        return wechat_word#将结果返回给好友

    embed()#d堵塞线程,保持监听
Ejemplo n.º 12
0
def get_friends_signature(bot: wxpy.Bot) -> dict:

    signature_data = {}
    friends = bot.friends()
    for friend in friends:
        signature_data[friend.nick_name] = friend.signature
    return signature_data
Ejemplo n.º 13
0
 def login(self, app: models.AppModel):
     cache_pkl = app.cache_pkl(delete=True)
     bot = Bot(qr_callback=self.qr_callback, cache_path=cache_pkl)
     bot = robot.Robot(bot, app)
     result = self.check_bot_permissions(bot, app)
     if result:
         robot.quene.update({app.app_id: bot})
def main():
    bot = Bot()  #登录微信的命令
    my_friend = bot.friends()  #发给所有好友

    @bot.register(my_friend)
    def SHARING_Msg(msg):
        if msg.type == 'Sharing':
            response = requests.get(msg.url)
            document = PyQuery(response.text)
            contect = document('#js_content').text()
            c = str(stats_word.stats_text(content, 10))
            msg.reply(c)
        else:
            print('waiting......')

    embed()  #保持监听状态
    print(msg)
Ejemplo n.º 15
0
def init_bot():
    bot = Bot(cache_path=False, console_qr=True)

    # 启用 puid 属性,并指定 puid 所需的映射数据保存/载入路径
    # bot.enable_puid('wxpy_puid.pkl')

    # 自动消除手机端的新消息小红点提醒
    # Bot.auto_mark_as_read = True

    return bot
Ejemplo n.º 16
0
def send_note(bot: Bot):
    while True:
        with open(note_file) as fp:
            all_notes = fp.readlines()
            for text in all_notes:
                note = text.split(',')
                name = note[0]
                alert_time = note[1]
                alert_msg = note[2]
                friend = bot.friends().search(name)[0]
                if _should_send(alert_time):
                    friend.send(alert_msg)
                    all_notes.remove(text)
            fp.write('\n'.join(all_notes))
        news = [get_weekly_news(), get_hellogit_news()]
        friend = bot.friends().search('秦')[0]
        for new in news:
            friend.send(f'news: {new}')
        time.sleep(60 * 59)
Ejemplo n.º 17
0
def main():
    bot = Bot(cache_path=True)#扫描二维码登陆微信 #issue1195 avoiding scanning again shortly
    my_friend = bot.friends()#回复对象为所有好友
    @bot.register(my_friend)
    @bot.register(msg_types='Sharing')#监听好友分享的消息 why 'Sharing'expression? SHARING got errors why oh why? input distinguish problems again?
    
    def reply_my_friend(msg):
         
        wechat = requests.get(msg.url)
        document = PyQuery(wechat.text)
        content = document('#js_content').text()
#        result = sw.stats_text_cn(content,count=100)
#        wechat_word = ''.join(str(i)for i in result) # seems better str this type in case causing trouble in reading
#        return
        list_a = sw.stats_text_cn(content,100)#接收发来的分享链接的文字,并处理成词频统计结果
           
        msg.reply_image(chartImg(list_a)) #回复刚才保存的图片给好友        
        return

    embed()#让程序执行到这里后返回,以便于重新执行
Ejemplo n.º 18
0
def main():
    bot = Bot() #登录微信的命令
    my_friend = bot.friends() #发给所有好友

    @bot.register(my_friend)

    def SHARING_Msg(msg):
        print(msg)
        if msg.type == 'Sharing':
            response = requests.get(msg.url)
            document = PyQuery(response.text)
            content = document('#js_content').text()
            print('line 21 ==>',stats_word.stats_text(content,10))
            c=stats_word.stats_text(content,10)
            np_list=np.array(c)
            word_list=[]
            number_list=[]
            for i in range(len(np_list)):
                word_list+=[np_list[i][0]]
                number_list+=[int(np_list[i][1])]
            
            #为了能在matplotlib中显示中文,需要中文字体的支持
            font = FontProperties(fname=r"c:\windows\fonts\simsun.ttc",size=8)
            
            plt.rcdefaults()
            fig,ax=plt.subplots()
            y_pos=np.arange(len(word_list))

            ax.barh(y_pos,number_list,align='center',color='green',ecolor='black')
            ax.set_yticks(y_pos)
            ax.set_yticklabels(word_list,fontproperties=font)
            ax.invert_yaxis()
            ax.set_xlabel('词频',fontproperties=font)
            ax.set_title('词频统计',fontproperties=font)
            plt.savefig("stats.png")
            msg.reply_image("stats.png")
            
        else:
            print('waiting......')

    embed() #保持监听状态
Ejemplo n.º 19
0
    def get_friend():
        bot = Bot()
        friends = bot.friends(update=True)

        friend_data = []
        for friend in friends:
            if friend.sex == 1:
                sex = "男"
            elif friend.sex == 2:
                sex = "女"
            else:
                sex = ""
            friend_dict = {
                "city": friend.city,
                "province": friend.province,
                "sex": sex,
                "signature": friend.signature,
            }
            friend_data.append(friend_dict)

        return friend_data
Ejemplo n.º 20
0
def send():
    sql = 'select gonggao from blog_baseinfo'
    name = ['小可爱', '宝宝', '小菲菲']
    info = ['爸爸', 'Dad', '爹爹']
    message = query(sql)[0][0]
    bot = Bot(cache_path=True)
    # my_friend = bot.friends().search('白米饭er')[0]
    bot.file_helper.send(
        message + '~' + '\n'
        '{}今天是我们在一起的第{}天哟~'.format(random.choice(name), dayNum()) + '\n'
        '\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t来自{}的关爱~'.format(
            random.choice(info)))
Ejemplo n.º 21
0
    def get_friend():
        bot = Bot(console_qr=False)
        friends = bot.friends(update=True)

        friend_data = []
        for friend in friends:
            if friend.sex == 1:
                sex = '男'
            elif friend.sex == 2:
                sex = '女'
            else:
                sex = ''
            friend_dic = {
                "city": friend.city,
                "province": friend.province,
                "sex": sex,
                "signature": friend.signature
            }
            friend_data.append(friend_dic)

        return friend_data
Ejemplo n.º 22
0
def sendMsg(name):
    duration = 60000
    try:
        bot.file_helper.send('我是助手')
        # print(bot.groups())

        # for i in bot.friends():
        #     print(i.puid)
        friends = bot.friends()
        chats = bot.chats()
        groups = bot.groups()
        # for i in groups:
        #     i.update_group(True);
        #     print(i.members.stats_text())
        # print(friends.stats_text())
        friend = friends.search(name)[0]
        self_messages = bot.messages.search(sender=friend)
        print('自己发送的消息: ', self_messages)
        p = getInfo(url)
        content, note = p
        i = '''
        来自 男朋友的 问候:\n
        ''' + content + '\n' + note
        i = ' 昭昭 '
        # friend.send(i);

        Timer(duration, sendMsg(name)).start()

    except Exception as e:

        bot = Bot(cache_path=True).friends().search(u'撒丫子就跑')[0]

        bot.send('消息发送失败(' + str(
            time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))) +
                 ')')
        print('>>>: ', e)
    finally:
        print('发送完毕')
Ejemplo n.º 23
0
 def __init__(self,
              chat_type_=WechatChatType.EMPTY,
              enabled_=False,
              original_filter_=None,
              bot_=None,
              logger_=None):
     self._bot = bot_ if bot_ else Bot()
     self._logger = logger_ if logger_ else getLogger()
     self._name = chat_type_
     self._set_type()
     self._enabled = enabled_
     self._enabled_real = enabled_
     self._original_filter = original_filter_
     self._apply_filter()
Ejemplo n.º 24
0
def _init():
    global bot
    global ice
    print("小冰AI初始化......")
    # 设置一个保存登陆账户文件的文件
    loacation = get_resourceLocation()+"Manager/TalkWidget/reply/wxpy.pkl"
    
    # 初始化机器人,扫码登陆
    bot = Bot(cache_path=loacation)
    ice = bot.mps(update=False).search("小冰") # 在公众号里找到小冰
    if(len(ice) == 1):
        ice = ice[0]
    else:
        global ice_reply
        ice_reply ="尚未关注小冰"
    
    # 注册事件,当接收到来自小冰的信息时,执行,将信息保存
    @bot.register(chats=ice)
    def print_group_msg(msg):
        global ice_reply
        if(ice_reply is None):
            ice_reply = msg
        if(isinstance(ice_reply, str)):
            ice_reply = ice_reply + msg
Ejemplo n.º 25
0
    def login(self):
        self.bg_stop = True
        #机器人对象,有的微信无法登陆...
        self.bot = Bot(cache_path=True)
        try:
            location = pyautogui.locateOnScreen(image=Bak.erweima_png_path)
            x, y = pyautogui.center(location)
            pyautogui.click(x=x, y=y, clicks=1, button='left')
        except:
            pass

        try:
            #真实环境
            self.datafriends = self.friends()
            self.datagroups = self.groups()
        except:
            pass
        if len(self.datafriends) > 0 or len(self.datagroups) > 0:
            self.login_button.pack_forget()
            self.bg_frame.pack_forget()
            self.basic_frame.pack(side=tk.TOP, fill=tk.BOTH, expand=1)
            self.logout_button = tk.Button(self.basic_frame,
                                           width=10,
                                           text="退出",
                                           bg="red",
                                           fg="black",
                                           command=self.logout)
            self.logout_button.place(x=400, y=5)
            self.friend["stat"] = "active"
            self.group["stat"] = "active"
            self.basic_listbox.delete(0, tk.END)
            self.basic_listbox.insert(0, "恭喜,登陆成功!")
            return True
        else:
            msg.showerror("提示", "登陆失败,请稍后再试!")
            return False
Ejemplo n.º 26
0
    def startMonitor(self):
        '''[对 groups 群聊开始监听, 检查是否出现了包含 contents 内容的消息]

        登陆微信, 注册消息接受函数, 接收到的消息将传递给 _checkMessage() 进行过滤
        不满足条件的消息将会被过滤, 满足条件的消息将会传递给 _capturedContent() 进行下一步处理
        '''

        if self._groups == None or len(self._groups) == 0:
            print('Error: starting monitor with an empty [groups] list')
            print('       please set [groups] with setGroups() method or')
            print('       ! you will get no message !')

        if self._contents == None or len(self._contents) == 0:
            print('Error: starting monitor with an empty [contents] list')
            print('       please set [contents] with setContents() method or')
            print('       ! you will get no message !')

        self._bot = Bot()
        @self._bot.register()
        def _receiveMessage(msg):
            self._checkMessage(msg)
Ejemplo n.º 27
0
class BookPushBot:
    CHAPTER_URL = "http://127.0.0.1:8080/api"
    PUSH_URL = "http://127.0.0.1:8080/render"

    def __init__(self, db):
        self.db = db
        self.bot = None
        self.push_url = self.PUSH_URL + "?" + urlencode({"name": self.db.name})

    def login(self):
        print('登录微信中...请扫描二维码')
        self.bot = Bot(cache_path=True)

    def get_last_chapter_name(self):
        r = requests.get(self.CHAPTER_URL, params={"name": self.db.name})
        return r.json()['LastChapterName']

    def push_to_ireader(self):
        ireader = self.bot.search('掌阅iReader')[0]
        ireader.send(self.push_url)
        print(f"push to ireader...")

    def run(self):
        print(f"当前追书: {db.name} 已经追到的章节: {db.last_chapter_name}")
        self.login()
        self.cron_job()

    def cron_job(self):
        while True:
            now_last_chapter = self.get_last_chapter_name()
            print(f"目前网上最新章节: {now_last_chapter}")
            if now_last_chapter != self.db.last_chapter_name:
                self.push_to_ireader()
                self.db.last_chapter_name = now_last_chapter
                self.db.save_to_json()
            else:
                print("你已经看到最新章节了....休眠中")
            time.sleep(60*60)
Ejemplo n.º 28
0
# -*- coding: utf-8 -*-
from wxpy import Bot, FRIENDS
from wxpy import embed
import requests
import re
import json
import sys

reload(sys)
sys.setdefaultencoding('utf-8')

# 扫码登录
bot = Bot(cache_path=True)
"""
默认消息处理方法
==============================================================================
"""


def _get_red_pack(user, link, mobile):
    try:
        data = {'url': link, 'mobile': mobile}
        geturl = 'http://101.132.113.122:3007/hongbao'
        r = requests.post(url=geturl, data=data)
        response = r.text
        if response is not None:
            result = json.loads(response)
            result = '领取结果:\n%s' % result['message']
            user.send(result)
    except Exception as e:
        print e
Ejemplo n.º 29
0
    def run(self):
        self.bot = Bot(cache_path=True)
        self.myself = self.bot.self
        self._signal_2.emit(self.myself.name)
        self.get_friendslist()
        self.get_chatroomslist()

        ############################
        # 处理接收到的微信消息
        ############################
        # @self.bot.register(msg_types=TEXT,except_self=False)
        # def just_print(msg):
        #     print(msg)

        # 私聊信息,文字
        @self.bot.register(msg_types=TEXT, except_self=False)
        def get_msg(msg):
            fromChatroom = False
            #print(msg)
            if msg.sender.name == self.myself.name:
                # 这是我发出的消息
                from_Name = '我'
                if msg.receiver.name == '文件传输助手':
                    to_Name = '助手'
                    if '#' in msg.text and myshow.remote_pc == True:  # 执行命令条件:1发给助手 2命令中带井号 3远控开启
                        do_what = msg.text.split('#')[1]  # 以#分割,取第二个元素,即:具体指令。
                        self.wechat_do(do_what)  # 调用微信远控的方法
                else:
                    to_Name = msg.chat.name
            elif msg.receiver.name == self.myself.name:
                # 这是别人发给我的
                to_Name = '我'
                if msg.sender.name == '文件传输助手':
                    from_Name = '助手'
                else:
                    from_Name = msg.chat.name
                # 自动回复
                if myshow.reply_busy == True:  # 忙碌回复
                    msg_busy = myshow.lineEdit_busy.text()
                    msg.reply('[自动回复] %s' % msg_busy)
                if myshow.reply_robot == True:  # 机器人回复
                    myshow.tuling.do_reply(msg)  # 调用图灵机器人回复
            message = from_Name + '→' + to_Name + ':' + msg.text
            msg_time = msg.create_time
            #print(msg_time,type(msg_time),str(msg_time))  # wxpy的时间格式是datetime
            send_time = time.mktime(msg_time.timetuple())  #datetime转时间戳
            self._signal_1.emit(fromChatroom, message,
                                send_time)  # 信号焕发,连接 write_log

        # 私聊信息,图片、视频等
        @self.bot.register(chats=User,
                           msg_types=[PICTURE, RECORDING, ATTACHMENT, VIDEO])
        def download_files(msg):
            #print(msg)
            fromChatroom = False
            if msg.sender.name == self.myself.name:
                # 这是我发出的消息
                from_Name = '我'
                if msg.receiver.name == '文件传输助手':
                    to_Name = '助手'
                else:
                    to_Name = msg.chat.name
            elif msg.receiver.name == self.myself.name:
                # 这是别人发给我的
                to_Name = '我'
                if msg.sender.name == '文件传输助手':
                    from_Name = '助手'
                else:
                    from_Name = msg.chat.name
                # 自动回复
                if myshow.reply_busy == True:
                    msg_busy = myshow.lineEdit_busy.text()
                    msg.reply('[自动回复] %s' % msg_busy)
                if myshow.reply_robot == True:  # 机器人回复
                    myshow.tuling.do_reply(msg)
                    # 新建接收文件夹
            downloadDir = '接收文件'
            if not os.path.exists(downloadDir):  # 目录如果不存在
                os.makedirs(downloadDir)
            workPath = os.getcwd()  # 当前程序工作的路径
            downloadPath = os.path.join(workPath, downloadDir)  # 接收文件的路径
            os.chdir(downloadPath)  # 改变当前工作目录
            msg.get_file(msg.file_name)  # 下载文件
            os.chdir(workPath)
            message = from_Name + '→' + to_Name + ':' + '[文件: %s]' % msg.file_name
            msg_time = msg.create_time
            send_time = time.mktime(msg_time.timetuple())  #datetime转时间戳
            self._signal_1.emit(fromChatroom, message,
                                send_time)  # 信号焕发,连接 write_log

        # 群聊信息,@我的文字信息
        @self.bot.register(chats=Group, msg_types=TEXT)
        def get_msg_at(msg):
            #print(msg)
            if msg.is_at:
                #print(msg.member.name)
                if myshow.reply_busy == True:
                    msg_busy = myshow.lineEdit_busy.text()
                    msg.reply(u'@%s\u2005[自动回复] %s' %
                              (msg.member.nick_name, msg_busy))
                if myshow.reply_robot == True:
                    myshow.tuling.do_reply(msg)
                from_Name = msg.member.name  # 成员名
                chatroom_NickName = msg.chat.name  #群聊名
                fromChatroom = True
                message = '[' + chatroom_NickName + '] ' + from_Name + ' :' + msg.text
                msg_time = msg.create_time
                send_time = time.mktime(msg_time.timetuple())
                self._signal_1.emit(fromChatroom, message,
                                    send_time)  # 信号焕发,连接 write_log

        self.bot.join()  # 堵塞线程,这里不要用embed(),否则pyinstaller打包无窗口会报错
Ejemplo n.º 30
0
class MyThread(QtCore.QThread):
    _signal_1 = QtCore.pyqtSignal(bool, str,
                                  int)  # 定义信号,用于记录聊天信息,含:是否群聊,消息内容,消息时间
    _signal_2 = QtCore.pyqtSignal(str)  # 定义信号,仅用于传出用户名
    _signal_3 = QtCore.pyqtSignal(str)  # 定义信号,用于记录远控信息
    _signal_4 = QtCore.pyqtSignal(list)  # 定义信号,用于记录好友列表
    _signal_5 = QtCore.pyqtSignal(list)  # 定义信号,用于记录群聊列表
    _signal_6 = QtCore.pyqtSignal(str)  # 定义信号,用于截图

    def __int__(self, parent=None):
        super(MyThread, self).__init__()

    def run(self):
        self.bot = Bot(cache_path=True)
        self.myself = self.bot.self
        self._signal_2.emit(self.myself.name)
        self.get_friendslist()
        self.get_chatroomslist()

        ############################
        # 处理接收到的微信消息
        ############################
        # @self.bot.register(msg_types=TEXT,except_self=False)
        # def just_print(msg):
        #     print(msg)

        # 私聊信息,文字
        @self.bot.register(msg_types=TEXT, except_self=False)
        def get_msg(msg):
            fromChatroom = False
            #print(msg)
            if msg.sender.name == self.myself.name:
                # 这是我发出的消息
                from_Name = '我'
                if msg.receiver.name == '文件传输助手':
                    to_Name = '助手'
                    if '#' in msg.text and myshow.remote_pc == True:  # 执行命令条件:1发给助手 2命令中带井号 3远控开启
                        do_what = msg.text.split('#')[1]  # 以#分割,取第二个元素,即:具体指令。
                        self.wechat_do(do_what)  # 调用微信远控的方法
                else:
                    to_Name = msg.chat.name
            elif msg.receiver.name == self.myself.name:
                # 这是别人发给我的
                to_Name = '我'
                if msg.sender.name == '文件传输助手':
                    from_Name = '助手'
                else:
                    from_Name = msg.chat.name
                # 自动回复
                if myshow.reply_busy == True:  # 忙碌回复
                    msg_busy = myshow.lineEdit_busy.text()
                    msg.reply('[自动回复] %s' % msg_busy)
                if myshow.reply_robot == True:  # 机器人回复
                    myshow.tuling.do_reply(msg)  # 调用图灵机器人回复
            message = from_Name + '→' + to_Name + ':' + msg.text
            msg_time = msg.create_time
            #print(msg_time,type(msg_time),str(msg_time))  # wxpy的时间格式是datetime
            send_time = time.mktime(msg_time.timetuple())  #datetime转时间戳
            self._signal_1.emit(fromChatroom, message,
                                send_time)  # 信号焕发,连接 write_log

        # 私聊信息,图片、视频等
        @self.bot.register(chats=User,
                           msg_types=[PICTURE, RECORDING, ATTACHMENT, VIDEO])
        def download_files(msg):
            #print(msg)
            fromChatroom = False
            if msg.sender.name == self.myself.name:
                # 这是我发出的消息
                from_Name = '我'
                if msg.receiver.name == '文件传输助手':
                    to_Name = '助手'
                else:
                    to_Name = msg.chat.name
            elif msg.receiver.name == self.myself.name:
                # 这是别人发给我的
                to_Name = '我'
                if msg.sender.name == '文件传输助手':
                    from_Name = '助手'
                else:
                    from_Name = msg.chat.name
                # 自动回复
                if myshow.reply_busy == True:
                    msg_busy = myshow.lineEdit_busy.text()
                    msg.reply('[自动回复] %s' % msg_busy)
                if myshow.reply_robot == True:  # 机器人回复
                    myshow.tuling.do_reply(msg)
                    # 新建接收文件夹
            downloadDir = '接收文件'
            if not os.path.exists(downloadDir):  # 目录如果不存在
                os.makedirs(downloadDir)
            workPath = os.getcwd()  # 当前程序工作的路径
            downloadPath = os.path.join(workPath, downloadDir)  # 接收文件的路径
            os.chdir(downloadPath)  # 改变当前工作目录
            msg.get_file(msg.file_name)  # 下载文件
            os.chdir(workPath)
            message = from_Name + '→' + to_Name + ':' + '[文件: %s]' % msg.file_name
            msg_time = msg.create_time
            send_time = time.mktime(msg_time.timetuple())  #datetime转时间戳
            self._signal_1.emit(fromChatroom, message,
                                send_time)  # 信号焕发,连接 write_log

        # 群聊信息,@我的文字信息
        @self.bot.register(chats=Group, msg_types=TEXT)
        def get_msg_at(msg):
            #print(msg)
            if msg.is_at:
                #print(msg.member.name)
                if myshow.reply_busy == True:
                    msg_busy = myshow.lineEdit_busy.text()
                    msg.reply(u'@%s\u2005[自动回复] %s' %
                              (msg.member.nick_name, msg_busy))
                if myshow.reply_robot == True:
                    myshow.tuling.do_reply(msg)
                from_Name = msg.member.name  # 成员名
                chatroom_NickName = msg.chat.name  #群聊名
                fromChatroom = True
                message = '[' + chatroom_NickName + '] ' + from_Name + ' :' + msg.text
                msg_time = msg.create_time
                send_time = time.mktime(msg_time.timetuple())
                self._signal_1.emit(fromChatroom, message,
                                    send_time)  # 信号焕发,连接 write_log

        self.bot.join()  # 堵塞线程,这里不要用embed(),否则pyinstaller打包无窗口会报错

    # 获取好友列表
    def get_friendslist(self):
        friends_info = self.bot.friends(update=False)
        frinends_list = [friend.name for friend in friends_info
                         ]  # 好友列表 ['张三','Mango','李四']
        frinends_pinyin = [
            ''.join(lazy_pinyin(frinend)) for frinend in frinends_list
        ]  # 根据好友列表生成拼音列表 ['zhangsan','Mango','lisi']
        dict1 = dict(
            zip(frinends_pinyin, frinends_list)
        )  # 拼音列表和昵称列表并成字典 {'zhangsan':'张三','Mango':'Mango','lisi':'李四'}
        sort1 = sorted(dict1.items(), key=lambda x: x[0].lower(
        ))  # 转小写拼音排序 [('lisi','李四'),('Mango','Mango'),('zhangsan','张三')]
        friends_sorted = [i[1] for i in sort1]  # ['李四','Mango','张三']
        self._signal_4.emit(friends_sorted)

    #获取群聊列表
    def get_chatroomslist(self):
        chatrooms_info = self.bot.groups(update=False)
        chatrooms_list = [chatroom.name for chatroom in chatrooms_info]
        self._signal_5.emit(chatrooms_list)

    #######################################
    # 微信远程控制
    #######################################

    def wechat_do(self, do_what):
        '''判断并执行具体指令,格式为:命令@参数'''
        self._signal_3.emit('[接收指令] ' + do_what)
        remote_switch = {
            '帮助': self.read_me,
            '截图': self.img_to_myself,
            '关机': self.shutdown_pc,
            '取消关机': self.cancel_shutdown,
            '关闭网页': self.close_browser,
            '最小化窗口': self.send_win_d,
            '切换窗口': self.send_alt_tab,
            '打开': self.run_file,
            '关闭': self.shutdown_process,
            '网页': self.open_web,
            '控制': self.more_cmd,
            '忙碌回复开': self.reply_busy_on,
            '忙碌回复关': self.reply_busy_off,
            '机器人回复开': self.reply_robot_on,
            '机器人回复关': self.reply_robot_off
        }
        if '@' not in do_what:  # 不带参数的指令
            try:
                remote_switch[do_what]()
            except:
                pass
        elif '@' in do_what:  # 带参数的指令
            do_at_1 = do_what.split('@')[0]  # @分割,取第一个元素,即:指令
            do_at_2 = do_what.split('@')[1]  # 指令的参数
            try:
                remote_switch[do_at_1](do_at_2)
            except:
                pass

    def read_me(self):
        '''帮助信息'''
        readme_msg = '[帮助信息] 指令示例:\n' \
                     '#帮助\n' \
                     '#截图\n' \
                     '#关机\n' \
                     '#取消关机\n' \
                     '#打开@d:\\abc.txt\n' \
                     '#关闭@notepad\n' \
                     '#网页@www.baidu.com\n' \
                     '#关闭网页\n' \
                     '#控制@explorer c:\\windows\n' \
                     '#最小化窗口\n' \
                     '#切换窗口\n' \
                     '#忙碌回复开\n' \
                     '#忙碌回复关\n' \
                     '#机器人回复开\n' \
                     '#机器人回复关\n'
        self.bot.file_helper.send(readme_msg)  # 发送帮助信息
        self._signal_3.emit('[远控信息] 已发送帮助信息')

    def img_to_myself(self):
        '''截图并发送'''
        timeArray = time.localtime(time.time())
        now_time = time.strftime("%y/%m/%d %H:%M:%S", timeArray)
        time_msg = '时间: [%s]' % now_time
        filename_time = time.strftime("%y%m%d_%H%M%S",
                                      timeArray)  # 用时间来命名图片,格式中不能有/ : 和空格
        img_name = filename_time + '.png'
        self._signal_6.emit(img_name)  # 信号通知主线程截图
        QtCore.QThread.sleep(1)  # 等一下,等主线程截图...
        isImgExist = os.path.exists(img_name)  # 是否存在
        if not isImgExist:
            print('找不到截图文件')
            QtCore.QThread.sleep(1)  # 再等一等......
        self.bot.file_helper.send_image(img_name)  # 微信发送截图给自己
        # print('发送截图完成!')
        os.chdir(current_path)
        # print(os.getcwd())
        self.bot.file_helper.send(time_msg)  # 发送消息,截图时间
        self._signal_3.emit('[远控信息] 已发送截图')

    def shutdown_pc(self):
        '''本机关机'''
        os.system('shutdown -s -t 60')  # 执行计算机系统指令,这里是60秒后关机
        send_msg = '[远控信息] 60秒后电脑关机\n取消关机命令:\n#取消关机'  # 发送警告消息,提醒取消指令
        self.bot.file_helper.send(send_msg)
        self._signal_3.emit('[远控信息] 警告:60秒后关机')

    def cancel_shutdown(self):
        '''取消关机'''
        os.system('shutdown -a')
        send_msg = '[远控信息] 此次关机已取消'
        self.bot.file_helper.send(send_msg)
        self._signal_3.emit(send_msg)

    def run_file(self, do_at_2):
        '''打开文件或程序,文件位置套上英文双引号'''
        # file_cmd = '"' +do_at_2+ '"'
        file_cmd = 'start ' + do_at_2
        os.system(file_cmd)
        send_msg = '[远控信息] 已打开文件/程序:' + do_at_2
        self.bot.file_helper.send(send_msg)
        self._signal_3.emit(send_msg)

    def shutdown_process(self, do_at_2):
        '''关闭程序'''
        process_cmd = 'taskkill /f /t /im ' + do_at_2 + '.exe'
        os.system(process_cmd)
        send_msg = '[远控信息] 已关闭进程:' + do_at_2
        self.bot.file_helper.send(send_msg)
        self._signal_3.emit(send_msg)

    def open_web(self, do_at_2):
        '''浏览器打开网页'''
        # web_cmd = 'start https://' + do_at_2         # 可以使用默认浏览器打开网页,但接下来关闭浏览器进程时,需要作相应修改
        web_cmd = 'start iexplore https://' + do_at_2  # 使用IE打开网页
        os.system(web_cmd)
        send_msg = '[远控信息] 已打开网页:' + do_at_2
        self.bot.file_helper.send(send_msg)
        self._signal_3.emit(send_msg)

    def close_browser(self):
        '''关闭IE浏览器,其他浏览器请自行加入进程名'''
        # close_ie = 'tskill iexplore' # 需要设置环境变量
        close_ie = 'taskkill /f /t /im iexplore.exe'
        os.system(close_ie)
        send_msg = '[远控信息] 已关闭IE浏览器'
        self.bot.file_helper.send(send_msg)
        self._signal_3.emit(send_msg)

    def more_cmd(self, do_at_2):
        '''更多指令,即cmd命令,如:explorer是资源管理器,具体请百度cmd命令大全'''
        os.system(do_at_2)
        send_msg = '[远控信息] 已执行CMD指令:' + do_at_2
        self.bot.file_helper.send(send_msg)
        self._signal_3.emit(send_msg)

    def send_2key(self, key_1, key_2):
        '''发送键盘组合键,key_1,key_2,查按键码表'''
        win32api.keybd_event(key_1, 0, 0, 0)  # 键盘按下
        time.sleep(1)
        win32api.keybd_event(key_2, 0, 0, 0)  # 键盘按下
        time.sleep(1)
        win32api.keybd_event(key_2, 0, win32con.KEYEVENTF_KEYUP, 0)  # 键盘松开
        win32api.keybd_event(key_1, 0, win32con.KEYEVENTF_KEYUP, 0)  # 键盘松开
        # 不发送信息

    def send_win_d(self):
        '''发送组合键win+D,显示桌面,再按一次显示原程序窗口'''
        self.send_2key(91, 68)  # 查按键码表 win->91  d->68
        send_msg = '[远控信息] Win+D窗口最小化\n再次发送,还原窗口'
        self.bot.file_helper.send(send_msg)
        self._signal_3.emit('[远控信息] Win+D窗口最小化')

    def send_alt_tab(self):
        '''发送组合键alt+tab,切换窗口'''
        self.send_2key(18, 9)  # 查按键码表 win->91  d->68
        time.sleep(1)  # 等1秒再执行下面的截图
        self.img_to_myself()  # 发送截图
        send_msg = '[远控信息] 已切换程序窗口\n当前窗口见上图'
        self.bot.file_helper.send(send_msg)
        self._signal_3.emit('[远控信息] 已切换程序窗口')

    def reply_busy_on(self):
        '''打开忙碌回复'''
        myshow.checkBox_busy.setChecked(True)
        send_msg = '[远控信息] 已打开忙碌回复功能'
        self.bot.file_helper.send(send_msg)
        self._signal_3.emit(send_msg)

    def reply_busy_off(self):
        '''关闭忙碌回复'''
        myshow.checkBox_busy.setChecked(False)
        send_msg = '[远控信息] 已关闭忙碌回复功能'
        self.bot.file_helper.send(send_msg)
        self._signal_3.emit(send_msg)

    def reply_robot_on(self):
        '''打开机器人回复'''
        myshow.checkBox_robot.setChecked(True)
        send_msg = '[远控信息] 已打开机器人回复功能'
        self.bot.file_helper.send(send_msg)
        self._signal_3.emit(send_msg)

    def reply_robot_off(self):
        '''关闭机器人回复'''
        myshow.checkBox_robot.setChecked(False)
        send_msg = '[远控信息] 已关闭机器人回复功能'
        self.bot.file_helper.send(send_msg)
        self._signal_3.emit(send_msg)