Rework: Rework memes and audio

This commit is contained in:
Marco Thomas
2021-05-24 14:10:31 +02:00
parent b506fba338
commit d58f901cda
7 changed files with 85 additions and 73 deletions

View File

@@ -1,11 +1,10 @@
FROM python:3.8-alpine FROM python:3.9
WORKDIR /data WORKDIR /data
COPY . /data COPY . /data
RUN apk add gcc libc-dev libffi-dev make \ RUN apt update && apt install -y ffmpeg libopus0 opus-tools \
&& python3 -m pip install -r requirements.txt \ && python3 -m pip install -r requirements.txt
&& apk del gcc libc-dev
ENV PREFIX /data ENV PREFIX /data
ENV TOKEN /data ENV TOKEN /data
@@ -13,4 +12,4 @@ ENV REDDIT_CLIENT_ID /data
ENV REDDIT_CLIENT_SECRET /data ENV REDDIT_CLIENT_SECRET /data
ENV REDDIT_CLIENT_USERAGENT /data ENV REDDIT_CLIENT_USERAGENT /data
CMD [ "python3", "./aquabot.py" ] CMD [ "python3", "./aquabot.py" ]

View File

@@ -2,8 +2,8 @@
Admin commands, that can be used within the Discord Client Admin commands, that can be used within the Discord Client
""" """
import discord
from discord.ext import commands from discord.ext import commands
import discord
class Admin(commands.Cog): class Admin(commands.Cog):
def __init__(self, bot): def __init__(self, bot):

View File

@@ -1,13 +1,13 @@
""" """
Play some audio samples Play some audio clips
""" """
import discord from asyncio import Lock
from discord.ext import commands
from discord import FFmpegPCMAudio from discord import FFmpegPCMAudio
from discord import VoiceClient, VoiceChannel from discord import VoiceClient, VoiceChannel
from discord.ext import commands
import asyncio import asyncio
from asyncio import Lock import discord
import youtube_dl import youtube_dl
@@ -18,9 +18,11 @@ class Player:
await self.__class__.lock.acquire() await self.__class__.lock.acquire()
return self return self
async def __aexit__(self, exc_type, exc_val, exc_tb): async def __aexit__(self, exc_type, exc_val, exc_tb):
self.__class__.lock.release() self.__class__.lock.release()
@staticmethod @staticmethod
async def connect(bot, voice_channel): async def connect(bot, voice_channel):
""" """
@@ -38,10 +40,12 @@ class Player:
await asyncio.sleep(0.3) await asyncio.sleep(0.3)
return vc return vc
@staticmethod @staticmethod
async def disconnect(vc): async def disconnect(vc):
await vc.disconnect() await vc.disconnect()
@staticmethod @staticmethod
async def play(vc, audio_source): async def play(vc, audio_source):
vc.play(audio_source) vc.play(audio_source)
@@ -53,17 +57,20 @@ class Audio(commands.Cog):
def __init__(self, bot): def __init__(self, bot):
self.bot = bot self.bot = bot
def parse(self, query): def parse(self, query):
""" """
Parse a request into an uri Parse a request into an uri
""" """
memes = {"schokobons": "https://www.youtube.com/watch?v=qX7V3EVr1BA", # TODO: maybe put this into a db?
clips = {"schokobons": "https://www.youtube.com/watch?v=qX7V3EVr1BA",
"raus": "https://youtu.be/_e1cWuQ8WQw"} "raus": "https://youtu.be/_e1cWuQ8WQw"}
try: try:
return memes[query] return clips[query]
except KeyError as e: except KeyError:
return None return None
@commands.command(name="dc") @commands.command(name="dc")
async def disconnect(self, ctx): async def disconnect(self, ctx):
""" """
@@ -71,6 +78,7 @@ class Audio(commands.Cog):
""" """
await Player.disconnect(self.bot.voice_clients[0]) await Player.disconnect(self.bot.voice_clients[0])
@commands.command(name="play") @commands.command(name="play")
async def play(self, ctx, query): async def play(self, ctx, query):
""" """
@@ -89,9 +97,7 @@ class Audio(commands.Cog):
} }
uri = self.parse(query) uri = self.parse(query)
if uri is None: if uri:
await ctx.send("Clip not found!")
else:
with youtube_dl.YoutubeDL(ydl_opts) as ydl: with youtube_dl.YoutubeDL(ydl_opts) as ydl:
song_info = ydl.extract_info(uri, download=False) song_info = ydl.extract_info(uri, download=False)
audio_stream = song_info["formats"][0]["url"] audio_stream = song_info["formats"][0]["url"]
@@ -101,6 +107,8 @@ class Audio(commands.Cog):
vc = await player.connect(self.bot, ctx.author.voice.channel) vc = await player.connect(self.bot, ctx.author.voice.channel)
await player.play(vc, audio_source) await player.play(vc, audio_source)
await ctx.send(f"Playing: {uri}") await ctx.send(f"Playing: {uri}")
else:
await ctx.send(f"Clip '{query}' not found")
def setup(bot): def setup(bot):

View File

@@ -28,17 +28,7 @@ class Jikan(commands.Cog):
search = jikan.search("anime", query) search = jikan.search("anime", query)
results = search.get("results") results = search.get("results")
#await ctx.send("Which one of these do you mean?") top = results[0] # get top result
#anime_list = ""
#for i in range(5):
# anime_list += f'{i+1}: {results[i].get("title")}\n'
#await ctx.send(anime_list)
#reply = await commands.wait_for('message', timeout=30.0)
#top = results[reply+1]
top = results[0]
embed = discord.Embed(colour=discord.Colour.blue()) embed = discord.Embed(colour=discord.Colour.blue())
embed.set_thumbnail(url=top.get("image_url")) embed.set_thumbnail(url=top.get("image_url"))

View File

@@ -1,41 +1,46 @@
""" """
Send spicy memes to chat Send memes to chat
""" """
import discord
from discord.ext import commands from discord.ext import commands
import discord
import random import random
import memes import memes
class Meme(commands.Cog): class Meme(commands.Cog):
def __init__(self, bot): def __init__(self, bot):
self.bot = bot self.bot = bot
@staticmethod
def parse(query):
"""
Parse a request
"""
try:
to_choose = memes.memes[query.capitalize()]
return random.choice(to_choose)
except KeyError:
return None
@commands.command(name="meme") @commands.command(name="meme")
async def meme(self, ctx, meme: str): async def meme(self, ctx, query: str):
""" """
Sends a spicy meme to the chat Sends a meme
- marc
- cenk
- olli
""" """
query = meme.capitalize() meme = self.parse(query)
if meme:
if query == "List": await ctx.send(meme)
meme_list = ""
for key in memes.__memes_list__.keys():
if not meme_list:
meme_list = meme_list + key
else:
meme_list = meme_list + ", " + key
await ctx.send(f"Currently listed memes: `{meme_list}`")
else: else:
try: await ctx.send(f"Meme '{query}' not found")
meme = random.choice(memes.__memes_list__[query])
await ctx.send(meme)
except KeyError as e:
await ctx.send("Meme not found in database")
def setup(bot): def setup(bot):
bot.add_cog(Meme(bot)) bot.add_cog(Meme(bot))
q

View File

@@ -2,20 +2,42 @@
Fetch pictures from subreddits Fetch pictures from subreddits
""" """
import discord
from discord.ext import commands from discord.ext import commands
import random import discord
import praw import praw
import random
from __main__ import REDDIT_CLIENT_ID from __main__ import REDDIT_CLIENT_ID
from __main__ import REDDIT_CLIENT_SECRET from __main__ import REDDIT_CLIENT_SECRET
from __main__ import REDDIT_CLIENT_USERAGENT from __main__ import REDDIT_CLIENT_USERAGENT
class Reddit(commands.Cog): class Reddit(commands.Cog):
def __init__(self, bot): def __init__(self, bot):
self.bot = bot self.bot = bot
@staticmethod
def find_post(posts):
rand_post = random.randint(1, 100)
# Make sure you're not sending a pinned post
for i in range(0, rand_post):
submission = next(post for post in posts if not post.stickied)
return submission
async def output(self, ctx, submission):
output = f"'{submission.title}' by {submission.author.name} - 🔼 {submission.score}"
if submission.over_18:
if not ctx.channel.is_nsfw():
await ctx.send("The post is marked as NSFW, but your channel isn't!")
return
else:
output = f"❗ NSFW ❗ " + output
await ctx.send(output)
await ctx.send(submission.url)
@commands.command(name="reddit") @commands.command(name="reddit")
async def reddit(self, ctx, sub: str, sorting="hot", time_filter="all"): async def reddit(self, ctx, sub: str, sorting="hot", time_filter="all"):
""" """
@@ -23,12 +45,13 @@ class Reddit(commands.Cog):
""" """
reddit = praw.Reddit(client_id=REDDIT_CLIENT_ID, reddit = praw.Reddit(client_id=REDDIT_CLIENT_ID,
client_secret=REDDIT_CLIENT_SECRET, client_secret=REDDIT_CLIENT_SECRET,
user_agent=REDDIT_CLIENT_USERAGENT) user_agent=REDDIT_CLIENT_USERAGENT,
check_for_async=False)
try: try:
reddit.subreddits.search_by_name(sub, exact=True) reddit.subreddits.search_by_name(sub, exact=True)
except: except:
await ctx.send(f"Subreddit {sub} not found!") await ctx.send(f"Subreddit '{sub}' not found!")
if sorting == "hot": if sorting == "hot":
posts = reddit.subreddit(sub).hot() posts = reddit.subreddit(sub).hot()
@@ -38,21 +61,11 @@ class Reddit(commands.Cog):
posts = reddit.subreddit(sub).new() posts = reddit.subreddit(sub).new()
else: else:
await ctx.send(f"Invalid Argument: {sorting}") await ctx.send(f"Invalid Argument: {sorting}")
return
rand_post = random.randint(1, 100) await ctx.trigger_typing()
# Make sure you're not sending a pinned post submission = self.find_post(posts)
for i in range(0, rand_post): await self.output(ctx, submission)
submission = next(x for x in posts if not x.stickied)
if submission.over_18 and not ctx.channel.is_nsfw():
await ctx.send("The post is marked as NSFW, but your text channel isn't!")
else:
text = ""
if submission.over_18:
text += "❗ NSFW ❗"
text += f"'{submission.title}' by {submission.author.name} - 🔼 {submission.score}"
await ctx.send(text)
await ctx.send(submission.url)
def setup(bot): def setup(bot):

View File

@@ -1,4 +1,3 @@
# Meme list
olli = [ olli = [
"https://i.imgur.com/t11G5nZ.jpg", "https://i.imgur.com/t11G5nZ.jpg",
"https://i.imgur.com/jFx5Jjp.jpg", "https://i.imgur.com/jFx5Jjp.jpg",
@@ -60,10 +59,8 @@ marc = [
"https://cdn.discordapp.com/attachments/541641216110886932/626153093226299411/MaddlsticksTransparent.png" "https://cdn.discordapp.com/attachments/541641216110886932/626153093226299411/MaddlsticksTransparent.png"
] ]
# Exports memes = {
"Olli": olli,
__memes_list__ = { "Cenk": cenk,
"Olli": olli, "Marc": marc
"Cenk": cenk, }
"Marc": marc
}