skip to Main Content

How can I find out the user id by his username? I use the aiogram library and I have not found information on the Internet how to do this. Is there any method?

import logging

from configparser import ConfigParser
from aiogram import Bot, Dispatcher, executor, types


logging.basicConfig(level=logging.INFO)

config = ConfigParser()
config.read('config.ini')

TOKEN = config.get('BOT', 'Token')

bot = Bot(token=TOKEN)
dp = Dispatcher(bot)


@dp.message_handler(commands=['start'])
async def start(message: types.Message):
    text = config.get('BOT_TEXT', 'Start')
    await bot.send_message(message.chat.id, text)


@dp.message_handler()
async def forward(message: types.Message):
    await bot.send_message(message.forward_from.id, 'Kuku')


if __name__ == '__main__':
    executor.start_polling(dp, skip_updates=True)

2

Answers


  1. from aiogram.dispatcher import FSMContext
    from aiogram.dispatcher.filters.state import State, StatesGroup
    
    username = ''
    answer = 0
    
    class Name(StatesGroup):
    get_message = State()
    
    @dp.message_handler(commands=['start'], state=get_message)
    async def get_message(self: types.Message, state: FSMContext):
        global username
        global answer
        answer = self.from_id
        await state.finish()
        ...
        await bot.send_message(self.from_user.id, f'Your id: {answer}')
    

    You will receive the from_id
    Don’t forget to install fsm

    Login or Signup to reply.
  2. You could create a ReplyKeyboardMarkup with a KeyboardButtonRequestChat
    After that just send the contact over to your bot using the ReplyKeyboardMarkup you’ve created, handle the shared chat & fetch the user_id.

    As far as I remember it should be something like this:

    from aiogram.types import ContentTypes, Message
    
    @dp.message_handler(content_types=[ContentType.CHAT_SHARED])
    async def fetch_user_id(message: Message):
         user_id = message.chat_shared.chat_id
         return user_id
    

    ⚠️ Caution, I didn’t test the code, but as far as I remember, it should work like this in aiogram 2.*

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search