前情提要

以前接了图灵机器人的api做过一个微信小机器人,但是这个机器人只会尬聊也就算了,竟然连斗图都不能!!!虽说图灵机器人官网上有这个api,可是由于我是用python手动接入而不是直接授权,发送表情包给他依然会回复尬聊。我深信没有斗图的机器人是没有灵魂的,于是想动手自己写一个。

参考:用python爬取斗图网

打印从用户哪里获得的消息,会发现,接收表情包返回的是一行文本信息:【收到不支持的消息类型,暂无法显示】

于是我们稍微改一改之前的代码,对这行文本进行判断,只要接收到这行消息,参考爬取代码从斗图网随机爬取一个表情包下载下来,再传入临时素材库,获取mediaid,再生成图片消息发送给用户就可以了。

效果:因为又要下载又要上传显得稍微有点卡顿,但是还可以。

[外链图片转存失败(img-LcIYYqi5-1567160626891)(https://sika0819.top//images/pasted-48.png)]

核心代码:

handler.py

# -*- coding=utf-8 -*-
import hashlib
import reply
import receive
import web
import robot
import getemoticon
from basic import Basic
from media import Media
import json
class Handle(object):def GET(self):try:data = web.input()if len(data) == 0:return "hello, this is handle view"signature = data.signaturetimestamp = data.timestampnonce = data.nonceechostr = data.echostrtoken = "yourtoken"list = [token, timestamp, nonce]list.sort()sha1 = hashlib.sha1()map(sha1.update, list)hashcode = sha1.hexdigest()if hashcode == signature:return echostrelse:return ""except Exception:return Exception.messagedef POST(self):try:webData = web.data()#print("Handle Post webdata is ", webData)recMsg=receive.parse_xml(webData)if isinstance(recMsg, receive.Msg):toUser = recMsg.FromUserNamefromUser = recMsg.ToUserNameif recMsg.MsgType=='text':content = recMsg.Contentprint(content);if content=="【收到不支持的消息类型,暂无法显示】":path=getemoticon.getRandomEmoticon()print(path)myMedia = Media()accessToken = Basic().get_access_token()mediaType = "image"callbackjson = myMedia.upload(accessToken, path, mediaType)callback = json.loads(callbackjson)mediaId=callback[u'media_id']createTime=callback[u'created_at']replyMsg = reply.ImageMsg(toUser, fromUser,createTime,mediaType,mediaId)return replyMsg.send()else:rpyMsg= robot.get_response(content,fromUser)replyMsg=reply.TextMsg(toUser, fromUser,rpyMsg)return replyMsg.send()if recMsg.MsgType == 'image':mediaId = recMsg.MediaIdreplyMsg = reply.ImageMsg(toUser, fromUser, mediaId)return replyMsg.send()else:print("none handler yet")return "success"except Exception as Argument:print Exception.messagereturn "fail"

media.py

# -*- coding: utf-8 -*-
# filename: media.py
from basic import Basic
import urllib2
import poster.encode
from poster.streaminghttp import register_openersclass Media(object):def __init__(self):register_openers()#上传图片def upload(self, accessToken, filePath, mediaType):openFile = open(filePath, "rb")param = {'media': openFile}postData, postHeaders = poster.encode.multipart_encode(param)postUrl = "https://api.weixin.qq.com/cgi-bin/media/upload?access_token=%s&type=%s" % (accessToken, mediaType)request = urllib2.Request(postUrl, postData, postHeaders)urlResp = urllib2.urlopen(request)return urlResp.read()# if __name__ == '__main__':# myMedia = Media()# accessToken = Basic().get_access_token()# filePath = "img/帽冷汗.jpg"   #请安实际填写# mediaType = "image"# myMedia.upload(accessToken, filePath, mediaType)

reply.py

# -*- coding=utf-8 -*-
import time
class Msg(object):def __init__(self):passdef send(self):return "success"
class TextMsg(Msg):def __init__(self, toUserName, fromUserName, content):self.__dict = dict()self.__dict['ToUserName'] = toUserNameself.__dict['FromUserName'] = fromUserNameself.__dict['CreateTime'] = int(time.time())self.__dict['Content'] = contentdef send(self):XmlForm = """<xml><ToUserName><![CDATA[{ToUserName}]]></ToUserName><FromUserName><![CDATA[{FromUserName}]]></FromUserName><CreateTime>{CreateTime}</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[{Content}]]></Content></xml>"""return XmlForm.format(**self.__dict)
class ImageMsg(Msg):def __init__(self, toUserName, fromUserName, mediaId):self.__dict = dict()self.__dict['ToUserName'] = toUserNameself.__dict['FromUserName'] = fromUserNameself.__dict['CreateTime'] = int(time.time())self.__dict['MediaId'] = mediaIddef __init__(self, toUserName, fromUserName,createTime,msgType, mediaId):self.__dict = dict()self.__dict['ToUserName'] = toUserNameself.__dict['FromUserName'] = fromUserNameself.__dict['CreateTime'] = createTimeself.__dict['MsgType'] = msgTypeself.__dict['MediaId'] = mediaIddef send(self):XmlForm = """<xml><ToUserName><![CDATA[{ToUserName}]]></ToUserName><FromUserName><![CDATA[{FromUserName}]]></FromUserName><CreateTime>{CreateTime}</CreateTime><MsgType><![CDATA[image]]></MsgType><Image><MediaId><![CDATA[{MediaId}]]></MediaId></Image></xml>"""return XmlForm.format(**self.__dict)

随机爬取表情包
getemoticon.py

# -*- coding=utf-8 -*-#导入模块
import random
import requests
import re
from bs4 import BeautifulSoup
import bs4
import os#创建请求头列表,帮助我们在进行数据爬取的时候伪装成浏览器
my_headers = ["Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36","Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.153 Safari/537.36","Mozilla/5.0 (Windows NT 6.1; WOW64; rv:30.0) Gecko/20100101 Firefox/30.0","Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_2) AppleWebKit/537.75.14 (KHTML, like Gecko) Version/7.0.3 Safari/537.75.14","Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Win64; x64; Trident/6.0)",
]kv = {"User-Agent": "Mozilla/5.0"}def getHTMLText(url, headers):try:#随机从headers列表中选择一个header使用random_header = random.choice(headers)r = requests.get(url, headers={"User-Agent": random_header}, timeout = 30)#校验是否爬取成功,如果获取失败,输出“爬取失败”r.raise_for_status()r.encoding = r.apparent_encoding# print r.textreturn r.textexcept:print("爬取失败")def getImgList(Ilist, html):#使用python自带的html解析器,html.parser进行返回的html数据的解析工作soup = BeautifulSoup(html, "html.parser")# print html#分析解析后的html代码,通过正则表达式获取每一个图片对应的url地址,然后组成获取url的正则表达式pattern_img = re.compile(r'data-original="(.+?)"')#获取图片对应的标题pattern_title = re.compile(r'alt="(.+?)"')#找到所有的图片url值imgList = re.findall(pattern_img, html)# print imgList#获取所有的图片对应的标题信息titleList = re.findall(pattern_title, html)# print titleList[0].encode('utf-8')#将每一对urli地址和title组成一个列表项,放入到另外一个列表项中可以通过下表进行调用for i in range(len(imgList)):# print i,titleList[i] = titleList[i].encode('utf-8')# print titleList[i]Ilist.append([imgList[i], titleList[i]])return Ilist#判断是否存在指定的文件夹,然后创建文件夹
def mkdir():if not os.path.exists('img'):os.mkdir('img')def saveImg(Ilistcontent):mkdir()img_content = requests.get(Ilistcontent[0]).contentimg_path=""if (Ilistcontent[0][-4:] == '.jpg'):img_path='img/%s.jpg' % (Ilistcontent[1].decode('utf-8'))elif (Ilistcontent[0][-4:] == '.gif'):img_path='img/%s.gif' % (Ilistcontent[1].decode('utf-8'))if os.path.exists(img_path):return img_pathwith open(img_path, 'wb') as f:f.write(img_content)f.close()return img_path
def download(page):Ilist = []url = "https://www.doutula.com/photo/list/?page=%d" %pagehtml = getHTMLText(url, my_headers)Ilist = getImgList(Ilist, html)#printImg(Ilist,page)return Ilist#page = 1
def getRandomEmoticon():print("下载图片")page= 1;print("第%d页"%page)Ilist= download(page);i=random.randint(0,len(Ilist)-1)print("第%d张图"%i)path=saveImg(Ilist[i])return path

这里我因为怕速度太慢只爬取了第一页,然后从第一页随机下载一个图片下来。逻辑应该还可以在优化,从本地直接上传表情包会更快。最好的方式应该是定期下载表情包,把表情存成永久素材,每次直接调用。但由于我是个懒癌晚期,完全不想进行后台管理,于是做成了随用随下载。

Python实现微信机器人斗图相关推荐

  1. Python 技术篇-20行代码实现微信机器人斗图功能实例演示!斗图啦官网API调用方法

    话不多说,看效果图: 先说下原理: 微信接收到你说的话,发给机器人来回复,用回复的话传参给斗图网,然后获得斗图网返回的图片,保存后把图片再发给跟你斗图的人. 斗图啦官网API调用文档 斗图啦官网 菜单 ...

  2. 用python创建微信机器人_用Python创建微信机器人

    原标题:用Python创建微信机器人 文/裸睡的猪哥 图片来源于网络 微信,一个日活10亿的超级app,不仅在国内社交独领风骚,在国外社交也同样占有一席之地.今天我们要讲的便是如何用Python来做一 ...

  3. 利用Python制作微信机器人(三)实现爬取JD商品价格

    从前两篇的博客来看,目前已经实现了机器人单向给微信发消息,和与机器人进行交互式发消息,详情如下: 利用Python制作微信机器人(一)机器人单向发消息 利用Python制作微信机器人(二)与机器人进行 ...

  4. python多线程爬取斗图啦数据

    python多线程爬取斗图啦网的表情数据 使用到的技术点 requests请求库 re 正则表达式 pyquery解析库,python实现的jquery threading 线程 queue 队列 ' ...

  5. 群里又会python的吗_自从会了Python在群里斗图就没输过,Python批量下载表情包!...

    原标题:自从会了Python在群里斗图就没输过,Python批量下载表情包! 导语 最近图慌,于是随便写了个表情包批量下载的脚本,没什么技术含量,纯娱乐性质. 让我们愉快地开始吧~ 开发工具 Pyth ...

  6. 利用Python制作微信机器人(二)

    上次写了利用Python制作微信机器人,其中只实现了通过api来控制微信机器人来给自己发送消息,具体详情可查看: 利用Python制作微信机器人(一) 本篇博客主要编写如何是实现给微信机器人发送消息, ...

  7. python企业微信机器人发送文件

    python企业微信机器人发送文件 import requests#传入文件 def post_file(id_url,wx_url,file):data = {'file': open(file,' ...

  8. Python itchat微信机器人自动回复

    ** Python itchat微信机器人自动回复 ** 第一次写博客,以后会继续更新; 以下是使用Pythobn写的自动微信回复功能,目前支持设置离开状态及机器人回复状态,适合新手学习: 环境:WI ...

  9. 基于python 开发 微信机器人自动回复 app

    基于python 开发 微信机器人自动回复 app # coding:utf-8 __author__ = "zhou" # create by zhou on 2020/3/3 ...

最新文章

  1. Swing组件集合的事件处理(四)
  2. Weka 3.7.12源码学习、阅读、分析(1)
  3. Readline-select
  4. oracle: 在sqlplus中,执行sql语句
  5. java-第九章-循环结构进阶-三个班级每班4位同学成绩大于85的算平均分.
  6. 广西大学计算机技术复试题库,2018年广西大学计算机与电子信息学院408计算机学科专业基础综合之计算机操作系统考研基础五套测试题...
  7. CF708E-Student‘s Camp【数学期望,dp】
  8. Visual Studio 2005结合Direct 9.0 SDK(Aug2007)时应该注意的事项
  9. springboot前后端分离项目MultipartFile获取前端传的file为null问题
  10. c# mysql 连接
  11. 计算机特殊符号大全集,{精心收藏}电脑输入特殊字符大全
  12. c++小游戏代码(5个) 免费
  13. np.roll()的理解和用法
  14. 诺基亚Nokia的PC套件导出短信乱码问题解决(转)
  15. Jackson初次学习
  16. 2020 dns排名_2020年最快的dns是多少_动漫台
  17. 华为杭州研究所面试记
  18. Expression<Func<T, bool>> 扩展方法的使用方法
  19. cluster_acc计算
  20. win10设置默认浏览器

热门文章

  1. L4操作系统(L4/Fiasco)
  2. python3多进程多种使用情况下详解
  3. 小程序公众号制作新媒体运营策划网站制作APP制作运营
  4. AnyPi智能浴室镜方案 智能落地镜方案 智能化妆镜方案开发 带LED
  5. 伺服电机控制器的参数整定
  6. 数据结构------后序遍历,不用栈实现和用栈实现
  7. python为什么要创建央视对象_案例研究:使用python获取中央电视台的节目单
  8. rf+jenkins
  9. html点击图片翻转效果,jquery+css 点击图片旋转特效
  10. 汇编语言 王爽 第四版 第二章 检测点2.2