You can listen to a public or private channel, group, and even a personal chat using this method without any bots or administrator permission.
- Python >= 3.7
- datetime
- pandas==0.3.1
- pygsheets==2.0.6
- Telethon @ https://github.com/LonamiWebs/Telethon/archive/v1.zip
- Visit https://my.telegram.org/ and login to your Telegram account with the phone number of the developer account to use.
- Click
API development tools
to get theApp api_id
andApp api_hash
. - Get channel or chat ID via different methods:
- Copy the invite link (if it exists, public channel normally).
- Open
https://web.telegram.org/
and select your chat room, the website might likehttps://web.telegram.org/z/#-123456789
, copy the number after/#
(include the negative symbol). In this case, it is-123456789
. - Run the code (ref: https://docs.telethon.dev/en/stable/basic/quick-start.html), it will print all the dialogs/conversations that you are part of.
from telethon import TelegramClient
api_id = INT_TELEGRAM_API_ID
api_hash = 'STR_TELEGRAM_API_HASH'
client = TelegramClient('session', api_id, api_hash)
async def main():
async for dialog in client.iter_dialogs():
print(dialog.name, 'has ID', dialog.id)
with client:
client.loop.run_until_complete(main())
- Remember that your API hash is secret and Telegram won’t let you revoke it. Don’t post it anywhere!
- Visit Google API Console and create a new project.
- In this new project, click
APIs & Services > +ENABLE APIS AND SERVICES
.
- Find
Google Sheets API
and enable it. - Back to
APIs & Services
, select Credentials in the sidebar. - Click
+ CREATE CREDENTIALS > Service Account
and follow the instructions. - Download credential JSON file and name it
credentials.json
. - Back to
Credentials
, you'll see a new Service Accounts below. Copy the Email (...@...iam.gserviceaccount.com
).
- Create a new Google Sheets.
- Click the
Share
orSend
button in the upper right corner. - Invite the Service Account Email we created above as an editor.
- Name the Sheet. For example,
chats
. - The first row (column name) is
Time | Username | User Id | Message Length | Message
. You can create the column data filters later.
- Run it on a 24/7 machine or VPS.
- To listen the chat, run
listen.py
- To crawl the history chat, run
crawl-history.py
. Check here to find more detail ofiter_messages()
function.