Files
upload-bot/DiscordBot.py
2025-03-08 17:59:55 +00:00

150 lines
5.4 KiB
Python

import os
import discord
from dotenv import load_dotenv
import re
import requests
from bs4 import BeautifulSoup
import logging
##########################################
#Logging
loglevel = logging.DEBUG
logger = logging.getLogger('Uploadbot')
logger.setLevel(loglevel)
#Console Handler
ch = logging.StreamHandler()
ch.setLevel(loglevel)
#Formatter
formatter = logging.Formatter('[%(asctime)s] [%(levelname)s] %(message)s')
formatter.default_msec_format = None
ch.setFormatter(formatter)
logger.addHandler(ch)
##########################################
load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')
#Bot intents
intents = discord.Intents.default()
intents.messages = True
intents.message_content = True
bot = discord.Bot(intents=intents)
def urlencode(inp: str):
return "".join([i if i in ["~", "-", "_", "."] or i.isalnum() else "%"+str(hex(ord(i))[2:].upper()) for i in inp])
def pixelget(url: str):
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
title = soup.title.string[:-13]
try:
assert ".torrent" in title.lower()
except AssertionError:
logger.warning("Link was not a torrent")
else:
response = requests.get(f'https://pixeldrain.com/api/file/{url.split("/")[-1]}?download', headers={"Authorization": (":bdf70819-9e47-4a3f-861a-41fd448939db")})
with open(title, "wb") as f:
f.write(response.content)
def dayuploads_get(url: str):
request = requests.get(url)
soup = BeautifulSoup(request.content, 'html.parser')
title = str(list(soup.find_all('p', class_="mb-0 text-ellipsis"))[0]).split(">")[1].split('<')[0]
try:
assert ".torrent" in title.lower()
except AssertionError:
logger.warning("Link was not a torrent")
else:
download_url = str(list(soup.find_all('a', class_="download-link"))[0]).split('href="')[1].split('"')[0]
torrent_file = requests.get(download_url)
with open(title, "wb") as file:
file.write(torrent_file.content)
def uploadfile(file_name: str):
with open(file_name, "rb") as torrent_file:
response = requests.put(f"https://upload.fieryeagle.org/torfiles/{file_name}",
torrent_file, auth=("admin","TVcZRYhT5Cd#@eY8P9NxNN2mC"))
try:
assert response.status_code in range(200, 300)
except AssertionError:
logging.error(f'Error uploading file {file_name}. Status code:', response.status_code) # noqa: E501
# with open(file_name, "rb") as file:
# response = requests.put(f"https://cloud.woelkli.com/remote.php/dav/files/ddseed%40tutanota.com/torfiles/{file_name}",
# file, auth=("ddseed@tutanota.com", "hsPBH0S60&DQB6dD.2"))
# try:
# assert response.status_code in range(200, 300)
# except AssertionError:
# logging.error(f'Error uploading file {file_name}. Status code:', response.status_code) # noqa: E501
def regex(inp: str) -> str:
if "pixeldrain.com" in inp.lower():
cleaned = regmatch(inp, r'http?.://pixeldrain.com/u/.{8}$')
pixelget(cleaned)
logger.debug(cleaned)
if "dayuploads.com" in inp.lower():
cleaned = regmatch(inp, r'http?.://dayuploads.com/.*/file')
dayuploads_get(cleaned)
logger.debug(cleaned)
def regmatch(inp: str, pattern: str) -> list:
regmatch = re.search(pattern, inp).group(0) # noqa: E501
return regmatch
def files_to_upload(dir: str) -> list:
files = os.listdir(dir)
return [i for i in files if os.path.splitext(i)[1] == ".torrent" in i]
@bot.event
async def on_ready():
logger.info(f'{bot.user} has connected to Discord!')
logger.info(f"Websocket latency is {bot.latency*1000} ms")
@bot.slash_command()
async def upload(ctx):
messagechannel = bot.get_channel(862039084683624468)
if ctx.user.id == 345153972765720577 or ctx.user.id == 468866369782415360:
files = files_to_upload(".")
try:
assert len(files) > 0
except AssertionError:
await ctx.respond("Tried to upload 0 files")
else:
for i in files:
uploadfile(i)
await messagechannel.send(f"{i[:-8]}\nhttps://torfiles.fieryeagle.org/{urlencode(i)}")
os.remove(i)
await ctx.respond(f"Sucessfully uploaded {files}")
@bot.event
async def on_message(message):
user_message = str(message.content)
if message.author.id == 1094991519812956270:
return
messagechannel = bot.get_channel(862039084683624468)
logger.debug(f"{user_message}")
if ("http" in user_message and (message.channel.id == 918559776269553756 or message.author.id == 345153972765720577)): #and 1081399528265089125 in [roles.id for roles in username.roles]) # noqa: E501
links = user_message.replace("\n", " ")
links = links.split(" ")
for i in links:
regex(i)
files = files_to_upload('.')
for i in files:
try:
uploadfile(i)
except AssertationError:
logger.error("Upload failed, quitting...")
return
else:
await messagechannel.send(f"{i[:-8]}\nhttps://torfiles.fieryeagle.org/{urlencode(i)}")
# await messagechannel.send(f"{i[:-8]}\nhttps://torfiles.ddseed.cf/{urlencode(i)}")
os.remove(i)
# noqa: E501
logger.info(f"Posted link for {i}")
return
bot.run(TOKEN)