第一句子网 - 唯美句子、句子迷、好句子大全
第一句子网 > python实现微信发消息_Python实现通过微信企业号发送文本消息的Class

python实现微信发消息_Python实现通过微信企业号发送文本消息的Class

时间:2024-03-23 19:38:23

相关推荐

python实现微信发消息_Python实现通过微信企业号发送文本消息的Class

前文《Python实现获取微信企业号access_token的Class》提供了获取微信企业号的access_token,本文中的代码做实际发送文本消息。

编程要点和调用方法:支持发送中文,核心语句“payload = json.dumps(self.data, encoding='utf-8', ensure_ascii=False)”,关键字“python json 中文”

这个Class只有一个公共方法send()。

使用方法:import这个class,然后调用send方法即可,方法参数只需要两个,给谁(多UserID用"|"隔开),内容是什么,例如:import odbp_sendMessage

msg = odbp_sendMessage.WeiXinSendMsgClass()

msg.send("dingguodong", "Python 大魔王!")

运行效果图如下:

手机端效果:

脚本内容如下:#!/usr/bin/python

# encoding: utf-8

# -*- coding: utf8 -*-

"""

Created by PyCharm.

File: LinuxBashShellScriptForOps:odbp_sendMessage.py

User: Guodong

Create Date: /8/12

Create Time: 14:49

"""

import odbp_getToken

class WeiXinSendMsgClass(object):

def __init__(self):

self.access_token = odbp_getToken.WeiXinTokenClass().get()

self.to_user = ""

self.to_party = ""

self.to_tag = ""

self.msg_type = "text"

self.agent_id = 2

self.content = ""

self.safe = 0

self.data = {

"touser": self.to_user,

"toparty": self.to_party,

"totag": self.to_tag,

"msgtype": self.msg_type,

"agentid": self.agent_id,

"text": {

"content": self.content

},

"safe": self.safe

}

def send(self, to_user, content):

if to_user is not None and content is not None:

self.data['touser'] = to_user

self.data['text']['content'] = content

else:

print

raise RuntimeError

import requests

import json

url = "https://qyapi./cgi-bin/message/send"

querystring = {"access_token": self.access_token}

payload = json.dumps(self.data, encoding='utf-8', ensure_ascii=False)

headers = {

'content-type': "application/json",

'cache-control': "no-cache",

}

response = requests.request("POST", url, data=payload, headers=headers, params=querystring)

return_content = json.loads(response.content)

if return_content["errcode"] == 0 and return_content["errmsg"] == "ok":

print "Send successfully! %s " % return_content

else:

print "Send failed! %s " % return_content

tag:python,微信企业号发送报警,微信企业号发送文本消息

--end--

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。