自动推送微信公共账号群消息

fmnisme python520,3051字数 3728阅读12分25秒阅读模式

微信公众平台的基础接口没有推送群消息的api(高级接口貌似也没有),所以用python写了个程序模拟微信公众平台的post请求来实现这个功能,附带实现了发送消息给单个用户。

需要的模块文章源自运维生存时间-https://www.ttlsa.com/python/wechat-auto-push-group-message/

requests:给人用的HTTP请求模块,python自带的urllib和urllib2实在是难用。requests支持会话模式,意思就是所有的请求都用一个实例,共享同一个cookies,十分方便。具体参考官方文档(中文):http://cn.python-requests.org/zh_CN/latest/index.html文章源自运维生存时间-https://www.ttlsa.com/python/wechat-auto-push-group-message/

实现文章源自运维生存时间-https://www.ttlsa.com/python/wechat-auto-push-group-message/

requests.seesion()就是会话模式文章源自运维生存时间-https://www.ttlsa.com/python/wechat-auto-push-group-message/

首先设置主请求头文章源自运维生存时间-https://www.ttlsa.com/python/wechat-auto-push-group-message/

然后login()函数登录,获取token。发送的密码用md5加密文章源自运维生存时间-https://www.ttlsa.com/python/wechat-auto-push-group-message/

最后masssend()函数发送群消息文章源自运维生存时间-https://www.ttlsa.com/python/wechat-auto-push-group-message/

singlesend()函数用来给单人发送消息,形参tofakeid不是用户的微信号,并且和api中"FromUserName 发送方帐号"也不一样,这样就没办法将用户直接关联起来,只能手动观察绑定-。-文章源自运维生存时间-https://www.ttlsa.com/python/wechat-auto-push-group-message/

ps:如果在本机浏览器上登录了微信公众平台,然后在另一个电脑上运行脚本,可能会导致脚本登录失败,解决的办法是退出本机登录。文章源自运维生存时间-https://www.ttlsa.com/python/wechat-auto-push-group-message/

#coding:utf-8
"""
微信公众平台管理界面
"""
import requests
import hashlib
import random
import ttlsa
import json
import sys

session=requests.session()
session.headers={
                'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:28.0) Gecko/20100101 Firefox/28.0',
                'Accept': 'application/json, text/javascript, */*; q=0.01',
                'Accept-Language': 'zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3',
                'Accept-Encoding': 'deflate',
                'DNT': '1',
                'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
                'X-Requested-With': 'XMLHttpRequest',
                'Referer': 'https://mp.weixin.qq.com/',
                'Connection': 'keep-alive',
                'Pragma': 'no-cache',
                'Cache-Control': 'no-cache'
                }
token=None

def login(username,pwd):
    """登录"""
    #正确响应:{"base_resp":{"ret":0,"err_msg":"ok"},"redirect_url":"\/cgi-bin\/home?t=home\/index&lang=zh_CN&token=898262162"}
    global token
    pwd=hashlib.md5(pwd).hexdigest()
    url='https://mp.weixin.qq.com/cgi-bin/login?lang=zh_CN'
    data={'f':'json',
          'imgcode':'',
          'pwd':pwd,
          'username':username}
    res=session.post(url,data)
    print 'response: login',res.text
    j=json.loads(res.text)
    status=j['base_resp']['err_msg']
    if status=='ok':
        token=j['redirect_url'].split('=')[-1]
        return True
    return False

def singlesend(tofakeid,content):
    """发送消息给单个人
    多次发送消息可能需要发送心跳信息(未测试)"""
    #正确响应:{"base_resp":{"ret":0,"err_msg":"ok"}}
    url='https://mp.weixin.qq.com/cgi-bin/singlesend'
    data={'ajax':'1',
            'content':content,
            'f':'json',
            'imgcode':'',
            'lang':'zh_CN',
            'random':str(random.random()),
            't':'ajax-response',
            'tofakeid':tofakeid,
            'token':token,
            'type':'1',
            }
    res=session.post(url,data)
    print 'response: singlesend',res.text
    j=json.loads(res.text)
    status=j['base_resp']['err_msg']
    if status=='ok':
        return True
    return False

def masssend(content):
    """群发消息"""
    #正确响应:{"ret":"0", "msg":"ok"}
    url='https://mp.weixin.qq.com/cgi-bin/masssend'
    data={'ajax':'1',
            'city':'',
            'content':content,
            'country':'',
            'f':'json',
            'groupid':'-1',
            'imgcode':'',
            'lang':'zh_CN',
            'province':'',
            'random':str(random.random()),
            'sex':'0',
            'synctxnews':'0',
            'synctxweibo':'0',
            't':'ajax-response',
            'token':token,
            'type':'1'
            }
    res=session.post(url,data)
    print 'response: masssend',res.text
    j=json.loads(res.text)
    if j['msg']=='ok':
        return True
    return False

if __name__=='__main__':
    res=login('username','password')
    print 'response: login',res
    if not res:
        sys.exit()

    #群发
    res=masssend('呵呵')
    print 'response: masssend',str(res)
    
    #发送给单人
    #res=singlesend('尼玛蛋')
    #print 'response: singlesend',str(res)
文章源自运维生存时间-https://www.ttlsa.com/python/wechat-auto-push-group-message/文章源自运维生存时间-https://www.ttlsa.com/python/wechat-auto-push-group-message/
weinxin
我的微信
微信公众号
扫一扫关注运维生存时间公众号,获取最新技术文章~
fmnisme
  • 本文由 发表于 03/05/2014 16:25:22
  • 转载请务必保留本文链接:https://www.ttlsa.com/python/wechat-auto-push-group-message/
评论  5  访客  5
    • 叶枫
      叶枫 9

      客服号是要认证的

      • falcon
        falcon 9

        公众帐号要一周内跟用户有交互,用这个还不如用API的客服接口

        • youngman
          youngman 9

          这个NB,收藏!

          • 邓贇
            邓贇 7

            思路很好

            • 路一起
              路一起 9

              路过 看看

            评论已关闭!