How to retrieve user ID from username in Telegram Bot API?

I’m working on a Telegram bot and need to implement a function that can find a user’s ID when I only have their username. Basically, I want users to be able to send a command with someone’s username and get back that person’s user ID number.

Is there a way to do this with the Telegram Bot API? I’ve been looking through the documentation but can’t figure out if this kind of username-to-ID lookup is supported. Has anyone managed to build this feature before?

Any help or suggestions would be really appreciated!

The Bot API doesn’t let you do this directly - caught me off guard too when I first tried. Here’s what actually works: have someone forward a message from the target user to your bot. You can grab both username and user ID from that forwarded message. Not pretty, but it’s reliable. I’ve also had luck with a simple registration system where users just share their info through the bot. Or if you’re both in the same group chat, try the search function - though your bot needs admin rights for that to work.

yeah, this limitation sucks but I’ve found a workaround. if both users are in the same group, use getChatAdministrators or getChatMember to grab their data. another trick - ask users to mention (@username) whoever they’re looking for. your bot can pull the user_id from mention entities as long as that person messaged recently.

Unfortunately, Telegram’s Bot API doesn’t allow for direct conversion of usernames to user IDs due to privacy concerns. The best approach is to maintain your own database that associates usernames with user IDs as users interact with your bot. Whenever a user sends a message or uses a command, you can save their user ID alongside their username. It’s important to note that usernames can change, so regularly updating your records is essential. Additionally, if you’re operating within a group, you can utilize the getChatMember method, provided the user is part of that specific chat.