如何通过ID查找Telegram用户?PyTelegramBotApi分享联系人问题
解决Telegram机器人分享无用户名联系人的问题
需求:通过Telegram机器人分享好友联系人,但好友没有Telegram用户名,仅知晓其用户ID。使用PyTelegramBotApi编写代码时,
tg://user?id=<1427022865>的URL写法有误,需要正确用法或其他可行方案。
原代码:
from telebot import TeleBot, types bot = TeleBot(token=TOKEN) @bot.message_handler(commands=['start']) def start_bot(message): text = "My friend contact" markup = types.InlineKeyboardMarkup() markup.add(types.InlineKeyboardButton(text='Contact', url="tg://user?id=<1427022865>")) bot.send_message(message.chat.id, text=text, reply_markup=markup) bot.polling()
方案一:修正tg://链接格式
你的URL错误在于多余的尖括号<>,正确格式不需要包裹用户ID,直接写成tg://user?id=1427022865即可。点击该链接后,用户会跳转到对应ID的联系人对话框(前提是双方有过互动或已在联系人列表中,否则会提示找不到用户)。
修正后的代码:
from telebot import TeleBot, types TOKEN = "你的机器人令牌" bot = TeleBot(token=TOKEN) @bot.message_handler(commands=['start']) def start_bot(message): text = "My friend contact" markup = types.InlineKeyboardMarkup() # 移除ID两侧的尖括号 markup.add(types.InlineKeyboardButton(text='Contact', url="tg://user?id=1427022865")) bot.send_message(message.chat.id, text=text, reply_markup=markup) bot.polling()
方案二:直接发送联系人卡片(更友好)
如果用户尚未添加该联系人,tg://链接可能无法直接定位对方。此时可以用send_contact方法发送联系人卡片,用户点击卡片即可直接添加好友,无需额外操作。
示例代码:
from telebot import TeleBot, types TOKEN = "你的机器人令牌" bot = TeleBot(token=TOKEN) @bot.message_handler(commands=['start']) def start_bot(message): # 发送联系人卡片:聊天ID、用户ID、联系人姓名(可自定义) bot.send_contact( chat_id=message.chat.id, user_id=1427022865, first_name="你的好友姓名" ) bot.polling()
内容的提问来源于stack exchange,提问作者Ulug'bek Shermetov
相关产品推荐
相关产品推荐

