Read telegram group message - python

I am into one telegram group. I wanted to read those messages in my python code. Is there any way to read those messages without adding bot in that group.. for example abc is my user id... And abc is added in xyz group. So wanted to read xyz group message in my python code.

Yes, you can do that via using Telegram API named Telethon.
Telethon Github
Here is an example for setting up processes of the Telethon API. I've written this code to pull all newly posted images from one telegram group. It will give you an idea of how to start to use it.
import sys
import os
from telethon import TelegramClient
from telethon.tl.functions.messages import GetFullChatRequest
from telethon.tl.functions.messages import GetHistoryRequest
from telethon.tl.functions.channels import GetChannelsRequest
from telethon.tl.functions.contacts import ResolveUsernameRequest
from telethon.tl.types import PeerUser, PeerChat, PeerChannel
import re
# These example values won't work. You must get your own api_id and
# api_hash from https://my.telegram.org, under API Development.
api_id = 11111 #number
api_hash = 'x'#string
phone = 'x'
client = TelegramClient('session_name', api_id, api_hash,update_workers=1, spawn_read_thread=False)
client.connect()
Also if you are interested in all of my code on this Telethon integration, you can find it in the following GitHub link;
Telegram Group Bot

Based on this thread : thread
I found this code really works for me. Note that this is a synchronous function, if you want to use multiple channels at the same time you may need to make use of asyncio. Detailed information about that in the next link --> Async Quick-Start
from telethon import TelegramClient, events, sync
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()
For the code above, you have to replace "channel_name" with the name of the group your user is on.
api_id and api_hash are obtained when you setup your API app in Telegram.

Related

Telegram Bot not Connecting to API

I have been using the Telegram API for a while to listen for messages in specific channels on one account. The code below works ok. I tried to use the same code to create another listener for a different account but it doesn't work. I don't get any errors.
When I look on the official Telegram app the listener is not listed under "Devices" which suggests it is not connecting to the API correctly.
Before testing I created a new API ID and hash at my.telegram.org. I've triple checked that the ID, hash and channel ID are all correct.
Can anyone think what the issue might be?
Thanks
from telethon import TelegramClient, events, sync
api_id = 'xxxxxxxxxx'
api_hash = 'xxxxxxxxxxxxxxxxxx'
client = TelegramClient('anon', api_id, api_hash)
chat_id = xxxxxxxx
#client.on(events.NewMessage(chats=chat_id))
async def newMessageListener(event):
new_message = event.message.message
chat_id = event.chat_id
print(chat_id)
print(new_message)
print()
screenshot = "new_image.jpg"
if event.message.photo:
await event.download_media(screenshot)
print("New image received")
#client.on(events.NewMessage(chats=[chat_id]))
chats=[] - here must be a python list,
like chats=[-123456789]

Telethon events.NewMessage() doesn't work

I try to catch new messages in 4 certain channels, but not all channels work.
If I write to account from my second account - script works.
If there is new message in some channel - script doesn't see the event at all.
from telethon.sync import TelegramClient, events
api_id = 11111
api_hash = 'fjnbkdnslkfnbksbs'
client = TelegramClient('test', api_id, api_hash)
client.start()
#client.on(events.NewMessage())
async def handle(event):
print('I see the message')
client.run_until_disconnected()
What is the problem?
Answer was pretty simple. I needed to upgrade telethon using
pip install --upgrade telethon

How to connect to Telegram using telethon without entering your phone (or bot token)?

I have written the following script that listens for new messages on telegram public channels. Problem is that every time the script is used on a new machine telegram is sending a code to the phone number linked to the dev account. You have to enter this code to authorize the new machine. Is there a way to avoid this?
import configparser
from telethon.errors import SessionPasswordNeededError
from telethon import TelegramClient, events, sync
from telethon.tl.functions.messages import (GetHistoryRequest)
from telethon.tl.types import (
PeerChannel
)
api_id = 'xxxxxx'
api_hash = 'xxxxxxxxxxxxxxxxxxxxxxx'
# Here you define the target channel that you want to listen to:
input_channels = ('https://t.me/xxxxxx','https://t.me/xxxx','https://t.me/xxxxxxx')
print(input_channels)
#create a client
client = TelegramClient('anon', api_id, api_hash)
# Listen to messages from target channel
#client.on(events.NewMessage(chats=input_channels))
async def newMessageListener(event):
# Get message text
newMessage = event.message.message
print(newMessage)
with client:
client.run_until_disconnected()

How to export group history using telethon

Somewhere I found a post in which I saw that telegram group history can be exported using following command.
from telethon.sync import TelegramClient
with TelegramClient(name, api_id, api_hash) as client:
for message in client.iter_messages(chat):
print( message.media)
I get some information print to screen. But I need need value of messagemediaphoto caption name etc. How to get inner values.

Want to extract pinned messages from the groups/channels on Telegram i am part of using Telethon

I'm using Telethon API
Want to extract pinned messages of all the channels i am member.
Please guide me with the procedure.
Thank you.
As of Telethon 1.2, the code is a lot simpler:
from telethon import TelegramClient, types, sync
with TelegramClient('name', api_id, api_hash) as client:
message = client.get_messages('TelethonChat', ids=types.InputMessagePinned())
This won't work for private chats, however (e.g. to fetch the pinned message with yourself). For that, as the currently accepted answer hints, we have to fetch the Full object. For the case of the private chat, this is UserFull by using GetFullUserRequest:
chat = 'me'
full = client(functions.users.GetFullUserRequest(chat))
message = client.get_messages(chat, ids=full.pinned_msg_id)
You can use GetFullChannelRequest and GetHistoryRequest methods to extract pinned message from one channel
from telethon import TelegramClient
from telethon.tl.functions.channels import GetFullChannelRequest
from telethon.tl.functions.messages import GetHistoryRequest
from telethon.tl.types import PeerChannel
api_id = XXXXX
api_hash = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
phone_number = '+98XXXXXXXX'
################################################
client = TelegramClient('session_name',
api_id,
api_hash
)
assert client.connect()
if not client.is_user_authorized():
client.send_code_request(phone_number)
me = client.sign_in(phone_number, input('Enter code: '))
channel_entity = client.get_entity(PeerChannel(channel_id))
channel_info = client(GetFullChannelRequest(channel_entity))
pinned_msg_id = channel_info.full_chat.pinned_msg_id
if pinned_msg_id is not None:
posts = client(GetHistoryRequest(
channel_entity,
limit=1,
offset_date=None,
offset_id=pinned_msg_id + 1,
max_id=0,
min_id=0,
add_offset=0,
hash=0
))
print(posts.messages[0].to_dict())
I used Telethon V0.19, but the previous versions are pretty much the same
To get all pinned messages from channel using Telethon 1.19.5 (sync version) and above you can
from telethon.tl.types import InputMessagesFilterPinned
from telethon import TelegramClient, sync # noqa: F401
channel_id = -1009999999999
with TelegramClient("name", api_id, api_hash) as client:
# we need to set limit
# because otherwise it will return only first pinned message
pinned_messages = client.get_messages(
channel_id,
filter=InputMessagesFilterPinned,
limit=1000,
)
for message in pinned_messages:
print(message.message)

Categories

Resources