searchbot.py
· 4.8 KiB · Python
Raw
#!/usr/bin/env python3
import discord
import asyncio
import aiohttp
from urllib.parse import quote_plus, urlencode
import os.path
from os import getcwd, chdir
from urllib.parse import unquote
from mutagen import File
import youtube_dl
client = discord.Client()
if not discord.opus.is_loaded():
discord.opus.load_opus("libopus.so.0")
def is_safe_path(basedir, path, follow_symlinks=True):
# resolves symbolic links
if follow_symlinks:
return os.path.realpath(path).startswith(basedir)
return os.path.abspath(path).startswith(basedir)
lastresults = []
player = None
@client.event
async def on_message(message):
global lastresults
global player
if message.content.startswith("!upload ") and any(role.name == "Uploader" for role in message.author.roles):
url, path = message.content[8:].split(" ", 1)
opts = {}
if path[-2:] == " v":
opts["format"] = "bestvideo"
opts["outtmpl"] = os.path.join("/var/www/html/", "vid", path[:-2], "%(title)s.%(ext)s")
else:
opts["postprocessors"] = [{
'key': 'FFmpegExtractAudio',
'preferredcodec': "mp3",
'preferredquality': "5",
'nopostoverwrites': False,
}]
opts["outtmpl"] = os.path.join("/var/www/html/", path, "%(title)s.%(ext)s")
if not url or not path:
await client.send_message(message.channel, "Usage: !upload <url> <path>")
return
resp = await client.send_message(message.channel, "On it, just a second")
await client.send_typing(message.channel)
with youtube_dl.YoutubeDL(opts) as ydl:
ydl.download([url])
await client.edit_message(resp, "Job done!")
if message.content.startswith("!search "):
with aiohttp.ClientSession() as session:
async with session.get("http://tallyall.club/search.php", params={"q": message.content[8:], "json": ""}) as resp:
data = await resp.json()
if len(data["results"]) < 1:
await client.send_message(message.channel, ":sos: No results")
return
out = ["Search results:"]
lastresults = data["results"]
numbers = [":one:", ":two:", ":three:", ":four:", ":five:", ":six:", ":seven:", ":eight:"]
for n,r in enumerate(data["results"][:8]):
out.append("{} **{}** ({})".format(numbers[n], os.path.basename(r),os.path.dirname(r).split("/")[-1]))
out.append(":signal_strength: !play <number>")
out.append(":arrow_right: Full results at http://tallyall.club/search.php?" + urlencode({"q": message.content[8:]}))
await client.send_message(message.channel, "\n".join(out))
if message.content.startswith("!play "):
if player:
player.stop()
msg = message.content[6:]
if msg.isdigit():
if int(msg) <= len(lastresults) and int(msg) > 0:
msg = lastresults[int(msg)-1]
else:
await client.send_message(message.channel, "Invalid result number")
return
path = "/var/www/html/" + unquote(msg.strip().replace("http://tallyall.club/", ""))
if is_safe_path("/var/www/html", path) and os.path.isfile(path) and File(path):
voice = client.voice_client_in(message.server)
if voice:
await voice.disconnect()
voice = await client.join_voice_channel(client.get_channel("386339345914920980"))
player = voice.create_ffmpeg_player(path)
player.start()
else:
await client.send_message(message.channel, "Invalid path")
if message.content.startswith("!stop"):
if player:
player.stop()
voice = client.voice_client_in(message.server)
await voice.disconnect()
if message.content.startswith("!link "):
msg = message.content[6:]
if msg.isdigit():
if int(msg) <= len(lastresults) and int(msg) > 0:
msg = lastresults[int(msg)-1]
else:
await client.send_message(message.channel, "Invalid result number")
return
path = "/var/www/html/" + unquote(msg.strip().replace("http://tallyall.club/", ""))
if is_safe_path("/var/www/html", path) and os.path.isfile(path):
with open(path, "rb") as f:
await client.send_file(message.channel, f, filename=os.path.basename(path))
else:
await client.send_message(message.channel, "Something went wrong")
@client.event
async def on_ready():
print("Logged in as {} ({})".format(client.user.name, client.user.id))
print(discord.utils.oauth_url(client.user.id, permissions=discord.Permissions(3197952)))
with open(".bottoken") as f:
creds = f.read()
if " " in creds:
client.run(*creds.split(None, 1))
else:
client.run(creds.strip())
| 1 | #!/usr/bin/env python3 |
| 2 | import discord |
| 3 | import asyncio |
| 4 | import aiohttp |
| 5 | from urllib.parse import quote_plus, urlencode |
| 6 | import os.path |
| 7 | from os import getcwd, chdir |
| 8 | from urllib.parse import unquote |
| 9 | from mutagen import File |
| 10 | import youtube_dl |
| 11 | client = discord.Client() |
| 12 | |
| 13 | if not discord.opus.is_loaded(): |
| 14 | discord.opus.load_opus("libopus.so.0") |
| 15 | |
| 16 | def 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 | |
| 22 | lastresults = [] |
| 23 | player = None |
| 24 | |
| 25 | @client.event |
| 26 | async 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 |
| 111 | async 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 | |
| 115 | with 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()) |