企业微信机器人读取服务器,企业微信机器人 获取当前天气

这段代码演示了如何利用Python结合腾讯地图API获取地址的经纬度,然后通过彩云天气API查询该位置的实时天气信息,包括气温、湿度、天气状况和空气质量指数。最后,将结果发送到企业微信机器人。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import requests

import json

import time

# address = input() # 输入要查询的地址

address = '湘潭市湖南科技大学'

# 获取输入地址的经纬度

map_key = '腾讯地图API key'

map_url = 'https://apis.map.qq.com/ws/geocoder/v1/?address=' + address + '&key=' + map_key

map_response = requests.get(map_url)

map_json = json.loads(map_response.text)

latitude = str(map_json['result']['location']['lat'])

longitude = str(map_json['result']['location']['lng'])

# print(address + longitude + latitude)

# 根据经纬度查询天气

api_key = '彩云天气API key' # api秘钥

json_url = 'https://api.caiyunapp.com/v2/' + api_key + '/' + longitude + ',' + latitude + '/realtime.json'

json_response = requests.get(json_url)

json_str = json.loads(json_response.text)

timeStamp = json_str['server_time']

localTime = time.localtime(timeStamp)

formatTime = time.strftime("%Y{y}%m{m}%d{d} %H{c}%M{mi}%S{s}").format(y='年', m='月', d='日', c='点', mi='分', s='秒')

temperature = str(json_str['result']['temperature']) # 气温

humidity = json_str['result']['humidity'] # 湿度

skyconndition = str(json_str['result']['skycon']) # 天气状况

weatherdic = {'CLEAR_DAY': '晴', 'CLEAR_NIGHT': '晴', 'PARTLY_CLOUDY_DAY': '多云', 'PARTLY_CLOUDY_NIGHT': '多云',

'CLOUDY': '阴', 'WIND': '阴', 'HAZE': '雾霾', 'RAIN': '雨', 'SNOW': '雪'}

skyconndition = weatherdic[skyconndition] # 匹配代码与文字

aqi = str(json_str['result']['aqi']) # 空气质量指数

if int(aqi) >= 200:

aqi = '200 \n雾霾天要少出去玩哦'

# pm25 = str(json_str['result']['pm25'])

real_humidity = str(humidity * 100)

current_weather = address + '\n北纬' + str(latitude) + ' 东经' + str(

longitude) + '\n实时天气:\n气温:' + temperature + '℃\n湿度:' + real_humidity + '%\n天气:' + skyconndition + '\nAQI:' + aqi + '\n时间:' + formatTime

print(current_weather)

def weather():

headers = {"Content-Type": "text/plain"}

# 苏宁接口获取时间

# timeUrl = 'http://quan.suning.com/getSysTime.do'

# timeResponse = requests.get(timeUrl)

# timeJson = json.loads(timeResponse.text)

# severTime = timeJson['sysTime2'] # 2020-02-21 12:26:12

s = current_weather

data = {

"msgtype": "text",

"text": {

"content": s,

}

}

r = requests.post(

url='http://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=企业微信机器人key', # webhook地址

headers=headers, json=data)

print(r.text)

weather()

### 获取并处理企业微信机器人API中的群聊消息 为了使企业微信机器人能够接收和处理来自群聊的消息,需配置回调模式。通过设置服务器URL以及Token验证来确保安全性和可靠性。当有新消息时,企业微信会向指定的URL推送数据包。 #### 设置回调接口 首先,在管理后台为企业微信应用开启回调功能,并填写用于接收事件通知的服务端地址(URL)、Token 和 EncodingAESKey。这些参数将在后续的消息签名验证过程中起到重要作用[^1]。 #### 接收与解析XML格式的数据包 每当收到新的聊天记录时,企业微信将以POST请求的形式把加密后的XML字符串发送给预先设定好的服务端脚本。该XML包含了诸如消息类型、时间戳、随机数等字段,具体结构如下: ```xml <xml> <ToUserName><![CDATA[toUser]]></ToUserName> <AgentID>agentid</AgentID> ... </xml> ``` 对于不同类型的消息体,则会有不同的子标签描述具体内容。例如文本消息中还可能携带`Content`表示实际的文字内容;如果是图片或语音类多媒体文件,则提供下载链接供调用方自行拉取资源[^2]。 #### 解密过程 由于接收到的信息已被加密保护,因此需要按照官方文档说明的方式对其进行解码操作才能读取出真正的明文信息。这通常涉及到使用Python或其他编程语言编写专门负责加解密工作的模块,利用提供的EncodingAESKey完成相应的计算逻辑[^3]。 #### 处理业务逻辑 一旦成功获取到了原始未加密版本的消息实体之后就可以根据自身需求定义具体的响应策略了——无论是简单的回复确认还是触发更复杂的自动化流程皆可由开发者自由定制实现。 ```python import requests from wechatpy.enterprise.crypto import WeChatCrypto crypto = WeChatCrypto(token='your_token', encoding_aes_key='your_encoding_aes_key', corp_id='your_corp_id') def handle_message(request_body): decrypted_msg = crypto.decrypt_message( request_body, timestamp=request.args.get('timestamp'), nonce=request.args.get('nonce'), msg_signature=request.args.get('msg_signature') ) xml_data = parse_xml(decrypted_msg) # 假设有一个parse_xml函数可以将xml转换成字典形式 if xml_data['MsgType'] == 'text': process_text(xml_data) def process_text(data): sender = data['FromUserName'] content = data['Content'] reply_content = f"Received your message: {content}" send_reply(sender, reply_content) def send_reply(to_user, content): response = { "touser": to_user, "msgtype": "text", "agentid": AGENT_ID, "text": {"content": content}, "safe": 0 } encrypted_response = crypto.encrypt_message(json.dumps(response)) result = requests.post(WEBHOOK_URL, json={"encrypt": encrypted_response}) ``` 此代码片段展示了如何对接收到的企业微信群聊消息进行基本处理,并且回复一条简单消息作为回应。需要注意的是这里假设已经完成了必要的环境搭建工作,比如安装依赖库(`wechatpy`)等前置条件。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值