How to get a message from Telegram groups by API?
Question:
I was looking for some way to listen and catch new messages provided by telegram groups.
I have not found libraries or API in order to do this in Python.
Someone having any suggestion?
Answers:
There are two ways to achieve your goal:
Method 1:
My suggested library for python: python-telegram-bot
- Create a bot.
- Add the bot to the desired group as administrator.
- Listen to messages as you normally listen in bots.
Method 2:
My suggested library for python: Telethon
- Join the desired group as a user (not a bot).
- Create a simple client that listens to new messages.
Using Telethon
Replace channel_name
with your telegram channel.
from telethon import TelegramClient, events, sync
# Remember to use your own values from my.telegram.org!
api_id = ...
api_hash = '...'
client = TelegramClient('anon', api_id, api_hash)
@client.on(events.NewMessage(chats='channel_name'))
async def my_event_handler(event):
print(event.raw_text)
client.start()
client.run_until_disconnected()
I was looking for some way to listen and catch new messages provided by telegram groups.
I have not found libraries or API in order to do this in Python.
Someone having any suggestion?
There are two ways to achieve your goal:
Method 1:
My suggested library for python: python-telegram-bot
- Create a bot.
- Add the bot to the desired group as administrator.
- Listen to messages as you normally listen in bots.
Method 2:
My suggested library for python: Telethon
- Join the desired group as a user (not a bot).
- Create a simple client that listens to new messages.
Using Telethon
Replace channel_name
with your telegram channel.
from telethon import TelegramClient, events, sync
# Remember to use your own values from my.telegram.org!
api_id = ...
api_hash = '...'
client = TelegramClient('anon', api_id, api_hash)
@client.on(events.NewMessage(chats='channel_name'))
async def my_event_handler(event):
print(event.raw_text)
client.start()
client.run_until_disconnected()