From efca547108c5ab5890f4d882774c32efdd7a3a61 Mon Sep 17 00:00:00 2001 From: FieryEagle Date: Mon, 6 Jan 2025 12:11:18 +0000 Subject: [PATCH] add code --- .gitignore | 2 + DiscordBot.py | 137 ++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 139 insertions(+) create mode 100644 .gitignore create mode 100644 DiscordBot.py diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..66bca12 --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +.env +venv/ diff --git a/DiscordBot.py b/DiscordBot.py new file mode 100644 index 0000000..39d873c --- /dev/null +++ b/DiscordBot.py @@ -0,0 +1,137 @@ +import os +import discord +from dotenv import load_dotenv +import re +import requests +from bs4 import BeautifulSoup +import logging + +########################################## +#Logging +loglevel = logging.INFO +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 file: + response = requests.put(f"https://upload.fieryeagle.org/remote.php/dav/files/admin/torfiles/{file_name}", + file, auth=("admin", "tcbAY-WgBb7-zYm25-QftPn-zKBpR")) + 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: + uploadfile(i) + await messagechannel.send(f"{i[:-8]}\nhttps://torfiles.fieryeagle.org/{urlencode(i)}") + os.remove(i) + logger.info(f"Files to upload are {files}") + # noqa: E501 + logger.info(f"Posted link for {i}") + return + +bot.run(TOKEN)