【Python】微信发送信息

本文介绍了如何利用Python编程语言来发送微信消息。通过特定的执行方式,可以实现在自动化脚本或应用中集成微信通知的功能。
部署运行你感兴趣的模型镜像

Python微信发送信息

cat /opt/shell/weixin.py
#!/usr/bin/python
# -*- coding:utf-8 -*-

import sys
import urllib2
import time
import json
import requests
reload(sys)
sys.setdefaultencoding('utf-8')


touser = sys.argv[1]
title = sys.argv[2]
content = sys.argv[3]

class Token(object):
    def __init__(self,corpid,corpsecret):
        self.baseurl = 'https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={0}&corpsecret={1}'.format(corpid,corpsecret)
        self.expire_time = sys.maxint
        
    def get_token(self):
        if self.expire_time > time.time():
            request = urllib2.Request(self.baseurl)
            response = urllib2.urlopen(request)
            ret = response.read().strip()
            ret = json.loads(ret)
            print(ret)
            if ret['errcode'] == 0:
                pass
            else:
                print >> ret['errmsg'], sys.stderr
                sys.exit(1)
            self.expire_time = time.time() + ret['expires_in']
            self.access_token = ret['access_token']
        return self.access_token

def send_msg(touser,title,content):
    corpid = 'xxxxxxxxx'
    corpsecret = 'm1GxxxZibsT7_Mg7-DJg2xxxcAZpA'
    qs_token = Token(corpid=corpid, corpsecret=corpsecret).get_token()
    url = 'https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={0}'.format(qs_token)
    payload = {
        "touser": touser,
        "msgtype":"text",
        "agentid": 1000002,
        "text":{
            "content":"{0}\n\n{1}".format(title,content)
        },
        "safe":0
    }
    res = requests.post(url,data=json.dumps(payload,ensure_ascii=False))
    print res.json()
    
if __name__ == '__main__':
    send_msg(touser,title,content)

执行方式:

/opt/python/bin/python2.7  /opt/shell/weixin.py 'duanpenghui|chengyongli|zhutong|zhouzhihua' '图库访问异常' "$LOG_TIME 172.17.81.200:5000  线上访问图库无数据"

您可能感兴趣的与本文相关的镜像

Python3.9

Python3.9

Conda
Python

Python 是一种高级、解释型、通用的编程语言,以其简洁易读的语法而闻名,适用于广泛的应用,包括Web开发、数据分析、人工智能和自动化脚本

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值