一、前言:添加企业微信群机器人
1、企业微信APP端,在群里添加机器人如命名为test;
2、PC端点击test可查看Webhook地址,也可修改相关资料,Webhook下方的配置说明,可查看相信的机器人配置说明。
二、文本类消息
1、接口说明
2、企业机器人发送文本类消息
代码:
# -*- coding: utf-8 -*-
import requests
import os,time
import pandas as pd
#发送txt文本
def post_txt(url,txt):
data_txt = {"msgtype": "text",
"text": {"content": txt}
}
requests.post(url,json = data_txt).json()
if __name__ == "__main__":
u0 = 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key='
path_0 = os.path.dirname(__file__)
print(path_0)
#读取 全部的key(Sheet列:name key)
path_xlsx = path_0 + '/robot_keys.xlsx'
all_keys = pd.read_excel(path_xlsx, sheet_name = 'Sheet1')
all_keys_dict = all_keys.T.to_dict()
now_h = int(time.strftime("%H", time.localtime()))
for m,n in all_keys_dict.items():
key = u0+n['key']
test_post = '嗨!'+n['name']+'群的老师们,大家好!\n'
test_post += '当前时间:'+time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())+'\n'
test_post_onduty = test_post + '上班请打卡!上班请打卡!'
test_post_onduty += '\n—— 🤖机器人(鲸头鹳)'
test_post_offduty = test_post + '下班请打卡!下班请打卡!'
test_post_offduty += '\n—— 🤖机器人(鲸头鹳)'
if now_h <= 9:
post_txt(key, test_post_onduty)
if now_h >= 19:
post_txt(key, test_post_offduty)
执行结果:
二、Markdown类型消息
1、接口说明
2、企业机器人发送Markdown类型消息
代码:
# -*- coding:utf-8 -*-
import pandas as pd
import requests
from bs4 import BeautifulSoup
import os
# 发送markdown文本--前4条新闻
def post_markdown(url,a):
x = a[0][0]
x0 = "[1." + x + "](" + a[0][1] + ")"
x1 = "[2." + a[1][0] + "](" + a[1][1] + ")"
x2 = "[3." + a[2][0] + "](" + a[2][1] + ")"
x3 = "[4." + a[3][0] + "](" + a[3][1] + ")"
data_txt = {"msgtype": "markdown",
"markdown": {"content": "<font color=\"warning\">今日新闻:</font>\n {}\n > {}\n > {}\n > {}".format(x0,x1,x2,x3)}
}
requests.post(url,json = data_txt).json()
# 解析36kr网站,获取推荐新闻链接
def request_news(url):
re = requests.get(url)
lx = re.content
soup = BeautifulSoup(lx, 'lxml')
news_list = soup.find_all('div', attrs={'class': 'newsflash-item'})
news_all_list = []
for news_i in news_list:
news_link = 'https://36kr.com' + news_i.find('a', attrs={'class': 'item-title'})['href']
news_title = news_i.find('a', attrs={'class': 'item-title'}).getText()
news_desc = news_i.find_all('div', attrs={'class': 'item-desc'})[0].getText()
news_info = news_desc + news_link
news_all_list.append([news_title, news_link, news_info])
return(news_all_list)
if __name__ == "__main__":
u0 = 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key='
path_0 = os.path.dirname(__file__)
print(path_0)
# 读取 全部的key(Sheet列:name key)
path_xlsx = path_0 + '/robot_keys.xlsx'
all_keys = pd.read_excel(path_xlsx, sheet_name='Sheet1')
all_keys_dict = all_keys.T.to_dict()
url_36 = 'https://36kr.com/newsflashes'
a = request_news(url_36)
for m,n in all_keys_dict.items():
key = u0+ n['key']
post_markdown(key,a)
执行结果:
特别特别要注意:一定要保护好机器人的webhook地址,避免泄漏!不要分享到github、博客等可被公开查阅的地方,否则坏人就可以用你的机器人来发垃圾消息了。