简体   繁体   中英

Get all recent users or participants from a telegram channel with telegram API and telethon

I'm using peewee to store participants in a telegram channel. How do I get only new participants, ie those who have not been previously added?

Maybe we can offset by time? or offset by those who are already in the database?

Not so sure how to perform offsets in GetParticipantsRequest

from telethon import TelegramClient
from telethon.tl.functions.channels import GetParticipantsRequest
from telethon.tl.types import ChannelParticipantsSearch
from time import sleep
from schema import channel_users as cudb
from datetime import datetime
import json
from dotenv import load_dotenv
load_dotenv()
import os

api_id = os.getenv('API_ID')
api_hash = os.getenv('API_HASH')
PHONE = os.getenv('PHONE')
USERNAME = os.getenv('USERNAME')


# Remember to use your own values from my.telegram.org!

client = TelegramClient('anon', api_id, api_hash)

async def main():
    # Getting information about yourself
    me = await client.get_me()
    my_channel = 'https://t.me/some_channel_url'
    offset = 0
    limit = 100
    all_participants = []

    while True:
        participants = await client(GetParticipantsRequest(
            my_channel, ChannelParticipantsSearch(''), offset, limit,
            hash=0
        ))
        if not participants.users:
            break
        all_participants.extend(participants.users)
        offset += len(participants.users)

    all_user_details = []
    for participant in all_participants:

        now = datetime.now()
        date_added = now.strftime("%d/%m/%Y, %H:%M:%S")
        channel_user_id, created = cudb.get_or_create(
            id = participant.id,
            defaults = {'first_name' : participant.first_name,
                        'last_name'  : participant.last_name,
                        'username'   : participant.username,
                        'phone'      : participant.phone,
                        'is_bot'     : participant.bot,
                        'date_added' : date_added}
        )

        if (created):
            print(f'successfully created channel_usersID = {channel_user_id}')
        else:
            print(f'did not create anything, user information found in channel_usersID {channel_user_id}')

with client:
    client.loop.run_until_complete(main())

ok I've sort of solved it with this . Problem is - Now trying to figure out how to update every time new user joins

while True:
    participants = await client(GetParticipantsRequest(
        my_channel, ChannelParticipantsSearch(''), offset, limit,
        hash=0
    ))
    number_of_participants = len(participants.users)
    print(f'{len(participants.users)} length')
    max_cudb = cudb.select(fn.MAX(cudb.channel_usersID)).scalar()
    if max_cudb == len(participants.users):
        print('id is same as number of participants in group, hence nothing new')
        break
    if not participants.users:
        break

    # calculate the difference between number of participants and last user added to DB
    number_to_add = number_of_participants - max_cudb

    # adds missing users chronologically from oldest to most recent
    print(f'number_to_add = {number_to_add}')
    for i in range(number_to_add-1,-1,-1):
        print(f'i =  {i}')
        participant = participants.users[i]
        now = datetime.now()
        date_added = now.strftime("%d/%m/%Y, %H:%M:%S")
        channel_user_id, created = cudb.get_or_create(
            id = participant.id,
            defaults = {'first_name' : participant.first_name,
                        'last_name'  : participant.last_name,
                        'username'   : participant.username,
                        'phone'      : participant.phone,
                        'is_bot'     : participant.bot,
                        'date_added' : date_added}
        )

        # Prints status of DB addition
        if (created):
            print(f'successfully created channel_usersID = {channel_user_id}')
        else:
            print(f'did not create anything, user information found in channel_usersID {channel_user_id}')

https://docs.telethon.dev/en/stable/quick-references/events-reference.html?highlight=chataction#chataction here you are the docs for chataction, exactly what you need just make sure to filter the event.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM