#!/usr/bin/env python
# -*- coding: utf-8 -*-

import requests
import json
from ..utils import get_wechat_access_token
from .. import app


def send_text(openid, content):
    """组装文本回复数据"""
    data = {
        "touser": openid,
        "msgtype": "text",
        "text":
        {
            "content": content
        }
    }
    return send_message(data)


def send_music(openid, title, desc, music_url, thumb_media_id):
    """组装音乐回复数据"""
    data = {
        "touser": openid,
        "msgtype": "music",
        "music":
        {
            "title": title,
            "description": desc,
            "musicurl": music_url,
            "hqmusicurl": music_url,
            "thumb_media_id": thumb_media_id
        }
    }
    return send_message(data)


def send_news(openid, content):
    """组装图文回复数据"""
    data = {
        "touser": openid,
        "msgtype": "news",
        "news": {
            "articles": content
        }
    }
    return send_message(data)


def send_message(data):
    """
    使用客服接口主动推送消息
    """
    url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?" + \
        "access_token=%s" % get_wechat_access_token()
    try:
        payload = json.dumps(data, ensure_ascii=False).encode('utf8')
        r = requests.post(url, data=payload)
        response = r.json()
    except Exception, e:
        content = u"客服接口超时或解析失败，错误信息：%s\n提交内容：%r"
        app.logger.warning(content % (e, payload))
    else:
        if response["errmsg"] != 'ok':
            content = u"客服推送失败: %s\n推送内容：%s"
            app.logger.warning(content % (response["errmsg"], data))
        return None

@@ -1379,17 +1379,17 @@
 %5Cn%E6%8F%90%E4%BA%A4%E5%86%85%E5%AE%B9%EF%BC%9A%25
-r
+s
 %22%0A      
@@ -1423,23 +1423,20 @@
 t %25 (e, 
-payload
+data
 ))%0A    e

修改打印的 log