Search code examples
pythontelegramtelethon

i want to send an auto reply to a new chat with whom i havent had a conversation earlier on Telegram


I'm new to Python and Telethon.

I've gone through the documentation of Telethon module. I would like to send auto reply to a new person if they send me a message on Telegram private message.

I've found one (in this gist) which sends an autoreply to every incoming private chat. but i want to send a reply to new people only.

please guide

i want to check if user is present in the df below and send a reply accordingly.

code to get list of dialog id's is as below:

import time
from telethon import TelegramClient
from telethon import events
import pandas as pd

api_id = 123456
api_hash = 'enterownapihash'

# fill in your own details here
phone = '+111111111'
session_file = 'username'  # use your username if unsure
password = 'passwords'  # if you have two-step verification enabled

client = TelegramClient(session_file, api_id, api_hash, sequential_updates=True)
xyz = pd.DataFrame()
z = pd.DataFrame()
client.connect()
client.start()

for dialog in client.iter_dialogs():
    x = dialog.id
    y = dialog.title
    #print('{:>14}: {}'.format(dialog.id, dialog.title))
    xyz['dialog id'] = [x]
    xyz['username'] = [y]
    z = pd.concat([z,xyz],ignore_index= True)
print(xyz)
print(z)

EDIT: below is the code i've tried which hasnt worked.

import time
from telethon import TelegramClient
from telethon import events
import pandas as pd

api_id = 123456
api_hash = 'enterownapihash'

# fill in your own details here
phone = '+111111111'
session_file = 'username'  # use your username if unsure
password = 'passwords'  # if you have two-step verification enabled

# content of the automatic reply
message = "Hello!"

client = TelegramClient(session_file, api_id, api_hash, sequential_updates=True)
xyz = pd.DataFrame()
z = pd.DataFrame()
#client.connect()
#client.start()

for dialog in client.iter_dialogs():
    x = dialog.id
    y = dialog.title
    print('{:>14}: {}'.format(dialog.id, dialog.title))
    xyz['x'] = [x]
    xyz['y'] = [y]
    z = pd.concat([z,xyz],ignore_index= True)

if __name__ == '__main__':

    @client.on(events.NewMessage(incoming=True))
    async def handle_new_message(event):
        if event.is_private:  # only auto-reply to private chats
            from_ = await event.client.get_entity(event.from_id)  # this lookup will be cached by telethon
            if event.client.get_entity != z['x'].values:
                if not from_.bot:  # don't auto-reply to bots
                    print(time.asctime(), '-', event.message)  # optionally log time and message
                    time.sleep(1)  # pause for 1 second to rate-limit automatic replies
                    await event.respond(message)


    client.start(phone, password)
    client.run_until_disconnected()

Solution

  • One way to do this is to fetch all the IDs present in your dialogs on start up. When a new message arrives, if their ID is not there, you know it's a new person (the code assumes you run it inside an async def):

    async def setup():
        users = set()
        async for dialog in client.iter_dialogs():
            if dialog.is_user:
                users.add(dialog.id)
    
    # later, on a handler
    
    async def handler(event):
        if event.is_private and event.sender_id not in users:
            # new user
    

    Another option is to use messages.GetPeerSettingsRequest, which will have result.report_spam as True when it's a new chat. Ideally, you would also cache this:

    user_is_new = {}
    
    async def handler(event):
        if event.is_private:
            if event.sender_id not in user_is_new:
                res = client(functions.messages.GetPeerSettingsRequest(event.sender_id))
                # if you can report them for spam it's a new user
                user_is_new[event.sender_id] = res.report_spam
    
            if user_is_new[event.sender_id]:
                # new user