def get_component_access_token(rds): WX = weixin component_token = WX.get_component_access_token(rds) if not component_token: ticket = WX.get_ticket(rds) if not ticket: return None wx = WXAPI(WX_APPID, WX_APPSECRET) r = wx.request_token(ticket) logging.debug("request token:%s", r) if r.get('errcode'): logging.error("request token error:%s %s", r['errcode'], r['errmsg']) return None access_token = r['component_access_token'] expires = r['expires_in'] #提前10分钟过期 if expires > 20 * 60: expires = expires - 10 * 60 logging.debug("request component access token:%s expires:%s", access_token, r['expires_in']) WX.set_componet_access_token(rds, access_token, expires) component_token = access_token return component_token
def send_text(token, openid, text): """ 向用户发送文本消息 """ wx = WX(token) result = wx.send_text_message(openid, text) return _check_error(result)
def send_template(wx_appid, wx_app_secret, token, template_id, openid, title, text): """ 向用户发送模板消息 """ wx = WX(wx_appid, wx_app_secret, token) n = int(time.time()) arr = time.localtime(n) user = wx.get_user_by_openid(openid) if not user or user.get('subscribe') == 0: return False if not template_id: return False result = wx.send_template_message(openid, { 'template_id': template_id, 'data': { 'first': { 'value': title }, 'keyword1': { 'value': user.get('nickname') }, 'keyword2': { 'value': time.strftime(u'%Y年%m月%d日 %H:%M'.encode('utf-8'), arr).decode('utf-8') }, 'remark': { 'value': text } } }) return _check_error(result)
def send_article(wx_appid, wx_app_secret, token, openid, articles): """ 向用户发送文章 """ wx = WX(wx_appid, wx_app_secret, token) for article in articles: if not article.get('title'): article['title'] = '' if not article.get('description'): article['description'] = '' result = wx.send_common_message(openid, msgtype='news', content={'articles': articles}) return _check_error(result)
def send_voice(token, openid, files): """ 发送语音 """ wx = WX(token) if isinstance(files, str) or isinstance(files, unicode): res = requests.get(files) content = res.content else: media = files['media'] content = media.stream filename = random_ascii_string(10) + '.amr' result_1 = wx.add_media('voice', [('voice', (filename, content, 'audio/amr'))]) result_1 = _check_error(result_1) media_id = result_1.get('media_id') result_2 = wx.send_common_message(openid, msgtype='voice', content={'media_id': media_id}) return _check_error(result_2)