passportbot.py

  1#!/usr/bin/env python
  2# pylint: disable=unused-argument, wrong-import-position
  3# This program is dedicated to the public domain under the CC0 license.
  4
  5"""
  6Simple Bot to print/download all incoming passport data
  7
  8See https://telegram.org/blog/passport for info about what telegram passport is.
  9
 10See https://github.com/python-telegram-bot/python-telegram-bot/wiki/Telegram-Passport
 11 for how to use Telegram Passport properly with python-telegram-bot.
 12
 13"""
 14import logging
 15from pathlib import Path
 16
 17from telegram import __version__ as TG_VER
 18
 19try:
 20    from telegram import __version_info__
 21except ImportError:
 22    __version_info__ = (0, 0, 0, 0, 0)  # type: ignore[assignment]
 23
 24if __version_info__ < (20, 0, 0, "alpha", 5):
 25    raise RuntimeError(
 26        f"This example is not compatible with your current PTB version {TG_VER}. To view the "
 27        f"{TG_VER} version of this example, "
 28        f"visit https://docs.python-telegram-bot.org/en/v{TG_VER}/examples.html"
 29    )
 30from telegram import Update
 31from telegram.ext import Application, ContextTypes, MessageHandler, filters
 32
 33# Enable logging
 34
 35logging.basicConfig(
 36    format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.INFO
 37)
 38
 39logger = logging.getLogger(__name__)
 40
 41
 42async def msg(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
 43    """Downloads and prints the received passport data."""
 44    # Retrieve passport data
 45    passport_data = update.message.passport_data
 46    # If our nonce doesn't match what we think, this Update did not originate from us
 47    # Ideally you would randomize the nonce on the server
 48    if passport_data.decrypted_credentials.nonce != "thisisatest":
 49        return
 50
 51    # Print the decrypted credential data
 52    # For all elements
 53    # Print their decrypted data
 54    # Files will be downloaded to current directory
 55    for data in passport_data.decrypted_data:  # This is where the data gets decrypted
 56        if data.type == "phone_number":
 57            print("Phone: ", data.phone_number)
 58        elif data.type == "email":
 59            print("Email: ", data.email)
 60        if data.type in (
 61            "personal_details",
 62            "passport",
 63            "driver_license",
 64            "identity_card",
 65            "internal_passport",
 66            "address",
 67        ):
 68            print(data.type, data.data)
 69        if data.type in (
 70            "utility_bill",
 71            "bank_statement",
 72            "rental_agreement",
 73            "passport_registration",
 74            "temporary_registration",
 75        ):
 76            print(data.type, len(data.files), "files")
 77            for file in data.files:
 78                actual_file = await file.get_file()
 79                print(actual_file)
 80                await actual_file.download_to_drive()
 81        if (
 82            data.type in ("passport", "driver_license", "identity_card", "internal_passport")
 83            and data.front_side
 84        ):
 85            front_file = await data.front_side.get_file()
 86            print(data.type, front_file)
 87            await front_file.download_to_drive()
 88        if data.type in ("driver_license" and "identity_card") and data.reverse_side:
 89            reverse_file = await data.reverse_side.get_file()
 90            print(data.type, reverse_file)
 91            await reverse_file.download_to_drive()
 92        if (
 93            data.type in ("passport", "driver_license", "identity_card", "internal_passport")
 94            and data.selfie
 95        ):
 96            selfie_file = await data.selfie.get_file()
 97            print(data.type, selfie_file)
 98            await selfie_file.download_to_drive()
 99        if data.translation and data.type in (
100            "passport",
101            "driver_license",
102            "identity_card",
103            "internal_passport",
104            "utility_bill",
105            "bank_statement",
106            "rental_agreement",
107            "passport_registration",
108            "temporary_registration",
109        ):
110            print(data.type, len(data.translation), "translation")
111            for file in data.translation:
112                actual_file = await file.get_file()
113                print(actual_file)
114                await actual_file.download_to_drive()
115
116
117def main() -> None:
118    """Start the bot."""
119    # Create the Application and pass it your token and private key
120    private_key = Path("private.key")
121    application = (
122        Application.builder().token("TOKEN").private_key(private_key.read_bytes()).build()
123    )
124
125    # On messages that include passport data call msg
126    application.add_handler(MessageHandler(filters.PASSPORT_DATA, msg))
127
128    # Run the bot until the user presses Ctrl-C
129    application.run_polling()
130
131
132if __name__ == "__main__":
133    main()

HTML Page

 1<!DOCTYPE html>
 2<html lang="en">
 3<head>
 4    <title>Telegram passport test!</title>
 5    <meta charset="utf-8">
 6    <meta content="IE=edge" http-equiv="X-UA-Compatible">
 7    <meta content="width=device-width, initial-scale=1" name="viewport">
 8</head>
 9<body>
10<h1>Telegram passport test</h1>
11
12<div id="telegram_passport_auth"></div>
13</body>
14
15<!--- Needs file from https://github.com/TelegramMessenger/TGPassportJsSDK downloaded --->
16<script src="telegram-passport.js"></script>
17<script>
18    "use strict";
19
20    Telegram.Passport.createAuthButton('telegram_passport_auth', {
21        bot_id: 1234567890, // YOUR BOT ID
22        scope: {
23            data: [{
24                type: 'id_document',
25                selfie: true
26            }, 'address_document', 'phone_number', 'email'], v: 1
27        }, // WHAT DATA YOU WANT TO RECEIVE
28        public_key: '-----BEGIN PUBLIC KEY-----\n', // YOUR PUBLIC KEY
29        nonce: 'thisisatest', // YOUR BOT WILL RECEIVE THIS DATA WITH THE REQUEST
30        callback_url: 'https://example.org' // TELEGRAM WILL SEND YOUR USER BACK TO THIS URL
31    });
32
33</script>
34</html>