You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何基于Telethon实现点击电话号码显示Telegram ID?新手求指导

实现点击电话号码展示Telegram ID的Telethon方案

实现思路

  • 先完成Telethon客户端的初始化与登录授权,确保能正常调用Telegram API
  • 用轻量UI库(如tkinter)构建界面,展示目标电话号码列表
  • 给列表中的电话号码绑定点击事件,触发ID查询逻辑
  • 通过Telethon的get_entity()方法根据电话号码获取用户实体,提取ID后在界面展示

技术建议

  • 优先选tkinter作为UI框架,无额外复杂依赖,适合新手快速实现原型
  • 从Telegram官方开发者平台获取API_ID和API_HASH,这是调用Telegram API的必备凭证
  • 电话号码必须带国家码(如+86138xxxxxxx),否则get_entity()无法正确识别目标账号
  • Telethon方法均为异步,结合async-tkinter-loop库可简化UI线程与异步任务的交互,避免界面卡顿
  • 首次运行客户端会要求输入手机号和验证码,登录状态会保存在session文件中,后续启动无需重复验证

完整可运行源码

先安装依赖:

pip install telethon async-tkinter-loop
import asyncio
import tkinter as tk
from tkinter import messagebox
from telethon import TelegramClient
from telethon.errors import UsernameNotOccupiedError
from async_tkinter_loop import async_handler

# 替换为你从Telegram开发者平台获取的API信息
API_ID = 123456
API_HASH = 'your_api_hash_here'
SESSION_NAME = 'phone_id_lookup'

# 初始化Telethon客户端
client = TelegramClient(SESSION_NAME, API_ID, API_HASH)

async def get_telegram_id(phone_number):
    """通过电话号码查询对应的Telegram ID"""
    try:
        # 调用API获取用户实体
        entity = await client.get_entity(phone_number)
        return entity.id
    except UsernameNotOccupiedError:
        # 号码未注册Telegram的情况
        return None
    except Exception as e:
        print(f"查询过程出错: {str(e)}")
        return None

class PhoneIDLookupApp:
    def __init__(self, root):
        self.root = root
        self.root.title("Telegram 手机号查ID")
        
        # 电话号码列表展示区
        self.list_label = tk.Label(root, text="双击列表中的号码查询ID:")
        self.list_label.pack(pady=5)
        
        self.phone_listbox = tk.Listbox(root, width=35, height=8)
        self.phone_listbox.pack(pady=10)
        # 添加示例号码(可根据需求替换或动态加载)
        self.phone_listbox.insert(tk.END, "+8613800000000")
        self.phone_listbox.insert(tk.END, "+12345678901")
        self.phone_listbox.insert(tk.END, "+447900000000")
        
        # 绑定双击事件
        self.phone_listbox.bind('<Double-1>', self.on_phone_double_click)
        
        # 结果展示标签
        self.result_label = tk.Label(root, text="", fg="darkgreen", font=('Arial', 10, 'bold'))
        self.result_label.pack(pady=5)

    @async_handler
    async def on_phone_double_click(self, event):
        """处理电话号码双击事件"""
        # 获取选中的电话号码
        selected_indices = self.phone_listbox.curselection()
        if not selected_indices:
            return
        target_phone = self.phone_listbox.get(selected_indices[0])
        
        # 确保客户端已连接
        if not client.is_connected():
            await client.start()
        
        # 查询ID
        user_id = await get_telegram_id(target_phone)
        if user_id:
            result_text = f"号码 {target_phone} 的ID: {user_id}"
            self.result_label.config(text=result_text)
            messagebox.showinfo("查询成功", result_text)
        else:
            self.result_label.config(text=f"未找到号码 {target_phone} 对应的账号")
            messagebox.showwarning("查询失败", f"号码 {target_phone} 未注册Telegram或查询出错")

if __name__ == "__main__":
    # 初始化事件循环并完成客户端登录
    loop = asyncio.get_event_loop()
    loop.run_until_complete(client.start())
    
    # 启动UI
    root = tk.Tk()
    app = PhoneIDLookupApp(root)
    root.mainloop()
    
    # 退出时关闭客户端连接
    loop.run_until_complete(client.disconnect())

界面示例截图

  • 主界面:主界面
  • 查询结果弹窗:查询结果

内容的提问来源于stack exchange,提问作者Abror Aliyev

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.14 16:43:12