Aamir Siddiqui
Aamir Siddiqui

Reputation: 131

telethon : How to search a keyword globally from telegram messages in python?

So basically I want to search messages by a keyword irrespective of a member of that group/channel or not. For example, in some group/channel of which I am not a member, there is a message-

"Hello, this is some information about banana"

and let's say I search keyword 'banana' then I should get the whole above message.

I wrote a script but it only searches the name of groups instead of messages.

from telethon import functions
import os, sys


try:
    api_id = api_id
    api_hash = api_hash
    phone = phone
    client = TelegramClient(phone, api_id, api_hash)
except KeyError:
    os.system("clear")

    print(re + "[!] run python3 setup.py first !!\n")
    sys.exit(1)

client.connect()
if not client.is_user_authorized():
    client.send_code_request(phone)
    os.system("clear")

    client.sign_in(phone, input(gr + "[+] Enter the code: " + re))

os.system("clear")

last_date = None
chunk_size = 200
results = client(
    functions.contacts.SearchRequest(q="banana", limit=100)
)
print(results.stringify())

Upvotes: 0

Views: 3235

Answers (1)

Lonami
Lonami

Reputation: 7141

You can use client.iter_messages with the chat set as None to perform a global search:

async for message in client.iter_messages(None, search='banana'):
    ...

Underneath it's using SearchGlobalRequest .

Upvotes: 1

Related Questions