更新:我用一个非常简单的 PHP 应用程序创建了一个 GitHub 存储库来说明下面解释的概念:
https://github.com/pevdh/telegram-auth-example
是否使用 webhook无关紧要。
“深度链接”解释说:
- 让用户使用实际的用户名密码身份验证登录实际网站。
- 生成唯一的哈希码(我们将其称为 unique_code)
- 将 unique_code->username 保存到数据库或键值存储。
- 向用户显示 URL https://telegram.me/YOURBOTNAME?start=unique_code
- 现在,只要用户在 Telegram 中打开此 URL 并按下“开始”,您的机器人就会收到一条包含“/start unique_code”的文本消息,其中 unique_code 当然会被实际的哈希码替换。
- 让机器人通过在数据库或键值存储中查询 unique_code 来检索用户名。
- 将 chat_id->username 保存到数据库或键值存储。
现在,当您的机器人收到另一条消息时,它可以查询数据库中的 message.chat.id 以检查该消息是否来自该特定用户。(并相应地处理)
一些代码(使用pyTelegramBotAPI):
import telebot
import time
bot = telebot.TeleBot('TOKEN')
def extract_unique_code(text):
# Extracts the unique_code from the sent /start command.
return text.split()[1] if len(text.split()) > 1 else None
def in_storage(unique_code):
# Should check if a unique code exists in storage
return True
def get_username_from_storage(unique_code):
# Does a query to the storage, retrieving the associated username
# Should be replaced by a real database-lookup.
return "ABC" if in_storage(unique_code) else None
def save_chat_id(chat_id, username):
# Save the chat_id->username to storage
# Should be replaced by a real database query.
pass
@bot.message_handler(commands=['start'])
def send_welcome(message):
unique_code = extract_unique_code(message.text)
if unique_code: # if the '/start' command contains a unique_code
username = get_username_from_storage(unique_code)
if username: # if the username exists in our database
save_chat_id(message.chat.id, username)
reply = "Hello {0}, how are you?".format(username)
else:
reply = "I have no clue who you are..."
else:
reply = "Please visit me via a provided URL from the website."
bot.reply_to(message, reply)
bot.polling()
while True:
time.sleep(0)
注意:在 Telegram 客户端中,unique_code 不会显示为“/start unique_code”,只会显示为“/start”,但您的机器人仍会收到“/start unique_code”。