python发送微信消息和企业号消息

python3发送微信消息

bot = Bot(cache_path=True)可以保持登陆状态

embed()# 堵塞线程可以一直不掉线

代码如下:

from wxpy import *
bot = Bot(cache_path=True)

# 定位好友
boss = bot.search('好友名字')[0]
boss.send("python测试微信发送")

# 堵塞线程
embed()

发送群把好友名改成群名就行,以上脚本参考自网上

 

实际使用时发现效果不好,可以改成使用企业号推送

注册企业号https://work.weixin.qq.com/wework_admin/frame

下面是4个参数:

 

 

 

发送脚本转自https://www.cnblogs.com/bluezms/p/8948187.html

修改后适应py3

#!/usr/bin/env python
# -*- coding: utf-8 -*-

# @Time    : 2018/4/25 17:06
# @Author  : zms
# @Site    : 
# @File    : WeChat.py
# @Software: PyCharm Community Edition

# !/usr/bin/env python
# coding:utf-8
# file wechat.py

import time
import requests
import json
import sysclass WeChat:
    def __init__(self):
        self.CORPID = '企业号'
        self.CORPSECRET = '应用号见图2箭头2'       # 应用加密字符串
        self.AGENTID = '1000002'                # 应用号
        self.TOUSER = "联系人1|联系人2|联系人3"

    def _get_access_token(self):
        url = 'https://qyapi.weixin.qq.com/cgi-bin/gettoken'
        values = {'corpid': self.CORPID,
                  'corpsecret': self.CORPSECRET,
                  }
        req = requests.post(url, params=values)
        data = json.loads(req.text)
        # print(data)
        return data["access_token"]

    def get_access_token(self):
        try:
            with open('../Common/tmp/access_token.conf', 'r') as f:
                t, access_token = f.read().split()
                # print(access_token)
        except:
            with open('./tmp/access_token.conf', 'w') as f:
                access_token = self._get_access_token()
                cur_time = time.time()
                f.write('\t'.join([str(cur_time), access_token]))
                return access_token
        else:
            cur_time = time.time()
            if 0 < cur_time - float(t) < 7260:
                return access_token
            else:
                with open('./access_token.conf', 'w') as f:
                    access_token = self._get_access_token()
                    f.write('\t'.join([str(cur_time), access_token]))
                    return access_token

    def send_data(self,msg):
        send_url = 'https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=' + self.get_access_token()
        send_values = {
            "touser": self.TOUSER,
            "msgtype": "text",
            "agentid": self.AGENTID,
            "text": {
                "content": msg
                },
            "safe": "0"
            }
        send_data = '{"msgtype": "text", "safe": "0", "agentid": %s, "touser": "%s", "text": {"content": "%s"}}' % (
            self.AGENTID, self.TOUSER, msg)
        r = requests.post(send_url, json=send_values)
        # print r.content
        return r.content


if __name__ == '__main__':
    wx = WeChat()
    wx.send_data('测试中文')

 

被邀请者不想下载企业微信可以选择与个人微信互通,详细请参考微工作台

 

posted @ 2019-02-26 16:23  carlvine  阅读(594)  评论(0编辑  收藏  举报