How to search for groups and channel in telegram using telethon?

↘锁芯ラ 提交于 2020-08-26 13:37:55

问题


I use telethon for sending messages to telegram using python script.
I did not find anything in telethon to search for groups and channels I like used to search on telegram app. Please see iamge. How can I get such list using telethon?


回答1:


Create file with your secrets: config.ini

[Telegram]
# no need for quotes

# you can get telegram development credentials in telegram API Development Tools
api_id = 1234
api_hash = 1234

# use full phone number including + and country code
phone = +4411111111111
username = session_user

One solution is this, do_search.py

#!/usr/bin/env python
# -*- coding: utf-8 -*-

# Tested with Telethon version 1.14.0

import configparser
from telethon import TelegramClient
from telethon.errors import SessionPasswordNeededError
from telethon.sync import TelegramClient
from telethon import functions, types

# Reading Configs
config = configparser.ConfigParser()
config.read("config.ini")

# These example values won't work. You must get your own api_id and
# api_hash from https://my.telegram.org, under API Development.
# (1) Use your own values here
api_id = config['Telegram']['api_id']
api_hash = config['Telegram']['api_hash']

# (2) Create the client and connect
phone = config['Telegram']['phone']
username = config['Telegram']['username']
client = TelegramClient(username, api_id, api_hash)

async def main():
    await client.start()
    # Ensure you're authorized
    if not await client.is_user_authorized():
        await client.send_code_request(phone)
        try:
            await client.sign_in(phone, input('Enter the code: '))
        except SessionPasswordNeededError:
            await client.sign_in(password=input('Password: '))

    search = 'linux'
    result = await client(functions.contacts.SearchRequest(
        q=search,
        limit=100
    ))
    print(result.stringify())

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

And don't forget to always thank @lonami for creating this awesome library Telethon :)



来源:https://stackoverflow.com/questions/62016386/how-to-search-for-groups-and-channel-in-telegram-using-telethon

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!