Fully converted to slash commands

This commit is contained in:
NikolajDanger
2021-03-31 00:38:51 +02:00
parent a8a7e5eabd
commit b345720468
50 changed files with 1102 additions and 1111 deletions

View File

@ -1,8 +1,5 @@
"""Misc. functions for Gwendolyn."""
__all__ = ["Generators", "movieFunc","BedreNetflix","NerdShit"]
__all__ = ["Other"]
from .bedreNetflix import BedreNetflix
from .generators import Generators
from .movie import movieFunc
from .nerdShit import NerdShit
from .other import Other

View File

@ -1,5 +1,4 @@
import requests, imdb, discord, json, math, time, asyncio
from funcs import logThis
class BedreNetflix():
def __init__(self,bot):
@ -14,7 +13,7 @@ class BedreNetflix():
#Returns a list of no more than 5 options when user requests a movie
async def requestMovie(self, ctx, movieName):
logThis("Searching for "+movieName)
self.bot.log("Searching for "+movieName)
movieList = imdb.IMDb().search_movie(movieName)
movies = []
for movie in movieList:
@ -41,7 +40,7 @@ class BedreNetflix():
messageText += "Error"
imdbIds.append(movie.movieID)
logThis("Returning a list of "+str(len(movies))+" possible movies: "+str(imdbIds))
self.bot.log("Returning a list of "+str(len(movies))+" possible movies: "+str(imdbIds), level = 10)
em = discord.Embed(title=messageTitle,description=messageText,colour=0x00FF00)
@ -63,10 +62,10 @@ class BedreNetflix():
#Adds the requested movie to Bedre Netflix
async def addMovie(self,channel,imdbId):
if imdbId == None:
logThis("Did not find what the user was searching for")
self.bot.log("Did not find what the user was searching for")
await channel.send("Try searching for the IMDB id")
else:
logThis("Trying to add movie "+str(imdbId))
self.bot.log("Trying to add movie "+str(imdbId))
apiKey = self.bot.credentials.radarrKey
response = requests.get(self.radarrURL+"movie/lookup/imdb?imdbId=tt"+imdbId+"&apiKey="+apiKey)
lookupData = response.json()
@ -81,16 +80,16 @@ class BedreNetflix():
if r.status_code == 201:
await channel.send(postData["title"]+" successfully added to Bedre Netflix")
logThis("Added "+postData["title"]+" to Bedre Netflix")
self.bot.log("Added "+postData["title"]+" to Bedre Netflix")
elif r.status_code == 400:
await channel.send("The movie is already requested for or added to Bedre Netflix")
else:
await channel.send("Something went wrong")
logThis(str(r.status_code)+" "+r.reason)
self.bot.log(str(r.status_code)+" "+r.reason)
#Returns a list of no more than 5 options when user requests a show
async def requestShow(self, ctx, showName):
logThis("Searching for "+showName)
self.bot.log("Searching for "+showName)
movies = imdb.IMDb().search_movie(showName) #Replace with tvdb
shows = []
for movie in movies:
@ -117,7 +116,7 @@ class BedreNetflix():
messageText += "Error"
imdbNames.append(show["title"])
logThis("Returning a list of "+str(len(shows))+" possible shows: "+str(imdbNames))
self.bot.log("Returning a list of "+str(len(shows))+" possible shows: "+str(imdbNames), level = 10)
em = discord.Embed(title=messageTitle,description=messageText,colour=0x00FF00)
@ -139,10 +138,10 @@ class BedreNetflix():
#Adds the requested show to Bedre Netflix
async def addShow(self,channel,imdbName):
if imdbName == None:
logThis("Did not find what the user was searching for")
self.bot.log("Did not find what the user was searching for")
await channel.send("Try searching for the IMDB id")
else:
logThis("Trying to add show "+str(imdbName))
self.bot.log("Trying to add show "+str(imdbName))
apiKey = self.bot.credentials.sonarrKey
response = requests.get(self.sonarrURL+"series/lookup?term="+imdbName.replace(" ","%20")+"&apiKey="+apiKey)
lookupData = response.json()[0]
@ -157,16 +156,16 @@ class BedreNetflix():
if r.status_code == 201:
await channel.send(postData["title"]+" successfully added to Bedre Netflix")
logThis("Added a "+postData["title"]+" to Bedre Netflix")
self.bot.log("Added a "+postData["title"]+" to Bedre Netflix")
elif r.status_code == 400:
await channel.send("The show is already requested for or added to Bedre Netflix")
else:
await channel.send("Something went wrong")
logThis(str(r.status_code)+" "+r.reason)
self.bot.log(str(r.status_code)+" "+r.reason)
#Generates a list of all torrents and returns formatted list and whether all torrents are downloaded
async def genDownloadList(self, showDM, showMovies, showShows, episodes):
logThis("Generating torrent list")
self.bot.log("Generating torrent list")
titleWidth = 100
message = []
allDownloaded = True
@ -366,10 +365,10 @@ class BedreNetflix():
if messageText.startswith("```"):
if allDownloaded:
logThis("All torrents are downloaded")
self.bot.log("All torrents are downloaded")
else:
messageText = messageText[:-3]+"\nThis message will not update anymore\n```"
logThis("The message updated 20 times")
self.bot.log("The message updated 20 times")
await oldMessage.edit(content = messageText)

View File

@ -1,9 +1,9 @@
#import numpy as np
import random
from funcs import logThis
class Generators():
def __init__(self, bot):
self.bot = bot
# Returns a list of all letter pairs in the text
def make_pairs(self, corpus):
for i in range(len(corpus)-1):
@ -73,7 +73,7 @@ class Generators():
if new_letter == "\n":
done = True
genName = "".join(chain)
logThis("Generated "+genName)
self.bot.log("Generated "+genName[:-1])
# Returns the name
return(genName)
@ -86,7 +86,7 @@ class Generators():
# Picks one of each
genTav = random.choice(fp)+" "+random.choice(sp)+random.choice(tp)
logThis("Generated "+genTav)
self.bot.log("Generated "+genTav)
# Return the name
return(genTav)

View File

@ -1,46 +0,0 @@
import imdb
import random
from funcs import logThis
# Picks a random movie and returns information about it
def movieFunc():
try:
logThis("Creating IMDb object")
ia = imdb.IMDb()
try:
logThis("Picking a movie")
movs = open("resources/movies.txt", "r")
movlist = movs.read().split("\n")
mov = random.choice(movlist)
movs.close()
except:
logThis("Problem picking the movie (error code 801)")
return("error","804","","")
try:
logThis("Searching for "+mov)
s_result = ia.search_movie(mov)
except:
logThis("Couldn't find on imdb (error code 802)")
return("error","802","","")
try:
logThis("Getting the data")
movie = s_result[0]
ia.update(movie)
cast = movie['cast']
pcast = ""
for x in range(3):
if cast[x]:
pcast += cast[x]['name']+", "
except:
logThis("Couldn't extract data (error code 803)")
return("error","803","","")
logThis("Successfully ran !movie")
return(movie['title'], movie['plot'][0].split("::")[0], movie['cover url'].replace("150","600").replace("101","404"), pcast[:-2])
except:
logThis("Something bad happened... (error code 801)")
return("error","801","","")

View File

@ -1,20 +1,19 @@
import discord, wolframalpha, requests, os
from PIL import Image, ImageDraw, ImageFont
from funcs import logThis
class NerdShit():
def __init__(self,client):
def __init__(self, bot):
"""Runs misc commands."""
self.client = client
self.bot = bot
async def wolfSearch(self,ctx,content):
fnt = ImageFont.truetype('resources/times-new-roman.ttf', 20)
fnt = ImageFont.truetype('resources/fonts/times-new-roman.ttf', 20)
await ctx.defer()
logThis("Requesting data")
client = wolframalpha.Client(self.client.credentials.wolfKey)
res = client.query(content)
self.bot.log("Requesting data")
bot = wolframalpha.Client(self.bot.credentials.wolfKey)
res = bot.query(content)
logThis("Processing data")
self.bot.log("Processing data")
titles = []
pods = []
if int(res.numpods) > 0:
@ -73,10 +72,10 @@ class NerdShit():
wolfImage.save("resources/wolf.png")
wolfImage.close()
await ctx.send(file = discord.File("resources/wolf.png"))
await ctx.channel.send(file = discord.File("resources/wolf.png"))
os.remove("resources/wolf.png")
os.remove("resources/wolfTemp.png")
else:
logThis("No returned data")
self.bot.log("No returned data")
await ctx.send("Could not find anything relating to your search")

151
funcs/other/other.py Normal file
View File

@ -0,0 +1,151 @@
import imdb # Used in movieFunc
import random # Used in movieFunc
import discord # Used in movieFunc
import datetime # Used in helloFunc
import urllib # Used in imageFunc
import lxml # Used in imageFunc
import wikia # Used in findWikiPage
import d20 # Used in rollDice
from .bedreNetflix import BedreNetflix
from .nerdShit import NerdShit
from .generators import Generators
class MyStringifier(d20.MarkdownStringifier):
def _str_expression(self, node):
if node.comment == None:
resultText = "Result"
else:
resultText = node.comment.capitalize()
return f"**{resultText}**: {self._stringify(node.roll)}\n**Total**: {int(node.total)}"
class Other():
def __init__(self, bot):
self.bot = bot
self.bedreNetflix = BedreNetflix(self.bot)
self.nerdShit = NerdShit(self.bot)
self.generators = Generators(self.bot)
# Picks a random movie and returns information about it
async def movieFunc(self, ctx):
await ctx.defer()
self.bot.log("Creating IMDb object")
imdbClient = imdb.IMDb()
self.bot.log("Picking a movie")
with open("resources/movies.txt", "r") as f:
movieList = f.read().split("\n")
movieName = random.choice(movieList)
self.bot.log(f"Searching for {movieName}")
searchResult = imdbClient.search_movie(movieName)
self.bot.log("Getting the data")
movie = searchResult[0]
imdbClient.update(movie)
self.bot.log("Successfully ran !movie")
title = movie["title"]
plot = movie['plot'][0].split("::")[0]
cover = movie['cover url'].replace("150","600").replace("101","404")
cast = ", ".join([i["name"] for i in movie['cast'][:5]])
embed = discord.Embed(title=title, description=plot, color=0x24ec19)
embed.set_thumbnail(url=cover)
embed.add_field(name="Cast", value=cast,inline = True)
await ctx.send(embed = embed)
# Responds with a greeting of a time-appropriate maner
def helloFunc(self, author):
def time_in_range(start, end, x):
# Return true if x is in the range [start, end]
if start <= end:
return start <= x <= end
else:
return start <= x or x <= end
now = datetime.datetime.now()
if time_in_range(now.replace(hour=5, minute=0, second=0, microsecond=0),now.replace(hour=10, minute=0, second=0, microsecond=0), now):
return("Good morning, "+str(author))
elif time_in_range(now.replace(hour=10, minute=0, second=0, microsecond=0),now.replace(hour=13, minute=0, second=0, microsecond=0), now):
return("Good day, "+str(author))
elif time_in_range(now.replace(hour=13, minute=0, second=0, microsecond=0),now.replace(hour=18, minute=0, second=0, microsecond=0), now):
return("Good afternoon, "+str(author))
elif time_in_range(now.replace(hour=18, minute=0, second=0, microsecond=0),now.replace(hour=22, minute=0, second=0, microsecond=0), now):
return("Good evening, "+str(author))
elif time_in_range(now.replace(hour=22, minute=0, second=0, microsecond=0),now.replace(hour=23, minute=59, second=59, microsecond=0), now):
return("Good night, "+str(author))
else:
return("Hello, "+str(author))
# Finds a random picture online
def imageFunc(self):
# Picks a type of camera, which decides the naming scheme
cams = ("one","two","three","four")
cam = random.choice(cams)
self.bot.log("Chose cam type "+cam)
if cam == "one":
a = str(random.randint(0 ,9))
b = str(random.randint(0,9))
c = str(random.randint(0,9))
d = str(random.randint(0,9))
search = ("img_"+a+b+c+d)
elif cam == "two":
a = str(random.randint(2012,2016))
b = str(random.randint(1,12)).zfill(2)
c = str(random.randint(1,29)).zfill(2)
search = ("IMG_"+a+b+c)
elif cam == "three":
a = str(random.randint(1,500)).zfill(4)
search = ("IMAG_"+a)
elif cam == "four":
a = str(random.randint(0,9))
b = str(random.randint(0,9))
c = str(random.randint(0,9))
d = str(random.randint(0,9))
search = ("DSC_"+a+b+c+d)
self.bot.log("Searching for "+search)
# Searches for the image and reads the resulting web page
page = urllib.request.urlopen("https://www.bing.com/images/search?q="+search+"&safesearch=off")
read = page.read()
tree = lxml.etree.HTML(read)
images = tree.xpath('//a[@class = "thumb"]/@href')
# Picks an image
number = random.randint(1,len(images))-1
image = images[number]
self.bot.log("Picked image number "+str(number))
# Returns the image
self.bot.log("Successfully returned an image")
return(image)
# Finds a page from the Senkulpa Wikia
def findWikiPage(self, search : str):
self.bot.log("Trying to find wiki page for "+search)
wikia.set_lang("da")
searchResults = wikia.search("senkulpa",search)
if len(searchResults) > 0:
searchResult = searchResults[0].replace(",","%2C")
self.bot.log("Found page \""+searchResult+"\"")
page = wikia.page("senkulpa",searchResult)
content = page.content.replace(u'\xa0', u' ').split("\n")[0]
images = page.images
if len(images) > 0:
image = images[len(images)-1]+"/revision/latest?path-prefix=da"
return page.title, content, image
else:
return page.title, content, ""
else:
self.bot.log("Couldn't find the page (error code 1002)")
return "", "Couldn't find page (error code 1002)", ""
def rollDice(self, user, rollString):
while len(rollString) > 1 and rollString[0] == " ":
rollString = rollString[1:]
return user+" :game_die:\n"+str(d20.roll(rollString, allow_comments=True,stringifier=MyStringifier()))