python 发送微信公众号消息_Python 微信公众号发送消息
#_*_coding:utf-8_*_
import requests
import json
import MySQLdb
def get_access_token():
"""
獲取微信全局接口的憑證(默認有效期倆個小時)
如果不每天請求次數(shù)過多, 通過設置緩存即可
"""
result = requests.get(
url="https://api.weixin.qq.com/cgi-bin/token",
params={
"grant_type": "client_credential",
"appid": "xxxxxxxxx", # 微信公眾號appid
"secret": "xxxxxxxx", # 微信公眾號secret
}
).json()
print(result)
if result.get("access_token"):
access_token = result.get("access_token")
else:
access_token = None
return access_token
def sendmsg(openid,msg):
access_token = get_access_token()
body = {
"touser": openid,
"msgtype": "text",
"text": {
"content": msg
}
}
response = requests.post(
url="https://api.weixin.qq.com/cgi-bin/message/custom/send",
params={
"access_token": access_token
},
data=bytes(json.dumps(body, ensure_ascii=False), encoding="utf-8")
)
# 這里可根據(jù)回執(zhí)code進行判定是否發(fā)送成功(也可以根據(jù)code根據(jù)錯誤信息)
result = response.json()
print(result)
path = r"C:\\Users\\Administrator\\Desktop\\weixingong\\user\\%s.txt" % (openid)
print(result["errcode"])
try:
db = MySQLdb.connect(host="192.168.1.4", user="root", db="public_opinion", port=3306, passwd="123456",
charset="utf8")
except Exception as e:
print(e, "數(shù)據(jù)庫連接錯誤")
if result["errcode"] == 0:
with open(path, "a+") as f:
f.write("1")
f.close()
cursor = db.cursor()
# 使用execute方法執(zhí)行SQL語句
sql = "update weixin_user set state = '%s' where userid = '%s'" % (str(result["errcode"]),openid)
print(sql)
cursor.execute(sql)
# 提交sql事五
db.commit()
# 關閉本次操作
cursor.close()
else:
cursor = db.cursor()
# 使用execute方法執(zhí)行SQL語句
sql = "update weixin_user set state = '%s' where userid = '%s'" % (str(result["errcode"]),openid)
print(sql)
cursor.execute(sql)
# 提交sql事五
db.commit()
# 關閉本次操作
cursor.close()
if __name__ == "__main__":
sendmsg("ofDDs0SP9rsDT_pupCsSSgagVVu8","你好?")
# 參數(shù)1,要發(fā)送的用戶tofakeid 微信公眾號點擊用戶頭像url連接中有
# 參數(shù)2,要發(fā)送的內容
總結
以上是生活随笔為你收集整理的python 发送微信公众号消息_Python 微信公众号发送消息的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 交换机和路由器的区别计算机网络,交换机和
- 下一篇: 微信分享网络图片