0% found this document useful (0 votes)
79 views3 pages

Robo de Videos Do Youtube Programado em Python para Telegram

The document is a Python script for a Telegram bot that allows users to search for and download videos. It includes functions for handling user commands, sending messages, and processing inline queries to display video options. The bot interacts with a video API and manages video downloads while providing user assistance and error handling.

Uploaded by

Nicolas Bressy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
79 views3 pages

Robo de Videos Do Youtube Programado em Python para Telegram

The document is a Python script for a Telegram bot that allows users to search for and download videos. It includes functions for handling user commands, sending messages, and processing inline queries to display video options. The bot interacts with a video API and manages video downloads while providing user assistance and error handling.

Uploaded by

Nicolas Bressy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd

import requests

import time
import json
import sys
import re
import os

def load_token():
try:
with open('tokenbot.json', 'r') as f:
data = json.load(f)
return data['token']
except (FileNotFoundError, json.JSONDecodeError):
sys.exit(1)

TOKEN = load_token()
BASE_URL = f"https://api.telegram.org/bot{TOKEN}"

def send_message(chat_id, text):


url = f"{BASE_URL}/sendMessage"
payload = {'chat_id': chat_id, 'text': text}
return requests.post(url, json=payload)

def answer_inline_query(query_id, results):


url = f"{BASE_URL}/answerInlineQuery"
payload = {'inline_query_id': query_id, 'results': json.dumps(results)}
return requests.post(url, json=payload)

def send_video_buttons(chat_id, video_choices):


button_list = [[{'text': video['name'], 'callback_data': video['url']}] for
video in video_choices]
reply_markup = {'inline_keyboard': button_list}
url = f"{BASE_URL}/sendMessage"
payload = {'chat_id': chat_id, 'text': "Escolha um vídeo para assistir:",
'reply_markup': json.dumps(reply_markup)}
return requests.post(url, json=payload)

def search_videos(query):
url = f"https://riitube.rc24.xyz/wiimc/?q={query}"
try:
response = requests.get(url)
if response.status_code == 200:
lines = response.text.split("\n")
results = []
for i in range(1, len(lines), 2):
try:
thumbnail_url = lines[i].split('"')[1]
video_name = lines[i].split(",")[1].strip().replace('"', '')
video_url = lines[i + 1].strip()
results.append({'thumbnail': thumbnail_url, 'name': video_name,
'url': video_url})
except IndexError:
continue
return results
return []
except requests.exceptions.RequestException:
return []

def handle_update(update):
if 'inline_query' in update:
query_id = update['inline_query']['id']
query = update['inline_query']['query']
if query:
formatted_query = query.replace(' ', '+')
results = search_videos(formatted_query)
inline_results = [{'type': 'article', 'id': str(index), 'title':
video['name'], 'input_message_content': {'message_text': video['name']},
'thumb_url': video['thumbnail'], 'url': video['url']} for index, video in
enumerate(results)]
answer_inline_query(query_id, inline_results)
elif 'message' in update:
chat_id = update['message']['chat']['id']
text = update['message']['text']
if text == "/start":
handle_start_command(chat_id)
elif text == "/help":
handle_help_command(chat_id)
elif text.startswith("/search"):
query = text.replace("/search", "").strip()
if query:
formatted_query = query.replace(' ', '+')
results = search_videos(formatted_query)
if results:
send_video_buttons(chat_id, results)
else:
send_message(chat_id, "Nenhum vídeo encontrado.")
else:
send_message(chat_id, "Por favor, forneça um termo de pesquisa.")
else:
send_message(chat_id, "Comando não reconhecido.")

def handle_start_command(chat_id):
welcome_message = ("Olá! Eu sou o VideoTubeBot.\n\nVocê pode me usar para
procurar vídeos. Para buscar vídeos, use o comando /search seguido do termo que
deseja procurar.\nPor exemplo: /search gatos engraçados.\n\nSe precisar de ajuda,
use /help.")
send_message(chat_id, welcome_message)

def handle_help_command(chat_id):
help_message = ("Aqui estão os comandos disponíveis:\n\n/start - Inicia o bot e
exibe uma mensagem de boas-vindas.\n/search [termo] - Procura vídeos com o termo
fornecido.\n/help - Exibe essa mensagem de ajuda.")
send_message(chat_id, help_message)

def handle_video_choice(update):
chat_id = update['callback_query']['message']['chat']['id']
video_url = update['callback_query']['data']
video_name = update['callback_query']['message']['text']
sanitized_video_name = sanitize_filename(video_name)
video_path = download_video(video_url, sanitized_video_name)
if video_path:
send_video(chat_id, video_path, sanitized_video_name)
else:
send_message(chat_id, "Erro ao baixar o vídeo.")

def sanitize_filename(filename):
return re.sub(r'[<>:"/\\|?*]', '_', filename)
def download_video(url, sanitized_video_name):
try:
response = requests.get(url, stream=True)
if response.status_code == 200:
video_path = f"{sanitized_video_name}.mp4"
with open(video_path, 'wb') as file:
for chunk in response.iter_content(chunk_size=8192):
file.write(chunk)
return video_path
return None
except requests.exceptions.RequestException:
return None

def send_video(chat_id, video_path, video_name):


url = f"{BASE_URL}/sendVideo"
try:
with open(video_path, 'rb') as video_file:
caption = f"{video_name}\nAproveite o vídeo!"
payload = {'chat_id': chat_id, 'caption': caption}
files = {'video': video_file}
response = requests.post(url, data=payload, files=files)
os.remove(video_path)
return response
except Exception:
return None

def get_updates(offset=None):
url = f"{BASE_URL}/getUpdates"
params = {'offset': offset, 'timeout': 100}
response = requests.get(url, params=params)
return response.json()

def shutdown_bot():
print("\033[91mBOT DESLIGADO ATÉ A PRÓXIMA\033[0m")
sys.exit(0)

def run_bot():
offset = None
while True:
try:
updates = get_updates(offset)
if 'result' in updates and updates['result']:
for update in updates['result']:
offset = update['update_id'] + 1
handle_update(update)
if 'callback_query' in update:
handle_video_choice(update)
except KeyboardInterrupt:
shutdown_bot()
except Exception as e:
print("Erro no bot:", e)
time.sleep(1)

if __name__ == "__main__":
run_bot()

You might also like