get_chat_id.py 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. """
  2. 获取飞书群聊 ID 工具
  3. 使用步骤:
  4. 1. 确保机器人已加入目标群聊
  5. 2. 运行此脚本
  6. 3. 在群聊中发送任意消息(@机器人)
  7. 4. 脚本会输出群聊 ID
  8. """
  9. import asyncio
  10. import logging
  11. import sys
  12. from pathlib import Path
  13. # 添加项目路径
  14. sys.path.insert(0, str(Path(__file__).parent.parent.parent))
  15. from agent.tools.builtin.feishu.feishu_client import FeishuClient
  16. from dotenv import load_dotenv
  17. load_dotenv()
  18. from config import FEISHU_APP_ID, FEISHU_APP_SECRET
  19. logging.basicConfig(level=logging.INFO)
  20. logger = logging.getLogger(__name__)
  21. def on_message_received(event):
  22. """消息回调函数"""
  23. print("\n" + "=" * 60)
  24. print("📩 收到消息")
  25. print("=" * 60)
  26. print(f"群聊 ID (chat_id): {event.chat_id}")
  27. print(f"发送者 ID (sender_open_id): {event.sender_open_id}")
  28. print(f"发送者姓名: {event.sender_name or '未知'}")
  29. print(f"消息内容: {event.content}")
  30. print(f"聊天类型: {event.chat_type.value}")
  31. print("=" * 60)
  32. if event.chat_type.value == "group":
  33. print(f"\n✅ 请将以下群聊 ID 配置到 .env 文件:")
  34. print(f"FEISHU_AD_PROJECT_CHAT_ID={event.chat_id}")
  35. else:
  36. print(f"\n⚠️ 这是私聊消息,群聊 ID 是 {event.chat_id}")
  37. print()
  38. def main():
  39. print("=" * 60)
  40. print("飞书群聊 ID 获取工具")
  41. print("=" * 60)
  42. print()
  43. print("📋 使用说明:")
  44. print("1. 确保机器人已加入目标群聊")
  45. print("2. 脚本启动后,在群聊中发送任意消息(建议@机器人)")
  46. print("3. 脚本会自动输出群聊 ID")
  47. print()
  48. print(f"飞书应用 ID: {FEISHU_APP_ID}")
  49. print()
  50. print("🚀 启动监听...")
  51. print("=" * 60)
  52. print()
  53. client = FeishuClient(
  54. app_id=FEISHU_APP_ID,
  55. app_secret=FEISHU_APP_SECRET
  56. )
  57. # 启动 WebSocket 监听(阻塞模式)
  58. try:
  59. client.start_websocket(
  60. on_message=on_message_received,
  61. blocking=True
  62. )
  63. except KeyboardInterrupt:
  64. print("\n\n✋ 用户中断,退出程序")
  65. except Exception as e:
  66. logger.error(f"监听失败: {e}", exc_info=True)
  67. print(f"\n❌ 启动失败: {e}")
  68. print("\n请检查:")
  69. print(" 1. FEISHU_APP_ID 和 FEISHU_APP_SECRET 是否正确")
  70. print(" 2. 机器人应用是否已启用事件订阅")
  71. print(" 3. 网络连接是否正常")
  72. if __name__ == "__main__":
  73. main()