写一段调用微信接口发送告警的python脚本
时间: 2024-04-21 21:24:33 浏览: 17
以下是一个使用Python调用微信接口发送告警的示例脚本:
```python
import requests
def send_wechat_alert(url, api_key, touser, message):
# 构建请求的数据
data = {
"touser": touser,
"msgtype": "text",
"agentid": 100001, # 替换为实际的应用AgentId
"text": {"content": message},
"safe": 0
}
# 构建请求头部
headers = {
"Content-Type": "application/json",
"charset": "UTF-8"
}
# 构建请求参数
params = {
"key": api_key # 替换为实际的API Key
}
try:
# 发送请求
response = requests.post(url, params=params, json=data, headers=headers)
response.raise_for_status()
print("Alert sent successfully!")
except requests.exceptions.RequestException as e:
print("Failed to send alert:", e)
# 使用示例
url = "https://qyapi.weixin.qq.com/cgi-bin/message/send"
api_key = "your_api_key"
touser = "user_id"
message = "This is an alert message!"
send_wechat_alert(url, api_key, touser, message)
```
请注意,上述代码中的 `url`、`api_key`、`touser` 和 `message` 都需要根据实际情况进行替换。此外,还需确保在微信企业号或企业微信中创建了相应的应用,并获得了正确的API Key和AgentId。
此脚本使用 `requests` 库发送HTTP请求,并将消息以JSON格式发送到指定的微信接口。根据实际需求,可根据微信接口文档调整请求的数据和参数。