微信python开发笔记2

目标实现自动回显(也就是发什么回什么功能)

准备

WechatConf 详解 由此可见是推荐使用 wechatConf


conf = WechatConf(token=token,
        appid=appid,
        appsecret=appsecret,
        encrypt_mode='normal'
        )
wechat = WechatBasic(conf=conf)



wechatmessage

message

可以看出除了图片之外,其他的使用media_id就可以进行自动回复。

图片自动回复


            picurl = message.picurl
            r = requests.get(picurl)
            data = wechat.upload_media('image',StringIO(r.content),'jpeg')
            response = wechat.response_image(data['media_id'])


这里使用上传临时素材功能要注意!

使用StringIO时upload_media最后一个参数要加扩展名,这个要注意!

实例




# -*- coding: utf-8 -*-

from StringIO import StringIO
import requests

from wechat_sdk import (
        WechatBasic,
        WechatConf
)

from bottle import (
        get,
        post,
        route,
        run,
        request
)

appid='************'
token = '************'
appsecret='***********',

conf = WechatConf(token=token,
        appid=appid,
        appsecret=appsecret,
        encrypt_mode='normal'
        )
wechat = WechatBasic(conf=conf)

@get('/')
def sig():
# 下面这些变量均假设已由 Request 中提取完毕
    signature = request.GET['signature']
    timestamp = request.GET['timestamp']
    nonce = request.GET['nonce']
# 实例化 wechat
# 对签名进行校验
    if wechat.check_signature(signature=signature, timestamp=timestamp, nonce=nonce):
        return request.GET['echostr']


@post('/')
def handle():
# 下面这些变量均假设已由 Request 中提取完毕
    token = '123456'
    signature = request.GET['signature']
    timestamp = request.GET['timestamp']
    nonce = request.GET['nonce']
    body_text = request.body.read().decode('utf-8')
# 对签名进行校验
    if wechat.check_signature(signature=signature, timestamp=timestamp, nonce=nonce):
        # 对 XML 数据进行解析 (必要, 否则不可执行 response_text, response_image 等操作)
        print body_text
        wechat.parse_data(body_text)
        # 获得解析结果, message 为 WechatMessage 对象 (wechat_sdk.messages中定义)
        message = wechat.get_message()
        response = None
        print message.type
        if message.type == 'text':
            content = message.content
            response = wechat.response_text(content)
        elif message.type == 'image':
            picurl = message.picurl
            r = requests.get(picurl)
            data = wechat.upload_media('image',StringIO(r.content),'jpeg')
            response = wechat.response_image(data['media_id'])
        elif message.type == 'voice':
            response = wechat.response_voice(message.media_id)
        elif message.type == 'video':
            response = wechat.response_video(message.media_id)
        elif message.type == 'shortvideo':
            response = wechat.response_voice(message.media_id)
        else:
            response = wechat.response_text(u'未知')
        # 现在直接将 response 变量内容直接作为 HTTP Response 响应微信服务器即可,此处为了演示返回内容,直接将响应进行输出
        return response

if __name__ == '__main__':
    run(host='123.56.92.104', port=8888, reloader=True, debug=True)


Loading Disqus comments...
Table of Contents