Download all files from a Telegram channel - python

I do know how to get all text messages using get_message_history method of Telethon, but I'm wondering if there is a way to download all files sent in a Telegram channel.
msgs = client.get_message_history('a_channel', limit=10000)
for msg in msgs:
print(msg)

I hope this code will help you. I used Telethon V0.19, but the previous versions are pretty much the same.
also get_message_history is deprecated, use get_messages instead.
from telethon import TelegramClient
api_id = XXXXXXX
api_hash = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXX'
phone_number = '+98XXXXXXXXX'
################################################
channel_username = 'tehrandb'
################################################
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: '))
# ---------------------------------------
msgs = client.get_messages(channel_username, limit=100)
for msg in msgs.data:
if msg.media is not None:
client.download_media(message=msg)

Related

Send message from bot to self with telethon

I'm trying to send a message to myself using a Telegram bot I have created, and I got the values from https://my.telegram.org as well as the BotFather.
import telebot
from telethon.sync import TelegramClient
def telegram_setup():
api_id = 12345678
api_hash = 'X'
token = 'X'
phone = '+111'
client = TelegramClient('session', api_id, api_hash)
client.connect()
if not client.is_user_authorized():
client.send_code_request(phone)
client.sign_in(phone, input('Enter the code: '))
return client
def send_message(client, message):
try:
entity = client.get_entity('username')
client.send_message(entity, message, parse_mode='html')
except Exception as e:
print(e)
client.disconnect()
if __name__ == "__main__":
client = telegram_setup()
message = "test"
send_message(client, message)
The first time I ran this, it sent me a message asking for a code which I supplied. Running it again caused "test" to appear under "Saved Messages" in Telegram, rather than coming from my bot.
Any idea what's causing this or how to resolve it?
Thanks.
EDIT: I realised I'm not using token anywhere, but I'm not sure where it goes.
The bot token is required in client.start() as bot_token (bot_token="token"), if what you do is a bot, your phone is not needed.
Edit: You made a userbot, not a bot.

Telethon events.NewMessage(channelId) to read all message from a channel?

Im trying to create a python script that can read all messages in a chat channel. I found this code, however, this will only read the message that I write myself or are directed at me. How do I change this code so it can read all the messages in the channel?
from telethon import TelegramClient, events
api_id = 242...
api_hash = '8a06ca620417c9964a058e0dc...'
bot_token = '1474729480:AAEhUPmVX_m...'
channelId = -36744...
client = TelegramClient('bot', api_id, api_hash).start(bot_token=bot_token)
client.start()
#client.on(events.NewMessage(chats = [channelId]))
async def my_event_handler(event):
text = event.text
print(text)
client.run_until_disconnected()
You may use iter_messages to get previous messages

python telethon wait for reply

I currently have code to send message to my friend
but how can I know if he reply
this is my current code
please see the commented line
from telethon import TelegramClient
api_id = '1234567'
api_hash = 'MYHASH'
client = TelegramClient('session', api_id, api_hash)
client.start(phone_number)
destination_user_username='friend'
entity=client.get_entity(destination_user_username)
client.send_message(entity=entity,message="hello")
#if he reply hi
client.send_message(entity=entity,message="have a nice day")
how can I do this?
I found in the doc
solution 1
for message in client.iter_messages(chat):
print(message)
solution 2
api_id = '1234567'
api_hash = 'MYHASH'
with TelegramClient('session') as client:
destination_user_username='friend'
entity=client.get_entity(destination_user_username)
client.send_message(entity=entity,message="hello")
from telethon import events
#client.on(events.NewMessage(pattern='hi'))
async def handler(event):
# here received messgae, do something with event
print(dir(event)) # check all possible methods/operations/attributes
# reply once and then disconnect
await event.reply("have a nice day")
await client.disconnect()
client.run_until_disconnected()

Telegram get chat messages /posts - python Telethon

I am using Telethon and Python 3.6xx
Been able to retreive message from groups, no problem but when it comes to channels I am stuck.
dialogs = client(get_dialogs)
for chat in dialogs.chats:
getmessage = client.get_messages(chat.id, limit=400)
for message in getmessage:
print(message.message)
I've searched the telethon documentation but most answers were in response to the old get_message_history.
When I'm trying with the following chat.id = 1097988869 (news.bitcoin.com) I'm getting an error below (for groups the chat.id works fine):
PeerIdInvalidError: An invalid Peer was used. Make sure to pass the right peer type
The accepted answer is good, but recent versions of Telethon let you achieve the same more easily. This will iterate over all messages in chat (for this example we use telethon.sync to avoid typing out async):
from telethon.sync import TelegramClient
with TelegramClient(name, api_id, api_hash) as client:
for message in client.iter_messages(chat):
print(message.sender_id, ':', message.text)
Where the variables should be obvious, for example (note these API values won't work, you need your own):
name = 'anon'
api_id = 123
api_hash = 'abcdefgh'
chat = 'me'
More examples using async are available in client.iter_messages documentation.
update :
in the new version of Telethon, #Lonami answer is best and use it.
############################################################
you can use this code for get messages :
client = TelegramClient('session_name',
api_id,
api_hash,
update_workers=1,
spawn_read_thread=False)
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_username='tehrandb' # your channel
channel_entity=client.get_entity(channel_username)
posts = client(GetHistoryRequest(
peer=channel_entity,
limit=100,
offset_date=None,
offset_id=0,
max_id=0,
min_id=0,
add_offset=0,
hash=0))
# messages stored in `posts.messages`
that work for me!
api_hash from https://my.telegram.org, under API Development.
from telethon import TelegramClient, events, sync
api_id = 'your api_id'
api_hash = 'your api_hash'
client = TelegramClient('session_name', api_id, api_hash)
client.start()
channel_username = 'username'# your channel
for message in client.get_messages(channel_username, limit=10):
print(message.message)

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