I want to make authorization by contact in Telegram bot using python and aiogram 3.13.0.…
- User
I want to make authorization by contact in Telegram bot using python and aiogram 3.13.0. How can i do it?
- Assistant
I want to make authorization by contact in Telegram bot using python and aiogram 3.13.0. How can i do it?
To implement authorization by contact in your Telegram bot using Python and aiogram 3.13.0, you can follow these steps:
Request the User's Contact: When a user starts the bot, send them a message with a custom keyboard that includes a button to share their contact. This button will send their phone number to the bot when pressed.
Handle the Shared Contact: Create a handler to process messages that contain contact information. When the bot receives the contact, you can perform your authorization logic, such as checking if the phone number matches a list of authorized users.
Here's a complete example demonstrating how to achieve this:
import logging
from aiogram import Bot, Dispatcher, F
from aiogram.filters import Command
from aiogram.types import (
Message,
ReplyKeyboardMarkup,
KeyboardButton,
ContentType,
KeyboardButtonRequestContact,
)
API_TOKEN = 'YOUR_API_TOKEN_HERE' # Replace with your bot's API token
logging.basicConfig(level=logging.INFO)
# Initialize bot and dispatcher
bot = Bot(token=API_TOKEN)
dp = Dispatcher()
# Handler for the /start command
@dp.message(Command('start'))
async def send_welcome(message: Message):
# Create a button that requests the user's contact
contact_button = KeyboardButton(
text='📲 Share Contact',
request_contact=True # This will prompt the user to share their contact
)
# Create a keyboard with the contact button
keyboard = ReplyKeyboardMarkup(
keyboard=[[contact_button]],
resize_keyboard=True,
one_time_keyboard=True
)
# Send a message with the keyboard
await message.answer(
"Welcome! Please share your contact for authorization:",
reply_markup=keyboard
)
# Handler for incoming contact messages
@dp.message(F.content_type == ContentType.CONTACT)
async def contact_handler(message: Message):
contact = message.contact
# Verify that the contact belongs to the user who sent the message
if contact.user_id == message.from_user.id:
phone_number = contact.phone_number
# Implement your authorization logic here
# For example, check if the phone number is in your database
# For this example, we'll just thank the user
await message.answer(f"Thank you! Your phone number is {phone_number}.")
# Optionally, remove the custom keyboard
await message.answer("You are now authorized.", reply_markup=ReplyKeyboardMarkup())
else:
# The contact shared does not belong to the sender
await message.answer("Please share your own contact for authorization.")
if __name__ == '__main__':
dp.run_polling(bot)
Explanation:
Import Statements: We import necessary classes and functions from aiogram.
Bot Initialization: We create an instance of the Bot and Dispatcher.
Start Command Handler (/start):
KeyboardButton with request_contact=True. This special button, when pressed, will prompt the user to share their contact information.ReplyKeyboardMarkup and send it to the user.one_time_keyboard=True, so it will disappear after the user presses a button.Contact Message Handler:
content_type is ContentType.CONTACT.user_id matches the from_user.id to ensure the user is sharing their own contact.Running the Bot:
dp.run_polling(bot).Notes:
Security Considerations: Always ensure that you handle user data securely and comply with relevant data protection regulations.
Authorization Logic: Replace the placeholder comments with your actual authorization mechanism. For example, you might check if the phone number exists in a database of authorized users.
Dependencies: Make sure you've installed aiogram version 3.13.0 or compatible. You can install it using:
pip install aiogram --upgrade
Bot Token: Replace 'YOUR_API_TOKEN_HERE' with the token provided by BotFather when you created your bot.
Additional Customization:
Handling Authorization Failure: If the phone number isn't authorized, you can send an appropriate message back to the user.
Logging: The logging module is configured to log info level messages. Adjust the logging level and format as needed for debugging or monitoring.
Removing the Keyboard: After authorization, you might want to remove the custom keyboard. You can send a new message with an empty ReplyKeyboardMarkup.
Example Authorization Logic:
Here's how you might implement a simple authorization check:
AUTHORIZED_NUMBERS = ["+1234567890", "+1987654321"] # Replace with your authorized numbers
@dp.message(F.content_type == ContentType.CONTACT)
async def contact_handler(message: Message):
contact = message.contact
if contact.user_id == message.from_user.id:
phone_number = contact.phone_number
if phone_number in AUTHORIZED_NUMBERS:
await message.answer("Authorization successful!")
# Proceed with authorized actions
else:
await message.answer("Sorry, your number is not authorized to use this bot.")
else:
await message.answer("Please share your own contact for authorization.")
Conclusion:
By requesting the user's contact and handling it appropriately, you can implement an authorization step in your Telegram bot using aiogram. This method provides a straightforward way to verify users based on their phone numbers.
References:
Not yet included in a published release.