import sys
import os
import csv
import re
import subprocess
import importlib
import importlib.util
============================================================
0. 面板专属:依赖检测与局部自动安装
============================================================
BASE_DIR = os.path.dirname(os.path.abspath(file))
LIB_PATH = os.path.join(BASE_DIR, “libs”)
os.makedirs(LIB_PATH, exist_ok=True)
优先从当前程序的 libs 目录加载依赖
if LIB_PATH not in sys.path:
sys.path.insert(0, LIB_PATH)
禁用 pip 版本检查
os.environ[“PIP_DISABLE_PIP_VERSION_CHECK”] = “1”
def check_dependencies():
print(">>> 正在检查 Python 依赖...")
dependencies = {
"telethon": "telethon",
"dotenv": "python-dotenv"
}
missing = []
for module, package in dependencies.items():
try:
spec = importlib.util.find_spec(module)
if spec is None:
missing.append(package)
except (ImportError, ValueError):
missing.append(package)
if not missing:
print(">>> 依赖检查完成:所有依赖已存在")
return
print(
f">>> 检测到缺少依赖:{', '.join(missing)}"
)
print(">>> 正在 libs 目录安装依赖,请稍候...")
subprocess.check_call([
sys.executable,
"-m",
"pip",
"install",
"--no-user",
"-t",
LIB_PATH,
*missing
])
importlib.invalidate_caches()
print(">>> 依赖安装完成")
只执行一次依赖检测
check_dependencies()
============================================================
1. 导入依赖
============================================================
from telethon import TelegramClient
from telethon.tl.types import (
Chat,
Channel,
ChannelParticipantsAdmins,
ChannelParticipantCreator,
ChatParticipantCreator,
PeerUser
)
from telethon.tl.functions.messages import GetFullChatRequest
from dotenv import load_dotenv
print(“>>> Python 依赖初始化完成”)
============================================================
2. 基础配置
============================================================
load_dotenv(
os.path.join(BASE_DIR, “.env”)
)
API_ID = os.getenv(“API_ID”)
API_HASH = os.getenv(“API_HASH”)
PHONE_NUMBER = os.getenv(“PHONE_NUMBER”)
TWO_STEP_PASSWORD = os.getenv(“TWO_STEP_PASSWORD”)
配置检查
if not API_ID or not API_HASH or not PHONE_NUMBER:
print("❌ 配置错误!")
print("请检查 .env 文件中的:")
print("API_ID")
print("API_HASH")
print("PHONE_NUMBER")
sys.exit(1)
try:
API_ID = int(API_ID)
except ValueError:
print("❌ API_ID 必须是数字")
sys.exit(1)
============================================================
3. 文件夹初始化
============================================================
safe_phone = re.sub(
r”\D”,
“”,
PHONE_NUMBER
)
SESSION_DIR = os.path.join(
BASE_DIR,
“session”
)
EXPORT_DIR = os.path.join(
BASE_DIR,
“namelist”
)
os.makedirs(SESSION_DIR, exist_ok=True)
os.makedirs(EXPORT_DIR, exist_ok=True)
Session 文件
session_filename = f”forwarder_session_{safe_phone}”
session_path = os.path.join(
SESSION_DIR,
session_filename
)
创建 Telegram 客户端
client = TelegramClient(
session_path,
API_ID,
API_HASH
)
============================================================
4. 名称截取功能
============================================================
def limit_name(name, max_length=10):
"""
名称最多保留前10个字符。
汉字、英文字母、数字、符号
均按照一个字符计算。
"""
if not name:
return ""
return str(name)[:max_length]
============================================================
5. Bot API ID 转换
============================================================
def get_bot_api_id(entity, entity_type):
raw_id = entity.id
if entity_type in [
"频道",
"超级群",
"频道(未知)"
]:
return int(f"-100{raw_id}")
elif entity_type == "普通群":
return int(f"-{raw_id}")
return raw_id
============================================================
6. 拥有者信息格式化
============================================================
def format_owner(user):
first_name = (
getattr(user, "first_name", None)
or ""
)
last_name = (
getattr(user, "last_name", None)
or ""
)
full_name = (
f"{first_name} {last_name}"
).strip()
username = getattr(
user,
"username",
None
)
return {
"拥有者姓名": full_name or "未知",
"拥有者用户名": (
f"@{username}"
if username
else "无"
),
"拥有者Telegram_ID": getattr(
user,
"id",
"未知"
),
"拥有者状态": "成功"
}
def empty_owner(status):
return {
"拥有者姓名": "未知",
"拥有者用户名": "未知",
"拥有者Telegram_ID": "未知",
"拥有者状态": status
}
============================================================
7. 获取普通群拥有者
============================================================
async def get_basic_group_owner(entity):
try:
# 获取普通群完整信息
result = await client(
GetFullChatRequest(
chat_id=entity.id
)
)
participants = (
result.full_chat.participants
)
participant_list = getattr(
participants,
"participants",
[]
)
# 遍历群组参与者
for participant in participant_list:
if isinstance(
participant,
ChatParticipantCreator
):
owner_id = participant.user_id
# 优先从本次 API 返回的用户列表获取资料
user = next(
(
item
for item in result.users
if item.id == owner_id
),
None
)
# 如果没有找到,再尝试通过 ID 获取
if user is None:
user = await client.get_entity(
PeerUser(owner_id)
)
return format_owner(user)
return empty_owner(
"未识别到创建者"
)
except Exception as e:
error_name = type(e).__name__
print(
f"普通群拥有者获取失败:{entity.id} | {error_name}"
)
if error_name == "FloodWaitError":
status = "频率限制"
elif error_name in (
"ChatAdminRequiredError",
"ChannelPrivateError",
"UserNotParticipantError"
):
status = "无权限"
else:
status = f"获取失败:{error_name}"
return empty_owner(status)
============================================================
8. 获取超级群 / 频道拥有者
============================================================
async def get_channel_owner(entity):
try:
# 只获取管理员,不遍历全部成员
async for user in client.iter_participants(
entity,
filter=ChannelParticipantsAdmins
):
participant = getattr(
user,
"participant",
None
)
# 判断当前管理员是否为 Creator
if isinstance(
participant,
ChannelParticipantCreator
):
return format_owner(user)
return empty_owner(
"未识别到创建者"
)
except Exception as e:
error_name = type(e).__name__
print(
f"频道/超级群拥有者获取失败:{entity.id} | {error_name}"
)
if error_name == "FloodWaitError":
status = "频率限制"
elif error_name in (
"ChatAdminRequiredError",
"ChannelPrivateError",
"UserNotParticipantError"
):
status = "无权限"
else:
status = f"获取失败:{error_name}"
return empty_owner(status)
============================================================
9. 统一拥有者识别入口
============================================================
async def get_chat_owner(entity):
if isinstance(entity, Chat):
return await get_basic_group_owner(entity)
elif isinstance(entity, Channel):
return await get_channel_owner(entity)
return empty_owner(
"不支持的实体类型"
)
============================================================
10. 获取群组和频道列表
============================================================
async def list_and_export_chats():
print("\n>>> 正在获取 Telegram 对话列表...\n")
chat_data_list = []
total_count = 0
async for dialog in client.iter_dialogs():
entity = dialog.entity
# ----------------------------------------------------
# 判断类型
# ----------------------------------------------------
if dialog.is_user:
continue
elif dialog.is_channel:
if getattr(
entity,
"broadcast",
False
):
entity_type = "频道"
elif getattr(
entity,
"megagroup",
False
):
entity_type = "超级群"
else:
entity_type = "频道(未知)"
elif dialog.is_group:
entity_type = "普通群"
else:
continue
total_count += 1
# ----------------------------------------------------
# 获取基本 ID
# ----------------------------------------------------
raw_id = entity.id
bot_api_id = get_bot_api_id(
entity,
entity_type
)
# ----------------------------------------------------
# 名称截取:最多10个字符
# ----------------------------------------------------
short_name = limit_name(
dialog.name,
10
)
# ----------------------------------------------------
# 获取拥有者
# ----------------------------------------------------
print(
f"\n>>> [{total_count}] 正在处理:{short_name}"
)
owner_info = await get_chat_owner(
entity
)
# ----------------------------------------------------
# 获取群组用户名
# ----------------------------------------------------
chat_username = (
getattr(entity, "username", None)
or "无"
)
# ----------------------------------------------------
# 获取成员数
# ----------------------------------------------------
member_count = getattr(
entity,
"participants_count",
None
)
if member_count is None:
member_count = "未知"
# ----------------------------------------------------
# 组装数据
# ----------------------------------------------------
chat_info = {
"类型": entity_type,
"名称": short_name,
"拥有者姓名": owner_info["拥有者姓名"],
"拥有者用户名": owner_info["拥有者用户名"],
"拥有者Telegram_ID": owner_info["拥有者Telegram_ID"],
"拥有者状态": owner_info["拥有者状态"],
"Bot_API_ID": bot_api_id,
"原始_ID": raw_id,
"用户名": chat_username,
"成员数": member_count
}
chat_data_list.append(chat_info)
# ----------------------------------------------------
# 控制台显示
# ----------------------------------------------------
print(
f"类型:{entity_type}"
)
print(
f"名称:{short_name}"
)
print(
f"拥有者:{owner_info['拥有者姓名']}"
)
print(
f"拥有者用户名:{owner_info['拥有者用户名']}"
)
print(
f"拥有者 Telegram ID:{owner_info['拥有者Telegram_ID']}"
)
print(
f"拥有者状态:{owner_info['拥有者状态']}"
)
print("-" * 50)
# ========================================================
# 11. CSV 导出
# ========================================================
if not chat_data_list:
print("\n⚠️ 没有找到任何群组或频道")
return
filename = (
f"telegram_chats_{safe_phone}.csv"
)
file_path = os.path.join(
EXPORT_DIR,
filename
)
# CSV 表头
headers = [
"类型",
"名称",
"拥有者姓名",
"拥有者用户名",
"拥有者Telegram_ID",
"拥有者状态",
"Bot_API_ID",
"原始_ID",
"用户名",
"成员数"
]
try:
with open(
file_path,
mode="w",
encoding="utf-8-sig",
newline=""
) as f:
writer = csv.DictWriter(
f,
fieldnames=headers
)
writer.writeheader()
writer.writerows(
chat_data_list
)
# ----------------------------------------------------
# 导出统计
# ----------------------------------------------------
success_count = sum(
1
for item in chat_data_list
if item["拥有者状态"] == "成功"
)
failed_count = (
len(chat_data_list) - success_count
)
print("\n" + "=" * 55)
print("✅ Telegram 数据导出成功!")
print(
f"群组和频道总数:{len(chat_data_list)}"
)
print(
f"成功获取拥有者:{success_count}"
)
print(
f"未成功识别拥有者:{failed_count}"
)
print(
f"CSV 保存位置:{file_path}"
)
print("=" * 55)
except Exception as e:
print(
f"❌ CSV 导出失败:{e}"
)
============================================================
12. 主程序
============================================================
async def main():
print("\n>>> 正在连接 Telegram...")
try:
# 只在这里启动客户端
await client.start(
phone=PHONE_NUMBER,
password=TWO_STEP_PASSWORD
)
me = await client.get_me()
print("\n✅ Telegram 登录成功!")
print(
f"账号 ID:{me.id}"
)
print(
f"Session 文件:{session_filename}.session"
)
# 执行一次群组和频道导出
await list_and_export_chats()
finally:
# 统一关闭连接
if client.is_connected():
print("\n>>> 正在关闭 Telegram 连接...")
await client.disconnect()
print(">>> Telegram 连接已关闭")
============================================================
13. 程序入口
============================================================
if name == “main“:
try:
client.loop.run_until_complete(
main()
)
except KeyboardInterrupt:
print("\n>>> 用户手动停止程序")
except Exception as e:
print(
f"\n❌ 程序运行异常:{type(e).__name__}: {e}"
)
finally:
if client.is_connected():
client.loop.run_until_complete(
client.disconnect()
)
print("\n>>> 程序执行结束")
发表回复