get-chat-id.js 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. #!/usr/bin/env node
  2. require('dotenv').config();
  3. const TelegramBot = require('node-telegram-bot-api');
  4. async function getChatId() {
  5. console.log('🔍 获取Telegram Chat ID...\n');
  6. const botToken = process.env.TELEGRAM_BOT_TOKEN;
  7. if (!botToken) {
  8. console.error('❌ 未配置TELEGRAM_BOT_TOKEN');
  9. process.exit(1);
  10. }
  11. try {
  12. console.log('📋 机器人配置信息:');
  13. console.log(` Bot Token: ${botToken.substring(0, 10)}...${botToken.substring(botToken.length - 10)}\n`);
  14. // 创建机器人实例
  15. const bot = new TelegramBot(botToken, { polling: false });
  16. console.log('🔄 测试机器人连接...');
  17. const me = await bot.getMe();
  18. console.log('✅ 机器人连接成功!');
  19. console.log(` 机器人名称: ${me.first_name}`);
  20. console.log(` 机器人用户名: @${me.username}\n`);
  21. console.log('📋 获取最近的更新...');
  22. const updates = await bot.getUpdates();
  23. if (updates.length === 0) {
  24. console.log('⚠️ 没有找到任何更新记录');
  25. console.log('\n📝 请按以下步骤操作:');
  26. console.log(' 1. 将机器人添加到群组或频道');
  27. console.log(' 2. 在群组中发送 /start 或任何消息');
  28. console.log(' 3. 再次运行此脚本');
  29. return;
  30. }
  31. console.log(`✅ 找到 ${updates.length} 条更新记录\n`);
  32. console.log('📊 Chat ID 列表:');
  33. const chatIds = new Set();
  34. updates.forEach((update, index) => {
  35. if (update.message) {
  36. const chat = update.message.chat;
  37. chatIds.add(chat.id);
  38. console.log(` ${index + 1}. Chat ID: ${chat.id}`);
  39. console.log(` 类型: ${chat.type}`);
  40. console.log(` 标题: ${chat.title || chat.first_name || '个人聊天'}`);
  41. console.log(` 用户名: ${chat.username ? '@' + chat.username : '无'}`);
  42. console.log('');
  43. }
  44. });
  45. if (chatIds.size > 0) {
  46. console.log('💡 建议使用的Chat ID:');
  47. chatIds.forEach((chatId, index) => {
  48. console.log(` ${index + 1}. ${chatId}`);
  49. });
  50. console.log('\n📝 配置方法:');
  51. console.log(' 在.env文件中设置:');
  52. console.log(` TELEGRAM_CHAT_ID=${Array.from(chatIds)[0]}`);
  53. }
  54. } catch (error) {
  55. console.error('❌ 获取Chat ID失败:', error.message);
  56. if (error.response) {
  57. console.error(' 错误详情:', error.response.data);
  58. }
  59. console.log('\n🔧 故障排除建议:');
  60. console.log(' 1. 检查Bot Token是否正确');
  61. console.log(' 2. 确保机器人已添加到群组/频道');
  62. console.log(' 3. 在群组中发送消息激活机器人');
  63. process.exit(1);
  64. }
  65. }
  66. // 如果直接运行此文件
  67. if (require.main === module) {
  68. getChatId();
  69. }
  70. module.exports = { getChatId };