├── images ├── logo.png └── screenshot.png ├── decoding.py ├── youtube.py ├── twitter.py ├── README.md ├── telegram_bot.py └── instagram.py /images/logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mateus-werneck/TelegramBot_MidiaSave/HEAD/images/logo.png -------------------------------------------------------------------------------- /images/screenshot.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mateus-werneck/TelegramBot_MidiaSave/HEAD/images/screenshot.png -------------------------------------------------------------------------------- /decoding.py: -------------------------------------------------------------------------------- 1 | import re 2 | from selenium.webdriver.firefox.options import Options 3 | from selenium import webdriver 4 | from twitter import getTwitter 5 | from instagram import instaPost, instaStories, instaTV 6 | from youtube import getYou 7 | ##################################### Open Firefox ######################################### 8 | firefox_options = Options() 9 | firefox_options.add_argument("--headless") 10 | firefox = webdriver.Firefox(options=firefox_options) 11 | firefox.set_page_load_timeout(60) 12 | #################################### Process Media Type and Get Media ####################### 13 | def getMedia(url, button, bot, chat_id, formato): 14 | url = url 15 | igtv = re.search('/tv/', url) 16 | stories = re.search('/stories/', url) 17 | posts = re.search('/p/', url) 18 | reel = re.search ('/reel/', url) 19 | igtv = re.search('/tv/', url) 20 | twt = re.search('twitter.com/', url) 21 | twt2 = re.search('t.co', url) 22 | yt = re.search('youtube', url) 23 | yt2 = re.search('youtu.be', url) 24 | ################### Posts and Reels Instagram ####################################### 25 | 26 | if (posts != None or reel != None): 27 | source = instaPost(url, firefox, button, bot, chat_id) 28 | if re.search('instagram', source) != None or re.search("IGTV", source) != None: 29 | return source 30 | else: 31 | source = '' 32 | return source 33 | 34 | ################## Instagram Stories ################################################ 35 | 36 | elif(stories != None): 37 | source = instaStories(url, firefox, button, bot, chat_id) 38 | if re.search('instagram', source) != None: 39 | return source 40 | else: 41 | source = '' 42 | return source 43 | 44 | #################### IGTV ############################################################### 45 | elif(igtv != None): 46 | source = instaTV(url, firefox, button, bot, chat_id) 47 | if type(source) is list: 48 | for i in source: 49 | if (re.search('IGTV', i) != None): 50 | return source 51 | elif type(source) is str: 52 | if re.search('.mp4', source) != None: 53 | return source 54 | else: 55 | source = '' 56 | return source 57 | 58 | ################ Twitter Videos ######################################################## 59 | 60 | elif twt != None or twt2 != None: 61 | path = '' 62 | path = getTwitter(url, firefox, bot, chat_id) 63 | return path 64 | 65 | ################ Youtube ########################################################## 66 | 67 | elif yt != None or yt2 != None: 68 | path = '' 69 | path = getYou(url, bot, chat_id, formato) 70 | return path 71 | -------------------------------------------------------------------------------- /youtube.py: -------------------------------------------------------------------------------- 1 | import os, time, glob, pytube, shutil, tempfile 2 | from moviepy.video.io.VideoFileClip import VideoFileClip 3 | from moviepy.audio.io.AudioFileClip import AudioFileClip 4 | from telegram.ext import Updater, CommandHandler, MessageHandler, Filters, CallbackQueryHandler 5 | import telegram 6 | from telegram import InlineKeyboardMarkup, InlineKeyboardButton 7 | 8 | 9 | load = u' \U0001f504' 10 | runner = u' \U0001f3c3' 11 | 12 | ################################## Get Mp4 ################################################ 13 | def getYou(url, bot, chat_id, formato): 14 | temp_dir = tempfile.mkdtemp() 15 | if (formato == '.mp4'): 16 | try: 17 | yt = pytube.YouTube(url).streams.filter(res="720p").first().download(temp_dir) 18 | except: 19 | yt = pytube.YouTube(url).streams.filter(res="360p").first().download(temp_dir) 20 | video = glob.glob(temp_dir + '/*.mp4') 21 | final_path = '' 22 | ytPath = [] 23 | for i in video: 24 | final_path = i 25 | size = os.path.getsize(i) / 1000000 26 | break 27 | if (size > 49.9999): 28 | video = VideoFileClip(final_path) 29 | duration = int(video.duration) 30 | start_time = 0 31 | end_time = 600 32 | parts = int(duration / 600) 33 | videopart = int(duration/ 600) + 1 34 | if (parts > (video.duration / 600)): 35 | parts = parts - 1 36 | if (duration <= 630): 37 | subvideo = video.subclip(0, duration) 38 | bot.send_message(chat_id=chat_id, text='Finalizando ' + runner, timeout=60) 39 | subvideo.write_videofile(temp_dir + '/youtube' + '01' + '.mp4', threads=8, logger=None, rewrite_audio=False, audio_codec='aac', preset = 'veryfast', fps=30, bitrate='520k') 40 | ytPath = temp_dir + '/youtube' + '01' + '.mp4' 41 | bot.send_video(chat_id=chat_id, video = open(ytPath, 'rb'), timeout=3600) 42 | shutil.rmtree(temp_dir) 43 | return ytPath 44 | elif (duration > 630): 45 | if (duration % 600 == 0): 46 | c = 1 47 | for i in range (parts): 48 | if(end_time > duration): 49 | break 50 | subvideo = video.subclip(start_time, end_time) 51 | bot.send_message(chat_id=chat_id, text='Processando ' + 'parte ' + str(c) + '/' + str(videopart) + '' + load, timeout=60) 52 | c += 1 53 | subvideo.write_videofile(temp_dir + '/youtube' + '0' + str(i+1) + '.mp4', threads=8, logger=None, rewrite_audio=False, audio_codec='aac', preset = 'veryfast', fps=30, bitrate='550k') 54 | bot.send_video(chat_id=chat_id, video = open(temp_dir + '/youtube' + '0' + str(i+1) + '.mp4', 'rb'), timeout=3600) 55 | start_time += 600.00 56 | end_time += 600.00 57 | elif (duration % 600 > 0): 58 | i = 0 59 | c = 1 60 | end_custom = (600 * parts) + (duration % 600) 61 | while i < parts: 62 | subvideo = video.subclip(start_time, end_time) 63 | bot.send_message(chat_id=chat_id, text='Processando ' + 'parte ' + str(c) + '/' + str(videopart) + '' + load, timeout=60) 64 | subvideo.write_videofile(temp_dir + '/youtube' + '0' + str(i+1) + '.mp4', threads=8, logger=None, rewrite_audio=False, audio_codec='aac', preset = 'veryfast', fps=30, bitrate='550k') 65 | bot.send_video(chat_id=chat_id, video = open(temp_dir + '/youtube' + '0' + str(i+1) + '.mp4', 'rb'), timeout=3600) 66 | start_time += 600.00 67 | end_time += 600.00 68 | i += 1 69 | c += 1 70 | if (i == parts): 71 | subvideo = video.subclip(start_time, end_custom) 72 | bot.send_message(chat_id=chat_id, text='Processando ' + 'parte ' + str(c) + '/' + str(videopart) + '' + load, timeout=60) 73 | subvideo.write_videofile(temp_dir + '/youtube' + '0' + str(i+1) + '.mp4', threads=8, logger=None, rewrite_audio=False, audio_codec='aac', preset = 'veryfast', fps=30, bitrate='550k') 74 | time.sleep(1) 75 | bot.send_video(chat_id=chat_id, video = open(temp_dir + '/youtube' + '0' + str(i+1) + '.mp4', 'rb'), timeout=3600) 76 | ytPath = glob.glob(temp_dir + '/*.mp4') 77 | shutil.rmtree(temp_dir) 78 | return ytPath 79 | else: 80 | bot.send_video(chat_id=chat_id, video = open(final_path, 'rb'), timeout=3600) 81 | shutil.rmtree(temp_dir) 82 | return final_path 83 | ############################## Get MP3 ################################################# 84 | elif formato == '.mp3': 85 | yt = pytube.YouTube(url).streams.filter(only_audio=True).first().download(temp_dir) 86 | video = glob.glob(temp_dir + '/*.mp4') 87 | for i in video: 88 | final_path = i 89 | break 90 | clip = AudioFileClip(final_path) 91 | audio_path = final_path.replace('mp4', 'mp3') 92 | clip.write_audiofile(audio_path, logger=None) 93 | bot.send_audio(chat_id=chat_id, audio = open(audio_path, 'rb'), timeout=3600) 94 | shutil.rmtree(temp_dir) 95 | return final_path 96 | -------------------------------------------------------------------------------- /twitter.py: -------------------------------------------------------------------------------- 1 | import requests, re, time, urllib, os, webbrowser, json, tempfile, shutil 2 | from selenium.webdriver.firefox.options import Options 3 | from selenium import webdriver 4 | from selenium.webdriver.common.by import By 5 | from moviepy.video.io.VideoFileClip import VideoFileClip 6 | from moviepy.video.compositing.concatenate import concatenate_videoclips 7 | 8 | ####################################### Twitter Video ##################################################### 9 | def getTwitter(url, firefox, bot, chat_id): 10 | temp_dir = tempfile.mkdtemp() 11 | directory_final = '/home/mateus/Documents/Python/telegram_bot' 12 | firefox.get(url) 13 | time.sleep(5) 14 | log = firefox.execute_script("var performance = window.performance || window.mozPerformance || window.msPerformance || window.webkitPerformance || {}; var network = performance.getEntries() || {}; return network;") 15 | video ='' 16 | path = '' 17 | with open(temp_dir + "/items.json", "w") as jsonFile: 18 | json.dump(log, jsonFile, indent = 6) 19 | jsonFile.close() 20 | with open (temp_dir + "/items.json", "r") as jsonFile: 21 | json_decoded = json.load(jsonFile) 22 | for i in range(len(json_decoded)): 23 | if (re.match(r'https://video.twimg.com/', json_decoded[i]['name']) != None): 24 | video = json_decoded[i]['name'] 25 | break 26 | jsonFile.close() 27 | if (re.search(r'https://video.twimg.com/(.*?).m3u8', video) != None): 28 | m3u8c = re.search(r'https://video.twimg.com(.*?)?tag=', video) 29 | encoded = [] 30 | if (m3u8c == None): 31 | tipo='m4s' 32 | urllib.request.urlretrieve(video, temp_dir + '/temp.txt') 33 | with open (temp_dir + "/temp.txt", "r") as tempF: 34 | for line in tempF: 35 | if(re.search(r'.ts', line) != None): 36 | encoded.append('https://video.twimg.com' + line) 37 | tipo ='ts' 38 | tempF.close() 39 | collection =[] 40 | if(tipo == 'ts'): 41 | for i in range(len(encoded)): 42 | name = temp_dir + '/temp' + '0' + str(i) + '.ts' 43 | urllib.request.urlretrieve(encoded[i], name) 44 | video = VideoFileClip(name) 45 | collection.append(video) 46 | bot.send_message(chat_id=chat_id, text='Finalizando...', timeout=60) 47 | twitter = concatenate_videoclips(collection) 48 | final_name = 'twitter.mp4' 49 | twitter.to_videofile(directory_final + '/' + final_name, threads=8, logger=None, rewrite_audio=False, audio_codec='aac', preset = 'veryfast', fps=24) 50 | path = (directory_final + '/' + final_name) 51 | return path 52 | else: 53 | path = 'inválido' 54 | return path 55 | 56 | elif (m3u8c != None): 57 | tipo='m4s' 58 | urllib.request.urlretrieve(video, temp_dir + '/temp.txt') 59 | with open (temp_dir + "/temp.txt", "r") as tempF: 60 | for line in tempF: 61 | if(re.search(r'.m3u8', line) != None): 62 | m3u8c2 = 'https://video.twimg.com' + line 63 | break 64 | tempF.close() 65 | urllib.request.urlretrieve(m3u8c2, temp_dir + '/temp.txt') 66 | with open (temp_dir + "/temp.txt", "r") as tempF: 67 | for line in tempF: 68 | if(re.search(r'.ts', line) != None): 69 | encoded.append('https://video.twimg.com' + line) 70 | tipo = 'ts' 71 | tempF.close() 72 | collection =[] 73 | if (tipo == 'ts'): 74 | for i in range(len(encoded)): 75 | name = temp_dir + '/temp' + '0' + str(i) + '.ts' 76 | urllib.request.urlretrieve(encoded[i], name) 77 | video = VideoFileClip(name) 78 | collection.append(video) 79 | bot.send_message(chat_id=chat_id, text='Finalizando...', timeout=60) 80 | twitter = concatenate_videoclips(collection) 81 | final_name = 'twitter.mp4' 82 | twitter.to_videofile(directory_final + '/' + final_name, threads=8, logger=None, rewrite_audio=False, audio_codec='aac', preset = 'veryfast', fps=24) 83 | path = (directory_final + '/' + final_name) 84 | return path 85 | else: 86 | path = 'inválido' 87 | return path 88 | 89 | else: 90 | tipo='m4s' 91 | encoded = [] 92 | with open (temp_dir + "/items.json", "r") as jsonFile: 93 | json_decoded = json.load(jsonFile) 94 | for i in range(len(json_decoded)): 95 | if(re.search('"(.*?).ts', json_decoded[i]['name']) != None): 96 | encoded.append(json_decoded[i]['name']) 97 | tipo='ts' 98 | jsonFile.close() 99 | collection =[] 100 | if (tipo == 'ts'): 101 | for i in range(len(encoded)): 102 | name = temp_dir + '/temp' + '0' + str(i) + '.ts' 103 | urllib.request.urlretrieve(encoded[i], name) 104 | video = VideoFileClip(name) 105 | collection.append(video) 106 | bot.send_message(chat_id=chat_id, text='Finalizando...', timeout=60) 107 | twitter = concatenate_videoclips(collection) 108 | final_name = 'twitter.mp4' 109 | twitter.to_videofile(directory_final + '/' + final_name, threads=8, logger=None, rewrite_audio=False, audio_codec='aac', preset = 'veryfast', fps=24) 110 | path = directory_final + '/' + final_name 111 | return path 112 | else: 113 | path = 'inválido' 114 | return path 115 | #################################################################################################### 116 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![LinkedIn][linkedin-shield]][linkedin-url] 2 | 3 | 4 | 5 |
6 |

7 | 8 | Logo 9 | 10 | 11 |

Media Saver Telegram Bot

12 | 13 |

14 | Preconfigured Telegram Bot to download Instagram (IGTV, Posts, Reels and Stories), Twitter Videos and Youtube Videos/Audio 15 |
16 |
17 | Bot do Telegram pré-configurado para baixar midias do Instagram (IGTV, Posts, Reels e Stories), Videos do Twitter e Youtube 18 |
19 | Português Brasil 20 |
21 |
22 |
23 | · 24 | Report Bug 25 | · 26 | Request Feature 27 |

28 |

29 | 30 | 31 | 32 |
33 |

Table of Contents

34 |
    35 |
  1. 36 | Built with 37 |
  2. 38 |
  3. 39 | Getting Started 40 | 43 |
  4. 44 |
  5. Usage
  6. 45 |
  7. Português Brasil
  8. 46 |
47 |
48 | 49 |
50 | 51 | ## Built With 52 | 53 | * [Python](https://www.python.org/) 54 | * [Selenium](https://www.selenium.dev/) 55 | * [MoviePy](https://github.com/Zulko/moviepy) 56 | * [Python-Telegram-Bot](https://github.com/python-telegram-bot/python-telegram-bot) 57 | * [PyTube](https://github.com/pytube/pytube) 58 | 59 | 60 | 61 |
62 | 63 | ## Getting Started 64 | 65 | ### Prerequisites 66 | 67 | * Python 68 | ```sh 69 | https://www.python.org/ftp/python/3.9.2/python-3.9.2-amd64.exe 70 | ``` 71 | 72 | ![image](https://user-images.githubusercontent.com/25112157/112496747-bf8e8800-8d63-11eb-89ab-b777142e5566.png) 73 | 74 | 75 | * Dependencies 76 | 77 | ```sh 78 | pip3 install requests selenium urllib3 moviepy pytube python-telegram-bot 79 | ``` 80 | 81 | ```sh 82 | Get geckodriver.exe from https://github.com/mozilla/geckodriver and put it on TelegramBot folder 83 | ``` 84 | 85 | ```sh 86 | Get Token from @botFather on Telegram 87 | ``` 88 | 89 | ![Bot](https://user-images.githubusercontent.com/25112157/116262112-a60ba200-a74e-11eb-8070-71805f4ceeba.png) 90 | 91 |
92 | 93 | ## Usage 94 | 95 | ```sh 96 | python3 telegram_bot.py 97 | ``` 98 | 99 | 100 | 101 | 102 | 103 | [contributors-shield]: https://img.shields.io/github/contributors/github_username/repo.svg?style=for-the-badge 104 | [contributors-url]: https://github.com/github_username/repo/graphs/contributors 105 | [forks-shield]: https://img.shields.io/github/forks/github_username/repo.svg?style=for-the-badge 106 | [forks-url]: https://github.com/mateus-werneck/MediaSavBr/network/members 107 | [stars-shield]: https://img.shields.io/github/stars/github_username/repo.svg?style=for-the-badge 108 | [stars-url]: https://github.com/github_username/repo/stargazers 109 | [issues-shield]: https://img.shields.io/github/issues/github_username/repo.svg?style=for-the-badge 110 | [issues-url]: https://github.com/mateus-werneck/MediaSavBr/issues 111 | [license-shield]: https://img.shields.io/github/license/github_username/repo.svg?style=for-the-badge 112 | [license-url]: https://github.com/github_username/repo/blob/master/LICENSE.txt 113 | [linkedin-shield]: https://img.shields.io/badge/-LinkedIn-black.svg?style=for-the-badge&logo=linkedin&colorB=555 114 | [linkedin-url]: https://www.linkedin.com/in/mateus-werneck/ 115 | 116 |
117 |
118 |
119 | 120 | # Português Brasil 121 | 122 | 123 | 124 | [contributors-shield]: https://img.shields.io/github/contributors/github_username/repo.svg?style=for-the-badge 125 | [contributors-url]: https://github.com/github_username/repo/graphs/contributors 126 | [forks-shield]: https://img.shields.io/github/forks/github_username/repo.svg?style=for-the-badge 127 | [forks-url]: https://github.com/mateus-werneck/MidiaSave/network/members 128 | [stars-shield]: https://img.shields.io/github/stars/github_username/repo.svg?style=for-the-badge 129 | [stars-url]: https://github.com/github_username/repo/stargazers 130 | [issues-shield]: https://img.shields.io/github/issues/github_username/repo.svg?style=for-the-badge 131 | [issues-url]: https://github.com/mateus-werneck/MidiaSaver/issues 132 | [license-shield]: https://img.shields.io/github/license/github_username/repo.svg?style=for-the-badge 133 | [license-url]: https://github.com/github_username/repo/blob/master/LICENSE.txt 134 | [linkedin-shield]: https://img.shields.io/badge/-LinkedIn-black.svg?style=for-the-badge&logo=linkedin&colorB=555 135 | [linkedin-url]: https://www.linkedin.com/in/mateus-werneck/ 136 | 137 | 138 | 139 | 140 |
141 |
142 |
143 |
144 |
145 |
146 |

147 | 148 | Logo 149 | 150 | 151 |

Media Saver Telegram Bot

152 | 153 |

154 | Bot do Telegram pré-configurado para baixar midias do Instagram (IGTV, Posts, Reels e Stories) e Videos do Twitter e Youtube 155 |
156 |
157 |
158 |
159 | · 160 | Reportar Bug 161 | · 162 | Requisitar Novo Recurso 163 |

164 |

165 | 166 | 167 | 168 | 169 |
170 |

Índice

171 |
    172 |
  1. 173 | Ferramentas Utilizadas 174 |
  2. 175 |
  3. 176 | Como Começar 177 | 180 |
  4. 181 |
  5. Como Usar
  6. 182 |
183 |
184 | 185 | 186 | 187 | ## Ferramentas Utilizadas 188 | 189 | * [Python](https://www.python.org/) 190 | * [Selenium](https://www.selenium.dev/) 191 | * [MoviePy](https://github.com/Zulko/moviepy) 192 | * [Python-Telegram-Bot](https://github.com/python-telegram-bot/python-telegram-bot) 193 | * [PyTube](https://github.com/pytube/pytube) 194 | 195 | 196 | 197 | 198 | ## Como Começar 199 | 200 | ### Pré-requisitos 201 | 202 | * Python 203 | ```sh 204 | https://www.python.org/ftp/python/3.9.2/python-3.9.2-amd64.exe 205 | ``` 206 | 207 | ![image](https://user-images.githubusercontent.com/25112157/112496747-bf8e8800-8d63-11eb-89ab-b777142e5566.png) 208 | 209 | 210 | * Dependências 211 | 212 | ```sh 213 | pip3 install requests selenium urllib3 moviepy pytube python-telegram-bot 214 | ``` 215 | 216 | ```sh 217 | Baixe o geckodriver.exe em https://github.com/mozilla/geckodriver e coloque na pasta TelegramBot 218 | ``` 219 | 220 | ```sh 221 | Pegue seu Token com o @botFather no Telegram 222 | ``` 223 | 224 | ![Bot](https://user-images.githubusercontent.com/25112157/116262172-b1f76400-a74e-11eb-817e-e5eb4d01baef.png) 225 | 226 |
227 | 228 | ## Como Usar 229 | 230 | ```sh 231 | python3 telegram_bot.py 232 | ``` 233 | 234 | 235 | 236 | 237 | [contributors-shield]: https://img.shields.io/github/contributors/github_username/repo.svg?style=for-the-badge 238 | [contributors-url]: https://github.com/github_username/repo/graphs/contributors 239 | [forks-shield]: https://img.shields.io/github/forks/github_username/repo.svg?style=for-the-badge 240 | [forks-url]: https://github.com/mateus-werneck/MediaSavBr/network/members 241 | [stars-shield]: https://img.shields.io/github/stars/github_username/repo.svg?style=for-the-badge 242 | [stars-url]: https://github.com/github_username/repo/stargazers 243 | [issues-shield]: https://img.shields.io/github/issues/github_username/repo.svg?style=for-the-badge 244 | [issues-url]: https://github.com/mateus-werneck/MediaSavBr/issues 245 | [license-shield]: https://img.shields.io/github/license/github_username/repo.svg?style=for-the-badge 246 | [license-url]: https://github.com/github_username/repo/blob/master/LICENSE.txt 247 | [linkedin-shield]: https://img.shields.io/badge/-LinkedIn-black.svg?style=for-the-badge&logo=linkedin&colorB=555 248 | [linkedin-url]: https://www.linkedin.com/in/mateus-werneck/ 249 | 250 | 251 | -------------------------------------------------------------------------------- /telegram_bot.py: -------------------------------------------------------------------------------- 1 | 2 | import logging, time, re, shutil, os 3 | from telegram.ext import Updater, CommandHandler, MessageHandler, Filters, CallbackQueryHandler, ConversationHandler 4 | import telegram 5 | from telegram import InlineKeyboardMarkup, InlineKeyboardButton 6 | from decoding import getMedia 7 | 8 | 9 | logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', 10 | level=logging.INFO) 11 | logger = logging.getLogger(__name__) 12 | 13 | ######################### Global Variables ################################## 14 | smile = u' \U0001F604' 15 | source='' 16 | btn = 0 17 | twitter = '' 18 | formato = '' 19 | url ='' 20 | chat_id = '' 21 | ############################################################################## 22 | ################################################## Start Message ######################################### 23 | def start(update, context): 24 | """Send a message when the command /start is issued.""" 25 | update.message.reply_text('Olá, me manda um link do Instagram, Twitter ou Youtube que eu irei procurar para você!') 26 | update.message.reply_text('Se você mandar um link e não receber seu arquivo em até 1 minuto. Por favor tente mandar mais uma vez!') 27 | ##################################################################################################################################### 28 | ##################################################### Help and Error ################################################################ 29 | def help(update, context): 30 | """Send a message when the command /help is issued.""" 31 | update.message.reply_text('Help!') 32 | 33 | 34 | def error(update, context): 35 | """Log Errors caused by Updates.""" 36 | logger.warning('Update "%s" caused error "%s"', update, context.error) 37 | ################################################################################################################################### 38 | ################################## Get link from Telegram/User ################################## 39 | 40 | def getLink(update, context): 41 | global twitter, url, chat_id, smile 42 | bot = telegram.Bot(token="TOKEN") 43 | url = update.message.text 44 | chat_id = update.message.chat_id 45 | ############################################### Twitter #################################### 46 | if re.search('twitter', url) != None or re.search('t.co', url) != None: 47 | bot.send_message(chat_id=update.message.chat_id, text='Isso pode demorar um pouco') 48 | if (getSource(url, chat_id, formato) == True): 49 | if (twitter != 'inválido' and twitter != ''): 50 | bot.send_message(chat_id=update.message.chat_id, text='Pronto ' + smile) 51 | print("Salvo com Sucesso. Twitter") 52 | #print(update.message.chat_id, update.message.chat.first_name, update.message.chat.last_name, "@" + update.message.chat.username) 53 | os.remove('/home/mateus/Documents/Python/telegram_bot/twitter.mp4') 54 | else: 55 | bot.send_message(chat_id=update.message.chat_id, text='Parece que você mandou um link inválido. No caso de uma Imagem ou GIF você pode salvar a partir do link que você mandou logo acima') 56 | else: 57 | bot.send_message(chat_id=update.message.chat_id, text='Parece que você mandou um link inválido. No caso de uma Imagem ou GIF você pode salvar a partir do link que você mandou logo acima') 58 | ############################################### Instagram #################################### 59 | 60 | elif (re.search('instagram', url) != None): 61 | if(getSource(url, chat_id, formato) == True): 62 | if(type(source) is str): 63 | if (re.search('instagram', source) != None): 64 | bot.send_video(chat_id=update.message.chat_id, video = source, timeout=3600) 65 | bot.send_message(chat_id=update.message.chat_id, text='Pronto ' + smile) 66 | print("Salvo com Sucesso. Instagram") 67 | #print(update.message.chat_id, update.message.chat.first_name, update.message.chat.last_name, "@" + update.message.chat.username) 68 | elif (re.search('IGTV', source) != None): 69 | bot.send_message(chat_id=update.message.chat_id, text='Pronto ' + smile) 70 | print("Salvo com Sucesso. Instagram") 71 | #print(update.message.chat_id, update.message.chat.first_name, update.message.chat.last_name, "@" + update.message.chat.username) 72 | elif type(source) is list: 73 | bot.send_message(chat_id=update.message.chat_id, text='Pronto ' + smile) 74 | print("Salvo com Sucesso. Instagram") 75 | #print(update.message.chat_id, update.message.chat.first_name, update.message.chat.last_name, "@" + update.message.chat.username) 76 | source.clear() 77 | else: 78 | bot.send_message(chat_id=update.message.chat_id, text='Não deu certo. Verifique se a conta do Instagram é privada/fechada') 79 | ############################################### Youtube #################################### 80 | 81 | elif re.search('youtube', url) != None or re.search('youtu.be', url) != None: 82 | buttons = [[InlineKeyboardButton("Video - MP4", callback_data = '.mp4')], 83 | [InlineKeyboardButton("Audio - MP3", callback_data ='.mp3')]] 84 | reply_markup = InlineKeyboardMarkup(buttons) 85 | bot.send_message(chat_id=update.message.chat_id, text='Qual formato você deseja salvar?', reply_markup = reply_markup) 86 | 87 | else: 88 | bot.send_message(chat_id=update.message.chat_id, text='Parece que você mandou um link inválido.') 89 | ############################### Get Media From User Input(URL) ################################## 90 | 91 | def getSource(url, chat_id, formato): 92 | bot = telegram.Bot(token="TOKEN") 93 | global source, btn, twitter 94 | ######################################### Instagram Check ####################################### 95 | if (re.search('instagram', url) != None): 96 | source=getMedia(url, btn, bot, chat_id, formato='') 97 | btn += 1 98 | if type(source) is str: 99 | if (re.search('instagram', source) != None or re.search('IGTV', source) != None): 100 | return True 101 | else: 102 | return False 103 | 104 | elif type(source) is list: 105 | for i in source: 106 | if re.search('.mp4', i) != None: 107 | return True 108 | else: 109 | return False 110 | ########################################### Twitter Check ####################################### 111 | elif re.search('twitter', url) != None or re.search('t.co', url) != None: 112 | twitter = getMedia(url, btn, bot, chat_id, formato='') 113 | if twitter == 'inválido': 114 | return False 115 | elif (twitter != '' and twitter != 'inválido'): 116 | return True 117 | ######################################### Youtube Check ######################################### 118 | 119 | elif re.search('youtube', url) != None or re.search('youtu.be', url) != None: 120 | source=getMedia(url, btn, bot, chat_id, formato) 121 | return True 122 | ################################## Button Check for Mp3/Mp4 ####################################################### 123 | def button(update, CallBackContext): 124 | bot = telegram.Bot(token="TOKEN") 125 | global url, chat_id, formato, smile 126 | query = update.callback_query 127 | query.answer() 128 | if (query.data == '.mp3'): 129 | formato = '.mp3' 130 | elif (query.data == '.mp4'): 131 | formato = '.mp4' 132 | bot.send_message(chat_id=chat_id, text='Isso pode levar um tempo. Aguarde...') 133 | bot.send_message(chat_id=chat_id, text='Se o video for muito grande ele será dividido em partes.') 134 | query.message.delete() 135 | if(getSource(url, chat_id, formato) == True): 136 | bot.send_message(chat_id=chat_id, text='Pronto ' + smile) 137 | print("Salvo com Sucesso. Youtube") 138 | else: 139 | bot.send_message(chat_id=chat_id, text='Parece que você mandou um link inválido.') 140 | ############################ Bot Main Function ######################################### 141 | def main(): 142 | """Start the bot.""" 143 | updater = Updater("TOKEN") 144 | 145 | # Get the dispatcher to register handlers 146 | dp = updater.dispatcher 147 | 148 | # on different commands - answer in Telegram 149 | dp.add_handler(CommandHandler("start", start)) 150 | dp.add_handler(CommandHandler("help", help)) 151 | 152 | # on noncommand i.e message - echo the message on Telegram 153 | dp.add_handler(MessageHandler(Filters.text, getLink)) 154 | dp.add_handler(CallbackQueryHandler(button)) 155 | 156 | # log all errors 157 | dp.add_error_handler(error) 158 | 159 | # Start the Bot 160 | updater.start_polling() 161 | 162 | # Run the bot until you press Ctrl-C or the process receives SIGINT, 163 | # SIGTERM or SIGABRT. This should be used most of the time, since 164 | # start_polling() is non-blocking and will stop the bot gracefully. 165 | updater.idle() 166 | 167 | if __name__ == '__main__': 168 | main() 169 | -------------------------------------------------------------------------------- /instagram.py: -------------------------------------------------------------------------------- 1 | import requests, re, time, json, os, urllib, glob, shutil, tempfile 2 | from selenium.webdriver.firefox.options import Options 3 | from selenium import webdriver 4 | from selenium.webdriver.common.by import By 5 | from moviepy.video.io.VideoFileClip import VideoFileClip 6 | from telegram.ext import Updater, CommandHandler, MessageHandler, Filters 7 | import telegram 8 | 9 | load = u'\U0001f504' 10 | runner = u'\U0001f3c3' 11 | ################################# Instagram Posts and Reels ######################################### 12 | def instaPost(url, firefox, button, bot, chat_id): 13 | bot.send_message(chat_id=chat_id, text='Só um segundo' + runner, timeout=60) 14 | if (auth(url, firefox, button, bot) == True): 15 | firefox.get(url) 16 | html = firefox.page_source 17 | try: 18 | if firefox.find_element_by_class_name("tWeCl"): 19 | video = firefox.find_element_by_class_name("tWeCl").get_attribute("src") 20 | if re.search("blob", video) == None: 21 | button += 1 22 | source = instaTV(url, firefox, button, bot, chat_id) 23 | return source 24 | else: 25 | encodedVideo = re.search(r'"video_url":"(.*?)",', html) 26 | decoded = (encodedVideo.group(1).replace(r"\u0026", "&")) 27 | return decoded 28 | except: 29 | encodedImg = re.search(r'"display_url":"(.*?)",', html) 30 | if encodedImg == None: 31 | decoded = '' 32 | return decoded 33 | else: 34 | decoded = (encodedImg.group(1).replace(r"\u0026", "&")) 35 | return decoded 36 | ############################### Instagram Stories ######################################################## 37 | def instaStories(url, firefox, button, bot, chat_id): 38 | bot.send_message(chat_id=chat_id, text='Só um segundo' + runner, timeout=60) 39 | if (auth(url, firefox, button, bot) == True): 40 | firefox.get(url) 41 | time.sleep(2) 42 | try: 43 | view = firefox.find_element_by_class_name('sqdOP.L3NKy.y1rQx.cB_4K') 44 | view.click() 45 | except: 46 | print("No Button Stories") 47 | time.sleep(1) 48 | img = '' 49 | video = '' 50 | if (bool (len(firefox.find_elements_by_tag_name('source'))) > 0): 51 | video = firefox.find_element_by_tag_name('source').get_attribute("src") 52 | return video 53 | elif (bool (len(firefox.find_elements_by_tag_name('source'))) == 0): 54 | img = firefox.find_element_by_tag_name("img").get_attribute("src") 55 | return img 56 | else: 57 | source = '' 58 | return source 59 | ############################### Instagram TV ############################################################ 60 | def instaTV(url, firefox, button, bot, chat_id): 61 | bot.send_message(chat_id=chat_id, text='Isso pode demorar um pouco', timeout=60) 62 | temp_dir = tempfile.mkdtemp() 63 | if (auth(url, firefox, button, bot) == True): 64 | firefox.get(url) 65 | time.sleep(1) 66 | html = firefox.page_source 67 | time.sleep(1) 68 | encodedVideo = re.search(r'"video_url":"(.*?)",', html) 69 | if (encodedVideo == None): 70 | decoded = '' 71 | return decoded 72 | else: 73 | if (encodedVideo != None): 74 | path = temp_dir + '/IGTV.mp4' 75 | decoded = (encodedVideo.group(1).replace(r"\u0026", "&")) 76 | urllib.request.urlretrieve(decoded, path) 77 | size = os.path.getsize(path) / 1000000 78 | if size <= 49.9999: 79 | bot.send_video(chat_id=chat_id, video = open(path, 'rb'), timeout=3600) 80 | shutil.rmtree(temp_dir) 81 | return path 82 | else: 83 | video = VideoFileClip(path) 84 | duration = int(video.duration) 85 | start_time = 0 86 | end_time = 600 87 | parts = int(duration / 600) 88 | videopart = int(duration/600) + 1 89 | end_custom = (600 * parts) + (duration % 600) 90 | igtvPath = [] 91 | if (parts > (video.duration / 600)): 92 | parts = parts - 1 93 | if (duration <= 630): 94 | bot.send_message(chat_id=chat_id, text='Finalizando ' + runner, timeout=60) 95 | subvideo = video.subclip(0, duration) 96 | subvideo.write_videofile(temp_dir + '/IGTV' + '01' + '.mp4', threads=8, preset="veryfast", logger=None, audio_codec='aac', rewrite_audio=False, fps=30, bitrate='520k') 97 | time.sleep(1) 98 | bot.send_video(chat_id=chat_id, video = open(temp_dir + '/IGTV' + '01' + '.mp4', 'rb'), timeout=3600) 99 | igtvPath = temp_dir + '/IGTV01.mp4' 100 | shutil.rmtree(temp_dir) 101 | return igtvPath 102 | else: 103 | if (duration % 600 == 0): 104 | c = 1 105 | for i in range (parts): 106 | if(end_time > duration): 107 | break 108 | subvideo = video.subclip(start_time, end_time) 109 | bot.send_message(chat_id=chat_id, text='Processando ' + 'parte ' + str(c) + '/' + str(videopart) + '' + load, timeout=60) 110 | subvideo.write_videofile(temp_dir + '/IGTV' + '0' + str(i+1) + '.mp4', threads=8, preset="veryfast", logger=None, audio_codec='aac', rewrite_audio=False, fps=30, bitrate='550k') 111 | time.sleep(1) 112 | bot.send_video(chat_id=chat_id, video = open(temp_dir + '/IGTV' + '0' + str(i+1) + '.mp4', 'rb'), timeout=3600) 113 | c +=1 114 | start_time += 600.00 115 | end_time += 600.00 116 | elif (duration % 600 > 0): 117 | i = 0 118 | c = 1 119 | while i < parts: 120 | subvideo = video.subclip(start_time, end_time) 121 | bot.send_message(chat_id=chat_id, text='Processando ' + 'parte ' + str(c) + '/' + str(videopart) + '' + load, timeout=60) 122 | subvideo.write_videofile(temp_dir + '/IGTV' + '0' + str(i+1) + '.mp4', threads=8, preset="veryfast", logger=None, audio_codec='aac', rewrite_audio=False, fps=30, bitrate='550k') 123 | time.sleep(1) 124 | bot.send_video(chat_id=chat_id, video = open(temp_dir + '/IGTV' + '0' + str(i+1) + '.mp4', 'rb'), timeout=3600) 125 | c +=1 126 | start_time += 600.00 127 | end_time += 600.00 128 | i += 1 129 | if (i == parts): 130 | subvideo = video.subclip(start_time, end_custom) 131 | bot.send_message(chat_id=chat_id, text='Processando ' + 'parte ' + str(c) + '/' + str(videopart) + '' + load, timeout=60) 132 | subvideo.write_videofile(temp_dir + '/IGTV' + '0' + str(i+1) + '.mp4', threads=8, preset="veryfast", logger=None, audio_codec='aac', rewrite_audio=False, fps=30, bitrate='550k') 133 | time.sleep(1) 134 | bot.send_video(chat_id=chat_id, video = open(temp_dir + '/IGTV' + '0' + str(i+1) + '.mp4', 'rb'), timeout=3600) 135 | igtvPath = temp_dir 136 | shutil.rmtree(temp_dir) 137 | return igtvPath 138 | else: 139 | decoded = '' 140 | return decoded 141 | ########################### Authentication Method (Login) #################################################### 142 | 143 | def auth(url, firefox, button, bot): 144 | if (button == 0): 145 | username = 'pythonauthusr12345' 146 | password = 'instagramauthpass123' 147 | firefox.get("https://www.instagram.com/accounts/login/") 148 | time.sleep(3) 149 | usern = firefox.find_element_by_name("username") 150 | usern.send_keys(username) 151 | passw = firefox.find_element_by_name("password") 152 | passw.send_keys(password) 153 | time.sleep(3) 154 | log_cl = firefox.find_element_by_class_name('sqdOP.L3NKy.y3zKF') 155 | log_cl.click() 156 | time.sleep(4) 157 | title = firefox.title 158 | if (title == "Login • Instagram"): 159 | time.sleep(1) 160 | username = 'pythonauthusr1234' 161 | usern = firefox.find_element_by_name("username") 162 | usern.send_keys(username) 163 | passw = firefox.find_element_by_name("password") 164 | passw.send_keys(password) 165 | time.sleep(3) 166 | log_cl = firefox.find_element_by_class_name('sqdOP.L3NKy.y3zKF') 167 | log_cl.click() 168 | time.sleep(4) 169 | title = firefox.title 170 | if (title == "Login • Instagram"): 171 | time.sleep(1) 172 | username = 'pythonauthusr123456' 173 | usern = firefox.find_element_by_name("username") 174 | usern.send_keys(username) 175 | passw = firefox.find_element_by_name("password") 176 | passw.send_keys(password) 177 | time.sleep(1) 178 | log_cl = firefox.find_element_by_class_name('sqdOP.L3NKy.y3zKF') 179 | log_cl.click() 180 | time.sleep(4) 181 | title = firefox.title 182 | if (title == "Login • Instagram"): 183 | firefox.quit() 184 | return False 185 | else: 186 | return True 187 | 188 | else: 189 | return True 190 | elif(button > 0): 191 | title = firefox.title 192 | if (title != "Login • Instagram"): 193 | return True 194 | else: 195 | username = 'pythonauthusr12345' 196 | password = 'instagramauthpass123' 197 | firefox.get("https://www.instagram.com/accounts/login/") 198 | time.sleep(3) 199 | usern = firefox.find_element_by_name("username") 200 | usern.send_keys(username) 201 | passw = firefox.find_element_by_name("password") 202 | passw.send_keys(password) 203 | time.sleep(3) 204 | log_cl = firefox.find_element_by_class_name('sqdOP.L3NKy.y3zKF') 205 | log_cl.click() 206 | time.sleep(4) 207 | title = firefox.title 208 | if (title == "Login • Instagram"): 209 | time.sleep(1) 210 | username = 'pythonauthusr1234' 211 | usern = firefox.find_element_by_name("username") 212 | usern.send_keys(username) 213 | passw = firefox.find_element_by_name("password") 214 | passw.send_keys(password) 215 | time.sleep(3) 216 | log_cl = firefox.find_element_by_class_name('sqdOP.L3NKy.y3zKF') 217 | log_cl.click() 218 | time.sleep(4) 219 | title = firefox.title 220 | if (title == "Login • Instagram"): 221 | time.sleep(1) 222 | username = 'pythonauthusr123456' 223 | usern = firefox.find_element_by_name("username") 224 | usern.send_keys(username) 225 | passw = firefox.find_element_by_name("password") 226 | passw.send_keys(password) 227 | time.sleep(1) 228 | log_cl = firefox.find_element_by_class_name('sqdOP.L3NKy.y3zKF') 229 | log_cl.click() 230 | time.sleep(4) 231 | title = firefox.title 232 | if (title == "Login • Instagram"): 233 | firefox.quit() 234 | return False 235 | --------------------------------------------------------------------------------