Python3调用微信企业号API发送文本消息代码示例

yipeiwu_com7年前Python基础

本文主要向大家分享了Python3调用微信企业号API发送文本消息示例的有关代码,具体如下:

#!/usr/bin/env python
# -*- coding:utf-8 -*-
import urllib.request
import json
import sys
import logging
touser = '@all'
agentid = 0
corpid = 'wx5aef2da956514535'
corpsecret = 'Co17m_OPlvE8Q4P2RKKwtq5oIA3p42xGUZEvCHBI8S0'
url = 'https://qyapi.weixin.qq.com'
subject = sys.argv[2]
message = sys.argv[3]
logging.basicConfig(level=logging.DEBUG, filename='E:\Python_project\Scripts\my.log',
          format='%(asctime)s - %(levelname)s: %(message)s')
class Weixin:
  def __init__(self, url, corpid, corpsecret):
    token_url = '%s/cgi-bin/gettoken?corpid=%s&corpsecret=%s' % (url, corpid, corpsecret)
    self.token = json.loads(urllib.request.urlopen(token_url).read().decode())['access_token']
  def send_message(self, url, data):
    send_url = '%s/cgi-bin/message/send?access_token=%s' % (url, self.token)
    self.respone = urllib.request.urlopen(urllib.request.Request(url=send_url, data=data)).read()
    x = json.loads(self.respone.decode())['errcode']
    if x == 0:
      logging.debug('Successfully %s  %s' % (subject, message))
      return 'Succesfully'
    else:
      logging.debug('Failed %s  %s' % (subject, message))
      return 'Failed'
  def messages(self, subject, message):
    values = {
      "touser": touser,
      "msgtype": 'text',
      "agentid": agentid,
      "text": {'content': subject + message},
      "safe": 0
    }
    return self.send_message(url, bytes(json.dumps(values), 'utf-8'))
if __name__ == '__main__':
  obj = Weixin(url, corpid, corpsecret)
  ret = obj.messages(subject, message)

总结

以上就是本文关于Python3调用微信企业号API发送文本消息代码示例的全部内容,希望对大家有所帮助。感兴趣的朋友可以继续参阅本站:在Python web中实现验证码图片代码分享python实现人脸识别代码Python爬虫实例爬取网站搞笑段子等,有什么问题可以随时留言,小编会及时回复大家的。感谢朋友们对本站的支持!

相关文章

Pandas_cum累积计算和rolling滚动计算的用法详解

Pandas主要统计特征函数: 方法名 函数功能 sum() 计算数据样本的总和(按列计...

Python中集合的内建函数和内建方法学习教程

Python中集合的内建函数和内建方法学习教程

集合内建函数和内建方法 (1)标准类型函数        len():把集合作为参数传递给内建函数 len(),返回集合的基数...

python采集博客中上传的QQ截图文件

哎,以前写博文的时候没注意,有些图片用QQ来截取,获得的图片文件名都是类似于QQ截图20120926174732-300×15.png的形式,昨天用ftp备份网站文件的时候发现,中文名在...

Windows上使用Python增加或删除权限的方法

在使用Python在 Windows 平台上开发的时候, 有时候我们需要动态增加或删除用户的某些权限, 此时我们可以通过 AdjustTokenPrivileges API 来实现。 比...

IntelliJ IDEA安装运行python插件方法

IntelliJ IDEA安装运行python插件方法

IDEA 工具是我们常用的开发工具,全称:IntelliJ IDEA,它的功能强大就在于我们可以添加各种插件来编写不同的代码,当然也可以用来编写python,这篇文章我们来讲解,如何用I...