闲着无事写了一个调用微信接口的脚本,但是发现一个问题,就是只能发送英文,无法发送中文,编码问题不知如何处理,特来请教各位。
#!/usr/bin/env python # -*-coding:utf-8-*- import urllib import urllib2 import json import sys import time toparty = 1 agentid = 0 corpid = 'wx5aef2da956514535' corpsecret = 'nWsDjAmbVpvS3kSdCVqfnoaeRuHUDd4VewauuVzRIy5uI0ueoiJ_J4lrXtv1EO_y' url = 'https://qyapi.weixin.qq.com' subject = sys.argv[2] message = sys.argv[3] send_url = 'https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=' local_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) class weixin: def __init__(self,url,corpid,corpsecret): token_url = '%s/cgi-bin/gettoken?corpid=%s&corpsecret=%s' %(url,corpid,corpsecret) self.token = json.loads(urllib.urlopen(token_url).read())['access_token'] def send_message(self,send_url,data): send_url = send_url + self.token self.respone = urllib2.urlopen(urllib2.Request(send_url,data)).read() print self.respone x = json.loads(str(self.respone))['errcode'] if x == 0: return 'Succesfully' else: return 'Failed' def messages(self,subject,message): values = { "toparty": toparty, "msgtype": "text", "agentid": agentid, "text": {"content": subject + message}, "safe": 0 } data = json.dumps(values) send_message = self.send_message(send_url,data) return send_message if __name__ == '__main__': obj = weixin(url,corpid,corpsecret) ret = obj.messages(subject,message)
上面的脚本运行时需要带三个脚本参数,任意字符即可,但是现在发现中文不行,请教各位如何处理编码问题?
可能是需要经过一次URL转码。
可以考虑换成第三方库requests,易用程度更加高。