157 lines
5.2 KiB
Python
157 lines
5.2 KiB
Python
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)
|
|
##########################################
|
|
|
|
load_dotenv()
|
|
TOKEN = os.getenv('DISCORD_TOKEN')
|
|
pixelget_token = os.getenv('PIXELGET_TOKEN')
|
|
copyparty_token = os.getenv('COPYPARTY_TOKEN')
|
|
nextcloud_token = os.getenv('NEXTCLOUD_TOKEN')
|
|
|
|
#Bot intents
|
|
intents = discord.Intents.default()
|
|
intents.messages = True
|
|
intents.message_content = True
|
|
bot = discord.Bot(intents=intents)
|
|
|
|
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": (f":{pixelget_token}")})
|
|
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 = 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)
|
|
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))
|
|
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):
|
|
if ctx.user.id == 345153972765720577 or ctx.user.id == 468866369782415360:
|
|
df = rss_gen.create_df()
|
|
rss_gen.create_48h_latest(df)
|
|
rss_gen.create_25_recent_feed(df)
|
|
await ctx.respond(f"Sucessfully uploaded updated RSS feed")
|
|
|
|
@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 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}")
|
|
df = rss_gen.create_df()
|
|
rss_gen.create_48h_latest(df)
|
|
rss_gen.create_25_recent_feed(df)
|
|
return
|
|
|
|
def main():
|
|
bot.run(TOKEN)
|
|
|
|
if __name__ == '__main__':
|
|
main() |