Added additional commands. Removed unnecessary code in cmd_list commands. Added alias for cmd_roll command.

This commit is contained in:
Tanner Van Teeffelen 2025-06-10 17:55:06 +00:00
parent d90658d0c1
commit 5c226105d1
3 changed files with 50 additions and 23 deletions

View file

@ -1,3 +1,5 @@
# G4_Bot # G4_Bot
Bot designed for exclusive use in the G4 Discord. Bot designed for exclusive use in the G4 Discord.
Lead Developer: Tanner Van Teeffelen

View file

@ -6,5 +6,6 @@
"checkpoints": "cmd_checkpoints", "checkpoints": "cmd_checkpoints",
"addcommand": "cmd_addcommand", "addcommand": "cmd_addcommand",
"listcommands": "cmd_listcommands", "listcommands": "cmd_listcommands",
"roll": "cmd_roll" "roll": "cmd_roll",
"r": "cmd_roll"
} }

View file

@ -1,5 +1,6 @@
#methods.py #methods.py
#Imports.
import os, json, discord, random, math import os, json, discord, random, math
from dotenv import load_dotenv from dotenv import load_dotenv
@ -20,80 +21,100 @@ async def cmd_goodbye(ctx):
async def cmd_whatareyou(ctx): async def cmd_whatareyou(ctx):
await ctx.send("An idiot sandwich.") await ctx.send("An idiot sandwich.")
#Add points for a user.
async def cmd_addpoints(ctx, member: discord.Member = None, number = None): async def cmd_addpoints(ctx, member: discord.Member = None, number = None):
points_data = loadpoints()
member = member or ctx.author points_data = loadpoints() #Load all point history into a variable.
user_id = str(member.id) member = member or ctx.author #Set the target equal to the user specified OR the sender of the message.
user_id = str(member.id) #Sets the user ID equal to the ID of the user specified.
pointAmount = number or 1 #Makes the amount to add either the amount specified, or just 1. pointAmount = number or 1 #Makes the amount to add either the amount specified, or just 1.
points_data[user_id] = points_data.get(user_id, 0) + int(pointAmount) points_data[user_id] = points_data.get(user_id, 0) + int(pointAmount) #Add the desired amount of points to the user.
loadpoints(points_data) loadpoints(points_data) #Reload the points data.
await ctx.send(f"{member.mention} now has {points_data[user_id]} points!") await ctx.send(f"{member.mention} now has {points_data[user_id]} points!")
#Checks the current points of a user.
async def cmd_checkpoints(ctx, member: discord.Member = None): async def cmd_checkpoints(ctx, member: discord.Member = None):
points_data = loadpoints()
points_data = loadpoints() #Load all point history into a variable.
member = member or ctx.author # Checks either the member specified, or the sender of the message. member = member or ctx.author # Checks either the member specified, or the sender of the message.
user_id = str(member.id) user_id = str(member.id) #Set the user ID equal to the ID of the user specified.
points = points_data.get(user_id, 0) points = points_data.get(user_id, 0) #Retrieve the points of the user ID.
await ctx.send(f"{member.mention} has {points} points.") await ctx.send(f"{member.mention} has {points} points.")
#Add a custom command to customcommands.json.
async def cmd_addcommand(ctx, command, *message): async def cmd_addcommand(ctx, command, *message):
response = (" ".join(message)) response = (" ".join(message)) #Takes in the custom message.
commands_temp = loadcommands("commands.json") commands_temp = loadcommands("commands.json") #Load the built-in commands to a temp variable.
customcommands_temp = loadcommands("customcommands.json") customcommands_temp = loadcommands("customcommands.json") #Load the custom commands to a temp variable.
#Checks to see if the command already exists in commands.json.
if command in commands_temp: if command in commands_temp:
await ctx.send(f"Command '{command}' already exists in base commands! Not overwriting.") await ctx.send(f"Command '{command}' already exists in base commands! Not overwriting.")
return return
#Checks to see if the command already exists in customcommands.json.
if command in customcommands_temp: if command in customcommands_temp:
await ctx.send(f"Command '{command}' already exists in custom commands! Not overwriting.") await ctx.send(f"Command '{command}' already exists in custom commands! Not overwriting.")
return return
#Takes the response, and adds it to the customcommands.json file.
customcommands_temp[command] = response customcommands_temp[command] = response
with open("customcommands.json", "w", encoding="utf-8") as file: with open("customcommands.json", "w", encoding="utf-8") as file:
json.dump(customcommands_temp, file, indent=4) json.dump(customcommands_temp, file, indent=4)
await ctx.send(f"Command '{command}' added successfully!") await ctx.send(f"Command '{command}' added successfully!")
#Lists all built-in and custom commands currently set up.
async def cmd_listcommands(ctx): async def cmd_listcommands(ctx):
try: try:
#Loads both custom and built-in commands to temp variables.
commands_dict = loadcommands("commands.json") commands_dict = loadcommands("commands.json")
customcommands_dict = loadcommands("customcommands.json") customcommands_dict = loadcommands("customcommands.json")
if not commands_dict: #Adds each set of commands into a list variable, then displays it.
await ctx.send("No commands found in the .JSON file.")
commands_list = "\n".join([f"{PREFIX}**{cmd}**" for cmd, resp in commands_dict.items()]) commands_list = "\n".join([f"{PREFIX}**{cmd}**" for cmd, resp in commands_dict.items()])
customcommands_list = "\n".join([f"{PREFIX}**{cmd}**" for cmd, resp in customcommands_dict.items()])
await ctx.send(f"**Available Built-In Commands:**\n\n{commands_list}") await ctx.send(f"**Available Built-In Commands:**\n\n{commands_list}")
#Checks to see if there are any custom commands, and then lists them if there are any.
with open ("customcommands.json", 'r') as file: with open ("customcommands.json", 'r') as file:
data = json.load(file) data = json.load(file)
if data != {}: if data != {}:
customcommands_list = "\n".join([f"{PREFIX}**{cmd}**" for cmd, resp in customcommands_dict.items()])
await ctx.send(f"\n\n**Available Custom Commands:**\n\n{customcommands_list}\n\n") await ctx.send(f"\n\n**Available Custom Commands:**\n\n{customcommands_list}\n\n")
#Exception for failing to load commands. Typically indicates a missing commands.json file.
except Exception as e: except Exception as e:
await ctx.send(f"Error loading commands: {e}") await ctx.send(f"Error loading commands: {e}")
#Rolls a dice roll. Supports modifiers as well.
async def cmd_roll(ctx, inputValue, sign = None, addition = None): async def cmd_roll(ctx, inputValue, sign = None, addition = None):
#Initializing variables for the subtotal and total.
subtotal = 0 subtotal = 0
total = 0 total = 0
#Rolls the dice.
try: try:
#Splits the input into variables separated by the letter 'd', for number of sides, and how many sides.
number, sides = map(int, inputValue.lower().split('d')) number, sides = map(int, inputValue.lower().split('d'))
#For however many times you roll, it passes the number of sides to a rolldie function, and adds the result to subtotal.
for _ in range(number): for _ in range(number):
subtotal += rolldie(sides) subtotal += rolldie(sides)
#Checks to see if any modifiers were applied. If so, apply the logic.
if sign and addition: if sign and addition:
total = subtotal total = subtotal
addition = int(addition) addition = int(addition) #Explicitly converts the modifier value to an integer.
if sign == '+': if sign == '+': #Addition.
total = subtotal + addition total = subtotal + addition
elif sign == '-': elif sign == '-': #Subtraction.
total = subtotal - addition total = subtotal - addition
elif sign in ('*', 'X', 'x'): elif sign in ('*', 'X', 'x'): #Multiplication.
total = subtotal * addition total = subtotal * addition
elif sign == '/': elif sign == '/': #Division, rounding down.
total = math.floor(subtotal / addition) total = math.floor(subtotal / addition)
else: else:
await ctx.send("Invalid mathematical sign passed.") await ctx.send("Invalid mathematical sign passed.")
@ -107,6 +128,7 @@ async def cmd_roll(ctx, inputValue, sign = None, addition = None):
### INTERNAL METHODS - ALL METHODS MUST BE LOWERCASE ### ### INTERNAL METHODS - ALL METHODS MUST BE LOWERCASE ###
######################################################## ########################################################
#Loads commands into variable.
def loadcommands(filename): def loadcommands(filename):
if not os.path.exists(filename): if not os.path.exists(filename):
with open(filename, "w", encoding="utf-8") as file: with open(filename, "w", encoding="utf-8") as file:
@ -115,6 +137,7 @@ def loadcommands(filename):
with open(filename, "r", encoding="utf-8") as file: with open(filename, "r", encoding="utf-8") as file:
return json.load(file) return json.load(file)
#Loads points into variable.
def loadpoints(): def loadpoints():
if not os.path.exists("points.json"): if not os.path.exists("points.json"):
with open("points.json", "w", encoding="utf-8") as file: with open("points.json", "w", encoding="utf-8") as file:
@ -128,6 +151,7 @@ def savepoints(points_data):
with open("points.json", "w", encoding="utf-8") as file: with open("points.json", "w", encoding="utf-8") as file:
json.dump(points_data, file, indent=4) json.dump(points_data, file, indent=4)
#Rolls die for cmd_roll
def rolldie(sides): def rolldie(sides):
return random.randint(1, sides) return random.randint(1, sides)