This commit is contained in:
2025-10-28 15:42:26 +01:00
parent 020c686c81
commit 18d7f318f6
44 changed files with 7168 additions and 7137 deletions

View File

@@ -1,6 +1,7 @@
"""A collection of all Gwendolyn functions."""
__all__ = ["Other","BetterNetflix", "Sonarr", "Radarr", "TMDb", "QBittorrent"]
__all__ = ["Other","BetterNetflix", "Sonarr", "Radarr", "TMDb", "QBittorrent", "Money"]
from .other import Other
from .better_netflix import Radarr, Sonarr, BetterNetflix, TMDb, QBittorrent
from .better_netflix import Radarr, Sonarr, BetterNetflix, TMDb, QBittorrent
from .games import Money, Games

View File

@@ -117,7 +117,7 @@ class BetterNetflix():
if "imdb" in picked_movie['ratings']:
description += f"<:imdb:1301506320603676782> {picked_movie['ratings']['imdb']['value']}"
description += "/10"
description += "/10 "
if "rottenTomatoes" in picked_movie['ratings']:
rt_value = picked_movie['ratings']['rottenTomatoes']['value']
@@ -195,7 +195,7 @@ class BetterNetflix():
return progress_bar
message = [""]
message = []
all_downloaded = True
dm_section_title = "*Torrent Downloads*"
@@ -260,222 +260,45 @@ class BetterNetflix():
torrent["last_activity"] < time()-7200):
message.append(torrent_info)
if download_ratio < 1 and torrent["state"] != "stalledDL":
all_downloaded = False
return message
return message, all_downloaded
async def _generate_download_list(self, show_dm, show_movies, show_shows,
episodes):
async def _generate_download_list(self):
"""Generate a list of all torrents.
*Returns*
message_text: str
A formatted list of all torrents
all_downloaded: bool
Whether all torrents are downloaded
"""
self.bot.log("Generating torrent list")
title_width = 100
message = []
title_width = 90
message = self._draw_torrent_list(title_width)
if show_dm:
m, all_downloaded = self._draw_torrent_list(title_width)
message += m
# if show_movies:
# message.append("")
# movies_section_title = "*Missing movies not downloading*"
# movies_section_line = (
# "-"*((title_width-len(movies_section_title))//2)
# )
# message.append(
# movies_section_line+movies_section_title+movies_section_line
# )
# movie_list = requests.get(
# self.radarr_url+"movie?apiKey="+self.credentials["radarr_key"]
# ).json()
# print(
# self.radarr_url+"movie?apiKey="+self.credentials["radarr_key"]
# )
# movie_queue = requests.get(
# self.radarr_url+"queue?apiKey="+self.credentials["radarr_key"]
# ).json()
# movie_queue_ids = []
# for queue_item in movie_queue["records"]:
# movie_queue_ids.append(queue_item["movieId"])
# for movie in movie_list:
# if (not movie["hasFile"] and
# movie["id"] not in movie_queue_ids):
# movie_name = movie["title"]
# if len(movie_name) > 40:
# if movie_name[36] == " ":
# movie_name = movie_name[:36]+"...."
# else:
# movie_name = movie_name[:37]+"..."
# while len(movie_name) < 41:
# movie_name += " "
# if movie["monitored"]:
# movie_info = movie_name+"Could not find a torrent"
# else:
# movie_info = self.long_strings["No torrent"].format(
# movie_name
# )
# message.append(movie_info)
# if show_shows:
# message.append("")
# show_section_title = "*Missing shows not downloading*"
# show_section_line = "-"*((title_width-len(show_section_title))//2)
# message.append(
# show_section_line+show_section_title+show_section_line
# )
# show_list = requests.get(
# self.sonarr_url+"series?apiKey="+self.credentials["sonarr_key"]
# ).json()
# for show in show_list:
# 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:
# missing_episodes = sum(
# (i["statistics"]["totalEpisodeCount"] -
# i["statistics"]["episodeCount"])
# for i in seasons)
# message.append(
# f"{show['title']} ({missing_episodes} episodes)"
# )
message.append("-"*title_width)
message_text = "```"+"\n".join(message[1:])+"```"
message_text = "```"+"\n".join(message)+"```"
if message_text == "``````":
message_text = self.long_strings["No torrents downloading"]
return message_text, all_downloaded
return message_text
# async def downloading(self, ctx, content):
# """Send message with list of all downloading torrents."""
# async def send_long_message(ctx,message_text):
# if len(message_text) <= 1994:
# await ctx.send("```"+message_text+"```")
# else:
# cut_off_index = message_text[:1994].rfind("\n")
# await ctx.send("```"+message_text[:cut_off_index]+"```")
# await send_long_message(ctx,message_text[cut_off_index+1:])
async def downloading(self, ctx: SlashContext):
"""Send message with list of all downloading torrents."""
async def send_long_message(ctx,message_text):
if len(message_text) <= 1994:
await ctx.send("```"+message_text+"```")
else:
cut_off_index = message_text[:1994].rfind("\n")
await ctx.send("```"+message_text[:cut_off_index]+"```")
await send_long_message(ctx,message_text[cut_off_index+1:])
# await self.bot.defer(ctx)
ctx.defer()
# # showDM, showMovies, showShows, episodes
# parameters = [False, False, False, False]
# show_dm_args = ["d", "dm", "downloading", "downloadmanager"]
# show_movies_args = ["m", "movies"]
# show_shows_args = ["s", "shows", "series"]
# show_episode_args = ["e", "episodes"]
# arg_list = [
# show_dm_args, show_movies_args, show_shows_args, show_episode_args
# ]
# input_args = []
# valid_arguments = True
message_text = await self._generate_download_list()
if not message_text.startswith("```"):
await ctx.send(message_text)
# while content != "" and valid_arguments:
# if content[0] == " ":
# content = content[1:]
# elif content[0] == "-":
# if content[1] == "-":
# arg_start = 2
# if " " in content:
# arg_stop = content.find(" ")
# else:
# arg_stop = None
# else:
# arg_start = 1
# arg_stop = 2
elif len(message_text) > 2000:
message_text = message_text[3:-3]
await send_long_message(ctx,message_text)
# input_args.append(content[arg_start:arg_stop])
# if arg_stop is None:
# content = ""
# else:
# content = content[arg_stop:]
# else:
# valid_arguments = False
else:
await ctx.send(message_text)
# if valid_arguments:
# for arg_index, arg_aliases in enumerate(arg_list):
# arg_in_input = [i in input_args for i in arg_aliases]
# if any(arg_in_input):
# input_args.remove(arg_aliases[arg_in_input.index(True)])
# parameters[arg_index] = True
# if len(input_args) != 0 or (not parameters[2] and parameters[3]):
# valid_arguments = False
# show_anything = any(i for i in parameters)
# if not (valid_arguments and show_anything):
# await ctx.send(self.long_strings["Invalid parameters"])
# else:
# message_text, all_downloaded = await self.__generate_download_list(
# *parameters
# )
# if not message_text.startswith("```"):
# await ctx.send(message_text)
# elif len(message_text) > 2000:
# message_text = message_text[3:-3]
# await send_long_message(ctx,message_text)
# elif all_downloaded:
# await ctx.send(message_text)
# else:
# updates_left = 60
# message_text = self.long_strings["Update"].format(
# message_text[:-3], ceil(updates_left/6)
# )
# old_message = await ctx.send(message_text)
# while ((not all_downloaded) and updates_left > 0):
# await asyncio.sleep(10)
# updates_left -= 1
# message_text, all_downloaded = await (
# self.__generate_download_list(*parameters)
# )
# message_text = self.long_strings["Update"].format(
# message_text[:-3],
# ceil(updates_left/6)
# )
# await old_message.edit(content = message_text)
# message_text, all_downloaded = await (
# self.__generate_download_list(*parameters)
# )
# if message_text.startswith("```"):
# if all_downloaded:
# self.bot.log("All torrents are downloaded")
# else:
# message_text = self.long_strings["No updates"].format(
# message_text[:-3]
# )
# self.bot.log("The message updated 20 times")
# await old_message.edit(content = message_text)

View File

@@ -0,0 +1,11 @@
"""Game functions for Gwendolyn."""
__all__ = ["Money", "Games"]
from .money import Money
class Games():
def __init__(self, bot):
"""Initialize the class."""
self.bot = bot
self.database = bot.database

View File

@@ -0,0 +1,150 @@
"""
Contains the code that deals with money.
*Classes*
---------
Money
Deals with money.
"""
import interactions # Used for typehints
class Money():
"""
Deals with money.
*Methods*
---------
checkBalance(user: str)
sendBalance(ctx: interactions.SlashContext)
addMoney(user: str, amount: int)
giveMoney(ctx: interactions.SlashContext, user: discord.User,
amount: int)
*Attributes*
------------
bot: Gwendolyn
The instance of Gwendolyn
database: pymongo.Client
The mongo database
"""
def __init__(self, bot):
"""Initialize the class."""
self.bot = bot
self.database = bot.database
def checkBalance(self, user: str):
"""
Get the account balance of a user.
*Parameters*
------------
user: str
The user to get the balance of.
*Returns*
---------
balance: int
The balance of the user's account.
"""
self.bot.log("checking "+user+"'s account balance")
user_data = self.database["users"].find_one({"_id": user})
if user_data is not None:
return user_data["money"]
else:
return 0
async def sendBalance(self, ctx: interactions.SlashContext):
"""
Get your own account balance.
*Parameters*
------------
ctx: interactions.SlashContext
The context of the command.
"""
await ctx.defer()
response = self.checkBalance("#"+str(ctx.author.id))
user_name = ctx.author.display_name
if response == 1:
new_message = f"{user_name} has {response} GwendoBuck"
else:
new_message = f"{user_name} has {response} GwendoBucks"
await ctx.send(new_message)
# Adds money to the account of a user
def addMoney(self, user: str, amount: int):
"""
Add money to a user account.
*Parameters*
------------
user: str
The id of the user to give money.
amount: int
The amount to add to the user's account.
"""
self.bot.log("adding "+str(amount)+" to "+user+"'s account")
user_data = self.database["users"].find_one({"_id": user})
if user_data is not None:
updater = {"$inc": {"money": amount}}
self.database["users"].update_one({"_id": user}, updater)
else:
new_user = {
"_id": user,
"user name": self.bot.database_funcs.get_name(user),
"money": amount
}
self.database["users"].insert_one(new_user)
# Transfers money from one user to another
async def giveMoney(self, ctx: interactions.SlashContext,
user: interactions.User, amount: int):
"""
Give someone else money from your account.
*Parameters*
------------
ctx: interactions.SlashContext
The context of the command.
user: interactions.User
The user to give money.
amount: int
The amount to transfer.
"""
await ctx.defer()
username = user.display_name
if self.bot.database_funcs.get_id(username) is None:
async for member in ctx.guild.fetch_members(limit=None):
if member.display_name.lower() == username.lower():
username = member.display_name
user_id = f"#{member.id}"
new_user = {
"_id": user_id,
"user name": username,
"money": 0
}
self.bot.database["users"].insert_one(new_user)
userid = f"#{ctx.author.id}"
user_data = self.database["users"].find_one({"_id": userid})
targetUser = self.bot.database_funcs.get_id(username)
if amount <= 0:
self.bot.log("They tried to steal")
await ctx.send("Yeah, no. You can't do that")
elif targetUser is None:
self.bot.log("They weren't in the system")
await ctx.send("The target doesn't exist")
elif user_data is None or user_data["money"] < amount:
self.bot.log("They didn't have enough GwendoBucks")
await ctx.send("You don't have that many GwendoBuck")
else:
self.addMoney(f"#{ctx.author.id}", -1 * amount)
self.addMoney(targetUser, amount)
await ctx.send(f"Transferred {amount} GwendoBucks to {username}")

View File

@@ -7,59 +7,59 @@ from .name_generator import NameGenerator
from .roll import DieRoller
def gen_help_text(commands: list[SlashCommand]):
return '\n'.join([f"`/{i.name}`\t{i.description}" for i in commands])
return '\n'.join(sorted([f"`/{i.name}`\t{i.description}" for i in commands]))
class Other():
def __init__(self, bot):
self.bot = bot
self._name_generator = NameGenerator()
self._roller = DieRoller()
def __init__(self, bot):
self.bot = bot
self._name_generator = NameGenerator()
self._roller = DieRoller()
# Responds with a greeting of a time-appropriate maner
async def hello_func(self, ctx: SlashContext):
def time_in_range(start, end, i):
# Return true if i is in the range [start, end]
if start <= end:
return start <= i <= end
else:
return start <= i or i <= end
# Responds with a greeting of a time-appropriate maner
async def hello_func(self, ctx: SlashContext):
def time_in_range(start, end, i):
# Return true if i is in the range [start, end]
if start <= end:
return start <= i <= end
else:
return start <= i or i <= 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):
send_message = "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):
send_message = "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):
send_message = "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):
send_message = "Good night, "+str(author)
else:
send_message = "Hello, "+str(author)
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):
send_message = "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):
send_message = "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):
send_message = "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):
send_message = "Good night, "+str(author)
else:
send_message = "Hello, "+str(author)
await ctx.send(send_message)
await ctx.send(send_message)
async def help_func(self, ctx: SlashContext, command: str):
if command == "":
text = gen_help_text([i for i in self.bot.application_commands if isinstance(i,SlashCommand)])
embed = Embed(title = "Help", description = text,color = 0x59f442)
await ctx.send(embed = embed)
else:
self.bot.log(f"Looking for help-{command}.txt",str(ctx.channel_id))
try:
with open(f"gwendolyn/resources/help/help-{command}.txt",encoding="utf-8") as file_pointer:
text = file_pointer.read()
embed = Embed(title = command.capitalize(), description = text,color = 0x59f442)
await ctx.send(embed = embed)
except:
await ctx.send(f"Could not find a help file for the command '/{command}'")
async def help_func(self, ctx: SlashContext, command: str):
if command == "":
text = gen_help_text([i for i in self.bot.application_commands if isinstance(i,SlashCommand)])
embed = Embed(title = "Help", description = text,color = 0x59f442)
await ctx.send(embed = embed)
else:
self.bot.log(f"Looking for help-{command}.txt",str(ctx.channel_id))
try:
with open(f"gwendolyn/resources/help/help-{command}.txt",encoding="utf-8") as file_pointer:
text = file_pointer.read()
embed = Embed(title = command.capitalize(), description = text,color = 0x59f442)
await ctx.send(embed = embed)
except:
await ctx.send(f"Could not find a help file for the command '/{command}'")
async def generate_name(self, ctx: SlashContext):
await ctx.send(self._name_generator.generate())
async def generate_name(self, ctx: SlashContext):
await ctx.send(self._name_generator.generate())
async def roll_dice(self, ctx: SlashContext, dice: str):
try:
roll = self._roller.roll(dice)
await ctx.send(f":game_die:Rolling dice `{dice}`\n{roll}")
except:
await ctx.send("There was an error in the rolling")
async def roll_dice(self, ctx: SlashContext, dice: str):
try:
roll = self._roller.roll(dice)
await ctx.send(f":game_die:Rolling dice `{dice}`\n{roll}")
except:
await ctx.send("There was an error in the rolling")