实现一个命令行界面下的微信淘宝客群聊机器人

3.1、初识 itchat 与实现微信的登录

如何在 Python 环境下登录和操作微信,我们可以选择使用第三方模块——itchat 来实现这一需求。

itchat 通过整理和封装微信网页版的 Web 接口,使得我们通过简短的 Python 代码就可以调用微信。

3.1.1、安装 itchat

直接通过 pip 命令即可安装 itchat:

pip install itchat

3.1.2、登录微信

安装好 itchat 之后,我们就可以借助 itchat 来实现微信的登录了。在我们的项目目录下继续新建一个 Python 文件——wechat_bot.py:

利用 itchat,我们通过一行代码就能够实现微信的登录:

# coding:utf-8import itchat itchat.auto_login()

运行上述代码,itchat 会自动下载弹出微信登录的二维码,等我们用手机扫码确认登录之后,就实现了在 Python 环境下通过代码进行微信登录,过程如下 gif 动图所示:

3.1.3、获取好友和群聊列表

在登录微信之后,我们就可以获取好友的信息和群聊的信息了。itchat 为好友和群聊都提供了获取所有列表和搜索的方法,下面来看一下:

获取所有好友

通过 get_friends() 方法,我们可以获取到完整的好友列表,使用示例如下:

# coding:utf-8import itchat itchat.auto_login() friends = itchat.get_friends()for friend in friends:    print(friend)

运行代码,会将好友列表中的每一个好友的信息以字典的形式打印出来,其格式如下所示(以我自己的用户信息为例):

{'City': '', 'ChatRoomId': 0, 'WebWxPluginSwitch': 0, 'RemarkPYInitial': '', 'AttrStatus': 0, 'AppAccountFlag': 0, 'OwnerUin': 0, 'NickName': '州的先生', 'SnsFlag': 1, 'HideInputBarFlag': 0, 'Signature': '觉来知是梦,不胜悲。', 'StarFriend': 0, 'Statues': 0, 'RemarkPYQuanPin': '', 'UserName': '@132a8de5d97228087bc656f29cc2c5d67bbde904cdfaaeedb7ff7db72d4bce0e', 'Province': '', 'KeyWord': '', 'Uin': 401807140, 'RemarkName': '', 'VerifyFlag': 0, 'PYInitial': '', 'ContactFlag': 0, 'MemberList': <ContactList: []>, 'DisplayName': '', 'Sex': 1, 'HeadImgUrl': '/cgi-bin/mmwebwx-bin/webwxgeticon?seq=1142454089&username=@132a8de5d97228087bc656f29cc2c5d67bbde904cdfaaeedb7ff7db72d4bce0e&skey=@crypt_82a3c949_8b576ebec932b4b550498cb7f3e88855', 'Alias': '', 'EncryChatRoomId': '', 'HeadImgFlag': 1, 'UniFriend': 0, 'PYQuanPin': '', 'MemberCount': 0}

对于我们而言,一个好友中,最重要的是他的 NickName 字段和 UserName 字段,因为通过这两个字段的值,我们可以搜索到这个好友。

搜索好友

搜索好友的方法为 search_friends(),我们可以传入 NickName 或 UserName 的值进行搜索,如果不传入参数,则会返回自己的用户信息。所以一下三种搜索方式返回的都是我的微信号的用户信息:

# coding:utf-8import itchat itchat.auto_login() user_info = itchat.search_friends()user_info_2 = itchat.search_friends(nickName="州的先生")user_info_3 = itchat.search_friends(userName='@132a8de5d97228087bc656f29cc2c5d67bbde904cdfaaeedb7ff7db72d4bce0e')

获取群聊列表

除了获取到好友的信息外,我们还需要获取到群聊的信息以便对群聊发送消息,通过 get_chatrooms() 方法,我们也将获取到微信号中完整的群聊列表,示例代码如下:

# coding:utf-8import itchat itchat.auto_login() chatrooms = itchat.get_chatrooms()for chatroom in chatrooms:    print(chatroom)

运行代码,会将群聊列表中的每一个群聊的信息以字典的形式打印出来,其格式如下所示(以我的一个群聊信息为例):

{'RemarkPYQuanPin': '', 'KeyWord': '', 'IsAdmin': None, 'ChatRoomId': 0, 'VerifyFlag': 0, 'UserName': '@@a4a7e4cd2430919cb41c2ea4f5bda7cb1c6ed7f2f4f7a649b62d4c9c1e02eead', 'PYInitial': '', 'Province': '', 'NickName': '州的先生Python学习交流', 'IsOwner': 1, 'Self': <User: {'RemarkPYQuanPin': '', 'KeyWord': '', 'ChatRoomId': 0, 'VerifyFlag': 0, 'UserName': '@fb371ab870eb94642cc3c62c573b8268305e81f00ab868c15a15dd40504e5036', 'PYInitial': '', 'MemberCount': 0, 'NickName': '州的先生', 'RemarkName': '', 'MemberList': <ContactList: []>, 'HideInputBarFlag': 0, 'AppAccountFlag': 0, 'HeadImgFlag': 1, 'EncryChatRoomId': '', 'Province': '', 'StarFriend': 0, 'Uin': 401807140, 'UniFriend': 0, 'RemarkPYInitial': '', 'DisplayName': '', 'Signature': '觉来知是梦,不胜悲。', 'PYQuanPin': '', 'City': '', 'OwnerUin': 0, 'ContactFlag': 0, 'HeadImgUrl': '/cgi-bin/mmwebwx-bin/webwxgeticon?seq=67715570&username=@fb371ab870eb94642cc3c62c573b8268305e81f00ab868c15a15dd40504e5036&skey=@crypt_82a3c949_1acf9a2dae8b8a3f849e0c247f45c4c1', 'WebWxPluginSwitch': 0, 'Statues': 0, 'Sex': 1, 'Alias': '', 'AttrStatus': 0, 'SnsFlag': 1}>, 'RemarkName': '', 'Alias': '', 'HideInputBarFlag': 0, 'AppAccountFlag': 0, 'EncryChatRoomId': '', 'MemberCount': 147, 'Uin': 0, 'StarFriend': 0, 'UniFriend': 0, 'RemarkPYInitial': '', 'Statues': 1, 'Signature': '', 'PYQuanPin': '', 'City': '', 'DisplayName': '', 'OwnerUin': 0, 'ContactFlag': 0, 'HeadImgUrl': '/cgi-bin/mmwebwx-bin/webwxgetheadimg?seq=0&username=@@a4a7e4cd2430919cb41c2ea4f5bda7cb1c6ed7f2f4f7a649b62d4c9c1e02eead&skey=@crypt_82a3c949_1acf9a2dae8b8a3f849e0c247f45c4c1', 'Sex': 0, 'MemberList': <ContactList: []>, 'AttrStatus': 0, 'SnsFlag': 0}

如同好友信息一样,在返回的群聊信息中,我们最在乎的还是群聊的 NickName 和 UserName 属性的值。通过这两个属性值,我们可以通过 search_chatrooms() 方法搜索到特定的群聊,代码如下所示:

# coding:utf-8import itchat itchat.auto_login() chat_info = itchat.search_chatrooms(userName="@@a4a7e4cd2430919cb41c2ea4f5bda7cb1c6ed7f2f4f7a649b62d4c9c1e02eead")chat_info_2 = itchat.search_chatrooms(name="州的先生Python学习交流")

3.1.4、发送消息

在 itchat 中,我们可以通过 send() 方法主动发送一条消息出去。send() 方法接受两个参数:

  • msg:消息的内容,内容为'@fil@文件地址'将会被识别为传送文件,'@img@图片地址'将会被识别为传送图片,'@vid@视频地址'将会被识别为小视频,除此之外都将作为文本消息发送;
  • toUserName:发送对象,如果为空,那么将发送给自己

所以如果我们需要给自己发送一条消息,那么代码如下所示:

# coding:utf-8import itchat itchat.auto_login() itchat.send(msg="哈哈,给自己发送一条信息")

3.1.5、接收消息

除了主动发送消息,我们还需要根据接收的消息来进行处理。在微信中,能够收到的消息有很多种类型,itchat.content 中包含了所有的消息类型的参数,其内容如下所示:

为什么要了解消息类型呢,在 itchat 中,如果我们想要登录后的微信能够接收到某个类型的消息,必须首先使用 itchat.msg_register() 装饰器对这个类型的消息进行注册。一个简单的示例如下所示:

import itchatfrom itchat.content import TEXT @itchat.msg_register(TEXT)def simple_reply(msg):    print('收到了一个消息: %s' % msg['Text']) itchat.auto_login(True)itchat.run()

在上面的代码中,我们首先引入了 itchat 模块和 itchat 的 TEXT 文本消息类型,然后对一个函数 simplereply() 调用了消息注册方法对文本消息进行注册,simplereply() 返回接收到的消息,最后调用 auto_login() 方法登录微信和 run() 方法侦听微信消息。

运行这段代码并登录微信后,程序将会一直侦听接收消息,如果收到文本消息,那么将会将消息打印出来,效果如下 gif 动图所示:

如果我们需要接收其他类型的消息,同样使用 @itchat.msgregister() 对消息类型进行注册即可。除了上述的通用消息注册方法,我们还可以指定消息的发送对象,来接收特定用户对象发来的特定消息类型,其通过 @itchat.msgregister() 装饰器的 isFriendChat 参数、isGroupChat 参数和 isMpChat 来实现。例如:

# 只接收来自好友的文本消息@itchat.msg_register(TEXT,isFriendChat=True) # 只接收来自于群聊的文本消息@itchat.msg_register(TEXT,isGroupChat=True) # 接收来自好友和群聊的文本消息@itchat.msg_register(TEXT,isGroupChat=True,isFriendChat=True)

这样,我们就可以自由地对接收的消息进行处理了。

3.1.6、注销登录

注销登录,就是退出在电脑网页端的登录状态。这在手机上可以直接操作,但是我们可以通过 itchat 来简单地实现:

itchat.logout()

如此一句代码,就完成了微信的注销。关于 itchat 更多的功能和使用方法,大家可以阅读官方文档进行学习,链接为:http://itchat.readthedocs.io/zh/latest/

下面我们借助 itchat 来写一个微信群聊机器人,并结合淘宝客 API 将淘宝客的功能加入其中。

3.2、在微信机器人中加入淘宝客功能

删除 wechat_bot.py 中所有的内容,开始我们的淘宝客微信机器人的编写。

引用相关模块

首先,我们引用接下来需要使用到的相关内置模块和第三方模块:

# coding:utf-8 import itchatfrom itchat.content import *import jsonimport requestsimport refrom  urllib.request import urlretrievefrom datetime import datetimeimport timeimport threadingimport osimport top

其中:

  • itchat 用于实现微信的一系列操作;
  • json 用于解析淘宝客 API 返回的 json 字符串;
  • requests 用于请求淘宝客 API;
  • re 用于正则匹配商品优惠信息中的数据;
  • urlretrieve 用于下载商品图片;
  • datetime 用于获取当前时间;
  • time 用于设置时间间隔;
  • threading 用于启用多线程;
  • os 用于获取系统变量信息;
  • top 是我们下载的淘宝客 SDK

定义几个全局变量

接着我们定义几个需要使用到的全局变量,其中包括淘宝客 api 中需要的 AppKey、AppSecret、adzone_id,以及当前文件的路径:

current_path = os.path.dirname(os.path.abspath(__file__)) appkey = '你自己的appkey'secret = '你自己的appsecret'adzone_id = 推广位的adzone_id

定义淘宝客商品优惠券获取函数

随后,定义两个函数,一个是通过关键词获取淘宝客商品优惠券信息的函数,一个是将淘宝客商品优惠券转换为淘口令的函数:

# 通过淘宝客API搜索优惠券def get_tk_coupon(kw,size=5):    req = top.api.TbkDgItemCouponGetRequest()    req.set_app_info(top.appinfo(appkey, secret))     req.adzone_id = int(adzone_id)    req.platform = 2    req.page_size = size    req.q = kw    req.page_no = 1    try:        resp = req.getResponse()['tbk_dg_item_coupon_get_response']['results']['tbk_coupon']        return resp    except Exception as e:        print(e)        return None # 获取淘口令def get_token(url, text):    req = top.api.TbkTpwdCreateRequest()    req.set_app_info(top.appinfo(appkey, secret))     req.text = text    req.url = url    try:        resp = req.getResponse()['tbk_tpwd_create_response']['data']['model']        return resp    except Exception as e:        print(e)        return None

注册接收微信文本消息并回复

接着,我们按照上一小节介绍的 itchat 注册消息类型的方法,使用 @itchat.msg_register() 装饰器注册群聊的文本消息,同时只接收 @我们的消息,然后对接收的消息进行回复。在本例中,我们通过群昵称来判断 @我们的消息是否来自于指定的群聊中:

# 回复群聊搜索@itchat.msg_register(TEXT, isGroupChat=True)def text_reply(msg):    # 如果消息为@我,且我的群昵称为“@我 + 商品”    if msg['isAt'] and msg['Content'][0:8] == '@@我 + 商品':        # 截取消息正文字符串,提取出搜索词        searchword = msg['Content'][9:]        print('消息来自于:{0},内容为:{1}\n'.format(msg['ActualNickName'], msg['Content']))        # 通过搜索词获取淘宝客商品优惠券信息        response = get_tk_coupon(searchword)        # 遍历获取到的淘宝客商品优惠券信息        for r in response:            # 商品标题            ordername = r['title']            # 商品当前价            orderprice = r['zk_final_price']            # 优惠券信息            coupon_info = r['coupon_info']            # 通过正则表达式提取优惠券信息中的面额            coupon_demonination = int(re.findall(r'(\d+)', coupon_info)[-1])            # 商品图片            orderimg = r['pict_url']            # 获取淘口令            token = get_token(url=r['coupon_click_url'], text=r['title'])            # 券后价            couponprice = round(float(orderprice) - int(coupon_demonination), 1)            # 通过新浪微博API生成优惠券链接的短链            link = r['item_url']            link_resp = requests.get(                'http://api.weibo.com/2/short_url/shorten.json?source=2849184197&url_long=' + link).text            link_short = json.loads(link_resp, encoding='utf-8')['urls'][0]['url_short']            # 拼接组合文本消息字符串            msgs = '''/:gift{name}\n/:rose【在售价】{orderprice}元\n/:heart【券后价】{conponprice}元\n/:cake 【抢购链接】{link_short}\n-----------------\n复制这条信息\n{token}打开【手机淘宝】,即可查看\n------------------\n            '''.format(name=ordername, orderprice=orderprice, conponprice=couponprice, token=token,                       link_short=link_short)            # 发送文本消息            itchat.send(msg=str(msgs), toUserName=msg['FromUserName'])            # 发送商品图片            try:                image = urlretrieve(url=orderimg, filename=r'%s' % os.path.join(current_path, 'orderimg.jpg'))                itchat.send_image(fileDir=r'%s' % os.path.join(current_path, 'orderimg.jpg'),                                  toUserName=msg['FromUserName'])            except Exception as e:                print("发送图片失败,{}\n".format(e))        # 等待3秒继续发送        time.sleep(3)

主动发送消息

除了被动的回复别人的搜索,为了保持群聊的活跃程度,在此我们设置主动推送商品优惠券的功能。

# 定时发送消息def send_order_info():    n = 1    while True:        # 判断当前时间是否大于早上7点且小于晚上十一点        if datetime.today().hour > 8 and datetime.today().hour < 23:            print('现在时间:',datetime.today())            # 获取群聊列表            chatroom = itchat.get_chatrooms()            # 遍历群聊列表            for c in chatroom:                n = datetime.today().hour - 7                print(c['UserName'],c['NickName'])                # 只选择指定的群聊                if c['NickName'] == '天猫内部精选优惠券1群':                    try:                        # 获取淘宝客商品优惠券信息                        response = get_tk_coupon('')                        # 遍历商品优惠券信息                        for r in response:                            # 商品标题                            ordername = r['title']                            # 商品当前价                            orderprice = r['zk_final_price']                            coupon_info = r['coupon_info']                            coupon_demonination = int(re.findall(r'(\d+)', coupon_info)[-1])                            # 商品图片                            orderimg = r['pict_url']                            # 获取淘口令                            token = get_token(url=r['coupon_click_url'], text=r['title'])                            # 券后价                            couponprice = round(float(orderprice) - int(coupon_demonination), 1)                            # 生成短链                            link = r['item_url']                            link_resp = requests.get(                                'http://api.weibo.com/2/short_url/shorten.json?source=2849184197&url_long=' + link).text                            link_short = json.loads(link_resp, encoding='utf-8')['urls'][0]['url_short']                            msgs = '''【{times}点档特惠精选】\n/:gift{name}\n/:rose【在售价】{orderprice}元\n/:heart【券后价】{conponprice}元\n/:cake 【抢购链接】{link_short}\n-----------------\n复制这条信息\n{token}打开【手机淘宝】,即可查看                            '''.format(times=str(datetime.today().hour),                                       name=ordername,                                       orderprice=orderprice,                                       conponprice=couponprice,                                       token=token,                                       link_short=link_short)                            # 发送文本消息                            itchat.send(msg=str(msgs), toUserName=c['UserName'])                            # 发送商品图片                            try:                                image = urlretrieve(url=orderimg,                                                    filename=r'%s' % os.path.join(current_path, 'orderimg.jpg'))                                itchat.send_image(fileDir=r'%s' % os.path.join(current_path, 'orderimg.jpg'),                                                  toUserName=c['UserName'])                            except Exception as e:                                print("发送图片失败,{}\n".format(e))                        time.sleep(3)                    except Exception as e:                        print('发送失败',e)            n += 1        else:            n = 1        time.sleep(3600)

在此,我们创建了一个定时发送淘宝客商品优惠券信息的函数,设定每天的早上 9 点到晚上 10 点间,每一个小时调用搜索淘宝客商品优惠券的函数 gettkcoupon() 来发送给指定的群。

运行机器人

完成了上述搜索淘宝客优惠券函数 gettkcoupon()、生成淘口令函数 gettoken()、被动回复群聊搜索函数 textreply() 和定时发送消息函数 sendorderinfo() 的创建后,我们的命令行版本的淘宝客微信机器人就基本完成了功能函数的创建,接下来对其进行运行即可:

if __name__ == '__main__':    # 登录    itchat.auto_login(hotReload=True,enableCmdQR=False,picDir=r'%s'%os.path.join(current_path,'qrcode.jpg'))    # 创建一个线程用于侦听微信的消息    t_reply = threading.Thread(target=itchat.run)    # 创建一个线程用于定时发送消息    t_send = threading.Thread(target=send_order_info)    # 启动线程    t_reply.start()    t_send.start()    t_reply.join()    t_send.join()

在这里,我们调用的 itchat 的 auto_login() 方法来进行登录,然后创建了两个线程,分别用于侦听微信的消息和定时发送消息。 最后,完整的代码如下所示:

# coding:utf-8'''    @name:淘宝客微信机器人命令行版    @author:州的先生    @version:beta0.1''' import itchat,timefrom itchat.content import *import jsonimport requestsimport refrom  urllib.request import urlretrievefrom datetime import datetimeimport threadingimport osimport top current_path = os.path.dirname(os.path.abspath(__file__)) appkey = '24842110'secret = '4887183bf0e9d5ce4e5db53d9319253e'adzone_id = 404486820 # 通过淘宝客API搜索优惠券def get_tk_coupon(kw,size=5):    req = top.api.TbkDgItemCouponGetRequest()    req.set_app_info(top.appinfo(appkey, secret))     req.adzone_id = int(adzone_id)    req.platform = 2    req.page_size = size    req.q = kw    req.page_no = 1    try:        resp = req.getResponse()['tbk_dg_item_coupon_get_response']['results']['tbk_coupon']        return resp    except Exception as e:        print(e)        return None # 获取淘口令def get_token(url, text):    req = top.api.TbkTpwdCreateRequest()    req.set_app_info(top.appinfo(appkey, secret))     req.text = text    req.url = url    try:        resp = req.getResponse()['tbk_tpwd_create_response']['data']['model']        return resp    except Exception as e:        print(e)        return None # 回复群聊搜索@itchat.msg_register(TEXT, isGroupChat=True)def text_reply(msg):    # 如果消息为@我,且我的群昵称为“@我 + 商品”    if msg['isAt'] and msg['Content'][0:8] == '@@我 + 商品':        # 截取消息正文字符串,提取出搜索词        searchword = msg['Content'][9:]        print('消息来自于:{0},内容为:{1}\n'.format(msg['ActualNickName'], msg['Content']))        # 通过搜索词获取淘宝客商品优惠券信息        response = get_tk_coupon(searchword)        # 遍历获取到的淘宝客商品优惠券信息        for r in response:            # 商品标题            ordername = r['title']            # 商品当前价            orderprice = r['zk_final_price']            # 优惠券信息            coupon_info = r['coupon_info']            # 通过正则表达式提取优惠券信息中的面额            coupon_demonination = int(re.findall(r'(\d+)', coupon_info)[-1])            # 商品图片            orderimg = r['pict_url']            # 获取淘口令            token = get_token(url=r['coupon_click_url'], text=r['title'])            # 券后价            couponprice = round(float(orderprice) - int(coupon_demonination), 1)            # 通过新浪微博API生成优惠券链接的短链            link = r['item_url']            link_resp = requests.get(                'http://api.weibo.com/2/short_url/shorten.json?source=2849184197&url_long=' + link).text            link_short = json.loads(link_resp, encoding='utf-8')['urls'][0]['url_short']            # 拼接组合文本消息字符串            msgs = '''/:gift{name}\n/:rose【在售价】{orderprice}元\n/:heart【券后价】{conponprice}元\n/:cake 【抢购链接】{link_short}\n-----------------\n复制这条信息\n{token}打开【手机淘宝】,即可查看\n------------------\n            '''.format(name=ordername, orderprice=orderprice, conponprice=couponprice, token=token,                       link_short=link_short)            # 发送文本消息            itchat.send(msg=str(msgs), toUserName=msg['FromUserName'])            # 发送商品图片            try:                image = urlretrieve(url=orderimg, filename=r'%s' % os.path.join(current_path, 'orderimg.jpg'))                itchat.send_image(fileDir=r'%s' % os.path.join(current_path, 'orderimg.jpg'),                                  toUserName=msg['FromUserName'])            except Exception as e:                print("发送图片失败,{}\n".format(e))        # 等待3秒继续发送        time.sleep(3) # 定时发送消息def send_order_info():    n = 1    while True:        # 判断当前时间是否大于早上7点且小于晚上十一点        if datetime.today().hour > 8 and datetime.today().hour < 23:            print('现在时间:',datetime.today())            # 获取群聊列表            chatroom = itchat.get_chatrooms()            # 遍历群聊列表            for c in chatroom:                n = datetime.today().hour - 7                print(c['UserName'],c['NickName'])                # 只选择指定的群聊                if c['NickName'] == '天猫内部精选优惠券1群':                    try:                        # 获取淘宝客商品优惠券信息                        response = get_tk_coupon('')                        # 遍历商品优惠券信息                        for r in response:                            # 商品标题                            ordername = r['title']                            # 商品当前价                            orderprice = r['zk_final_price']                            coupon_info = r['coupon_info']                            coupon_demonination = int(re.findall(r'(\d+)', coupon_info)[-1])                            # 商品图片                            orderimg = r['pict_url']                            # 获取淘口令                            token = get_token(url=r['coupon_click_url'], text=r['title'])                            # 券后价                            couponprice = round(float(orderprice) - int(coupon_demonination), 1)                            # 生成短链                            link = r['item_url']                            link_resp = requests.get(                                'http://api.weibo.com/2/short_url/shorten.json?source=2849184197&url_long=' + link).text                            link_short = json.loads(link_resp, encoding='utf-8')['urls'][0]['url_short']                            msgs = '''【{times}点档特惠精选】\n/:gift{name}\n/:rose【在售价】{orderprice}元\n/:heart【券后价】{conponprice}元\n/:cake 【抢购链接】{link_short}\n-----------------\n复制这条信息\n{token}打开【手机淘宝】,即可查看                            '''.format(times=str(datetime.today().hour),                                       name=ordername,                                       orderprice=orderprice,                                       conponprice=couponprice,                                       token=token,                                       link_short=link_short)                            # 发送文本消息                            itchat.send(msg=str(msgs), toUserName=c['UserName'])                            # 发送商品图片                            try:                                image = urlretrieve(url=orderimg,                                                    filename=r'%s' % os.path.join(current_path, 'orderimg.jpg'))                                itchat.send_image(fileDir=r'%s' % os.path.join(current_path, 'orderimg.jpg'),                                                  toUserName=c['UserName'])                            except Exception as e:                                print("发送图片失败,{}\n".format(e))                        time.sleep(3)                    except Exception as e:                        print('发送失败',e)            n += 1        else:            n = 1        time.sleep(3600) if __name__ == '__main__':    # 登录    itchat.auto_login(hotReload=True,enableCmdQR=False,picDir=r'%s'%os.path.join(current_path,'qrcode.jpg'))    # 创建一个线程用于侦听微信的消息    t_reply = threading.Thread(target=itchat.run)    # 创建一个线程用于定时发送消息    t_send = threading.Thread(target=send_order_info)    # 启动线程    t_reply.start()    t_send.start()    t_reply.join()    t_send.join()

最后我们来运行一下这个微信机器人,如果当前时间在早上 9 点到晚上 10 点之间,那么在程序运行之后他会首先主动发送 5 条淘宝客商品优惠券消息,效果如图所示:

如果有人在这个指定的群聊里面 @我们,我们就会调用 gettkcoupon() 方法获取淘宝客商品并回复,效果如下图所示:

只要我们的网络不断、电脑不关、微信不退,那么这个淘宝客微信机器人就会一直运行下去。

4、使用 PyQt5 创建微信机器人的桌面程序

上面创建的淘宝客微信机器人完全通过代码来操作和控制,自己使用倒是没什么问题,如果想给更多的人使用,就很不方便了。其便利性和使用的友好性很是欠缺,如果做成一个桌面应用程序,那么就很方便了。

Python 中提供了多种模块来支持编写桌面应用程序,其中包括内置的 tkinter 模块、第三方的 wxPython、PyQt、Kivy 等。这个模块各有优缺点,在此我们选择 PyQt5 来编写我们的淘宝客微信机器人桌面程序。

在开始使用 PyQt5 编写桌面程序之前,我们先来了解一下桌面应用程序的结构。

有前端开发经验的同学都知道,在最基础的前端架构(HTML、CSS、JS)中,HTML 用来定义网页的结构、CSS 用来定义网页页面的样式和布局,JS 则用来控制页面的行为。

而对于一个桌面应用程序,其势必也是有一个结构的,而且其与前端结构中的 HTML、CSS、JS 也有相似之处,比如:

  • 主窗体相当于 HTML 中的 标签;
  • 主窗体中的窗口部件相当于 HTML 中的标签;
  • 窗体中的 Layout 布局层则相当于 CSS 中的浮动定位、绝对定位、Flex 布局定位等;
  • 程序中的一些按钮可能点击后停留在上面会执行一些操作,则相当于 JS 的 click 等事件及其所执行的 javascript 代码。

这样应该就能理解了。那么咱们开始使用 PyQt5 写我们的淘宝客微信群聊机器人桌面程序。

4.1、创建 UI 界面和布局

PyQt5 可以通过 pip 命令直接进行安装:

pip install PyQt5

在安装完成之后,我们在我们的项目目录下再新建一个名为 mainUI.py 的 Python 文件:

我们的桌面程序的代码主要在这个文件中编写。在开始设计 UI 界面之前,我们先来规划一下我们的淘宝客微信群聊机器人的界面(画一个简单的原型图):

可以发现,界面主要由两部分组成:

  • 上层的功能按钮和输入框;
  • 下层的文本输入控制台;

上层的功能按钮和输入框使用两个 GroupBox 分组:

  • 一个为登录和注销按钮的按钮组;
  • 一个为功能选项的按钮和输入框组;

下层的文本控制台则就是一个文本标签。

4.1.1、创建主窗体

照例我们先引入所需要的所有模块:

# coding:utf-8 from PyQt5.QtCore import QThreadfrom PyQt5.QtWidgets import *from PyQt5 import QtGuiimport sysimport itchatfrom itchat.content import *import datetimeimport timeimport osimport top.apiimport requestsimport jsonimport refrom urllib.request import urlretrieve

然后定义一个全局变量,用于获取当前文件的路径:

current_path = os.path.dirname(os.path.abspath(__file__))

接着,通过继承 QMainWindow,创建一个主窗口的类:

class MainGUI(QMainWindow):    def __init__(self):        super().__init__()

在 MainGUI 类中,创建一个 iniUI() 方法,用于初始化设置主窗体的信息:

    '''        程序默认UI界面信息    '''    def iniUI(self):        self.setWindowTitle("州的先生淘宝客微信机器人v0.1")        self.resize(1200, 600)         # 设置程序图标        icon = QtGui.QIcon()        icon.addPixmap(QtGui.QPixmap("logo.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)        self.setWindowIcon(icon)

在 iniUI() 方法中,我们通过 setWindowTitle() 设置了主窗体的标题,通过 resize() 设置了主窗体的初始大小,通过 setWindowIcon() 设置了主窗体的 logo 图标。我们将这个 iniUI() 方法添加到 MainGUI() 类的init() 方法中,然后运行代码:

class MainGUI(QMainWindow):    def __init__(self):        super().__init__()        self.iniUI()    '''        程序默认UI界面信息    '''    def iniUI(self):        self.setWindowTitle("州的先生淘宝客微信机器人v0.1")        self.resize(1200, 600)        # 设置程序图标        icon = QtGui.QIcon()        icon.addPixmap(QtGui.QPixmap("logo.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)        self.setWindowIcon(icon) if __name__ == '__main__':    app = QApplication(sys.argv)    gui = MainGUI()    gui.show()    sys.exit(app.exec_())

最后出现了如下图这样的一个 GUI 界面:

里面空空如也,只有一个主窗体,没关系接下来我们就在这个主窗体里面添加其他的窗口部件和布局。

PS:如有需要Python学习资料的小伙伴可以加点击下方链接自行获取

python免费学习资料以及群交流解答点击即可加入

使用Python全栈打造淘宝客微信机器人(2)!功能太强大了相关推荐

  1. 使用 Python 全栈打造淘宝客微信机器人

    1 .前言 1.1.什么是淘宝客 相信很多人都听过或者接触过各类导购 APP.QQ 群.微信群分享一些淘宝商品的优惠券或是其他的优惠信息. 用户可以在这些渠道上获取到相较于从淘宝平台搜索出来的商品更加 ...

  2. 淘宝客微信机器人接口API开发

    淘宝客微信机器人API接口,淘客机器人API,微信机器人API 微信二次开发完整API功能 需要文档的自取wkteam.gitbook.io 今天给大家介绍微信个人号自动回复机器人的二次开发!使用微信 ...

  3. 淘宝客微信机器人SDK调用接口

    淘宝客微信机器人SDK调用接口定义 手机客户端上传的通知类消息 (删除了没用的) 8.手机客户端微信上线通知 9.手机客户端微信下线通知 10.微信个人号新增好友通知 11.微信个人号移除好友通知 1 ...

  4. 淘宝客返利机器人哪个好用点?怎么做?

    淘客返利机器人一般指的是微信群.微信公众号.微信小程序.微信号等终端,利用软件系统自动为用户提供找淘宝.京东.拼多多等平台的优惠券服务. 用户只要复制相关的商品链接或者淘口令发给微信机器人,微信机器人 ...

  5. 微信个人号客服系统淘宝客发单机器人sdk服务端接口列表

    微信个人号客服系统淘宝客发单机器人sdk服务端接口列表 case HeartBeatReq: {// 客户端发送的心跳包heartBeatReqHandler.handleMsg(ctx, msgVo ...

  6. 制作淘宝客微信公众号(二)

    制作淘宝客微信公众号(二) 这篇文章主要是记录开发淘宝客微信公众号机器人的主要开发过程. 1.完整淘宝客接口流程   上一篇文章已经介绍了如何去调用一个淘宝联盟的API,但是实际上,用户发送链接,我们 ...

  7. python 淘宝客服 机器人_Python实现资源代下|实现机器值守|全自动淘宝自动发货机器人...

    原标题:Python实现资源代下|实现机器值守|全自动淘宝自动发货机器人 发货机器人 帮你实现:淘宝虚拟商品的自动值守.自动资源下载.自动Email发货 1.运作流程 Trip: 使用小附件方式发送邮 ...

  8. Python+Vue计算机毕业设计淘宝客的导购网站的设计与实现7n318(源码+程序+LW+部署)

    该项目含有源码.文档.程序.数据库.配套开发软件.软件安装教程 项目运行环境配置: Python3.7.7+Django+Mysql5.7+pip list+HBuilderX(Vscode也行)+V ...

  9. 淘宝客微信html5,微信H5支付配置

    # 微信商户平台注册 [**https://pay.weixin.qq.com/index.php/core/home/login?return\_url=%2F**](https://pay.wei ...

  10. skycc淘宝客推广软件 V8.2免费版

    2019独角兽企业重金招聘Python工程师标准>>> skycc淘宝客推广软件,帮助企业实现最高效的网店营销,让网店营销不再局限于一个平台,而是实现全网覆盖式网店营销. skycc ...

最新文章

  1. 2018-11-05直播
  2. MVC中helper的用法。
  3. SpringBoot_数据访问-整合Druid配置数据源监控
  4. Arts 第十九周(7/22 ~ 7/28)
  5. centos8 阿里云yum源_CentOS7更换阿里yum源
  6. 计算机硬件认识与了解,计算机硬件认识实习报告参考
  7. 抖音壁纸小程序怎么做?教你开通和对接流量主拥有自己的小程序
  8. js正则表达式之match函数
  9. C语言 转义符\t占用几个空格
  10. linux安装nginx、php、mysql搭建网站
  11. 软考—信息项目管理师(信息化和信息系统二)
  12. 通过JAVA编写DOMINO服务器端插件程序
  13. Spark Streaming 图片处理案例介绍
  14. PermissionError: [WinError 5] 拒绝访问。: ‘E:\\IdeaProjects\\maintenance\\dist\\main‘
  15. CE进阶操作--自带小游戏TutorialGame的修改方法
  16. 【图解HTTP】——返回结果的HTTP状态码
  17. 使用vue报错Cannot use ‘in‘ operator to search for
  18. git 更新密码之后出现异常(雾)
  19. Python学习 day04打卡
  20. Tableau desktop(二)--数据连接及数据字段

热门文章

  1. 如何有效预防宕机?你需要掌握这4个方法
  2. 学而时习之语言篇: 我工作这么多年, 为什么不能准确读 “音标“ ?
  3. C# 使用Panel控件实现窗体嵌套
  4. 信息系统项目管理(二)网络协议、网络存储技术、网络工程、数据仓库和中间件
  5. 九宫格日记-2011年03月03日
  6. Android 开发环境搭建实验报告
  7. reviewboard mysql_ReviewBoard安装配置
  8. Ember.js 初学指南
  9. U盘中毒后被隐藏的文件夹无法隐藏选项无法取消
  10. linuxeth0路径_linux 驱动 路径(最新更新)网卡驱动路径