I work on the on the python
script, which downloads the contents of the telegram channel messages. I try to do this with pyrogram
. The task is to create a separate folder for each message, and in each folder download photos or videos of the message, as well as save its text (caption). The message id is used as the name for the created directory. The process occurs in a loop with a given limit. The script does everything correctly if each message has one photo or video. However, if any of the messages has several media files, then the reading and download process does not occur synchronously with the creation of directories. The text and photos of each message are not in the place where they should be. Please tell me how to modify the code so that everything is completed in the correct order. For example, I give a suitable channel (wondermoscow) in the code in which messages can have both one media file and gallery. Thanks for any help!
Here is the code:
import os
from pyrogram import Client
api_id = api_id
api_hash = "api_hash"
channel_name = 'wondermoscow'
docs_limit = 3
# init app
app = Client("my_name", api_id=api_id, api_hash=api_hash)
async def main():
# check directory exists/create
if not os.path.isdir(channel_name):
os.mkdir(channel_name)
await app.start()
chat = await app.get_chat(channel_name)
async for message in app.get_chat_history(chat.id, limit=docs_limit):
doc_folder = os.path.join(channel_name, str(message.id))
os.mkdir(doc_folder)
if(message.photo or message.video):
await app.download_media(message)
# copy downloaded content
await move_files('downloads',doc_folder)
text = str(message.caption)
with open(os.path.join(doc_folder,'data.txt'), 'w', encoding='utf-8') as file:
file.write(text)
# move files drim one directory to another
async def move_files(src,dest):
# gather all files
allfiles = os.listdir(src)
# iterate on all files to move them to destination folder
for f in allfiles:
src_path = os.path.join(src, f)
dst_path = os.path.join(dest, f)
os.rename(src_path, dst_path)
app.run(main())