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

I’m working on a Telegram bot and want to implement a function where users can find someone’s user ID by providing their username. For example, if someone types a command with another person’s username, the bot should return that person’s numeric user ID.

I’ve been looking through the Telegram Bot API documentation but I’m not sure if there’s a direct method to convert usernames to user IDs. Has anyone successfully implemented this feature? What’s the best approach to achieve this functionality?

Any help or code examples would be greatly appreciated!

Unfortunately, there’s no direct API method to convert usernames to user IDs in Telegram Bot API. The bot can only access user IDs when users directly interact with it through messages, commands, or callback queries. I faced this same challenge when building a user management bot. The workaround I implemented was maintaining a local database that stores username-to-user-ID mappings whenever users interact with the bot. Each time someone sends a message, I cache their user ID along with their current username. Another approach is using the getChatMember method if you’re working within a group context, but this requires knowing the chat ID and only works for group members. For general username lookups, you’ll need to rely on your own data collection from user interactions with your bot.

honestly this is one of the most frustating limitations of telegram’s api tbh. you basicaly cant do it unless the user has already messaged your bot at some point. i ended up creating a simple /register command where ppl can voluntarily add themselves to my bots database - not ideal but it works for most usecases if you explain why its needed

This limitation caught me off guard when I first started developing Telegram bots. The API doesn’t provide a direct username-to-ID conversion method, which makes sense from a privacy perspective. What worked for me was implementing a two-tier approach: first, I used inline queries to let users search for people who had previously interacted with my bot, and second, I created a voluntary registration system where users could opt-in to be discoverable by username. The key insight I learned is that Telegram’s architecture prioritizes user privacy, so you can only work with data from users who have willingly engaged with your bot. If you’re building for a specific community or group, consider asking users to register themselves with a simple command when they first join. This creates a legitimate database of willing participants while respecting Telegram’s privacy model.