Python实现坐标定时发送

发布时间:2026/7/12 1:31:06
Python实现坐标定时发送 方案一使用微信通过itchatpythonimport itchatimport timeimport schedulefrom datetime import datetimeimport requests# 通过地图API获取当前位置这里使用高德地图示例def get_location():try:# 使用IP定位示例url https://restapi.amap.com/v3/ipparams {key: 你的高德地图API密钥, # 需要去高德开放平台申请output: json}response requests.get(url, paramsparams)data response.json()if data[status] 1:location f省份{data.get(province, 未知)}\n城市{data.get(city, 未知)}\n经纬度{data.get(rectangle, 未知)}return locationelse:return 获取位置失败except Exception as e:return f获取位置出错{str(e)}# 发送位置信息def send_location():try:# 获取好友替换成你想发送的人friend itchat.search_friends(name好友昵称)[0] # 或使用userNamelocation get_location()current_time datetime.now().strftime(%Y-%m-%d %H:%M:%S)message f 当前位置汇报\n时间{current_time}\n{location}itchat.send(message, toUserNamefriend[UserName])print(f[{current_time}] 位置已发送)except Exception as e:print(f发送失败{str(e)})# 登录微信并启动def main():itchat.auto_login(hotReloadTrue) # hotReload保持登录状态# 立即发送一次send_location()# 每10分钟执行一次schedule.every(10).minutes.do(send_location)print(已启动每10分钟发送一次位置...)while True:schedule.run_pending()time.sleep(1)if __name__ __main__:main()方案二使用钉钉机器人更稳定pythonimport requestsimport timeimport schedulefrom datetime import datetimeimport json# 钉钉机器人Webhook地址在钉钉群中添加机器人获取WEBHOOK_URL https://oapi.dingtalk.com/robot/send?access_token你的token# 获取位置使用IP定位def get_location():try:url https://restapi.amap.com/v3/ipparams {key: 你的高德地图API密钥,output: json}response requests.get(url, paramsparams, timeout10)data response.json()if data[status] 1:return {province: data.get(province, 未知),city: data.get(city, 未知),adcode: data.get(adcode, ),rectangle: data.get(rectangle, )}return Noneexcept Exception as e:print(f获取位置失败{e})return None# 发送钉钉消息def send_dingtalk_message():location get_location()if not location:returncurrent_time datetime.now().strftime(%Y-%m-%d %H:%M:%S)# 构建消息message {msgtype: text,text: {content: f 位置汇报⏰ 时间{current_time} 位置{location[province]} {location[city]}️ 区域码{location[adcode]} 坐标范围{location[rectangle]}}}try:response requests.post(WEBHOOK_URL,datajson.dumps(message),headers{Content-Type: application/json})if response.status_code 200:print(f[{current_time}] 位置发送成功)else:print(f[{current_time}] 发送失败{response.text})except Exception as e:print(f发送异常{e})# 主程序def main():print(启动位置定时发送程序...)# 立即发送一次send_dingtalk_message()# 每10分钟执行一次schedule.every(10).minutes.do(send_dingtalk_message)while True:schedule.run_pending()time.sleep(1)if __name__ __main__:main()使用说明准备工作1. 安装依赖包bashpip install requests schedule itchat2. 获取高德地图API密钥· 访问 https://lbs.amap.com/· 注册并创建应用获取Key3. 方案一微信注意事项· 微信可能封号建议使用小号· 需要扫码登录· 好友昵称要准确4. 方案二钉钉更推荐· 创建钉钉群添加机器人· 获取Webhook地址· 更稳定不会被封