diff --git a/redditbot.py b/redditbot.py index 8997117..48c90a9 100644 --- a/redditbot.py +++ b/redditbot.py @@ -402,20 +402,26 @@ async def main(): elif getattr(random_post, 'is_gallery', None): files = [] captions = [] - if getattr(random_post, 'gallery_data', None): - gallery_keys = map(lambda i: i[1], sorted(map(lambda i: (i['id'], i['media_id']), random_post.gallery_data['items']), key=lambda i: i[0])) - else: - gallery_keys = random_post.media_metadata.keys() - for a, i in enumerate(gallery_keys): - i = random_post.media_metadata[i] - if i['status'] == 'valid': - filename = os.path.join(tempdir, str(time.time())) - for j in ('u', 'mp4', 'gif'): - if j in i['s']: - await _download_file(filename, i['s'][j]) - break - captions.append(f'{text}\n#{a + 1}') - files.append(filename) + gallery_data = sorted(random_post.gallery_data['items'], key=lambda i: i['id']) + # no enumerate() because we want to update the count only if the media's status is valid + count = 1 + for gallery_data_item in gallery_data: + media_metadata_item = random_post.media_metadata[gallery_data_item['media_id']] + if media_metadata_item['status'] != 'valid': + continue + filename = os.path.join(tempdir, str(time.time())) + for media_type in ('u', 'mp4', 'gif'): + if media_type not in media_metadata_item['s']: + continue + await _download_file(filename, media_metadata_item['s'][media_type]) + break + caption = f'{text}\n#{count}' + real_caption = (gallery_data_item.get('caption') or '').strip() + if real_caption: + caption += f': {html.escape(real_caption)}' + captions.append(caption) + files.append(filename) + count += 1 url = None if url: parsed = list(urlparse(url))