Search code examples
pythontelethon

Telethon Bot - how to check if a user is subscribed to my channel by user's id


Via my telegram bot I have to check if the user who texting the bot is in my telegram channel or not, I tried:

        user_id = event.message.peer_id.user_id #user's id
        async for i in bot.iter_participants(mychannelID, filter=ChannelParticipantsRecent):
            if user_id != i.id:
                status = False
            else:
                status = True
                break

it worked only on my localhost, but on my Linux server it results an error:

Traceback (most recent call last):
  File "/home/runner/ConcernedHonoredVolume-rcmov/venv/lib/python3.8/site-packages/telethon/client/updates.py", line 467, in _dispatch_update
    await callback(event)
  File "main.py", line 226, in enter
    async for i in bot.iter_participants(MAIN_CHANNEL_ID, filter=ChannelParticipantsRecent):
  File "/home/runner/ConcernedHonoredVolume-rcmov/venv/lib/python3.8/site-packages/telethon/requestiter.py", line 58, in __anext__
    if await self._init(**self.kwargs):
  File "/home/runner/ConcernedHonoredVolume-rcmov/venv/lib/python3.8/site-packages/telethon/client/chats.py", line 111, in _init
    entity = await self.client.get_input_entity(entity)
  File "/home/runner/ConcernedHonoredVolume-rcmov/venv/lib/python3.8/site-packages/telethon/client/users.py", line 466, in get_input_entity
    raise ValueError(
ValueError: Could not find the input entity for PeerUser(user_id=******8242) (PeerUser). Please read https://docs.telethon.dev/en/latest/concepts/entities.html to find out more details.

I have already read entities.html as mentioned, but nothing is working.

Also I tried:

        result = await bot(functions.channels.GetParticipantsRequest(
            channel='username',
            filter=types.ChannelParticipantsRecent(),
            offset=42,
            limit=20,
            hash=0
        ))
        if user_id not in result:
            ...

but I keep getting TypeError: argument of type 'ChannelParticipants' is not iterable


Solution

  • It turns out that I had to re-add my bot to the channel, because the bot lost access hash to the channel when I moved it to another device, since access hash is stored in the .session file and lost after the transfer.