Last active 1639361745

searchbot.py Raw
1#!/usr/bin/env python3
2import discord
3import asyncio
4import aiohttp
5from urllib.parse import quote_plus, urlencode
6import os.path
7from os import getcwd, chdir
8from urllib.parse import unquote
9from mutagen import File
10import youtube_dl
11client = discord.Client()
12
13if not discord.opus.is_loaded():
14 discord.opus.load_opus("libopus.so.0")
15
16def is_safe_path(basedir, path, follow_symlinks=True):
17 # resolves symbolic links
18 if follow_symlinks:
19 return os.path.realpath(path).startswith(basedir)
20 return os.path.abspath(path).startswith(basedir)
21
22lastresults = []
23player = None
24
25@client.event
26async def on_message(message):
27 global lastresults
28 global player
29 if message.content.startswith("!upload ") and any(role.name == "Uploader" for role in message.author.roles):
30 url, path = message.content[8:].split(" ", 1)
31 opts = {}
32 if path[-2:] == " v":
33 opts["format"] = "bestvideo"
34 opts["outtmpl"] = os.path.join("/var/www/html/", "vid", path[:-2], "%(title)s.%(ext)s")
35 else:
36 opts["postprocessors"] = [{
37 'key': 'FFmpegExtractAudio',
38 'preferredcodec': "mp3",
39 'preferredquality': "5",
40 'nopostoverwrites': False,
41 }]
42 opts["outtmpl"] = os.path.join("/var/www/html/", path, "%(title)s.%(ext)s")
43 if not url or not path:
44 await client.send_message(message.channel, "Usage: !upload <url> <path>")
45 return
46 resp = await client.send_message(message.channel, "On it, just a second")
47 await client.send_typing(message.channel)
48 with youtube_dl.YoutubeDL(opts) as ydl:
49 ydl.download([url])
50 await client.edit_message(resp, "Job done!")
51
52 if message.content.startswith("!search "):
53 with aiohttp.ClientSession() as session:
54 async with session.get("http://tallyall.club/search.php", params={"q": message.content[8:], "json": ""}) as resp:
55 data = await resp.json()
56 if len(data["results"]) < 1:
57 await client.send_message(message.channel, ":sos: No results")
58 return
59 out = ["Search results:"]
60 lastresults = data["results"]
61 numbers = [":one:", ":two:", ":three:", ":four:", ":five:", ":six:", ":seven:", ":eight:"]
62 for n,r in enumerate(data["results"][:8]):
63 out.append("{} **{}** ({})".format(numbers[n], os.path.basename(r),os.path.dirname(r).split("/")[-1]))
64 out.append(":signal_strength: !play <number>")
65 out.append(":arrow_right: Full results at http://tallyall.club/search.php?" + urlencode({"q": message.content[8:]}))
66 await client.send_message(message.channel, "\n".join(out))
67
68 if message.content.startswith("!play "):
69 if player:
70 player.stop()
71 msg = message.content[6:]
72 if msg.isdigit():
73 if int(msg) <= len(lastresults) and int(msg) > 0:
74 msg = lastresults[int(msg)-1]
75 else:
76 await client.send_message(message.channel, "Invalid result number")
77 return
78 path = "/var/www/html/" + unquote(msg.strip().replace("http://tallyall.club/", ""))
79 if is_safe_path("/var/www/html", path) and os.path.isfile(path) and File(path):
80 voice = client.voice_client_in(message.server)
81 if voice:
82 await voice.disconnect()
83 voice = await client.join_voice_channel(client.get_channel("386339345914920980"))
84 player = voice.create_ffmpeg_player(path)
85 player.start()
86 else:
87 await client.send_message(message.channel, "Invalid path")
88
89 if message.content.startswith("!stop"):
90 if player:
91 player.stop()
92 voice = client.voice_client_in(message.server)
93 await voice.disconnect()
94
95 if message.content.startswith("!link "):
96 msg = message.content[6:]
97 if msg.isdigit():
98 if int(msg) <= len(lastresults) and int(msg) > 0:
99 msg = lastresults[int(msg)-1]
100 else:
101 await client.send_message(message.channel, "Invalid result number")
102 return
103 path = "/var/www/html/" + unquote(msg.strip().replace("http://tallyall.club/", ""))
104 if is_safe_path("/var/www/html", path) and os.path.isfile(path):
105 with open(path, "rb") as f:
106 await client.send_file(message.channel, f, filename=os.path.basename(path))
107 else:
108 await client.send_message(message.channel, "Something went wrong")
109
110@client.event
111async def on_ready():
112 print("Logged in as {} ({})".format(client.user.name, client.user.id))
113 print(discord.utils.oauth_url(client.user.id, permissions=discord.Permissions(3197952)))
114
115with open(".bottoken") as f:
116 creds = f.read()
117 if " " in creds:
118 client.run(*creds.split(None, 1))
119 else:
120 client.run(creds.strip())