import os import discord from dotenv import load_dotenv import re import requests from bs4 import BeautifulSoup import logging import rss_gen from urlencode import urlencode ########################################## #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) ########################################## #Discord ID resource bot_id = 1094991519812956270 fiery_eagle_id = 345153972765720577 dodi_id = 468866369782415360 torrent_link_channel_id = 862039084683624468 new_release_tag_channel = 918559776269553756 ########################################## load_dotenv() TOKEN = os.getenv('DISCORD_TOKEN') if not TOKEN: raise RuntimeError("DISCORD_TOKEN not set") pixelget_token = os.getenv('PIXELGET_TOKEN') copyparty_token = os.getenv('COPYPARTY_TOKEN') #Bot intents intents = discord.Intents.none() intents.messages = True intents.message_content = True intents.guilds = True bot = discord.Bot(intents=intents) def pixelget(url: str): response = requests.get(url, timeout=10) 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": (f":{pixelget_token}")}, timeout=10) with open(title, "wb") as f: f.write(response.content) def dayuploads_get(url: str): request = requests.get(url, timeout=10) soup = BeautifulSoup(request.content, 'html.parser') title = soup.find_all('p', class_="mb-0 text-ellipsis")[0].text try: assert ".torrent" in title.lower() except AssertionError: print("Link was not a torrent") else: download_url = soup.find_all('a', class_="download-link")[0]["href"] torrent_file = requests.get(download_url, timeout=10) 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=("torbot",copyparty_token)) if not (200 <= response.status_code < 300): logging.error(f'Error uploading file {file_name}. Status code: {response.status_code}') # noqa: E501 def url_regex(inp: str) -> str: if "pixeldrain.com" in inp.lower(): cleaned = regmatch(inp, r'https?.:\/\/pixeldrain.com\/u\/.{8}$') pixelget(cleaned) logger.debug(cleaned) if "dayuploads.com" in inp.lower(): cleaned = regmatch(inp, r'https?.:\/\/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 if not regmatch: return None return regmatch def files_to_upload(dir: str) -> list: files = os.listdir(dir) return [i for i in files if i.lower().endswith(".torrent")] def update_rss_feed(): df = rss_gen.create_df() rss_gen.create_48h_latest(df) rss_gen.create_25_recent_feed(df) logger.info(f'Updated RSS feed') @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 update_rss(ctx): if ctx.user.id == fiery_eagle_id or ctx.user.id == dodi_id: update_rss_feed() await ctx.respond("Sucessfully updated RSS feed") @bot.slash_command() async def upload(ctx): messagechannel = bot.get_channel(torrent_link_channel_id) if ctx.user.id == fiery_eagle_id or ctx.user.id == dodi_id: 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"{os.path.splitext(i)[0]}\nhttps://torfiles.fieryeagle.org/{urlencode(i)}") os.remove(i) await ctx.respond(f"Sucessfully uploaded {files}") @bot.slash_command() async def manual_upload(ctx, file_url: str): if ctx.user.id == fiery_eagle_id or ctx.user.id == dodi_id: url_regex(file_url) files = files_to_upload('.') for i in files: try: uploadfile(i) except AssertionError: logger.error("Upload failed, quitting...") return else: await ctx.respond(f"Sucessfully processed {file_url}") os.remove(i) logger.info(f"Manually uploaded file {i}") update_rss_feed() @bot.event async def on_message(message): user_message = str(message.content) if message.author.id == bot_id: return messagechannel = bot.get_channel(torrent_link_channel_id) logger.debug(f"{user_message}") if ("http" in user_message and (message.channel.id == new_release_tag_channel or message.author.id == fiery_eagle_id)): links = user_message.replace("\n", " ") links = links.split(" ") for i in links: url_regex(i) files = files_to_upload('.') for i in files: try: uploadfile(i) except AssertionError: logger.error("Upload failed, quitting...") return else: await messagechannel.send(f"{i[:-8]}\nhttps://torfiles.fieryeagle.org/{urlencode(i)}") os.remove(i) # noqa: E501 logger.info(f"Posted link for {i}") update_rss_feed() return await bot.process_commands(message) def main(): bot.run(TOKEN) if __name__ == '__main__': main()