Files
stroopwafel/General.py
T

164 lines
5.4 KiB
Python

import asyncio
import discord
import sys, os
import praw
import random
import re
import json, requests
from discord.ext import commands
from sympy import latex, symbols, preview, Symbol #for LaTeX images
import youtube_dl
import ffmpeg
class General(commands.Cog):
"""Overal toegestaan."""
def __init__(self, bot):
self.bot = bot
self.voice_states = {}
self.r = praw.Reddit(
user_agent='StroopwafelBot',
client_secret=self.bot.tokens["redditSecret"],
client_id=self.bot.tokens["redditId"]
)
self.r.read_only = True
def __check(self, ctx): #Todo: Is dit het porno kanaal?
return True
@commands.command()
@asyncio.coroutine
def huge(self, ctx, *, arg):
"""YUGE. Geeft een grote versie van de gegeven emoji terug. Werkt alleen voor custom emoji.
Bijvoorbeeld:
!huge :ancilla:
"""
id = re.search("\<\:([A-z]*)\:(\d*)\>", arg)
hugemoji = 'https://cdn.discordapp.com/emojis/' + id.group(2) + '.png'
em = discord.Embed(title=id.group(1), type='photo')
em.set_image(url=hugemoji)
try:
yield from ctx.message.delete()
except:
print("No permission to delete message")
yield from ctx.channel.send(ctx.author.mention, embed=em)
@commands.command()
@asyncio.coroutine
def tex(self, ctx, *, arg):
"""Geeft een mooi LaTeX plaatje terug.
Bijvoorbeeld:
!tex Je moeder is lelijk! $a^b b^c \\rightarrow d$
"""
preamble = "\\documentclass[10pt]{article}\\pagestyle{empty}\\usepackage[margin=1in]{geometry}\\usepackage{amsmath, amsfonts}\\begin{document}" #\\usepackage{CJKutf8}\\usepackage[T1]{fontenc}\\usepackage[english]{babel}
options = ["-T", "tight", "-z", "9", "--truecolor", "-D", "512"]
preview(r''+arg+'', viewer='file', filename='test.png', dvioptions=options, preamble=preamble)
#file = open('test.png', 'rb')
#yield from ctx.channel.send(file, filename ='test.png', content='')
try:
yield from ctx.message.delete()
except:
print("No permission to delete message")
yield from ctx.channel.send(ctx.author.mention, file=discord.File('test.png', 'tex.png'))
@commands.command(pass_context=True)
@asyncio.coroutine
def aww(self, ctx):
""" iets schattigs... """
print(type(ctx.message.channel))
raww = self.r.subreddit('aww+catloaf+tuckedinkitties+babyelephantgifs+babybigcatgifs+blep+holdmynip+gingerkitty+cathighfive+catsstandingup+catsareassholes+eyebleach')
post = raww.top('month', limit=250)
listing = list(post)
random.shuffle(listing)
post = listing[0]
try:
yield from ctx.message.delete()
except:
print("No permission to delete message")
yield from ctx.channel.send(ctx.author.mention + ' ' + post.url)
@commands.command(pass_context=True)
@asyncio.coroutine
def kopieerpasta(self, ctx):
"""Een willekeurige shitpost"""
rkopieerpasta = self.r.subreddit('kopieerpasta')
post = rkopieerpasta.random()
# Subreddits kunnen de random functie uitzetten, dus dit is de fallback:
if post == None:
post = rkopieerpasta.top('month', limit=250)
listing = list(post)
random.shuffle(listing)
post = listing[0]
try:
yield from ctx.message.delete()
except:
print("No permission to delete message")
# Er is een 2000 karakter limiet wat met sommige pastas overschreden kan worden.
# eigenlijk willen we het dan opnieuw proberen maar dat is lastiger, dus maar gewoon berichtje.
if (len(post.selftext)+len(post.title)) >= 1990:
yield from ctx.channel.send('Sorry, kopieerpasta te lang. Probeer het maar opnieuw .')
else:
yield from ctx.channel.send('**'+post.title+'**```'+post.selftext+'```')
@commands.command(pass_context=True)
@asyncio.coroutine
def gif(self, ctx, yt: str, start: str="0", duration: str="5", res: str="320", fps: int=10):
""" Giffify.
Syntax: !gif [YT] [START] [DUUR] [RESOLUTIE] [FPS]
Bv: !gif RPxvTd_jCPQ 10 5 320 10
Alleen de Youtube ID is nodig.
Start en duur zijn in seconden.
Resolutie is de breedte
"""
try:
yield from ctx.message.delete()
except:
print("No permission to delete message")
try:
os.remove('temp')
except:
pass
ydl_opts = {
'outtmpl': 'temp',
'format': 'bestvideo[ext=mp4]/mp4'
}
with youtube_dl.YoutubeDL(ydl_opts) as ydl:
ydl.download([yt])
split = ffmpeg.input('temp').trim(start=start, duration=duration).filter_('fps',fps=fps).filter_('scale', w=res, h=-1).filter_multi_output('split')
pal = split.stream(0).filter_('palettegen')
inputs = {
'v1':split.stream(1),
'v2':pal
}
gif = (
ffmpeg
.filter(stream_spec=[split.stream(1), pal], filter_name='paletteuse')
.output('out.gif')
.overwrite_output()
.run()
)
yield from ctx.channel.send(ctx.author.mention + ' hoi ', file=discord.File('out.gif'))
@commands.command(pass_context=True)
@asyncio.coroutine
def playlist(self, ctx):
"""HDcon2021 playlist"""
muzak_url = 'https://hdcon-muzak.herokuapp.com'
data = json.loads(requests.get(muzak_url + '/stroopwafel').content) # als dit faalt yolo no catch
msg = 'Stemmen en nomineren kan hier: {}\n'.format(muzak_url)
msg += '*Er zijn al {} nummers genomineerd*\n'.format(data['stemCount'])
yield from ctx.channel.send(msg)
@commands.command(pass_context=True, hidden=True)
@asyncio.coroutine
def reboot(self, ctx, password=""):
""" Reboot.. """
if password == self.bot.passwords["resetpassword"]:
yield from ctx.channel.send("Rebooting.. brb!")
os.execv(sys.executable, ['python3'] + sys.argv)
else:
yield from ctx.channel.send(ctx.author.mention + " What's the magic word?")