PEP in utils

This commit is contained in:
Nikolaj
2021-06-16 14:12:21 +02:00
parent 8c253aca3d
commit b68d62cf6c
137 changed files with 1159 additions and 1251 deletions

View File

@@ -0,0 +1,5 @@
"""Misc. functions for Gwendolyn."""
__all__ = ["Other"]
from .other import Other

View File

@@ -0,0 +1,413 @@
import requests, imdb, discord, json, math, time, asyncio
class BedreNetflix():
def __init__(self,bot):
self.bot = bot
ip = ["localhost", "192.168.0.40"][self.bot.options["testing"]]
self.radarrURL = "http://"+ip+":7878/api/v3/"
self.sonarrURL = "http://"+ip+":8989/api/"
self.qbittorrentURL = "http://"+ip+":8080/api/v2/"
self.moviePath = "/media/plex/Server/movies/"
self.showPath = "/media/plex/Server/Shows/"
#Returns a list of no more than 5 options when user requests a movie
async def requestMovie(self, ctx, movieName):
await self.bot.defer(ctx)
self.bot.log("Searching for "+movieName)
movieList = imdb.IMDb().search_movie(movieName)
movies = []
for movie in movieList:
if movie["kind"] == "movie":
movies.append(movie)
if len(movies) > 5:
movies = movies[:5]
if len(movies) == 1:
messageTitle = "**Is it this movie?**"
else:
messageTitle = "**Is it any of these movies?**"
messageText = ""
imdb_ids = []
for x, movie in enumerate(movies):
try:
messageText += "\n"+str(x+1)+") "+movie["title"]+" ("+str(movie["year"])+")"
except:
try:
messageText += "\n"+str(x+1)+") "+movie["title"]
except:
messageText += "Error"
imdb_ids.append(movie.movieID)
self.bot.log("Returning a list of "+str(len(movies))+" possible movies: "+str(imdb_ids))
em = discord.Embed(title=messageTitle,description=messageText,colour=0x00FF00)
message = await ctx.send(embed=em)
messageData = {"message_id":message.id,"imdb_ids":imdb_ids}
with open("gwendolyn/resources/bedre_netflix/old_message"+str(ctx.channel.id),"w") as f:
json.dump(messageData,f)
if len(movies) == 1:
await message.add_reaction("✔️")
else:
for x in range(len(movies)):
await message.add_reaction(["1","2","3","4","5"][x])
await message.add_reaction("")
message = await ctx.channel.fetch_message(message.id)
if message.content != "" and not isinstance(ctx.channel, discord.DMChannel):
await message.clear_reactions()
#Adds the requested movie to Bedre Netflix
async def add_movie(self, message, imdbId, editMessage = True):
if imdbId == None:
self.bot.log("Did not find what the user was searching for")
if editMessage:
await message.edit(embed = None, content = "Try searching for the IMDB id")
else:
await message.channel.send("Try searching for the IMDB id")
else:
self.bot.log("Trying to add movie "+str(imdbId))
apiKey = self.bot.credentials["radarr_key"]
response = requests.get(self.radarrURL+"movie/lookup/imdb?imdbId=tt"+imdbId+"&apiKey="+apiKey)
lookupData = response.json()
postData = {"qualityProfileId": 1,
"rootFolderPath" : self.moviePath,
"monitored" : True,
"addOptions": {"searchForMovie": True}}
for key in ["tmdbId","title","titleSlug","images","year"]:
postData.update({key : lookupData[key]})
r = requests.post(url= self.radarrURL+"movie?apikey="+apiKey,json = postData)
if r.status_code == 201:
if editMessage:
await message.edit(embed = None, content = postData["title"]+" successfully added to Bedre Netflix")
else:
await message.channel.send(postData["title"]+" successfully added to Bedre Netflix")
self.bot.log("Added "+postData["title"]+" to Bedre Netflix")
elif r.status_code == 400:
text = f"{postData['title']} is either already on Bedre Netflix, downloading, or not available"
if editMessage:
await message.edit(embed = None, content = text)
else:
await message.channel.send(text)
else:
if editMessage:
await message.edit(embed = None, content = "Something went wrong")
else:
await message.channel.send("Something went wrong")
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):
await self.bot.defer(ctx)
self.bot.log("Searching for "+showName)
movies = imdb.IMDb().search_movie(showName) #Replace with tvdb
shows = []
for movie in movies:
if movie["kind"] in ["tv series","tv miniseries"]:
shows.append(movie)
if len(shows) > 5:
shows = shows[:5]
if len(shows) == 1:
messageTitle = "**Is it this show?**"
else:
messageTitle = "**Is it any of these shows?**"
messageText = ""
imdb_names = []
for x, show in enumerate(shows):
try:
messageText += "\n"+str(x+1)+") "+show["title"]+" ("+str(show["year"])+")"
except:
try:
messageText += "\n"+str(x+1)+") "+show["title"]
except:
messageText += "Error"
imdb_names.append(show["title"])
self.bot.log("Returning a list of "+str(len(shows))+" possible shows: "+str(imdb_names))
em = discord.Embed(title=messageTitle,description=messageText,colour=0x00FF00)
message = await ctx.send(embed=em)
messageData = {"message_id":message.id,"imdb_names":imdb_names}
with open("gwendolyn/resources/bedre_netflix/old_message"+str(ctx.channel.id),"w") as f:
json.dump(messageData,f)
if len(shows) == 1:
await message.add_reaction("✔️")
else:
for x in range(len(shows)):
await message.add_reaction(["1","2","3","4","5"][x])
await message.add_reaction("")
message = await ctx.channel.fetch_message(message.id)
if message.content != "" and not isinstance(ctx.channel, discord.DMChannel):
await message.clear_reactions()
#Adds the requested show to Bedre Netflix
async def add_show(self, message, imdb_name):
if imdb_name == None:
self.bot.log("Did not find what the user was searching for")
await message.edit(embed = None, content = "Try searching for the IMDB id")
else:
self.bot.log("Trying to add show "+str(imdb_name))
apiKey = self.bot.credentials["sonarr_key"]
response = requests.get(self.sonarrURL+"series/lookup?term="+imdb_name.replace(" ","%20")+"&apiKey="+apiKey)
lookupData = response.json()[0]
postData = {"ProfileId" : 1,
"rootFolderPath" : self.showPath,
"monitored" : True,
"addOptions" : {"searchForMissingEpisodes" : True}}
for key in ["tvdbId","title","titleSlug","images","seasons"]:
postData.update({key : lookupData[key]})
r = requests.post(url= self.sonarrURL+"series?apikey="+apiKey,json = postData)
if r.status_code == 201:
await message.edit(embed = None, content = postData["title"]+" successfully added to Bedre Netflix")
self.bot.log("Added a "+postData["title"]+" to Bedre Netflix")
elif r.status_code == 400:
text = f"{postData['title']} is either already on Bedre Netflix, downloading, or not available"
await message.edit(embed = None, content = text)
else:
await message.edit(embed = None, content = "Something went wrong")
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):
self.bot.log("Generating torrent list")
titleWidth = 100
message = []
allDownloaded = True
if showDM:
message.append("")
DMSectionTitle = "*Torrent Downloads*"
DMSectionTitleLine = "-"*((titleWidth-len(DMSectionTitle))//2)
message.append(DMSectionTitleLine+DMSectionTitle+DMSectionTitleLine)
response = requests.get(self.qbittorrentURL+"torrents/info")
torrentList = response.json()
if len(torrentList) > 0:
for torrent in torrentList:
torrentName = torrent["name"]
if len(torrentName) > 30:
if torrentName[26] == " ":
torrentName = torrentName[:26]+"...."
else:
torrentName = torrentName[:27]+"..."
while len(torrentName) < 30:
torrentName += " "
if torrent["size"] == 0:
downloadedRatio = 0
elif torrent["amount_left"] == 0:
downloadedRatio = 1
else:
downloadedRatio = min(torrent["downloaded"]/torrent["size"],1)
progressBar = "|"+(""*math.floor(downloadedRatio*20))
while len(progressBar) < 21:
progressBar += " "
progressBar += "| "+str(math.floor(downloadedRatio*100))+"%"
while len(progressBar) < 27:
progressBar += " "
etaInSeconds = torrent["eta"]
if etaInSeconds >= 8640000:
eta = ""
else:
eta = ""
if etaInSeconds >= 86400:
eta += str(math.floor(etaInSeconds/86400))+"d "
if etaInSeconds >= 3600:
eta += str(math.floor((etaInSeconds%86400)/3600))+"h "
if etaInSeconds >= 60:
eta += str(math.floor((etaInSeconds%3600)/60))+"m "
eta += str(etaInSeconds%60)+"s"
torrentInfo = torrentName+" "+progressBar+" (Eta: "+eta+")"
if torrent["state"] == "stalledDL":
torrentInfo += " (Stalled)"
if not (downloadedRatio == 1 and torrent["last_activity"] < time.time()-7200):
message.append(torrentInfo)
if downloadedRatio < 1 and torrent["state"] != "stalledDL":
allDownloaded = False
else:
message.append("No torrents currently downloading")
if showMovies:
message.append("")
movieSectionTitle = "*Missing movies not downloading*"
movieSectionTitleLine = "-"*((titleWidth-len(movieSectionTitle))//2)
message.append(movieSectionTitleLine+movieSectionTitle+movieSectionTitleLine)
movieList = requests.get(self.radarrURL+"movie?apiKey="+self.bot.credentials["radarr_key"]).json()
movieQueue = requests.get(self.radarrURL+"queue?apiKey="+self.bot.credentials["radarr_key"]).json()
movieQueueIDs = []
for queueItem in movieQueue["records"]:
movieQueueIDs.append(queueItem["movieId"])
for movie in movieList:
if not movie["hasFile"]:
if movie["id"] not in movieQueueIDs:
movieName = movie["title"]
if len(movieName) > 40:
if movieName[36] == " ":
movieName = movieName[:36]+"...."
else:
movieName = movieName[:37]+"..."
while len(movieName) < 41:
movieName += " "
if movie["monitored"]:
movieInfo = movieName+"Could not find a torrent"
else:
movieInfo = movieName+"No torrent exists. Likely because the movie is not yet released on DVD"
message.append(movieInfo)
if showShows:
message.append("")
showSectionTitle = "*Missing shows not downloading*"
showSectionTitleLine = "-"*((titleWidth-len(showSectionTitle))//2)
message.append(showSectionTitleLine+showSectionTitle+showSectionTitleLine)
showList = requests.get(self.sonarrURL+"series?apiKey="+self.bot.credentials["sonarr_key"]).json()
for show in showList:
if show["seasons"][0]["seasonNumber"] == 0:
seasons = show["seasons"][1:]
else:
seasons = show["seasons"]
if any(i["statistics"]["episodeCount"] != i["statistics"]["totalEpisodeCount"] for i in seasons):
if all(i["statistics"]["episodeCount"] == 0 for i in seasons):
message.append(show["title"] + " (all episodes)")
else:
if episodes:
missingEpisodes = sum(i["statistics"]["totalEpisodeCount"] - i["statistics"]["episodeCount"] for i in seasons)
message.append(show["title"] + f" ({missingEpisodes} episodes)")
message.append("-"*titleWidth)
messageText = "```"+"\n".join(message[1:])+"```"
if messageText == "``````":
messageText = "There are no torrents downloading right. If the torrent you're looking for was added more than 24 hours ago, it might already be on Bedre Netflix."
return messageText, allDownloaded
async def downloading(self, ctx, content):
async def SendLongMessage(ctx,messageText):
if len(messageText) <= 1994:
await ctx.send("```"+messageText+"```")
else:
cutOffIndex = messageText[:1994].rfind("\n")
await ctx.send("```"+messageText[:cutOffIndex]+"```")
await SendLongMessage(ctx,messageText[cutOffIndex+1:])
await self.bot.defer(ctx)
# showDM, showMovies, showShows, episodes
params = [False, False, False, False]
showDMArgs = ["d", "dm", "downloading", "downloadmanager"]
showMoviesArgs = ["m", "movies"]
showShowsArgs = ["s", "shows", "series"]
episodesArgs = ["e", "episodes"]
argList = [showDMArgs, showMoviesArgs, showShowsArgs, episodesArgs]
inputArgs = []
validArguments = True
while content != "" and validArguments:
if content[0] == " ":
content = content[1:]
elif content[0] == "-":
if content[1] == "-":
argStart = 2
if " " in content:
argStop = content.find(" ")
else:
argStop = None
else:
argStart = 1
argStop = 2
inputArgs.append(content[argStart:argStop])
if argStop is None:
content = ""
else:
content = content[argStop:]
else:
validArguments = False
if validArguments:
for x, argAliases in enumerate(argList):
argInInput = [i in inputArgs for i in argAliases]
if any(argInInput):
inputArgs.remove(argAliases[argInInput.index(True)])
params[x] = True
if len(inputArgs) != 0 or (params[2] == False and params[3] == True):
validArguments = False
showAnything = any(i for i in params)
if validArguments and showAnything:
messageText, allDownloaded = await self.genDownloadList(*params)
if messageText.startswith("```"):
if len(messageText) <= 2000:
if not allDownloaded:
updatesLeft = 60
messageText = messageText[:-3]+"\nThis message will update every 10 seconds for "+str(math.ceil(updatesLeft/6))+" more minutes\n```"
old_message = await ctx.send(messageText)
while ((not allDownloaded) and updatesLeft > 0):
await asyncio.sleep(10)
updatesLeft -= 1
messageText, allDownloaded = await self.genDownloadList(*params)
messageText = messageText[:-3]+"\nThis message will update every 10 seconds for "+str(math.ceil(updatesLeft/6))+" more minutes\n```"
await old_message.edit(content = messageText)
messageText, allDownloaded = await self.genDownloadList(*params)
if messageText.startswith("```"):
if allDownloaded:
self.bot.log("All torrents are downloaded")
else:
messageText = messageText[:-3]+"\nThis message will not update anymore\n```"
self.bot.log("The message updated 20 times")
await old_message.edit(content = messageText)
else:
await ctx.send(messageText)
else:
messageText = messageText[3:-3]
await SendLongMessage(ctx,messageText)
else:
await ctx.send(messageText)
else:
await ctx.send("Invalid or repeated parameters. Use '/help downloading' to see valid parameters.")

View File

@@ -0,0 +1,93 @@
import random
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):
yield (corpus[i], corpus[i+1])
# Returns a list of all letter triplets in the text
def make_triplets(self, corpus):
for i in range(len(corpus)-2):
yield (corpus[i], corpus[i+1], corpus[i+2])
# Generates a random name
async def nameGen(self, ctx):
# Makes a list of all names from "names.txt"
names = open('gwendolyn/resources/names.txt', encoding='utf8').read()
corpus = list(names)
# Makes a list of pairs
pairs = self.make_pairs(corpus)
triplets = self.make_triplets(corpus)
letter_dict = {}
# Makes a dictionary of all letters that come after all other letters
for letter_1, letter_2 in pairs:
if letter_1 in letter_dict.keys():
letter_dict[letter_1].append(letter_2)
else:
letter_dict[letter_1] = [letter_2]
for letter_1, letter_2, letter_3 in triplets:
if letter_1+letter_2 in letter_dict.keys():
letter_dict[letter_1+letter_2].append(letter_3)
else:
letter_dict[letter_1+letter_2] = [letter_3]
# Choses a random first letter
first_letter = random.choice(corpus)
# Makes sure the first letter is not something a name can't start with.
while first_letter.islower() or first_letter == " " or first_letter == "-" or first_letter == "\n":
first_letter = random.choice(corpus)
# Starts the name
chain = [first_letter]
# Picks second letter
second_letter = random.choice(letter_dict[chain[-1]])
while second_letter == "\n":
second_letter = random.choice(letter_dict[chain[-1]])
chain.append(second_letter)
done = False
# Creates the name one letter at a time
while done == False:
if random.randint(1,10) > 1:
try:
new_letter = random.choice(letter_dict[chain[-2]+chain[-1]])
except KeyError():
new_letter = random.choice(letter_dict[chain[-1]])
else:
new_letter = random.choice(letter_dict[chain[-1]])
chain.append(new_letter)
# Ends name if the name ends
if new_letter == "\n":
done = True
genName = "".join(chain)
self.bot.log("Generated "+genName[:-1])
# Returns the name
await ctx.send(genName)
# Generates a random tavern name
async def tavernGen(self, ctx):
# Lists first parts, second parts and third parts of tavern names
fp = ["The Silver","The Golden","The Staggering","The Laughing","The Prancing","The Gilded","The Running","The Howling","The Slaughtered","The Leering","The Drunken","The Leaping","The Roaring","The Frowning","The Lonely","The Wandering","The Mysterious","The Barking","The Black","The Gleaming","The Tap-Dancing","The Sad","The Sexy","The Artificial","The Groovy","The Merciful","The Confused","The Pouting","The Horny","The Okay","The Friendly","The Hungry","The Handicapped","The Fire-breathing","The One-Eyed","The Psychotic","The Mad","The Evil","The Idiotic","The Trusty","The Busty"]
sp = ["Eel","Dolphin","Dwarf","Pegasus","Pony","Rose","Stag","Wolf","Lamb","Demon","Goat","Spirit","Horde","Jester","Mountain","Eagle","Satyr","Dog","Spider","Star","Dad","Rat","Jeremy","Mouse","Unicorn","Pearl","Ant","Crab","Penguin","Octopus","Lawyer","Ghost","Toad","Handjob","Immigrant","SJW","Dragon","Bard","Sphinx","Soldier","Salmon","Owlbear","Kite","Frost Giant","Arsonist"]
tp = [" Tavern"," Inn","","","","","","","","",""]
# Picks one of each
genTav = random.choice(fp)+" "+random.choice(sp)+random.choice(tp)
self.bot.log("Generated "+genTav)
# Return the name
await ctx.send(genTav)

View File

@@ -0,0 +1,81 @@
import discord, discord_slash, wolframalpha, requests, os
from PIL import Image, ImageDraw, ImageFont
class NerdShit():
def __init__(self, bot):
"""Runs misc commands."""
self.bot = bot
async def wolfSearch(self,ctx,content):
await self.bot.defer(ctx)
fnt = ImageFont.truetype('gwendolyn/resources/fonts/times-new-roman.ttf', 20)
self.bot.log("Requesting data")
bot = wolframalpha.Client(self.bot.credentials["wolfram_alpha_key"])
res = bot.query(content)
self.bot.log("Processing data")
titles = []
pods = []
if int(res.numpods) > 0:
for pod in res.pods:
titles += [pod.title]
for x, sub in enumerate(pod.subpods):
pods += [sub]
if x > 0:
titles += [""]
podChunks = [pods[x:x+2] for x in range(0, len(pods), 2)]
titleChucks = [titles[x:x+2] for x in range(0, len(titles), 2)]
await ctx.send(f"Response for \"{content}\"")
for x, chunk in enumerate(podChunks):
width = 0
for title in titleChucks[x]:
width = max(width,fnt.getsize(title)[0])
height = 5
heights = []
for count, pod in enumerate(chunk):
heights += [height]
width = max(width,int(pod.img['@width']))
if titleChucks[x][count] == "":
placeForText = 0
else:
placeForText = 30
height += int(pod.img["@height"]) + 10 + placeForText
width += 10
height += 5
wolfImage = Image.new("RGB",(width,height),color=(255,255,255))
for count, pod in enumerate(chunk):
response = requests.get(pod.img["@src"])
file = open("gwendolyn/resources/wolfTemp.png", "wb")
file.write(response.content)
file.close()
old_image = Image.open("gwendolyn/resources/wolfTemp.png")
oldSize = old_image.size
if titleChucks[x][count] == "":
placeForText = 0
else:
placeForText = 30
newSize = (width,int(oldSize[1]+10+placeForText))
newImage = Image.new("RGB",newSize,color=(255,255,255))
newImage.paste(old_image, (int((int(oldSize[0]+10)-oldSize[0])/2),int(((newSize[1]-placeForText)-oldSize[1])/2)+placeForText))
if titleChucks[x][count] != "":
d = ImageDraw.Draw(newImage,"RGB")
d.text((5,7),titleChucks[x][count],font=fnt,fill=(150,150,150))
wolfImage.paste(newImage,(0,heights[count]))
newImage.close()
old_image.close()
count += 1
wolfImage.save("gwendolyn/resources/wolf.png")
wolfImage.close()
await ctx.channel.send(file = discord.File("gwendolyn/resources/wolf.png"))
os.remove("gwendolyn/resources/wolf.png")
os.remove("gwendolyn/resources/wolfTemp.png")
else:
self.bot.log("No returned data")
await ctx.send("Could not find anything relating to your search")

View File

@@ -0,0 +1,196 @@
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 fandom # Used in findWikiPage
import d20 # Used in rollDice
import ast
from .bedre_netflix import BedreNetflix
from .nerd_shit import NerdShit
from .generators import Generators
from gwendolyn.utils import cap
fandom.set_lang("da")
fandom.set_wiki("senkulpa")
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.bedre_netflix = BedreNetflix(self.bot)
self.nerd_shit = NerdShit(self.bot)
self.generators = Generators(self.bot)
# Picks a random movie and returns information about it
async def movieFunc(self, ctx):
await self.bot.defer(ctx)
self.bot.log("Creating IMDb object")
imdbClient = imdb.IMDb()
self.bot.log("Picking a movie")
with open("gwendolyn/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
async def helloFunc(self, ctx):
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
author = ctx.author.display_name
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):
sendMessage = "Good morning, "+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):
sendMessage = "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):
sendMessage = "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):
sendMessage = "Good night, "+str(author)
else:
sendMessage = "Hello, "+str(author)
await ctx.send(sendMessage)
# Finds a random picture online
async def imageFunc(self, ctx):
# 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 = "iusc"]/@m')
if len(images) == 0:
await ctx.send("Found no images")
else:
# Picks an image
number = random.randint(1,len(images))-1
image = ast.literal_eval(str(images[number]))
imageUrl = image["murl"]
self.bot.log("Picked image number "+str(number))
# Returns the image
self.bot.log("Successfully returned an image")
await ctx.send(imageUrl)
# Finds a page from the Senkulpa Wikia
async def findWikiPage(self, ctx, search : str):
await self.bot.defer(ctx)
foundPage = False
if search != "":
self.bot.log("Trying to find wiki page for "+search)
searchResults = fandom.search(search)
if len(searchResults) > 0:
foundPage = True
searchResult = searchResults[0]
else:
self.bot.log("Couldn't find the page")
await ctx.send("Couldn't find page (error code 1002)")
else:
foundPage = True
self.bot.log("Searching for a random page")
searchResult = fandom.random()
if foundPage:
self.bot.log(f"Found page \"{searchResult[0]}\"")
page = fandom.page(pageid = searchResult[1])
content = page.summary
images = page.images
if len(images) > 0:
image = images[0]
else:
image = ""
self.bot.log("Sending the embedded message",str(ctx.channel_id))
content += f"\n[Læs mere]({page.url})"
embed = discord.Embed(title = page.title, description = content, colour=0xDEADBF)
if image != "":
embed.set_thumbnail(url=image)
await ctx.send(embed = embed)
async def rollDice(self, ctx, rollString):
user = ctx.author.display_name
while len(rollString) > 1 and rollString[0] == " ":
rollString = rollString[1:]
roll = d20.roll(rollString, allow_comments=True, stringifier=MyStringifier())
await ctx.send(f"{user} :game_die:\n{roll}")
async def helpFunc(self, ctx, command):
if command == "":
with open("gwendolyn/resources/help/help.txt",encoding="utf-8") as f:
text = f.read()
em = discord.Embed(title = "Help", description = text,colour = 0x59f442)
await ctx.send(embed = em)
else:
self.bot.log(f"Looking for help-{command}.txt",str(ctx.channel_id))
with open(f"gwendolyn/resources/help/help-{command}.txt",encoding="utf-8") as f:
text = f.read()
em = discord.Embed(title = command.capitalize(), description = text,colour = 0x59f442)
await ctx.send(embed = em)