""" 钉钉推送使用示例 演示如何配置和使用钉钉推送功能 """ import os import sys # 添加父目录到路径 current_dir = os.path.dirname(os.path.abspath(__file__)) parent_dir = os.path.dirname(os.path.dirname(current_dir)) if parent_dir not in sys.path: sys.path.insert(0, parent_dir) from applications.reporter.daily import DailyReporter from applications.reporter.weekly import WeeklyReporter from applications.reporter.dingtalk_webhook import DingTalkWebhook def example_with_config(): """示例1:通过config.py配置""" print("=" * 50) print("示例1:使用config.py中的配置") print("=" * 50) # 需要在config.py中设置 DINGTALK_WEBHOOK reporter = DailyReporter() result = reporter.generate() print(f"✅ 报告已生成并推送\n") def example_with_env_var(): """示例2:通过环境变量配置""" print("=" * 50) print("示例2:使用环境变量配置") print("=" * 50) # 设置环境变量 webhook_url = os.getenv('DINGTALK_WEBHOOK', '') if webhook_url: reporter = DailyReporter(dingtalk_webhook=webhook_url) result = reporter.generate() print(f"✅ 报告已生成并推送\n") else: print("⚠️ 未设置环境变量 DINGTALK_WEBHOOK\n") def example_with_direct_url(): """示例3:直接指定Webhook地址""" print("=" * 50) print("示例3:直接指定Webhook地址") print("=" * 50) # 直接指定webhook地址(请替换为实际的webhook地址) webhook_url = "https://oapi.dingtalk.com/robot/send?access_token=YOUR_ACCESS_TOKEN" if webhook_url != "https://oapi.dingtalk.com/robot/send?access_token=YOUR_ACCESS_TOKEN": reporter = DailyReporter(dingtalk_webhook=webhook_url) result = reporter.generate() print(f"✅ 报告已生成并推送\n") else: print("⚠️ 请先设置实际的webhook地址\n") def example_without_push(): """示例4:生成报告但不推送""" print("=" * 50) print("示例4:生成报告但不推送到钉钉") print("=" * 50) reporter = DailyReporter() result = reporter.generate(send_dingtalk=False) print(f"✅ 报告已生成(未推送)\n") def example_weekly_report(): """示例5:生成周报并推送""" print("=" * 50) print("示例5:生成周报并推送") print("=" * 50) reporter = WeeklyReporter() result = reporter.generate() print(f"✅ 周报已生成并推送\n") def example_test_webhook(): """示例6:测试钉钉Webhook连接""" print("=" * 50) print("示例6:测试钉钉Webhook连接") print("=" * 50) webhook_url = input("请输入钉钉Webhook地址(直接回车跳过): ").strip() if not webhook_url: print("⚠️ 未输入Webhook地址,跳过测试\n") return client = DingTalkWebhook(webhook_url) # 发送测试消息 success = client.send_text("这是一条测试消息", at_all=False) if success: print("✅ 测试消息发送成功,Webhook配置正确\n") else: print("❌ 测试消息发送失败,请检查Webhook地址是否正确\n") def main(): """主函数""" print("\n" + "=" * 50) print("钉钉推送功能使用示例") print("=" * 50 + "\n") print("请选择要运行的示例:") print("1. 通过config.py配置(需要先在config.py中设置DINGTALK_WEBHOOK)") print("2. 通过环境变量配置") print("3. 直接指定Webhook地址") print("4. 生成报告但不推送") print("5. 生成周报并推送") print("6. 测试钉钉Webhook连接") print("0. 退出") choice = input("\n请输入选项(0-6): ").strip() if choice == "1": example_with_config() elif choice == "2": example_with_env_var() elif choice == "3": example_with_direct_url() elif choice == "4": example_without_push() elif choice == "5": example_weekly_report() elif choice == "6": example_test_webhook() elif choice == "0": print("退出") else: print("无效选项") print("=" * 50) print("示例运行完成!") print("=" * 50 + "\n") if __name__ == "__main__": main()