python發送微信及企業微信消息

1.發送微信消息

直接使用第三方庫 itchat,其文檔中有詳細使用方式; https://itchat.readthedocs.io/zh/latest/

如下實例爲 發送羣聊信息

# -*- coding: utf-8 -*-
# (C) Guangcai Ren, 2019
# All rights reserved
import logging

import itchat

log = logging.getLogger(__name__)

# itchat 微信官方教程:https://itchat.readthedocs.io/zh/latest/
# 微信登錄
# 登錄時如果斷網,則此程序直接停止
# 啓動熱登錄,並且生成 命令行 登錄二維碼
itchat.auto_login(hotReload=True, enableCmdQR=2)
# 保持心跳狀態,防止自動退出登錄
itchat.start_receiving()

# 獲取羣聊,注意羣 必須保持到通訊錄,否則可能會找不到羣
itchat.get_chatrooms(update=True)
room = itchat.search_chatrooms('python')
if len(room) == 0:
    log.error('沒有找到羣信息')
else:
    try:
        iRoom = room[0]['UserName']
        # 發送消息
        result = itchat.send('send message', iRoom)
        try:
            if result['BaseResponse']['ErrMsg'] == '請求成功':
                log.info('send wechat success')
        except Exception as e:
            print('resolve wechat result fail,result is :{},error is {}'.format(result, e))
    except Exception as e:
        print('wechat send message fail,reason is :{} '.format(e))

 

2.發送企業微信 信息

企業微信 官方有 相關文檔,直接按照文檔開發即可。

注意點:

  • 先開通企業微信 
  • 登錄網頁版 企業微信 https://work.weixin.qq.com/  從中查找相關 id(在獲取訪問token時需要)
  • 接口一般 流程爲 先 獲取 token,再用 token訪問其他接口
  • 發送羣聊信息時,羣id 只能通過 接口創建羣聊的纔有羣id
  • 創建羣聊時的 獲取token的參數 corpsecret必須 從 應用的 部門一定要選根目錄,否則報錯 86006;
  • 如果開發過程中有任何問題(錯誤提示有一定的誤導性) 可以通過 企業微信客服 進行溝通解決,他們非常有耐心,謝謝他們。 

如下代碼 做到了 獲取token,創建羣聊,發送羣聊信息,發送個人信息

# -*- coding: utf-8 -*-
# (C) Guangcai Ren <[email protected]>
# All rights reserved
# create time '2019/6/13 17:17'
import json

import requests

result = requests.get("https://qyapi.weixin.qq.com/cgi-bin/gettoken",
                      params={'corpid': 'fg',
                              'corpsecret': '45'})
access_token = None
if result.status_code != 200:
    print('連接到服務器失敗')
else:
    result_json = json.loads(result.text)
    if result_json['errcode'] != 0:
        print('響應結果不正確')
    else:
        access_token = result_json['access_token']
        print(access_token)

# 創建羣聊
result = requests.post('https://qyapi.weixin.qq.com/cgi-bin/appchat/create?access_token={}'.format(access_token),
                       data=json.dumps({
                           "name": "通知羣",
                           "owner": "user_name",
                           "userlist": ["user_name", "user_name1", "user_name2"],
                           "chatid": "secid"
                       }))
print(result.text)

# 推送羣聊信息
result = requests.post('https://qyapi.weixin.qq.com/cgi-bin/appchat/send?access_token={}'.format(access_token),
                       data=json.dumps({
                           "chatid": "secid",
                           "msgtype": "text",
                           "text": {
                               "content": "測試:你的快遞已到\n請攜帶工卡前往郵件中心領取"
                           },
                           "safe": 0
                       }))
print(result.text)

# 發送個人消息
result = requests.post('https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={}'.format(access_token),
                       data=json.dumps({
                           "touser": "user_name",
                           "msgtype": "text",
                           "agentid": 23,
                           "text": {
                               "content": "你的快遞已到,請攜帶工卡前往郵件中心領取。\n出發前可查看<a href=\"http://work.weixin.qq.com\">郵件中心視頻實況</a>,聰明避開排隊。"
                           },
                           "safe": 0
                       }
                       ))
print(result.text)

 

發佈了92 篇原創文章 · 獲贊 2 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章