Python实现的微信公众号群发图片与文本消息功能实例详解
作者:ZHOU YANG 发布时间:2023-02-04 07:43:48
标签:Python,微信
本文实例讲述了Python实现的微信公众号群发图片与文本消息功能。分享给大家供大家参考,具体如下:
在微信公众号开发中,使用api都要附加access_token内容。因此,首先需要获取access_token。如下:
#获取微信access_token
def get_token():
payload_access_token={
'grant_type':'client_credential',
'appid':'xxxxxxxxxxxxx',
'secret':'xxxxxxxxxxxxx'
}
token_url='https://api.weixin.qq.com/cgi-bin/token'
r=requests.get(token_url,params=payload_access_token)
dict_result= (r.json())
return dict_result['access_token']
在群发图片时,需要提供已经上传图片的media_id。注意,群发图片的时候,必须使用接口:https://api.weixin.qq.com/cgi-bin/material/add_material。
#获取上传文件的media_ID
#群发图片的时候,必须使用该api提供的media_ID
def get_media_ID(path):
img_url='https://api.weixin.qq.com/cgi-bin/material/add_material'
payload_img={
'access_token':get_token(),
'type':'image'
}
data ={'media':open(path,'rb')}
r=requests.post(url=img_url,params=payload_img,files=data)
dict =r.json()
return dict['media_id']
订阅号进行群发,必须通过分组id,首先需要获取所有的用户分组情况。
#查询所有用户分组信息
def get_group_id():
url="https://api.weixin.qq.com/cgi-bin/groups/get"
payload_id={
'access_token':get_token()
}
r=requests.get(url=url,params=payload_id)
result=r.json()
return result['groups']
需要选择一个分组进行群发,在这里我选择第一个有效的分组进行群发(即第一个分组用户数不为0的分组)。
#返回第一个有效的group 分组id
def get_first_group_id():
groups =get_group_id()
group_id =0
for group in groups:
if(group['count']!=0):
group_id=group['id']
break;
return group_id
下面的代码用于群发文本消息,群发给第一个有效的分组:
def send_txt_to_first_group(str='Hello World!'):
group_id =get_first_group_id()
pay_send_all={
"filter":{
"is_to_all":False,
"group_id":group_id
},
"text":{
"content":str
},
"msgtype":"text"
}
url="https://api.weixin.qq.com/cgi-bin/message/mass/sendall?access_token="+get_token()
#需要指定json编码的时候不会对中文转码为unicode,否则群发的消息会显示为unicode码,不能正确显示
r=requests.post(url=url,data=json.dumps(pay_send_all,ensure_ascii=False,indent=2))#此处的必须指定此参数
result=r.json()
#根据返回码的内容是否为0判断是否成功
return result['errcode']==0
下面的代码用于群发图片,群发给第一个有效的分组。
def send_img_to_first_group(path='/home/fit/Desktop/test.jpg'):
group_id =get_first_group_id()
pay_send_all={
"filter":{
"is_to_all":False,
"group_id":group_id
},
"image":{
"media_id":get_media_ID(path)
},
"msgtype":"image"
}
url="https://api.weixin.qq.com/cgi-bin/message/mass/sendall?access_token="+get_token()
r=requests.post(url=url,data=json.dumps(pay_send_all))
result=r.json()
#根据返回码的内容是否为0判断是否成功
return result['errcode']==0
以下是所有代码:
# -*- coding: utf-8 -*-
import requests
#首先获取access_token
import json
#获取微信access_token
def get_token():
payload_access_token={
'grant_type':'client_credential',
'appid':'xxxxxxxxxx',
'secret':'xxxxxxxxx'
}
token_url='https://api.weixin.qq.com/cgi-bin/token'
r=requests.get(token_url,params=payload_access_token)
dict_result= (r.json())
return dict_result['access_token']
#获取上传文件的media_ID
#群发图片的时候,必须使用该api提供的media_ID
def get_media_ID(path):
img_url='https://api.weixin.qq.com/cgi-bin/material/add_material'
payload_img={
'access_token':get_token(),
'type':'image'
}
data ={'media':open(path,'rb')}
r=requests.post(url=img_url,params=payload_img,files=data)
dict =r.json()
return dict['media_id']
#查询所有用户分组信息
def get_group_id():
url="https://api.weixin.qq.com/cgi-bin/groups/get"
payload_id={
'access_token':get_token()
}
r=requests.get(url=url,params=payload_id)
result=r.json()
return result['groups']
#返回第一个有效的group 分组id
def get_first_group_id():
groups =get_group_id()
group_id =0
for group in groups:
if(group['count']!=0):
group_id=group['id']
break;
return group_id
def send_img_to_first_group(path='/home/fit/Desktop/test.jpg'):
group_id =get_first_group_id()
pay_send_all={
"filter":{
"is_to_all":False,
"group_id":group_id
},
"image":{
"media_id":get_media_ID(path)
},
"msgtype":"image"
}
url="https://api.weixin.qq.com/cgi-bin/message/mass/sendall?access_token="+get_token()
r=requests.post(url=url,data=json.dumps(pay_send_all))
result=r.json()
print result
#根据返回码的内容是否为0判断是否成功
return result['errcode']==0
def send_txt_to_first_group(str='Hello World!'):
group_id =get_first_group_id()
pay_send_all={
"filter":{
"is_to_all":False,
"group_id":group_id
},
"text":{
"content":str
},
"msgtype":"text"
}
url="https://api.weixin.qq.com/cgi-bin/message/mass/sendall?access_token="+get_token()
#需要指定json编码的时候不会对中文转码为unicode,否则群发的消息会显示为unicode码,不能正确显示
r=requests.post(url=url,data=json.dumps(pay_send_all,ensure_ascii=False,indent=2))#此处的必须指定此参数
result=r.json()
#根据返回码的内容是否为0判断是否成功
return result['errcode']==0
if(send_txt_to_first_group("祝你合家欢乐,幸福美满!")):
print 'success!'
else:
print 'fail!'
附录:在使用微信测试订阅号测试群发图片接口的时候,返回码如下:
{u'errcode': 45028, u'errmsg': u'has no masssend quota hint: [OKvFdA0813ge12]'}
这是因为测试订阅号没有群发图文消息的权限,并不是因为接口调用有误。
PS:
作者的github: https://github.com/zhoudayang
希望本文所述对大家Python程序设计有所帮助。
0
投稿
猜你喜欢
- 系列最后一篇来说说Python中的类与对象,Python这门语言是无处不对象,如果你曾浅要了解过Python,你应该听过Python是一种面
- 一、Python 缓存① 缓存作用缓存是一种优化技术,可以在应用程序中使用它来将最近或经常使用的数据保存在内存中,通过这种方式来访问数据的速
- 在查询语句中使用 NOLOCK 和 READPAST 处理一个数据库死锁的异常时候,其中一个建议就是使用 NOLOCK 或者 READPAS
- 问题背景:新添加一个virtualenv环境时,需要安装指定的django==1.9.8,但是在添加解释器时,总报一个fuck egg的问题
- 前言登录跳转:不同的用户在登录成功之后跳转到不同的网页当中例如:网站管理员登录成功后跳转到网站后台,vip用户登录成功后跳转到vip页面准备
- 前言本博客默认读者对神经网络与Tensorflow有一定了解,对其中的一些术语不再做具体解释。并且本博客主要以图片数据为例进行介绍,如有错误
- 一、picklepickle模块用来实现python对象的序列化和反序列化。通常地pickle将python对象序列化为二进制流或文件。&n
- cos()方法返回x弧度的余弦值。语法以下是cos()方法的语法:cos(x)注意:此函数是无法直接访问的,所以我们需要导入ma
- 下面一段代码是小编给大家介绍的Python ldap实现登录实例代码,一起看看吧ldap_config = { 'lda
- 1.文本框只能输入数字代码(小数点也不能输入)<input onkeyup="this.value=this.va
- 一、使用NumPy读写文本文件在数据分析中,经常需要从文件中读取数据或将数据写入文件,常用的存储文件的格式有文本文件、CSV格式文件、二进制
- QL Server事件探查器(Profiler)可以帮助数据库管理员跟踪SQL Server数据库所执行的特定事件,监视数据库的行为;并将这
- 在PCA中有遇到,在这里记录一下计算矩阵的特征值个特征向量,下面给出几个示例代码:在使用前需要单独import一下>>>
- 一、前言下述配置的前提是服务器上存在多个虚拟环境,且 PyCharm为专业版二、配置方法配置远程服务器配置多个解释器在配置好远程服务器后,依
- 前言在python基础知识中有说过,字典是可变的数据类型,其参数又是键对值。setdefault()方法和字典的get()方法在一些地方比较
- 概述编程的内核是数学,而测试的本质是计算,专业名词叫容量预估,而测试的大体就是用程序模拟程序,检测程序的正确性,有两个点需要注意,QPS最佳
- 举例: 340%60 = 40 ,怎么来的?340 - 60*5 = 40340 - (比340小的那个可以被60整除的正整数) =. 40
- 有三种方法,一是用微软提供的扩展库win32com来操作IE,二是用selenium的webdriver,三是用python自带的HTMLP
- 比如说点的是图片的左边,还是右边,上边还是下边?点击图片左右显示上下张,我怎么知道?这样就可以做出像QQ空间那样,打开上一个图片和下一个图片
- Queue模块保持线程同步利用Queue对象先进先出的特性,将每个生产者的数据一次存入队列,而每个消费者将依次从队列中取出数据import